Compare commits

...

20 Commits

Author SHA1 Message Date
Matt Jacobson 43e8319ebf Add back removed test 2026-01-07 12:25:17 -05:00
Matt Jacobson 5a8696cf6b Fix route preview drawer policy name and link 2026-01-07 12:00:49 -05:00
Matt Jacobson 78f8acb056 Fix ROUTES_META_SYMBOL being lost because of RTK query cache transform 2026-01-07 12:00:49 -05:00
Matt Jacobson 589b359fef WIP: create modal 2026-01-07 12:00:49 -05:00
Matt Jacobson b833a10a0c Fix alert rule route preview and irmHooks use of route api 2026-01-07 12:00:49 -05:00
Matt Jacobson 993d2f80e8 Fix alert instance counts and preview in routes
Adds built-in matchers so existing code works as-is
Fixes route memoization and moves it to transformResponse so RTK handles it
2026-01-07 12:00:49 -05:00
Matt Jacobson e01043030c AsAMRoute -> AsRoute 2026-01-07 12:00:49 -05:00
Matt Jacobson 38103a2ff0 Fix Export All policies
Broken when moved to ManagedRoutes field on PostableUserConfig
2026-01-07 12:00:49 -05:00
Matt Jacobson d732af94ff Frontend 2026-01-07 12:00:49 -05:00
Matt Jacobson 0fa9f3a247 Backend 2026-01-07 12:00:49 -05:00
Matt Jacobson d220d765b8 FF 2025-11-03 13:51:45 -05:00
Bruno 4cda8669a5 Caching: GetKey requires a namespace argument (#113180)
* Caching: GetKey requires a namespace argument

* GetKey: special case empty namespace
2025-11-03 12:22:36 -03:00
Andres Martinez Gotor 14c45b6db2 Advisor: Standalone server mock (#113224) 2025-11-03 16:09:54 +01:00
Jo eeddc8cd18 Zanzana: Add team binding hooks (#113274)
add team binding hooks
2025-11-03 15:39:20 +01:00
Jo 99e4583cd1 Zanzana: Add user org role hooks (#113276)
* add user org role hooks

* update with feedback
2025-11-03 15:39:12 +01:00
Matias Chomicki cbd6b53182 New Logs Panel: Enable new visualization by default (#113340)
* New Logs Panel: enabled by default

* Update toggles

* Change feature flag availability
2025-11-03 06:21:39 -08:00
Alexander Zobnin 259c7807cb Zanzana: Respect action sets for dashboards and folders during reconciliation (#113352)
Zanzana: Respect action sets for dashboards and folders during legacy reconciliation
2025-11-03 15:19:23 +01:00
Alexander Zobnin d6fa822e89 Zanzana: Write API for org roles (#113339)
* Zanzana: Add write APIs for user org roles

* Add tests

* Fix tests

* fix role translation
2025-11-03 14:47:10 +01:00
Anna Urbiztondo a89377337b Docs: Full instance Git Sync notes (#113083)
* Full instance sync

* Edits

* Prettier

* Fix

* Edits, note on import

* Feedback

* Fix?

* Fix

* Prettier

* Fixing lists

* Fixes

* X-refs

* Prettier

* Update docs/sources/observability-as-code/provision-resources/git-sync-setup.md

Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>

* Update docs/sources/observability-as-code/provision-resources/intro-git-sync.md

Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>

* Edits

* Prettier

---------

Co-authored-by: Roberto Jiménez Sánchez <roberto.jimenez@grafana.com>
2025-11-03 14:32:04 +01:00
Tobias Skarhed 3b99370aac Scopes: Fix icon lookup for scope navigation (#113313)
Fix icon lookup for scope navigation
2025-11-03 13:09:58 +01:00
79 changed files with 5200 additions and 812 deletions
+8
View File
@@ -1,5 +1,9 @@
include ../sdk.mk
.PHONY: etcd
etcd:
@docker run -d --name etcd --env ALLOW_NONE_AUTHENTICATION=yes -p 22379:2379 bitnamilegacy/etcd:latest
.PHONY: generate # Run Grafana App SDK code generation
generate: install-app-sdk update-app-sdk
@$(APP_SDK_BIN) generate \
@@ -7,3 +11,7 @@ generate: install-app-sdk update-app-sdk
--gogenpath=./pkg/apis \
--grouping=group \
--defencoding=none
.PHONY: run
run:
@go run ./pkg/standalone/server.go --etcd-servers=http://127.0.0.1:22379 --secure-port 7445
+11
View File
@@ -152,3 +152,14 @@ Check [`security_config_step.go`](./pkg/app/checks/configchecks/security_config_
## Testing
Create tests for your check and its steps to ensure they work as expected. Test both successful and failure scenarios.
## Running the Standalone Mode
To run the standalone mode, you can use the `make run` command. This will start the advisor app in standalone mode, which means it will not be running in a Kubernetes cluster.
```bash
make etcd # Start etcd in a docker container
make run # Start the advisor app in standalone mode
```
This will start the advisor app on port 7445. You can then access the advisor app at `http://localhost:7445`.
+20 -2
View File
@@ -15,6 +15,8 @@ require (
github.com/stretchr/testify v1.11.1
k8s.io/apimachinery v0.34.1
k8s.io/apiserver v0.34.1
k8s.io/client-go v0.34.1
k8s.io/component-base v0.34.1
k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912
)
@@ -43,6 +45,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.7.0 // indirect
dario.cat/mergo v1.0.2 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
@@ -55,6 +58,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 +89,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/cpuguy83/go-md2man/v2 v2.0.7 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
@@ -101,6 +106,7 @@ require (
github.com/emicklei/go-restful/v3 v3.13.0 // 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
@@ -143,6 +149,7 @@ 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
@@ -162,6 +169,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.2 // indirect
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.1-0.20191002090509-6af20e3a5340 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
@@ -176,6 +184,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
@@ -250,7 +259,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
@@ -262,6 +273,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.1.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 // indirect
@@ -280,6 +294,8 @@ require (
go.opentelemetry.io/proto/otlp v1.7.1 // 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.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.43.0 // indirect
@@ -302,24 +318,26 @@ require (
google.golang.org/grpc v1.76.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/fsnotify/fsnotify.v1 v1.4.7 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/mail.v2 v2.3.1 // indirect
gopkg.in/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.1 // indirect
k8s.io/apiextensions-apiserver v0.34.1 // indirect
k8s.io/client-go v0.34.1 // indirect
k8s.io/component-base v0.34.1 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kms v0.34.1 // 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.39.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.0 // indirect
+26
View File
@@ -335,6 +335,7 @@ github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV
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.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
@@ -463,6 +464,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=
@@ -668,6 +671,8 @@ 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/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-20251009192429-9427c24835ae h1:NLPwY3tIP0lg0g9wTRiMcypm6VRXW6W+MOLBsq8JSVA=
github.com/grafana/alerting v0.0.0-20251009192429-9427c24835ae/go.mod h1:VGjS5gDwWEADPP6pF/drqLxEImgeuHlEW5u8E5EfIrM=
github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f h1:Cbm6OKkOcJ+7CSZsGsEJzktC/SIa5bxVeYKQLuYK86o=
@@ -811,6 +816,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=
@@ -1048,6 +1055,7 @@ github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSg
github.com/pressly/goose/v3 v3.25.0 h1:6WeYhMWGRCzpyd89SpODFnCBCKz41KrVbRT58nVjGng=
github.com/pressly/goose/v3 v3.25.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=
@@ -1065,6 +1073,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=
@@ -1079,6 +1088,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=
@@ -1135,6 +1145,8 @@ github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304 h1:Jpy1PX
github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c h1:Ho+uVpkel/udgjbwB5Lktg9BtvJSh2DT0Hi6LPSyI2w=
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s=
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=
@@ -1148,6 +1160,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=
@@ -1173,6 +1186,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.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
@@ -1190,6 +1204,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.3 h1:6SdexP3UIeg93KLFeiM1Wp1caRwdTLgsD/THxBUy1+o=
github.com/tjhop/slog-gokit v0.1.3/go.mod h1:Bbu5v2748qpAWH7k6gse/kw3076IJf6owJmh7yArmJs=
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=
@@ -1217,6 +1233,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=
@@ -1241,6 +1259,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=
@@ -1393,6 +1417,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=
@@ -1805,6 +1830,7 @@ google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090/go.
google.golang.org/genproto/googleapis/rpc v0.0.0-20251002232023-7c0ddcbb5797 h1:CirRxTOwnRWVLKzDNrs0CXAaVozJoR4G9xvdRecrdpk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20251002232023-7c0ddcbb5797/go.mod h1:HSkG/KdJWusxU1F6CNrwNDjBMgisKxGnc5dAZfT0mjQ=
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=
@@ -0,0 +1,12 @@
package mockchecks
import "github.com/grafana/grafana/apps/advisor/pkg/app/checks"
// mockchecks.CheckRegistry is a mock implementation of the checkregistry.CheckService interface
// TODO: Add mocked checks here
type CheckRegistry struct {
}
func (m *CheckRegistry) Checks() []checks.Check {
return []checks.Check{}
}
+58
View File
@@ -0,0 +1,58 @@
package main
import (
"log/slog"
"os"
"k8s.io/apiserver/pkg/admission"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/client-go/rest"
"k8s.io/component-base/cli"
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana-app-sdk/k8s/apiserver"
"github.com/grafana/grafana-app-sdk/k8s/apiserver/cmd/server"
"github.com/grafana/grafana-app-sdk/logging"
"github.com/grafana/grafana-app-sdk/simple"
"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/apps/advisor/pkg/app/checkregistry/mockchecks"
)
func main() {
logging.DefaultLogger = logging.NewSLogLogger(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
provider := simple.NewAppProvider(apis.LocalManifest(), nil, advisorapp.New)
config := app.Config{
KubeConfig: rest.Config{}, // this will be replaced by the apiserver loopback config
ManifestData: *apis.LocalManifest().ManifestData,
SpecificConfig: checkregistry.AdvisorAppConfig{
CheckRegistry: &mockchecks.CheckRegistry{},
PluginConfig: map[string]string{},
StackID: "1", // Numeric stack ID for standalone mode
OrgService: nil, // Not needed when StackID is set
},
}
installer, err := apiserver.NewDefaultAppInstaller(provider, config, &apis.GoTypeAssociator{})
if err != nil {
panic(err)
}
ctx := genericapiserver.SetupSignalContext()
opts := apiserver.NewOptions([]apiserver.AppInstaller{installer})
opts.RecommendedOptions.Authentication = nil
opts.RecommendedOptions.Authorization = nil
opts.RecommendedOptions.CoreAPI = nil
opts.RecommendedOptions.EgressSelector = nil
opts.RecommendedOptions.Admission.Plugins = admission.NewPlugins()
opts.RecommendedOptions.Admission.RecommendedPluginOrder = []string{}
opts.RecommendedOptions.Admission.EnablePlugins = []string{}
opts.RecommendedOptions.Features.EnablePriorityAndFairness = false
opts.RecommendedOptions.ExtraAdmissionInitializers = func(_ *genericapiserver.RecommendedConfig) ([]admission.PluginInitializer, error) {
return nil, nil
}
cmd := server.NewCommandStartServer(ctx, opts)
code := cli.Run(cmd)
os.Exit(code)
}
@@ -40,8 +40,7 @@ To set up file sync with local with local files, you need to:
Local file provisioning using **Administration** > **Provisioning** will eventually replace the traditional methods Grafana has used for referencing local file systems for dashboard files.
{{< admonition type="note" >}}
For production system, we recommend using the `folderFromFilesStructure` capability instead of **Administration** > **Provisioning** to include dashboards from a local file system in your Grafana instance.
Refer to [Provision Grafana](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#provision-folders-structure-from-filesystem-to-grafana) for more information.
For production systems, use the `folderFromFilesStructure` capability instead of **Administration** > **Provisioning** to include dashboards from a local file system in your Grafana instance. Refer to [Provision Grafana](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#provision-folders-structure-from-filesystem-to-grafana) for more information.
{{< /admonition >}}
### Limitations
@@ -125,6 +124,18 @@ The set up process verifies the path and provides an error message if a problem
### Choose what to synchronize
#### Synchronization limitations
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, the connection will be blocked.
- You won't be able to create new alerts or library panels after setup is completed.
- If you opted for full instance sync and want to use alerts and library panels, you'll have to delete the provisioned repository and connect again with folder sync.
#### Set up synchronization
Choose to either sync your entire organization resources with external storage, or to sync certain resources to a new Grafana folder (with up to 10 connections).
- 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.
@@ -61,6 +61,8 @@ Refer to [Known limitations](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/
{{< /admonition >}}
### Requirements
To set up Git Sync, you need:
- Administration rights in your Grafana organization.
@@ -128,34 +130,37 @@ 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.
- 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.
#### Synchronization limitations
Git Sync only supports dashboards and folders. Alerts, panels, and other resources are not supported yet.
{{< admonition type="caution" >}}
Git Sync only works with specific folders for the moment. Full-instance sync is not currently supported. Refer to [Supported resources](/docs/grafana/<GRAFANA_VERSION>/observability-as-code/provision-resources/intro-git-sync#supported-resources) for more details about which resources you can sync.
Refer to [Known limitations](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/observability-as-code/provision-resources/intro-git-sync#known-limitations/) before using Git Sync. Refer to [Supported resources](/docs/grafana/<GRAFANA_VERSION>/observability-as-code/provision-resources/intro-git-sync#supported-resources) for details about which resources you can sync.
{{< /admonition >}}
In this step you can decide which elements to synchronize. Keep in mind the available options depend on the status of your GitHub repository. The first time you connect Grafana with a GitHub repository, you need to synchronize with external storage. If you are syncing with a new or empty repository, you won't have an option to migrate dashboards.
Full instance sync is not available in Grafana Cloud.
1. 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).
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).
- Choose **Sync all resources with external storage** if you want to sync and manage your entire Grafana instance through external storage. With this option, all of your dashboards are synced to that one repository. You can only have one provisioned connection with this selection, and you won't have the option of setting up additional repositories to connect to.
- Choose **Sync external storage to new Grafana folder** to sync external resources into a new folder without affecting the rest of your instance. You can repeat this process for up to 10 connections.
1. Enter a **Display name** for the repository connection. Resources stored in this connection appear under the chosen display name in the Grafana UI.
1. Click **Synchronize** to continue.
<!-- ### Synchronize with external storage
{{< admonition type="note">}}
During the synchronization process, your dashboards will be temporarily unavailable.
No data or configuration will be lost.
However, no one will be able to create, edit, or delete resources during this process.
In the last step, the resources will disappear and will reappear and be managed through external storage.
{{< /admonition >}}
1. Select **History** to include commits for each historical value in the synchronized data.
1. Select **Begin synchronization** to continue. -->
Next, enter a **Display name** for the repository connection. Resources stored in this connection appear under the chosen display name in the Grafana UI. Click **Synchronize** to continue.
### Choose additional settings
@@ -163,7 +168,6 @@ Finally, you can set up how often your configured storage is polled for updates.
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.
<!-- No workflow option listed in the UI. 1. For **Workflows**, select the GitHub workflows that you want to allow to run in the repository. Both **Branch** and **Write** are selected by default. -->
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. Select **Finish** to proceed.
@@ -179,23 +183,11 @@ You can extend Git Sync by getting instant updates and pull requests using webho
### Set up webhooks for realtime notification and pull request integration
When connecting to a GitHub repository, Git Sync use webhooks to enable real-time updates from GitHub public repositories or enable the pull request integration.
Without webhooks, the polling interval is set in the final configuration screen (default is 60 seconds).
Your Grafana instance must be exposed to the public internet.
You can do this via port forwarding and DNS, a tool such as `ngrok`, or any other method you prefer.
When connecting to a GitHub repository, Git Sync uses webhooks to enable real-time updates from GitHub public repositories or enable pull request integrations. Without webhooks, the polling interval is set in the final configuration screen, and the default is 60 seconds. If you use local storage, then Git Sync only provides periodic pulling.
The permissions set in your GitHub access token provide the authorization for this communication.
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`.
If you use local storage, then Git Sync only provides periodic pulling.
<!-- Grafana Cloud support not available yet
{{< admonition type="note" >}}
Webhooks are automatically available for Grafana Cloud users.
{{< /admonition >}}
-->
Set up webhooks with whichever service or tooling you prefer.
For example, 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.
After you have the public URL, you can add it to your Grafana configuration file:
@@ -204,23 +196,22 @@ After you have the public URL, you can add it to your Grafana configuration file
root_url = https://PUBLIC_DOMAIN.HERE
```
You can check the configured webhooks in the **View** link for your GitHub repository from **Administration** > **Provisioning**.
To check the configured webhooks, go to **Administration** > **Provisioning** and click the **View** link for your GitHub repository.
#### Necessary paths
#### 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 does not 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 (RegExp):
The necessary paths required to be exposed are, in RegExp:
- `/apis/provisioning\.grafana\.app/v0(alpha1)?/namespaces/[^/]+/repositories/[^/]+/(webhook|render/.*)$`
<!-- TODO: Path for the blob storage for image rendering? @ryantxu would know this best. -->
### Set up image rendering for dashboard previews
By setting up image rendering, you can add visual previews of dashboard updates directly in pull requests.
Image rendering also requires webhooks.
Set up image rendering to add visual previews of dashboard updates directly in pull requests. Image rendering also requires webhooks.
You can enable this capability by installing 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).
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
@@ -63,14 +63,31 @@ With Git Sync, you can make changes to the files in the provisioned folder in Gi
## Known limitations
Git Sync is under development and the following limitations apply:
{{< admonition type="caution" >}}
Refer to [Requirements](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/observability-as-code/provision-resources/git-sync-setup#requirements/) to learn what you need to use Git Sync.
{{< /admonition >}}
**Git Sync is under development and the following limitations apply.**
**Synced resources**
- You can only sync dashboards and folders. Refer to [Supported resources](#supported-resources) for more information.
- If you're using Git Sync in Grafana OSS and Grafana Enterprise, some resources might be in an incompatible data format and can't be synced.
- You can only authenticate in GitHub using your Personal Access Token token.
- Support for native Git, Git app, and other providers, such as GitLab or Bitbucket, is on the roadmap.
- If you're using Git Sync in Grafana OSS and Grafana Enterprise, some resources might be in an incompatible data format and won't be synced.
- Full-instance sync is not available in Grafana Cloud and has limitations in Grafana OSS and Grafana Enterprise. Refer to [Choose what to synchronize](../git-sync-setup.md#choose-what-to-synchronize) for more details.
- When migrating to full instance sync, during the synchronization process your resources will be temporarily unavailable. No one will be able to create, edit, or delete resources during this process.
- If you want to manage existing resources with Git Sync, you need to save them as JSON files and commit them to the synced repository. Open a PR to import, copy, move, or save a dashboard.
- Restoring resources from the UI is currently not possible. As an alternative, you can restore dashboards directly in your GitHub repository by raising a PR, and they will be updated in Grafana.
**Authentication**
- You can only authenticate in GitHub using your Personal Access Token token.
**Compatibility**
- Support for native Git, Git app, and other providers, such as GitLab or Bitbucket, is on the roadmap.
## Supported resources
Git Sync only supports dashboards and folders. Alerts, panels, and other resources are not supported yet.
@@ -86,9 +103,9 @@ A resource can be:
| **Supported** | The resource can be managed with Git Sync. | The resource is supported but has compatibility issues. It **cannot** be managed with Git Sync. |
| **Unsupported** | The resource is **not** supported and **cannot** be managed with Git Sync. | Not applicable. |
### Instance states
### Git Sync instance states
An instance can be in one of the following states:
An instance can be in one of the following Git Sync states:
- **Unprovisioned**: None of the instance's resources are being managed by Git Sync.
- **Partially provisioned**: Some of the resources are controlled by Git Sync.
@@ -74,6 +74,7 @@ Most [generally available](https://grafana.com/docs/release-life-cycle/#general-
| `elasticsearchCrossClusterSearch` | Enables cross cluster search in the Elasticsearch data source | |
| `lokiLabelNamesQueryApi` | Defaults to using the Loki `/labels` API instead of `/series` | Yes |
| `improvedExternalSessionHandlingSAML` | Enables improved support for SAML external sessions. Ensure the NameID format is correctly configured in Grafana for SAML Single Logout to function properly. | Yes |
| `newLogsPanel` | Enables the new logs panel | Yes |
| `alertingMigrationUI` | Enables the alerting migration UI, to migrate data source-managed rules to Grafana-managed rules | Yes |
| `alertingImportYAMLUI` | Enables a UI feature for importing rules from a Prometheus file to Grafana-managed rules | Yes |
| `unifiedNavbars` | Enables unified navbars | |
@@ -883,7 +883,8 @@ export interface FeatureToggles {
*/
fetchRulesUsingPost?: boolean;
/**
* Enables the new logs panel in Explore
* Enables the new logs panel
* @default true
*/
newLogsPanel?: boolean;
/**
@@ -1245,4 +1246,9 @@ export interface FeatureToggles {
* Enable template dashboards
*/
dashboardTemplates?: boolean;
/**
* Enables the ability to create multiple alerting policies
* @default false
*/
alertingMultiplePolicies?: boolean;
}
+15
View File
@@ -224,6 +224,14 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *ge
return err
}
// Only teamBindingStore exposes the AfterCreate, AfterDelete, and BeginUpdate hooks
if enableZanzanaSync {
b.logger.Info("Enabling hooks for TeamBinding to sync to Zanzana")
teamBindingStore.AfterCreate = b.AfterTeamBindingCreate
teamBindingStore.AfterDelete = b.AfterTeamBindingDelete
teamBindingStore.BeginUpdate = b.BeginTeamBindingUpdate
}
storage[teamBindingResource.StoragePath()] = teamBindingDW
}
@@ -238,6 +246,13 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *ge
return err
}
if enableZanzanaSync {
b.logger.Info("Enabling hooks for User to sync basic role assignments to Zanzana")
store.AfterCreate = b.AfterUserCreate
store.BeginUpdate = b.BeginUserUpdate
store.AfterDelete = b.AfterUserDelete
}
dw, err := opts.DualWriteBuilder(userResource.GroupResource(), legacyStore, store)
if err != nil {
return err
+348
View File
@@ -0,0 +1,348 @@
package iam
import (
"context"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/generic/registry"
iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1"
v1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
"github.com/grafana/grafana/pkg/services/authz/zanzana"
)
// convertTeamBindingToTuple converts a TeamBinding to a v1 TupleKey format
// TeamBinding represents a user's membership in a team with a specific permission level
func convertTeamBindingToTuple(tb *iamv0.TeamBinding) (*v1.TupleKey, error) {
if tb.Spec.Subject.Name == "" {
return nil, errEmptyName
}
if tb.Spec.TeamRef.Name == "" {
return nil, errEmptyName
}
// Map permission to relation
var relation string
switch tb.Spec.Permission {
case iamv0.TeamBindingTeamPermissionAdmin:
relation = zanzana.RelationTeamAdmin
case iamv0.TeamBindingTeamPermissionMember:
relation = zanzana.RelationTeamMember
default:
// Default to member if unknown permission
relation = zanzana.RelationTeamMember
}
// Create tuple: user:{subjectUID} has {relation} relation to team:{teamUID}
tuple := &v1.TupleKey{
User: zanzana.NewTupleEntry(zanzana.TypeUser, tb.Spec.Subject.Name, ""),
Relation: relation,
Object: zanzana.NewTupleEntry(zanzana.TypeTeam, tb.Spec.TeamRef.Name, ""),
}
return tuple, nil
}
// AfterTeamBindingCreate is a post-create hook that writes the team binding to Zanzana (openFGA)
func (b *IdentityAccessManagementAPIBuilder) AfterTeamBindingCreate(obj runtime.Object, _ *metav1.CreateOptions) {
if b.zClient == nil {
return
}
tb, ok := obj.(*iamv0.TeamBinding)
if !ok {
b.logger.Error("failed to convert object to TeamBinding type", "object", obj)
return
}
resourceType := "teambinding"
operation := "create"
// Grab a ticket to write to Zanzana
// This limits the amount of concurrent connections to Zanzana
wait := time.Now()
b.zTickets <- true
hooksWaitHistogram.WithLabelValues(resourceType, operation).Observe(time.Since(wait).Seconds())
go func(tb *iamv0.TeamBinding) {
start := time.Now()
status := "success"
defer func() {
// Release the ticket after write is done
<-b.zTickets
// Record operation duration and count
hooksDurationHistogram.WithLabelValues(resourceType, operation, status).Observe(time.Since(start).Seconds())
hooksOperationCounter.WithLabelValues(resourceType, operation, status).Inc()
}()
tuple, err := convertTeamBindingToTuple(tb)
if err != nil {
b.logger.Error("failed to convert team binding to tuple",
"namespace", tb.Namespace,
"name", tb.Name,
"subject", tb.Spec.Subject.Name,
"teamRef", tb.Spec.TeamRef.Name,
"err", err,
)
status = "failure"
return
}
b.logger.Debug("writing team binding to zanzana",
"namespace", tb.Namespace,
"name", tb.Name,
"subject", tb.Spec.Subject.Name,
"teamRef", tb.Spec.TeamRef.Name,
"permission", tb.Spec.Permission,
)
ctx, cancel := context.WithTimeout(context.Background(), defaultWriteTimeout)
defer cancel()
err = b.zClient.Write(ctx, &v1.WriteRequest{
Namespace: tb.Namespace,
Writes: &v1.WriteRequestWrites{
TupleKeys: []*v1.TupleKey{tuple},
},
})
if err != nil {
status = "failure"
b.logger.Error("failed to write team binding to zanzana",
"err", err,
"namespace", tb.Namespace,
"name", tb.Name,
"subject", tb.Spec.Subject.Name,
"teamRef", tb.Spec.TeamRef.Name,
)
} else {
// Record successful tuple write
hooksTuplesCounter.WithLabelValues(resourceType, operation, "write").Inc()
}
}(tb.DeepCopy()) // Pass a copy of the object
}
// BeginTeamBindingUpdate is a pre-update hook that prepares zanzana updates
// It converts old and new team bindings to tuples and performs the zanzana write after K8s update succeeds
func (b *IdentityAccessManagementAPIBuilder) BeginTeamBindingUpdate(ctx context.Context, obj, oldObj runtime.Object, options *metav1.UpdateOptions) (registry.FinishFunc, error) {
if b.zClient == nil {
return nil, nil
}
// Extract team bindings from both old and new objects
oldTB, ok := oldObj.(*iamv0.TeamBinding)
if !ok {
return nil, nil
}
newTB, ok := obj.(*iamv0.TeamBinding)
if !ok {
return nil, nil
}
// Convert old team binding to tuple for deletion
var oldTuple *v1.TupleKey
var oldErr error
if oldTB.Spec.Subject.Name != "" && oldTB.Spec.TeamRef.Name != "" {
oldTuple, oldErr = convertTeamBindingToTuple(oldTB)
if oldErr != nil {
b.logger.Error("failed to convert old team binding to tuple",
"namespace", oldTB.Namespace,
"name", oldTB.Name,
"err", oldErr,
)
}
}
// Convert new team binding to tuple for writing
var newTuple *v1.TupleKey
var newErr error
if newTB.Spec.Subject.Name != "" && newTB.Spec.TeamRef.Name != "" {
newTuple, newErr = convertTeamBindingToTuple(newTB)
if newErr != nil {
b.logger.Error("failed to convert new team binding to tuple",
"namespace", newTB.Namespace,
"name", newTB.Name,
"err", newErr,
)
}
}
// Return a finish function that performs the zanzana write only on success
return func(ctx context.Context, success bool) {
if !success {
// Update failed, don't write to zanzana
return
}
// Grab a ticket to write to Zanzana
// This limits the amount of concurrent connections to Zanzana
wait := time.Now()
b.zTickets <- true
hooksWaitHistogram.WithLabelValues("teambinding", "update").Observe(time.Since(wait).Seconds())
go func() {
start := time.Now()
status := "success"
defer func() {
<-b.zTickets
// Record operation duration and count
hooksDurationHistogram.WithLabelValues("teambinding", "update", status).Observe(time.Since(start).Seconds())
hooksOperationCounter.WithLabelValues("teambinding", "update", status).Inc()
}()
b.logger.Debug("updating team binding in zanzana",
"namespace", newTB.Namespace,
"name", newTB.Name,
"oldSubject", oldTB.Spec.Subject.Name,
"newSubject", newTB.Spec.Subject.Name,
"oldTeamRef", oldTB.Spec.TeamRef.Name,
"newTeamRef", newTB.Spec.TeamRef.Name,
"oldPermission", oldTB.Spec.Permission,
"newPermission", newTB.Spec.Permission,
)
ctx, cancel := context.WithTimeout(context.Background(), defaultWriteTimeout)
defer cancel()
// Prepare write request
req := &v1.WriteRequest{
Namespace: newTB.Namespace,
}
// Add delete for old tuple
if oldTuple != nil && oldErr == nil {
deleteTuple := toTupleKeysWithoutCondition([]*v1.TupleKey{oldTuple})
req.Deletes = &v1.WriteRequestDeletes{
TupleKeys: deleteTuple,
}
b.logger.Debug("deleting existing team binding from zanzana",
"namespace", newTB.Namespace,
"subject", oldTB.Spec.Subject.Name,
"teamRef", oldTB.Spec.TeamRef.Name,
)
}
// Add write for new tuple
if newTuple != nil && newErr == nil {
req.Writes = &v1.WriteRequestWrites{
TupleKeys: []*v1.TupleKey{newTuple},
}
b.logger.Debug("writing new team binding to zanzana",
"namespace", newTB.Namespace,
"subject", newTB.Spec.Subject.Name,
"teamRef", newTB.Spec.TeamRef.Name,
)
}
// Only make the request if there are deletes or writes
if (req.Deletes != nil && len(req.Deletes.TupleKeys) > 0) || (req.Writes != nil && len(req.Writes.TupleKeys) > 0) {
err := b.zClient.Write(ctx, req)
if err != nil {
status = "failure"
b.logger.Error("failed to update team binding in zanzana",
"err", err,
"namespace", newTB.Namespace,
"name", newTB.Name,
)
} else {
// Record successful tuple operations
if oldTuple != nil && oldErr == nil {
hooksTuplesCounter.WithLabelValues("teambinding", "update", "delete").Inc()
}
if newTuple != nil && newErr == nil {
hooksTuplesCounter.WithLabelValues("teambinding", "update", "write").Inc()
}
}
} else {
b.logger.Debug("no tuples to update in zanzana", "namespace", newTB.Namespace, "name", newTB.Name)
}
}()
}, nil
}
// AfterTeamBindingDelete is a post-delete hook that removes the team binding from Zanzana (openFGA)
func (b *IdentityAccessManagementAPIBuilder) AfterTeamBindingDelete(obj runtime.Object, _ *metav1.DeleteOptions) {
if b.zClient == nil {
return
}
tb, ok := obj.(*iamv0.TeamBinding)
if !ok {
b.logger.Error("failed to convert object to TeamBinding type", "object", obj)
return
}
resourceType := "teambinding"
operation := "delete"
// Grab a ticket to write to Zanzana
// This limits the amount of concurrent connections to Zanzana
wait := time.Now()
b.zTickets <- true
hooksWaitHistogram.WithLabelValues(resourceType, operation).Observe(time.Since(wait).Seconds())
go func(tb *iamv0.TeamBinding) {
start := time.Now()
status := "success"
defer func() {
// Release the ticket after write is done
<-b.zTickets
// Record operation duration and count
hooksDurationHistogram.WithLabelValues(resourceType, operation, status).Observe(time.Since(start).Seconds())
hooksOperationCounter.WithLabelValues(resourceType, operation, status).Inc()
}()
tuple, err := convertTeamBindingToTuple(tb)
if err != nil {
b.logger.Error("failed to convert team binding to tuple for deletion",
"namespace", tb.Namespace,
"name", tb.Name,
"subject", tb.Spec.Subject.Name,
"teamRef", tb.Spec.TeamRef.Name,
"err", err,
)
status = "failure"
return
}
// Convert tuple to TupleKeyWithoutCondition for deletion
deleteTuple := toTupleKeysWithoutCondition([]*v1.TupleKey{tuple})
b.logger.Debug("deleting team binding from zanzana",
"namespace", tb.Namespace,
"name", tb.Name,
"subject", tb.Spec.Subject.Name,
"teamRef", tb.Spec.TeamRef.Name,
"permission", tb.Spec.Permission,
)
ctx, cancel := context.WithTimeout(context.Background(), defaultWriteTimeout)
defer cancel()
err = b.zClient.Write(ctx, &v1.WriteRequest{
Namespace: tb.Namespace,
Deletes: &v1.WriteRequestDeletes{
TupleKeys: deleteTuple,
},
})
if err != nil {
status = "failure"
b.logger.Error("failed to delete team binding from zanzana",
"err", err,
"namespace", tb.Namespace,
"name", tb.Name,
"subject", tb.Spec.Subject.Name,
"teamRef", tb.Spec.TeamRef.Name,
)
} else {
// Record successful tuple deletion
hooksTuplesCounter.WithLabelValues(resourceType, operation, "delete").Inc()
}
}(tb.DeepCopy()) // Pass a copy of the object
}
@@ -0,0 +1,749 @@
package iam
import (
"context"
"sync"
"testing"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1"
"github.com/grafana/grafana/pkg/infra/log"
v1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
"github.com/stretchr/testify/require"
)
func TestAfterTeamBindingCreate(t *testing.T) {
var wg sync.WaitGroup
b := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
}
t.Run("should create zanzana entry for team binding with member permission", func(t *testing.T) {
wg.Add(1)
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-1",
Namespace: "org-1",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
External: false,
},
}
testMemberBinding := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(t, "org-1", req.Namespace)
require.Nil(t, req.Deletes)
expectedTuple := &v1.TupleKey{
User: "user:user-1",
Relation: "member",
Object: "team:team-1",
}
actualTuple := req.Writes.TupleKeys[0]
require.Equal(t, expectedTuple.User, actualTuple.User)
require.Equal(t, expectedTuple.Relation, actualTuple.Relation)
require.Equal(t, expectedTuple.Object, actualTuple.Object)
require.Nil(t, actualTuple.Condition)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testMemberBinding}
b.AfterTeamBindingCreate(&teamBinding, nil)
wg.Wait()
})
t.Run("should create zanzana entry for team binding with admin permission", func(t *testing.T) {
wg.Add(1)
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-2",
Namespace: "org-2",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-2",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-2",
},
Permission: iamv0.TeamBindingTeamPermissionAdmin,
External: true,
},
}
testAdminBinding := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(t, "org-2", req.Namespace)
require.Nil(t, req.Deletes)
expectedTuple := &v1.TupleKey{
User: "user:user-2",
Relation: "admin",
Object: "team:team-2",
}
actualTuple := req.Writes.TupleKeys[0]
require.Equal(t, expectedTuple.User, actualTuple.User)
require.Equal(t, expectedTuple.Relation, actualTuple.Relation)
require.Equal(t, expectedTuple.Object, actualTuple.Object)
require.Nil(t, actualTuple.Condition)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testAdminBinding}
b.AfterTeamBindingCreate(&teamBinding, nil)
wg.Wait()
})
t.Run("should not write to zanzana when zClient is nil", func(t *testing.T) {
builder := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
zClient: nil,
}
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-3",
Namespace: "org-3",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-3",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-3",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
// Should not panic or error when zClient is nil
builder.AfterTeamBindingCreate(&teamBinding, nil)
})
t.Run("should handle conversion error gracefully", func(t *testing.T) {
// TeamBinding with empty subject name should fail conversion
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-4",
Namespace: "org-4",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "", // Empty name should cause error
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-4",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
writeCalled := false
testErrorHandling := func(ctx context.Context, req *v1.WriteRequest) error {
writeCalled = true
// Should not be called due to conversion error
require.Fail(t, "Write should not be called when conversion fails")
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testErrorHandling}
b.AfterTeamBindingCreate(&teamBinding, nil)
// Wait a bit to ensure the goroutine has time to process
// The goroutine will complete but won't call the write callback
time.Sleep(100 * time.Millisecond)
require.False(t, writeCalled, "Write callback should not be called when conversion fails")
})
}
func TestBeginTeamBindingUpdate(t *testing.T) {
var wg sync.WaitGroup
b := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
}
t.Run("should update zanzana entry when permission changes from member to admin", func(t *testing.T) {
wg.Add(1)
oldBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-1",
Namespace: "org-1",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
newBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-1",
Namespace: "org-1",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionAdmin,
},
}
testPermissionUpdate := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-1", req.Namespace)
// Should delete old member permission
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
require.Equal(
t,
req.Deletes.TupleKeys[0],
&v1.TupleKeyWithoutCondition{User: "user:user-1", Relation: "member", Object: "team:team-1"},
)
// Should write new admin permission
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(
t,
req.Writes.TupleKeys[0],
&v1.TupleKey{User: "user:user-1", Relation: "admin", Object: "team:team-1"},
)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testPermissionUpdate}
finishFunc, err := b.BeginTeamBindingUpdate(context.Background(), &newBinding, &oldBinding, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
finishFunc(context.Background(), true)
wg.Wait()
})
t.Run("should update zanzana entry when user changes", func(t *testing.T) {
wg.Add(1)
oldBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-2",
Namespace: "org-2",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
newBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-2",
Namespace: "org-2",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-2",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
testUserUpdate := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-2", req.Namespace)
// Should delete old user binding
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
require.Equal(
t,
req.Deletes.TupleKeys[0],
&v1.TupleKeyWithoutCondition{User: "user:user-1", Relation: "member", Object: "team:team-1"},
)
// Should write new user binding
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(
t,
req.Writes.TupleKeys[0],
&v1.TupleKey{User: "user:user-2", Relation: "member", Object: "team:team-1"},
)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testUserUpdate}
finishFunc, err := b.BeginTeamBindingUpdate(context.Background(), &newBinding, &oldBinding, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
finishFunc(context.Background(), true)
wg.Wait()
})
t.Run("should update zanzana entry when team changes", func(t *testing.T) {
wg.Add(1)
oldBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-3",
Namespace: "org-3",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionAdmin,
},
}
newBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-3",
Namespace: "org-3",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-2",
},
Permission: iamv0.TeamBindingTeamPermissionAdmin,
},
}
testTeamUpdate := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-3", req.Namespace)
// Should delete old team binding
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
require.Equal(
t,
req.Deletes.TupleKeys[0],
&v1.TupleKeyWithoutCondition{User: "user:user-1", Relation: "admin", Object: "team:team-1"},
)
// Should write new team binding
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(
t,
req.Writes.TupleKeys[0],
&v1.TupleKey{User: "user:user-1", Relation: "admin", Object: "team:team-2"},
)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testTeamUpdate}
finishFunc, err := b.BeginTeamBindingUpdate(context.Background(), &newBinding, &oldBinding, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
finishFunc(context.Background(), true)
wg.Wait()
})
t.Run("should not write to zanzana when update fails", func(t *testing.T) {
oldBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-4",
Namespace: "org-4",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
newBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-4",
Namespace: "org-4",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-2",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
testNoWriteOnFailure := func(ctx context.Context, req *v1.WriteRequest) error {
// Should not be called when success=false
require.Fail(t, "Write should not be called when update fails")
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testNoWriteOnFailure}
finishFunc, err := b.BeginTeamBindingUpdate(context.Background(), &newBinding, &oldBinding, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
// Call finish function with success=false
finishFunc(context.Background(), false)
// No wait needed since write should not be called
})
t.Run("should not write to zanzana when zClient is nil", func(t *testing.T) {
builder := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
zClient: nil,
}
oldBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-5",
Namespace: "org-5",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
newBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-5",
Namespace: "org-5",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-2",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
finishFunc, err := builder.BeginTeamBindingUpdate(context.Background(), &newBinding, &oldBinding, nil)
require.NoError(t, err)
require.Nil(t, finishFunc) // Should return nil when zClient is nil
})
}
func TestAfterTeamBindingDelete(t *testing.T) {
var wg sync.WaitGroup
b := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
}
t.Run("should delete zanzana entry for team binding with member permission", func(t *testing.T) {
wg.Add(1)
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-1",
Namespace: "org-1",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
External: false,
},
}
testMemberDelete := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-1", req.Namespace)
// Should have deletes but no writes
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
require.Nil(t, req.Writes)
require.Equal(
t,
req.Deletes.TupleKeys[0],
&v1.TupleKeyWithoutCondition{User: "user:user-1", Relation: "member", Object: "team:team-1"},
)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testMemberDelete}
b.AfterTeamBindingDelete(&teamBinding, nil)
wg.Wait()
})
t.Run("should delete zanzana entry for team binding with admin permission", func(t *testing.T) {
wg.Add(1)
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-2",
Namespace: "org-2",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-2",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-2",
},
Permission: iamv0.TeamBindingTeamPermissionAdmin,
External: true,
},
}
testAdminDelete := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-2", req.Namespace)
// Should have deletes but no writes
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
require.Nil(t, req.Writes)
require.Equal(
t,
req.Deletes.TupleKeys[0],
&v1.TupleKeyWithoutCondition{User: "user:user-2", Relation: "admin", Object: "team:team-2"},
)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testAdminDelete}
b.AfterTeamBindingDelete(&teamBinding, nil)
wg.Wait()
})
t.Run("should not delete from zanzana when zClient is nil", func(t *testing.T) {
builder := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
zClient: nil,
}
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-3",
Namespace: "org-3",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-3",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-3",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
// Should not panic or error when zClient is nil
builder.AfterTeamBindingDelete(&teamBinding, nil)
})
t.Run("should handle conversion error gracefully", func(t *testing.T) {
// TeamBinding with empty team ref name should fail conversion
teamBinding := iamv0.TeamBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "binding-4",
Namespace: "org-4",
},
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-4",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "", // Empty name should cause error
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
writeCalled := false
testErrorHandling := func(ctx context.Context, req *v1.WriteRequest) error {
writeCalled = true
// Should not be called due to conversion error
require.Fail(t, "Write should not be called when conversion fails")
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testErrorHandling}
b.AfterTeamBindingDelete(&teamBinding, nil)
// Wait a bit to ensure the goroutine has time to process
// The goroutine will complete but won't call the write callback
time.Sleep(100 * time.Millisecond)
require.False(t, writeCalled, "Write callback should not be called when conversion fails")
})
}
func TestConvertTeamBindingToTuple(t *testing.T) {
t.Run("should convert member permission correctly", func(t *testing.T) {
tb := &iamv0.TeamBinding{
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
tuple, err := convertTeamBindingToTuple(tb)
require.NoError(t, err)
require.NotNil(t, tuple)
require.Equal(t, "user:user-1", tuple.User)
require.Equal(t, "member", tuple.Relation)
require.Equal(t, "team:team-1", tuple.Object)
require.Nil(t, tuple.Condition)
})
t.Run("should convert admin permission correctly", func(t *testing.T) {
tb := &iamv0.TeamBinding{
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-2",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-2",
},
Permission: iamv0.TeamBindingTeamPermissionAdmin,
},
}
tuple, err := convertTeamBindingToTuple(tb)
require.NoError(t, err)
require.NotNil(t, tuple)
require.Equal(t, "user:user-2", tuple.User)
require.Equal(t, "admin", tuple.Relation)
require.Equal(t, "team:team-2", tuple.Object)
require.Nil(t, tuple.Condition)
})
t.Run("should return error for empty subject name", func(t *testing.T) {
tb := &iamv0.TeamBinding{
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
tuple, err := convertTeamBindingToTuple(tb)
require.Error(t, err)
require.Nil(t, tuple)
require.Equal(t, errEmptyName, err)
})
t.Run("should return error for empty team ref name", func(t *testing.T) {
tb := &iamv0.TeamBinding{
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "",
},
Permission: iamv0.TeamBindingTeamPermissionMember,
},
}
tuple, err := convertTeamBindingToTuple(tb)
require.Error(t, err)
require.Nil(t, tuple)
require.Equal(t, errEmptyName, err)
})
t.Run("should default to member for unknown permission", func(t *testing.T) {
tb := &iamv0.TeamBinding{
Spec: iamv0.TeamBindingSpec{
Subject: iamv0.TeamBindingspecSubject{
Name: "user-1",
},
TeamRef: iamv0.TeamBindingTeamRef{
Name: "team-1",
},
Permission: "unknown", // Invalid permission
},
}
tuple, err := convertTeamBindingToTuple(tb)
require.NoError(t, err)
require.NotNil(t, tuple)
// Should default to member relation
require.Equal(t, "member", tuple.Relation)
})
}
+303
View File
@@ -0,0 +1,303 @@
package iam
import (
"context"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/generic/registry"
iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1"
v1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
"github.com/grafana/grafana/pkg/services/authz/zanzana"
)
// createUserBasicRoleTuple creates a tuple for a user's basic role assignment
func createUserBasicRoleTuple(userUID, orgRole string) *v1.TupleKey {
if orgRole == "" {
return nil
}
basicRole := zanzana.TranslateBasicRole(orgRole)
if basicRole == "" {
return nil
}
return &v1.TupleKey{
User: zanzana.NewTupleEntry(zanzana.TypeUser, userUID, ""),
Relation: zanzana.RelationAssignee,
Object: zanzana.NewTupleEntry(zanzana.TypeRole, basicRole, ""),
}
}
// AfterUserCreate is a post-create hook that writes the user's basic role assignment to Zanzana (openFGA)
func (b *IdentityAccessManagementAPIBuilder) AfterUserCreate(obj runtime.Object, _ *metav1.CreateOptions) {
if b.zClient == nil {
return
}
user, ok := obj.(*iamv0.User)
if !ok {
b.logger.Error("failed to convert object to User type", "object", obj)
return
}
resourceType := "user"
operation := "create"
// Skip if user has no role assigned
if user.Spec.Role == "" {
b.logger.Debug("user has no role assigned, skipping basic role sync",
"namespace", user.Namespace,
"userUID", user.Name,
)
return
}
// Grab a ticket to write to Zanzana
wait := time.Now()
b.zTickets <- true
hooksWaitHistogram.WithLabelValues(resourceType, operation).Observe(time.Since(wait).Seconds())
go func(u *iamv0.User) {
start := time.Now()
status := "success"
defer func() {
<-b.zTickets
hooksDurationHistogram.WithLabelValues(resourceType, operation, status).Observe(time.Since(start).Seconds())
hooksOperationCounter.WithLabelValues(resourceType, operation, status).Inc()
}()
tuple := createUserBasicRoleTuple(u.Name, u.Spec.Role)
if tuple == nil {
b.logger.Warn("failed to create user basic role tuple",
"namespace", u.Namespace,
"userUID", u.Name,
"role", u.Spec.Role,
)
status = "failure"
return
}
b.logger.Debug("writing user basic role to zanzana",
"namespace", u.Namespace,
"userUID", u.Name,
"role", u.Spec.Role,
)
ctx, cancel := context.WithTimeout(context.Background(), defaultWriteTimeout)
defer cancel()
err := b.zClient.Write(ctx, &v1.WriteRequest{
Namespace: u.Namespace,
Writes: &v1.WriteRequestWrites{
TupleKeys: []*v1.TupleKey{tuple},
},
})
if err != nil {
status = "failure"
b.logger.Error("failed to write user basic role to zanzana",
"err", err,
"namespace", u.Namespace,
"userUID", u.Name,
"role", u.Spec.Role,
)
} else {
hooksTuplesCounter.WithLabelValues(resourceType, operation, "write").Inc()
}
}(user.DeepCopy())
}
// BeginUserUpdate is a pre-update hook that gets called on user updates
// It compares old and new roles and performs the zanzana write after K8s update succeeds
func (b *IdentityAccessManagementAPIBuilder) BeginUserUpdate(ctx context.Context, obj, oldObj runtime.Object, options *metav1.UpdateOptions) (registry.FinishFunc, error) {
if b.zClient == nil {
return nil, nil
}
oldUser, ok := oldObj.(*iamv0.User)
if !ok {
return nil, nil
}
newUser, ok := obj.(*iamv0.User)
if !ok {
return nil, nil
}
// If role hasn't changed, no need to update
if oldUser.Spec.Role == newUser.Spec.Role {
return nil, nil
}
// Return a finish function that performs the zanzana write only on success
return func(ctx context.Context, success bool) {
if !success {
return
}
wait := time.Now()
b.zTickets <- true
hooksWaitHistogram.WithLabelValues("user", "update").Observe(time.Since(wait).Seconds())
go func(old, new *iamv0.User) {
start := time.Now()
status := "success"
defer func() {
<-b.zTickets
hooksDurationHistogram.WithLabelValues("user", "update", status).Observe(time.Since(start).Seconds())
hooksOperationCounter.WithLabelValues("user", "update", status).Inc()
}()
b.logger.Debug("updating user basic role in zanzana",
"namespace", new.Namespace,
"userUID", new.Name,
"oldRole", old.Spec.Role,
"newRole", new.Spec.Role,
)
ctx, cancel := context.WithTimeout(context.Background(), defaultWriteTimeout)
defer cancel()
req := &v1.WriteRequest{
Namespace: new.Namespace,
}
// Delete old role tuple if it existed
if old.Spec.Role != "" {
oldTuple := createUserBasicRoleTuple(old.Name, old.Spec.Role)
if oldTuple != nil {
deleteTuple := tupleToTupleKeyWithoutCondition(oldTuple)
req.Deletes = &v1.WriteRequestDeletes{
TupleKeys: []*v1.TupleKeyWithoutCondition{deleteTuple},
}
b.logger.Debug("deleting old user basic role from zanzana",
"namespace", new.Namespace,
"userUID", new.Name,
"role", old.Spec.Role,
)
}
}
// Write new role tuple if it exists
if new.Spec.Role != "" {
newTuple := createUserBasicRoleTuple(new.Name, new.Spec.Role)
if newTuple != nil {
req.Writes = &v1.WriteRequestWrites{
TupleKeys: []*v1.TupleKey{newTuple},
}
b.logger.Debug("writing new user basic role to zanzana",
"namespace", new.Namespace,
"userUID", new.Name,
"role", new.Spec.Role,
)
}
}
// Only make the request if there are deletes or writes
if (req.Deletes != nil && len(req.Deletes.TupleKeys) > 0) || (req.Writes != nil && len(req.Writes.TupleKeys) > 0) {
err := b.zClient.Write(ctx, req)
if err != nil {
status = "failure"
b.logger.Error("failed to update user basic role in zanzana",
"err", err,
"namespace", new.Namespace,
"userUID", new.Name,
)
} else {
if req.Deletes != nil && len(req.Deletes.TupleKeys) > 0 {
hooksTuplesCounter.WithLabelValues("user", "update", "delete").Inc()
}
if req.Writes != nil && len(req.Writes.TupleKeys) > 0 {
hooksTuplesCounter.WithLabelValues("user", "update", "write").Inc()
}
}
} else {
b.logger.Debug("no tuples to update in zanzana", "namespace", new.Namespace)
}
}(oldUser.DeepCopy(), newUser.DeepCopy())
}, nil
}
// AfterUserDelete is a post-delete hook that removes the user's basic role assignment from Zanzana (openFGA)
func (b *IdentityAccessManagementAPIBuilder) AfterUserDelete(obj runtime.Object, _ *metav1.DeleteOptions) {
if b.zClient == nil {
return
}
user, ok := obj.(*iamv0.User)
if !ok {
b.logger.Error("failed to convert object to User type", "object", obj)
return
}
resourceType := "user"
operation := "delete"
// Skip if user had no role assigned
if user.Spec.Role == "" {
b.logger.Debug("user had no role assigned, skipping basic role sync",
"namespace", user.Namespace,
"userUID", user.Name,
)
return
}
wait := time.Now()
b.zTickets <- true
hooksWaitHistogram.WithLabelValues(resourceType, operation).Observe(time.Since(wait).Seconds())
go func(u *iamv0.User) {
start := time.Now()
status := "success"
defer func() {
<-b.zTickets
hooksDurationHistogram.WithLabelValues(resourceType, operation, status).Observe(time.Since(start).Seconds())
hooksOperationCounter.WithLabelValues(resourceType, operation, status).Inc()
}()
tuple := createUserBasicRoleTuple(u.Name, u.Spec.Role)
if tuple == nil {
b.logger.Warn("failed to create user basic role tuple for deletion",
"namespace", u.Namespace,
"userUID", u.Name,
"role", u.Spec.Role,
)
status = "failure"
return
}
deleteTuple := tupleToTupleKeyWithoutCondition(tuple)
b.logger.Debug("deleting user basic role from zanzana",
"namespace", u.Namespace,
"userUID", u.Name,
"role", u.Spec.Role,
)
ctx, cancel := context.WithTimeout(context.Background(), defaultWriteTimeout)
defer cancel()
err := b.zClient.Write(ctx, &v1.WriteRequest{
Namespace: u.Namespace,
Deletes: &v1.WriteRequestDeletes{
TupleKeys: []*v1.TupleKeyWithoutCondition{deleteTuple},
},
})
if err != nil {
status = "failure"
b.logger.Error("failed to delete user basic role from zanzana",
"err", err,
"namespace", u.Namespace,
"userUID", u.Name,
"role", u.Spec.Role,
)
} else {
hooksTuplesCounter.WithLabelValues(resourceType, operation, "delete").Inc()
}
}(user.DeepCopy())
}
@@ -0,0 +1,609 @@
package iam
import (
"context"
"sync"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1"
"github.com/grafana/grafana/pkg/infra/log"
v1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
"github.com/stretchr/testify/require"
)
func TestAfterUserCreate(t *testing.T) {
var wg sync.WaitGroup
b := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
}
t.Run("should create zanzana entry for user with Admin role", func(t *testing.T) {
wg.Add(1)
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "df2p421det1q8c",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
testAdminRole := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(t, "org-1", req.Namespace)
tuple := req.Writes.TupleKeys[0]
require.Equal(t, "user:df2p421det1q8c", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_admin", tuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testAdminRole}
b.AfterUserCreate(&user, nil)
wg.Wait()
})
t.Run("should create zanzana entry for user with Editor role", func(t *testing.T) {
wg.Add(1)
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "user123",
Namespace: "org-2",
},
Spec: iamv0.UserSpec{
Role: "Editor",
},
}
testEditorRole := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(t, "org-2", req.Namespace)
tuple := req.Writes.TupleKeys[0]
require.Equal(t, "user:user123", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_editor", tuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testEditorRole}
b.AfterUserCreate(&user, nil)
wg.Wait()
})
t.Run("should create zanzana entry for user with Viewer role", func(t *testing.T) {
wg.Add(1)
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "viewer456",
Namespace: "org-3",
},
Spec: iamv0.UserSpec{
Role: "Viewer",
},
}
testViewerRole := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
require.Equal(t, "org-3", req.Namespace)
tuple := req.Writes.TupleKeys[0]
require.Equal(t, "user:viewer456", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_viewer", tuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testViewerRole}
b.AfterUserCreate(&user, nil)
wg.Wait()
})
t.Run("should skip when user has no role", func(t *testing.T) {
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "norole789",
Namespace: "org-4",
},
Spec: iamv0.UserSpec{
Role: "",
},
}
// Should not call zanzana client
b.zClient = nil
b.AfterUserCreate(&user, nil)
// If we get here without panic, the test passes
})
t.Run("should skip when zClient is nil", func(t *testing.T) {
builder := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
zClient: nil,
}
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
// Should return early without calling zanzana
builder.AfterUserCreate(&user, nil)
// If we get here without panic, the test passes
})
}
func TestBeginUserUpdate(t *testing.T) {
var wg sync.WaitGroup
b := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
}
t.Run("should update zanzana entry when role changes from Viewer to Admin", func(t *testing.T) {
wg.Add(1)
oldUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Viewer",
},
}
newUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
testRoleChange := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-1", req.Namespace)
// Should delete old role
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
deleteTuple := req.Deletes.TupleKeys[0]
require.Equal(t, "user:testuser", deleteTuple.User)
require.Equal(t, "assignee", deleteTuple.Relation)
require.Equal(t, "role:basic_viewer", deleteTuple.Object)
// Should write new role
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
writeTuple := req.Writes.TupleKeys[0]
require.Equal(t, "user:testuser", writeTuple.User)
require.Equal(t, "assignee", writeTuple.Relation)
require.Equal(t, "role:basic_admin", writeTuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testRoleChange}
finishFunc, err := b.BeginUserUpdate(context.Background(), &newUser, &oldUser, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
finishFunc(context.Background(), true)
wg.Wait()
})
t.Run("should delete old role when new role is empty", func(t *testing.T) {
wg.Add(1)
oldUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser2",
Namespace: "org-2",
},
Spec: iamv0.UserSpec{
Role: "Editor",
},
}
newUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser2",
Namespace: "org-2",
},
Spec: iamv0.UserSpec{
Role: "",
},
}
testRemoveRole := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-2", req.Namespace)
// Should delete old role
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
deleteTuple := req.Deletes.TupleKeys[0]
require.Equal(t, "user:testuser2", deleteTuple.User)
require.Equal(t, "assignee", deleteTuple.Relation)
require.Equal(t, "role:basic_editor", deleteTuple.Object)
// Should not write new role
require.Nil(t, req.Writes)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testRemoveRole}
finishFunc, err := b.BeginUserUpdate(context.Background(), &newUser, &oldUser, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
finishFunc(context.Background(), true)
wg.Wait()
})
t.Run("should be able to add a new role when old role was empty", func(t *testing.T) {
wg.Add(1)
oldUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser3",
Namespace: "org-3",
},
Spec: iamv0.UserSpec{
Role: "",
},
}
newUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser3",
Namespace: "org-3",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
testAddRole := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-3", req.Namespace)
// Should not delete old role (was empty)
require.Nil(t, req.Deletes)
// Should write new role
require.NotNil(t, req.Writes)
require.Len(t, req.Writes.TupleKeys, 1)
writeTuple := req.Writes.TupleKeys[0]
require.Equal(t, "user:testuser3", writeTuple.User)
require.Equal(t, "assignee", writeTuple.Relation)
require.Equal(t, "role:basic_admin", writeTuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testAddRole}
finishFunc, err := b.BeginUserUpdate(context.Background(), &newUser, &oldUser, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
finishFunc(context.Background(), true)
wg.Wait()
})
t.Run("should skip update when role hasn't changed", func(t *testing.T) {
oldUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser4",
Namespace: "org-4",
},
Spec: iamv0.UserSpec{
Role: "Editor",
},
}
newUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser4",
Namespace: "org-4",
},
Spec: iamv0.UserSpec{
Role: "Editor",
},
}
finishFunc, err := b.BeginUserUpdate(context.Background(), &newUser, &oldUser, nil)
require.NoError(t, err)
require.Nil(t, finishFunc) // Should return nil when no update needed
})
t.Run("should not call zanzana when update fails", func(t *testing.T) {
oldUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser5",
Namespace: "org-5",
},
Spec: iamv0.UserSpec{
Role: "Viewer",
},
}
newUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser5",
Namespace: "org-5",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
callCount := 0
testNoCall := func(ctx context.Context, req *v1.WriteRequest) error {
callCount++
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testNoCall}
finishFunc, err := b.BeginUserUpdate(context.Background(), &newUser, &oldUser, nil)
require.NoError(t, err)
require.NotNil(t, finishFunc)
// Call with success=false - should not trigger zanzana write
finishFunc(context.Background(), false)
require.Equal(t, 0, callCount, "zanzana should not be called when update fails")
})
t.Run("should skip when zClient is nil", func(t *testing.T) {
builder := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
zClient: nil,
}
oldUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Viewer",
},
}
newUser := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
finishFunc, err := builder.BeginUserUpdate(context.Background(), &newUser, &oldUser, nil)
require.NoError(t, err)
require.Nil(t, finishFunc) // Should return nil when zClient is nil
})
}
func TestAfterUserDelete(t *testing.T) {
var wg sync.WaitGroup
b := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
}
t.Run("should delete zanzana entry for user with Admin role", func(t *testing.T) {
wg.Add(1)
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "df2p421det1q8c",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
testDeleteAdmin := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-1", req.Namespace)
// Should have deletes but no writes
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
require.Nil(t, req.Writes)
deleteTuple := req.Deletes.TupleKeys[0]
require.Equal(t, "user:df2p421det1q8c", deleteTuple.User)
require.Equal(t, "assignee", deleteTuple.Relation)
require.Equal(t, "role:basic_admin", deleteTuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testDeleteAdmin}
b.AfterUserDelete(&user, nil)
wg.Wait()
})
t.Run("should delete zanzana entry for user with Editor role", func(t *testing.T) {
wg.Add(1)
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "editor123",
Namespace: "org-2",
},
Spec: iamv0.UserSpec{
Role: "Editor",
},
}
testDeleteEditor := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-2", req.Namespace)
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
deleteTuple := req.Deletes.TupleKeys[0]
require.Equal(t, "user:editor123", deleteTuple.User)
require.Equal(t, "assignee", deleteTuple.Relation)
require.Equal(t, "role:basic_editor", deleteTuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testDeleteEditor}
b.AfterUserDelete(&user, nil)
wg.Wait()
})
t.Run("should delete zanzana entry for user with Viewer role", func(t *testing.T) {
wg.Add(1)
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "viewer456",
Namespace: "org-3",
},
Spec: iamv0.UserSpec{
Role: "Viewer",
},
}
testDeleteViewer := func(ctx context.Context, req *v1.WriteRequest) error {
defer wg.Done()
require.NotNil(t, req)
require.Equal(t, "org-3", req.Namespace)
require.NotNil(t, req.Deletes)
require.Len(t, req.Deletes.TupleKeys, 1)
deleteTuple := req.Deletes.TupleKeys[0]
require.Equal(t, "user:viewer456", deleteTuple.User)
require.Equal(t, "assignee", deleteTuple.Relation)
require.Equal(t, "role:basic_viewer", deleteTuple.Object)
return nil
}
b.zClient = &FakeZanzanaClient{writeCallback: testDeleteViewer}
b.AfterUserDelete(&user, nil)
wg.Wait()
})
t.Run("should skip when user has no role", func(t *testing.T) {
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "norole789",
Namespace: "org-4",
},
Spec: iamv0.UserSpec{
Role: "",
},
}
// Should not call zanzana client
b.zClient = nil
b.AfterUserDelete(&user, nil)
// If we get here without panic, the test passes
})
t.Run("should skip when zClient is nil", func(t *testing.T) {
builder := &IdentityAccessManagementAPIBuilder{
logger: log.NewNopLogger(),
zTickets: make(chan bool, 1),
zClient: nil,
}
user := iamv0.User{
ObjectMeta: metav1.ObjectMeta{
Name: "testuser",
Namespace: "org-1",
},
Spec: iamv0.UserSpec{
Role: "Admin",
},
}
// Should return early without calling zanzana
builder.AfterUserDelete(&user, nil)
// If we get here without panic, the test passes
})
}
func TestCreateUserBasicRoleTuple(t *testing.T) {
t.Run("should create tuple for Admin role", func(t *testing.T) {
tuple := createUserBasicRoleTuple("user123", "Admin")
require.NotNil(t, tuple)
require.Equal(t, "user:user123", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_admin", tuple.Object)
})
t.Run("should create tuple for Editor role", func(t *testing.T) {
tuple := createUserBasicRoleTuple("user456", "Editor")
require.NotNil(t, tuple)
require.Equal(t, "user:user456", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_editor", tuple.Object)
})
t.Run("should create tuple for Viewer role", func(t *testing.T) {
tuple := createUserBasicRoleTuple("user789", "Viewer")
require.NotNil(t, tuple)
require.Equal(t, "user:user789", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_viewer", tuple.Object)
})
t.Run("should create tuple for None role", func(t *testing.T) {
tuple := createUserBasicRoleTuple("user000", "None")
require.NotNil(t, tuple)
require.Equal(t, "user:user000", tuple.User)
require.Equal(t, "assignee", tuple.Relation)
require.Equal(t, "role:basic_none", tuple.Object)
})
t.Run("should return nil for empty role", func(t *testing.T) {
tuple := createUserBasicRoleTuple("user123", "")
require.Nil(t, tuple)
})
t.Run("should return nil for invalid role", func(t *testing.T) {
tuple := createUserBasicRoleTuple("user123", "InvalidRole")
require.Nil(t, tuple)
})
}
@@ -16,13 +16,28 @@ import (
"github.com/grafana/grafana/pkg/services/apiserver/endpoints/request"
gapiutil "github.com/grafana/grafana/pkg/services/apiserver/utils"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/util"
)
func ConvertToK8sResource(orgID int64, r definitions.Route, version string, namespacer request.NamespaceMapper) (*model.RoutingTree, error) {
func ConvertToK8sResources(orgID int64, routes legacy_storage.ManagedRoutes, namespacer request.NamespaceMapper) (*model.RoutingTreeList, error) {
result := &model.RoutingTreeList{
Items: make([]model.RoutingTree, 0, len(routes)),
}
for _, r := range routes {
k8sResource, err := ConvertToK8sResource(orgID, r, namespacer)
if err != nil {
return nil, fmt.Errorf("failed to convert route %q to k8s resource: %w", r.Name, err)
}
result.Items = append(result.Items, *k8sResource)
}
return result, nil
}
func ConvertToK8sResource(orgID int64, r *legacy_storage.ManagedRoute, namespacer request.NamespaceMapper) (*model.RoutingTree, error) {
spec := model.RoutingTreeSpec{
Defaults: model.RoutingTreeRouteDefaults{
GroupBy: r.GroupByStr,
GroupBy: r.GroupBy,
GroupWait: optionalPrometheusDurationToString(r.GroupWait),
GroupInterval: optionalPrometheusDurationToString(r.GroupInterval),
RepeatInterval: optionalPrometheusDurationToString(r.RepeatInterval),
@@ -39,9 +54,9 @@ func ConvertToK8sResource(orgID int64, r definitions.Route, version string, name
var result = &model.RoutingTree{
ObjectMeta: metav1.ObjectMeta{
Name: model.UserDefinedRoutingTreeName,
Name: r.Name,
Namespace: namespacer(orgID),
ResourceVersion: version,
ResourceVersion: r.Version,
},
Spec: spec,
}
@@ -15,6 +15,7 @@ import (
"github.com/grafana/grafana/pkg/services/apiserver/endpoints/request"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
alerting_models "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
)
var (
@@ -22,9 +23,11 @@ var (
)
type RouteService interface {
GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error)
UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p alerting_models.Provenance, version string) (definitions.Route, string, error)
ResetPolicyTree(ctx context.Context, orgID int64, p alerting_models.Provenance) (definitions.Route, error)
GetManagedRoutes(ctx context.Context, orgID int64) (legacy_storage.ManagedRoutes, error)
GetManagedRoute(ctx context.Context, orgID int64, name string) (legacy_storage.ManagedRoute, error)
DeleteManagedRoute(ctx context.Context, orgID int64, name string, p alerting_models.Provenance, version string) error
CreateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p alerting_models.Provenance) (*legacy_storage.ManagedRoute, error)
UpdateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p alerting_models.Provenance, version string) (*legacy_storage.ManagedRoute, error)
}
type legacyStorage struct {
@@ -55,56 +58,76 @@ func (s *legacyStorage) ConvertToTable(ctx context.Context, object runtime.Objec
return s.tableConverter.ConvertToTable(ctx, object, tableOptions)
}
func (s *legacyStorage) getUserDefinedRoutingTree(ctx context.Context) (*model.RoutingTree, error) {
func (s *legacyStorage) List(ctx context.Context, _ *internalversion.ListOptions) (runtime.Object, error) {
orgId, err := request.OrgIDForList(ctx)
if err != nil {
return nil, err
}
res, version, err := s.service.GetPolicyTree(ctx, orgId)
managedRoutes, err := s.service.GetManagedRoutes(ctx, orgId)
if err != nil {
return nil, err
}
return ConvertToK8sResource(orgId, res, version, s.namespacer)
}
func (s *legacyStorage) List(ctx context.Context, _ *internalversion.ListOptions) (runtime.Object, error) {
user, err := s.getUserDefinedRoutingTree(ctx)
if err != nil {
return nil, err
}
return &model.RoutingTreeList{
Items: []model.RoutingTree{
*user,
},
}, nil
return ConvertToK8sResources(orgId, managedRoutes, s.namespacer)
}
func (s *legacyStorage) Get(ctx context.Context, name string, _ *metav1.GetOptions) (runtime.Object, error) {
if name != model.UserDefinedRoutingTreeName {
return nil, errors.NewNotFound(ResourceInfo.GroupResource(), name)
info, err := request.NamespaceInfoFrom(ctx, true)
if err != nil {
return nil, err
}
return s.getUserDefinedRoutingTree(ctx)
managedRoute, err := s.service.GetManagedRoute(ctx, info.OrgID, name)
if err != nil {
return nil, err
}
return ConvertToK8sResource(info.OrgID, &managedRoute, s.namespacer)
}
func (s *legacyStorage) Create(_ context.Context,
_ runtime.Object,
_ rest.ValidateObjectFunc,
func (s *legacyStorage) Create(ctx context.Context,
obj runtime.Object,
createValidation rest.ValidateObjectFunc,
_ *metav1.CreateOptions,
) (runtime.Object, error) {
return nil, errors.NewMethodNotSupported(ResourceInfo.GroupResource(), "create")
info, err := request.NamespaceInfoFrom(ctx, true)
if err != nil {
return nil, err
}
if createValidation != nil {
if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err
}
}
p, ok := obj.(*model.RoutingTree)
if !ok {
return nil, fmt.Errorf("expected %s but got %s", ResourceInfo.GroupVersionKind(), obj.GetObjectKind().GroupVersionKind())
}
domainModel, _, err := convertToDomainModel(p)
if err != nil {
return nil, err
}
created, err := s.service.CreateManagedRoute(ctx, info.OrgID, p.Name, domainModel, alerting_models.ProvenanceNone)
if err != nil {
return nil, err
}
return ConvertToK8sResource(info.OrgID, created, s.namespacer)
}
func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, _ rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, _ bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
if name != model.UserDefinedRoutingTreeName {
return nil, false, errors.NewNotFound(ResourceInfo.GroupResource(), name)
}
func (s *legacyStorage) Update(
ctx context.Context,
name string,
objInfo rest.UpdatedObjectInfo,
_ rest.ValidateObjectFunc,
updateValidation rest.ValidateObjectUpdateFunc,
_ bool,
_ *metav1.UpdateOptions,
) (runtime.Object, bool, error) {
info, err := request.NamespaceInfoFrom(ctx, true)
if err != nil {
return nil, false, err
}
old, err := s.Get(ctx, model.UserDefinedRoutingTreeName, nil)
old, err := s.Get(ctx, name, nil)
if err != nil {
return old, false, err
}
@@ -122,24 +145,26 @@ func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.Up
return nil, false, fmt.Errorf("expected %s but got %s", ResourceInfo.GroupVersionKind(), obj.GetObjectKind().GroupVersionKind())
}
model, version, err := convertToDomainModel(p)
domainModel, version, err := convertToDomainModel(p)
if err != nil {
return nil, false, err
}
updated, updatedVersion, err := s.service.UpdatePolicyTree(ctx, info.OrgID, model, alerting_models.ProvenanceNone, version)
updated, err := s.service.UpdateManagedRoute(ctx, info.OrgID, p.Name, domainModel, alerting_models.ProvenanceNone, version)
if err != nil {
return nil, false, err
}
obj, err = ConvertToK8sResource(info.OrgID, updated, updatedVersion, s.namespacer)
obj, err = ConvertToK8sResource(info.OrgID, updated, s.namespacer)
return obj, false, err
}
// Delete implements rest.GracefulDeleter. It is needed for API server to not crash when it registers DeleteCollection method
func (s *legacyStorage) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, opts *metav1.DeleteOptions) (runtime.Object, bool, error) {
if name != model.UserDefinedRoutingTreeName {
return nil, false, errors.NewNotFound(ResourceInfo.GroupResource(), name)
}
func (s *legacyStorage) Delete(
ctx context.Context,
name string,
deleteValidation rest.ValidateObjectFunc,
options *metav1.DeleteOptions,
) (runtime.Object, bool, error) {
info, err := request.NamespaceInfoFrom(ctx, true)
if err != nil {
return nil, false, err
@@ -155,10 +180,14 @@ func (s *legacyStorage) Delete(ctx context.Context, name string, deleteValidatio
return nil, false, err
}
}
_, err = s.service.ResetPolicyTree(ctx, info.OrgID, alerting_models.ProvenanceNone) // TODO add support for dry-run option
version := ""
if options.Preconditions != nil && options.Preconditions.ResourceVersion != nil {
version = *options.Preconditions.ResourceVersion
}
err = s.service.DeleteManagedRoute(ctx, info.OrgID, name, alerting_models.ProvenanceNone, version) // TODO add support for dry-run option
return old, false, err
}
func (s *legacyStorage) DeleteCollection(_ context.Context, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions, _ *internalversion.ListOptions) (runtime.Object, error) {
return nil, errors.NewMethodNotSupported(ResourceInfo.GroupResource(), "delete")
return nil, errors.NewMethodNotSupported(ResourceInfo.GroupResource(), "deleteCollection")
}
@@ -1,8 +1,10 @@
package routingtree
import (
"fmt"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
model "github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
@@ -14,5 +16,18 @@ var ResourceInfo = utils.NewResourceInfo(kind.Group(), kind.Version(),
kind.GroupVersionResource().Resource, strings.ToLower(kind.Kind()), kind.Kind(),
func() runtime.Object { return kind.ZeroValue() },
func() runtime.Object { return kind.ZeroListValue() },
utils.TableColumns{},
utils.TableColumns{
Definition: []metav1.TableColumnDefinition{
{Name: "Name", Type: "string", Format: "name"},
},
Reader: func(obj any) ([]interface{}, error) {
r, ok := obj.(*model.RoutingTree)
if !ok {
return nil, fmt.Errorf("expected resource or info")
}
return []interface{}{
r.Name,
}, nil
},
},
)
File diff suppressed because it is too large Load Diff
@@ -30,6 +30,8 @@ message MutateOperation {
DeleteFolderOperation delete_folder = 2;
CreatePermissionOperation create_permission = 3;
DeletePermissionOperation delete_permission = 4;
UpdateUserOrgRoleOperation update_user_org_role = 5;
DeleteUserOrgRoleOperation delete_user_org_role = 6;
}
}
@@ -61,6 +63,20 @@ message DeletePermissionOperation {
Permission permission = 2;
}
message UpdateUserOrgRoleOperation {
// User UID
string user = 1;
// Role name (e.g: "Admin", "Editor", "Viewer")
string role = 2;
}
message DeleteUserOrgRoleOperation {
// User UID
string user = 1;
// Role name (e.g: "Admin", "Editor", "Viewer")
string role = 2;
}
message Resource {
// group of the resource (e.g: "dashboard.grafana.app")
string group = 1;
@@ -67,6 +67,13 @@ var resourceTranslations = map[string]resourceTranslation{
"dashboards:write": newScopedMapping(RelationUpdate, dashboardGroup, dashboardResource, ""),
"dashboards:create": newScopedMapping(RelationCreate, dashboardGroup, dashboardResource, ""),
"dashboards:delete": newScopedMapping(RelationDelete, dashboardGroup, dashboardResource, ""),
// Action sets
"folders:view": newMapping(RelationSetView, ""),
"folders:edit": newMapping(RelationSetEdit, ""),
"folders:admin": newMapping(RelationSetAdmin, ""),
"dashboards:view": newScopedMapping(RelationSetView, dashboardGroup, dashboardResource, ""),
"dashboards:edit": newScopedMapping(RelationSetEdit, dashboardGroup, dashboardResource, ""),
"dashboards:admin": newScopedMapping(RelationSetAdmin, dashboardGroup, dashboardResource, ""),
},
},
KindDashboards: {
@@ -78,6 +85,10 @@ var resourceTranslations = map[string]resourceTranslation{
"dashboards:write": newMapping(RelationUpdate, ""),
"dashboards:create": newMapping(RelationCreate, ""),
"dashboards:delete": newMapping(RelationDelete, ""),
// Action sets
"dashboards:view": newMapping(RelationSetView, ""),
"dashboards:edit": newMapping(RelationSetEdit, ""),
"dashboards:admin": newMapping(RelationSetAdmin, ""),
},
},
}
@@ -350,6 +350,14 @@ func NewTypedTuple(typ, subject, relation, name string) *openfgav1.TupleKey {
}
}
func NewTuple(subject, relation, object string) *openfgav1.TupleKey {
return &openfgav1.TupleKey{
User: subject,
Relation: relation,
Object: object,
}
}
func ToAuthzExtTupleKey(t *openfgav1.TupleKey) *authzextv1.TupleKey {
tupleKey := &authzextv1.TupleKey{
User: t.GetUser(),
@@ -12,8 +12,9 @@ import (
type OperationGroup string
const (
OperationGroupFolder OperationGroup = "folder"
OperationGroupPermission OperationGroup = "permission"
OperationGroupFolder OperationGroup = "folder"
OperationGroupPermission OperationGroup = "permission"
OperationGroupUserOrgRole OperationGroup = "user_org_role"
)
func (s *Server) Mutate(ctx context.Context, req *authzextv1.MutateRequest) (*authzextv1.MutateResponse, error) {
@@ -58,6 +59,10 @@ func (s *Server) mutate(ctx context.Context, req *authzextv1.MutateRequest) (*au
if err := s.mutateResourcePermissions(ctx, storeInf, operations); err != nil {
return nil, fmt.Errorf("failed to mutate resource permissions: %w", err)
}
case OperationGroupUserOrgRole:
if err := s.mutateOrgRoles(ctx, storeInf, operations); err != nil {
return nil, fmt.Errorf("failed to mutate org roles: %w", err)
}
default:
s.logger.Warn("unsupported operation group", "operationGroup", operationGroup)
}
@@ -72,6 +77,8 @@ func getOperationGroup(operation *authzextv1.MutateOperation) (OperationGroup, e
return OperationGroupFolder, nil
case *authzextv1.MutateOperation_CreatePermission, *authzextv1.MutateOperation_DeletePermission:
return OperationGroupPermission, nil
case *authzextv1.MutateOperation_UpdateUserOrgRole, *authzextv1.MutateOperation_DeleteUserOrgRole:
return OperationGroupUserOrgRole, nil
}
return OperationGroup(""), errors.New("unsupported mutate operation type")
}
@@ -0,0 +1,84 @@
package server
import (
"context"
openfgav1 "github.com/openfga/api/proto/openfga/v1"
authzextv1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
zanzana "github.com/grafana/grafana/pkg/services/authz/zanzana/common"
)
func (s *Server) mutateOrgRoles(ctx context.Context, store *storeInfo, operations []*authzextv1.MutateOperation) error {
ctx, span := s.tracer.Start(ctx, "server.mutateOrgRoles")
defer span.End()
writeTuples := make([]*openfgav1.TupleKey, 0)
deleteTuples := make([]*openfgav1.TupleKeyWithoutCondition, 0)
for _, operation := range operations {
switch op := operation.Operation.(type) {
case *authzextv1.MutateOperation_UpdateUserOrgRole:
tuple, err := s.getUserOrgRoleWriteTuple(ctx, store, op.UpdateUserOrgRole)
if err != nil {
return err
}
writeTuples = append(writeTuples, tuple)
case *authzextv1.MutateOperation_DeleteUserOrgRole:
tuple, err := s.getUserOrgRoleDeleteTuple(ctx, store, op.DeleteUserOrgRole)
if err != nil {
return err
}
deleteTuples = append(deleteTuples, tuple)
default:
s.logger.Debug("unsupported mutate operation", "operation", op)
}
}
if len(writeTuples) == 0 && len(deleteTuples) == 0 {
return nil
}
writeReq := &openfgav1.WriteRequest{
StoreId: store.ID,
AuthorizationModelId: store.ModelID,
}
if len(writeTuples) > 0 {
writeReq.Writes = &openfgav1.WriteRequestWrites{
TupleKeys: writeTuples,
OnDuplicate: "ignore",
}
}
if len(deleteTuples) > 0 {
writeReq.Deletes = &openfgav1.WriteRequestDeletes{
TupleKeys: deleteTuples,
OnMissing: "ignore",
}
}
_, err := s.openfga.Write(ctx, writeReq)
if err != nil {
s.logger.Error("failed to write user org role tuples", "error", err)
return err
}
return nil
}
func (s *Server) getUserOrgRoleWriteTuple(ctx context.Context, store *storeInfo, req *authzextv1.UpdateUserOrgRoleOperation) (*openfgav1.TupleKey, error) {
basicRole := zanzana.TranslateBasicRole(req.GetRole())
return &openfgav1.TupleKey{
User: zanzana.NewTupleEntry(zanzana.TypeUser, req.GetUser(), ""),
Relation: zanzana.RelationAssignee,
Object: zanzana.NewTupleEntry(zanzana.TypeRole, basicRole, ""),
}, nil
}
func (s *Server) getUserOrgRoleDeleteTuple(ctx context.Context, store *storeInfo, req *authzextv1.DeleteUserOrgRoleOperation) (*openfgav1.TupleKeyWithoutCondition, error) {
basicRole := zanzana.TranslateBasicRole(req.GetRole())
return &openfgav1.TupleKeyWithoutCondition{
User: zanzana.NewTupleEntry(zanzana.TypeUser, req.GetUser(), ""),
Relation: zanzana.RelationAssignee,
Object: zanzana.NewTupleEntry(zanzana.TypeRole, basicRole, ""),
}, nil
}
@@ -0,0 +1,72 @@
package server
import (
"testing"
openfgav1 "github.com/openfga/api/proto/openfga/v1"
"github.com/stretchr/testify/require"
v1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
"github.com/grafana/grafana/pkg/services/authz/zanzana/common"
)
func setupMutateOrgRoles(t *testing.T, srv *Server) *Server {
t.Helper()
// seed tuples
tuples := []*openfgav1.TupleKey{
common.NewTuple("user:1", common.RelationAssignee, "role:basic_editor"),
}
return setupOpenFGADatabase(t, srv, tuples)
}
func testMutateOrgRoles(t *testing.T, srv *Server) {
setupMutateOrgRoles(t, srv)
t.Run("should update user org role and delete old role", func(t *testing.T) {
_, err := srv.Mutate(newContextWithNamespace(), &v1.MutateRequest{
Namespace: "default",
Operations: []*v1.MutateOperation{
{
Operation: &v1.MutateOperation_UpdateUserOrgRole{
UpdateUserOrgRole: &v1.UpdateUserOrgRoleOperation{
User: "1",
Role: "Admin",
},
},
},
{
Operation: &v1.MutateOperation_DeleteUserOrgRole{
DeleteUserOrgRole: &v1.DeleteUserOrgRoleOperation{
User: "1",
Role: "Editor",
},
},
},
},
})
require.NoError(t, err)
res, err := srv.Read(newContextWithNamespace(), &v1.ReadRequest{
Namespace: "default",
TupleKey: &v1.ReadRequestTupleKey{
Relation: common.RelationAssignee,
Object: "role:basic_admin",
},
})
require.NoError(t, err)
require.Len(t, res.Tuples, 1)
require.Equal(t, "user:1", res.Tuples[0].Key.User)
res, err = srv.Read(newContextWithNamespace(), &v1.ReadRequest{
Namespace: "default",
TupleKey: &v1.ReadRequestTupleKey{
Relation: common.RelationAssignee,
Object: "role:basic_editor",
},
})
require.NoError(t, err)
require.Len(t, res.Tuples, 0)
})
}
@@ -128,6 +128,10 @@ func TestIntegrationServer(t *testing.T) {
t.Run("test mutate resource permissions", func(t *testing.T) {
testMutateResourcePermissions(t, srv)
})
t.Run("test mutate org roles", func(t *testing.T) {
testMutateOrgRoles(t, srv)
})
}
func setupOpenFGAServer(t *testing.T, testDB db.DB, cfg *setting.Cfg) *Server {
+7 -1
View File
@@ -84,7 +84,7 @@ func (s *OSSCachingService) HandleResourceRequest(ctx context.Context, req *back
var _ CachingService = &OSSCachingService{}
// GetKey creates a prefixed cache key and uses the internal `encoder` to encode the query into a string
func GetKey(prefix string, query interface{}) (string, error) {
func GetKey(namespace, prefix string, query interface{}) (string, error) {
keybuf := bytes.NewBuffer(nil)
encoder := &JSONEncoder{}
@@ -98,6 +98,12 @@ func GetKey(prefix string, query interface{}) (string, error) {
return "", err
}
// The namespace is empty only when this function is used by the legacy caching module.
// This case can be removed when the legacy caching module is not being used anymore.
if namespace != "" {
return strings.Join([]string{namespace, prefix, key}, ":"), nil
}
return strings.Join([]string{prefix, key}, ":"), nil
}
+12 -2
View File
@@ -1516,10 +1516,11 @@ var (
},
{
Name: "newLogsPanel",
Description: "Enables the new logs panel in Explore",
Stage: FeatureStageExperimental,
Description: "Enables the new logs panel",
Stage: FeatureStageGeneralAvailability,
FrontendOnly: true,
Owner: grafanaObservabilityLogsSquad,
Expression: "true",
},
{
Name: "grafanaconThemes",
@@ -2157,6 +2158,15 @@ var (
Owner: grafanaSharingSquad,
FrontendOnly: false,
},
{
Name: "alertingMultiplePolicies",
Description: "Enables the ability to create multiple alerting policies",
Stage: FeatureStageExperimental,
Owner: grafanaAlertingSquad,
HideFromAdminPage: true,
HideFromDocs: true,
Expression: "false",
},
}
)
+2 -1
View File
@@ -198,7 +198,7 @@ grafanaAdvisor,privatePreview,@grafana/plugins-platform-backend,false,false,fals
elasticsearchImprovedParsing,experimental,@grafana/aws-datasources,false,false,false
datasourceConnectionsTab,privatePreview,@grafana/plugins-platform-backend,false,false,true
fetchRulesUsingPost,experimental,@grafana/alerting-squad,false,false,false
newLogsPanel,experimental,@grafana/observability-logs,false,false,true
newLogsPanel,GA,@grafana/observability-logs,false,false,true
grafanaconThemes,GA,@grafana/grafana-frontend-platform,false,true,false
alertingJiraIntegration,experimental,@grafana/alerting-squad,false,false,true
alertingUseNewSimplifiedRoutingHashAlgorithm,preview,@grafana/alerting-squad,false,true,false
@@ -277,3 +277,4 @@ pluginStoreServiceLoading,experimental,@grafana/plugins-platform-backend,false,f
onlyStoreActionSets,GA,@grafana/identity-access-team,false,false,false
panelTimeSettings,experimental,@grafana/dashboards-squad,false,false,false
dashboardTemplates,experimental,@grafana/sharing-squad,false,false,false
alertingMultiplePolicies,experimental,@grafana/alerting-squad,false,false,false
1 Name Stage Owner requiresDevMode RequiresRestart FrontendOnly
198 elasticsearchImprovedParsing experimental @grafana/aws-datasources false false false
199 datasourceConnectionsTab privatePreview @grafana/plugins-platform-backend false false true
200 fetchRulesUsingPost experimental @grafana/alerting-squad false false false
201 newLogsPanel experimental GA @grafana/observability-logs false false true
202 grafanaconThemes GA @grafana/grafana-frontend-platform false true false
203 alertingJiraIntegration experimental @grafana/alerting-squad false false true
204 alertingUseNewSimplifiedRoutingHashAlgorithm preview @grafana/alerting-squad false true false
277 onlyStoreActionSets GA @grafana/identity-access-team false false false
278 panelTimeSettings experimental @grafana/dashboards-squad false false false
279 dashboardTemplates experimental @grafana/sharing-squad false false false
280 alertingMultiplePolicies experimental @grafana/alerting-squad false false false
+5 -1
View File
@@ -804,7 +804,7 @@ const (
FlagFetchRulesUsingPost = "fetchRulesUsingPost"
// FlagNewLogsPanel
// Enables the new logs panel in Explore
// Enables the new logs panel
FlagNewLogsPanel = "newLogsPanel"
// FlagGrafanaconThemes
@@ -1117,4 +1117,8 @@ const (
// FlagDashboardTemplates
// Enable template dashboards
FlagDashboardTemplates = "dashboardTemplates"
// FlagAlertingMultiplePolicies
// Enables the ability to create multiple alerting policies
FlagAlertingMultiplePolicies = "alertingMultiplePolicies"
)
+24 -5
View File
@@ -405,6 +405,21 @@
"expression": "true"
}
},
{
"metadata": {
"name": "alertingMultiplePolicies",
"resourceVersion": "1762186293341",
"creationTimestamp": "2025-11-03T16:11:33Z"
},
"spec": {
"description": "Enables the ability to create multiple alerting policies",
"stage": "experimental",
"codeowner": "@grafana/alerting-squad",
"hideFromAdminPage": true,
"hideFromDocs": true,
"expression": "false"
}
},
{
"metadata": {
"name": "alertingNotificationHistory",
@@ -2775,14 +2790,18 @@
{
"metadata": {
"name": "newLogsPanel",
"resourceVersion": "1753448760331",
"creationTimestamp": "2025-02-04T17:40:17Z"
"resourceVersion": "1762166984808",
"creationTimestamp": "2025-02-04T17:40:17Z",
"annotations": {
"grafana.app/updatedTimestamp": "2025-11-03 10:49:44.808226 +0000 UTC"
}
},
"spec": {
"description": "Enables the new logs panel in Explore",
"stage": "experimental",
"description": "Enables the new logs panel",
"stage": "GA",
"codeowner": "@grafana/observability-logs",
"frontend": true
"frontend": true,
"expression": "true"
}
},
{
+38 -7
View File
@@ -20,6 +20,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/api/hcl"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
alerting_models "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/services/ngalert/provisioning"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/util"
@@ -58,6 +59,9 @@ type NotificationPolicyService interface {
GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error)
UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p alerting_models.Provenance, version string) (definitions.Route, string, error)
ResetPolicyTree(ctx context.Context, orgID int64, provenance alerting_models.Provenance) (definitions.Route, error)
GetManagedRoute(ctx context.Context, orgID int64, name string) (legacy_storage.ManagedRoute, error)
GetManagedRoutes(ctx context.Context, orgID int64) (legacy_storage.ManagedRoutes, error)
}
type MuteTimingService interface {
@@ -96,19 +100,43 @@ func (srv *ProvisioningSrv) RouteGetPolicyTree(c *contextmodel.ReqContext) respo
}
func (srv *ProvisioningSrv) RouteGetPolicyTreeExport(c *contextmodel.ReqContext) response.Response {
policies, _, err := srv.policies.GetPolicyTree(c.Req.Context(), c.GetOrgID())
if err != nil {
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return ErrResp(http.StatusNotFound, err, "")
if !srv.featureManager.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) {
// Default to the old behavior of exporting the single user-defined policy tree without a "name" field.
policy, _, err := srv.policies.GetPolicyTree(c.Req.Context(), c.GetOrgID())
if err != nil {
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
e, err := AlertingFileExportFromRoute(c.GetOrgID(), policy)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to create alerting file export")
}
return exportResponse(c, e)
}
e, err := AlertingFileExportFromRoute(c.GetOrgID(), policies)
routeName := c.Query("routeName")
var routesToExport legacy_storage.ManagedRoutes
if routeName == "" {
// Interpreted as Export All.
var err error
routesToExport, err = srv.policies.GetManagedRoutes(c.Req.Context(), c.GetOrgID())
if err != nil {
return response.ErrOrFallback(http.StatusInternalServerError, "failed to export all notification policy trees", err)
}
} else {
managedRoute, err := srv.policies.GetManagedRoute(c.Req.Context(), c.GetOrgID(), routeName)
if err != nil {
return response.ErrOrFallback(http.StatusInternalServerError, "failed to export notification policy tree", err)
}
routesToExport = legacy_storage.ManagedRoutes{&managedRoute}
}
e, err := AlertingFileExportFromManagedRoutes(c.GetOrgID(), routesToExport)
if err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to create alerting file export")
}
return exportResponse(c, e)
}
@@ -593,6 +621,9 @@ func escapeAlertingFileExport(body definitions.AlertingFileExport) definitions.A
}
func escapeRouteExport(r *definitions.RouteExport) {
if r.Name != nil {
r.Name = util.Pointer(addEscapeCharactersToString(*r.Name))
}
r.Receiver = addEscapeCharactersToString(r.Receiver)
if r.GroupByStr != nil {
groupByStr := make([]string, len(*r.GroupByStr))
@@ -2248,6 +2248,7 @@ func createTestRequestCtx() contextmodel.ReqContext {
}
type fakeNotificationPolicyService struct {
NotificationPolicyService
tree definitions.Route
prov models.Provenance
}
@@ -2318,7 +2319,9 @@ func (f *fakeNotificationPolicyService) ResetPolicyTree(ctx context.Context, org
return f.tree, nil
}
type fakeFailingNotificationPolicyService struct{}
type fakeFailingNotificationPolicyService struct {
NotificationPolicyService
}
func (f *fakeFailingNotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
return definitions.Route{}, "", fmt.Errorf("something went wrong")
@@ -2332,7 +2335,9 @@ func (f *fakeFailingNotificationPolicyService) ResetPolicyTree(ctx context.Conte
return definitions.Route{}, fmt.Errorf("something went wrong")
}
type fakeRejectingNotificationPolicyService struct{}
type fakeRejectingNotificationPolicyService struct {
NotificationPolicyService
}
type fakeRejectingNotificationSettingsValidatorProvider struct{}
+28
View File
@@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/util"
)
@@ -338,6 +339,21 @@ func AlertingFileExportFromRoute(orgID int64, route definitions.Route) (definiti
return f, nil
}
// AlertingFileExportFromManagedRoutes creates a definitions.AlertingFileExport DTO from one or more legacy_storage.ManagedRoute.
func AlertingFileExportFromManagedRoutes(orgID int64, routes legacy_storage.ManagedRoutes) (definitions.AlertingFileExport, error) {
f := definitions.AlertingFileExport{
APIVersion: 1,
Policies: make([]definitions.NotificationPolicyExport, 0, len(routes)),
}
for _, route := range routes {
f.Policies = append(f.Policies, definitions.NotificationPolicyExport{
OrgID: orgID,
RouteExport: RouteExportFromManagedRoute(route),
})
}
return f, nil
}
// RouteExportFromRoute creates a definitions.RouteExport DTO from definitions.Route.
func RouteExportFromRoute(route *definitions.Route) *definitions.RouteExport {
toStringIfNotNil := func(d *model.Duration) *string {
@@ -383,6 +399,18 @@ func RouteExportFromRoute(route *definitions.Route) *definitions.RouteExport {
return &export
}
// RouteExportFromManagedRoute creates a definitions.RouteExport DTO from legacy_storage.ManagedRoute.
func RouteExportFromManagedRoute(route *legacy_storage.ManagedRoute) *definitions.RouteExport {
apiRoute := route.AsRoute()
export := RouteExportFromRoute(&apiRoute)
if route.Name == legacy_storage.UserDefinedRoutingTreeName {
export.Name = nil // Functionally this shouldn't matter, aesthetically this prefers an empty name over "user-defined".
} else {
export.Name = OmitDefault(util.Pointer(route.Name))
}
return export
}
// OmitDefault returns nil if the value is the default.
func OmitDefault[T comparable](v *T) *T {
var def T
@@ -775,10 +775,11 @@ func fromPrometheusConfig(prometheusConfig config.Config) PostableApiAlertingCon
// swagger:model
type PostableUserConfig struct {
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig PostableApiAlertingConfig `yaml:"alertmanager_config" json:"alertmanager_config"`
ExtraConfigs []ExtraConfiguration `yaml:"extra_config,omitempty" json:"extra_config,omitempty"`
amSimple map[string]interface{} `yaml:"-" json:"-"`
TemplateFiles map[string]string `yaml:"template_files" json:"template_files"`
AlertmanagerConfig PostableApiAlertingConfig `yaml:"alertmanager_config" json:"alertmanager_config"`
ExtraConfigs []ExtraConfiguration `yaml:"extra_config,omitempty" json:"extra_config,omitempty"`
ManagedRoutes map[string]*definition.Route `yaml:"managed_routes,omitempty" json:"managed_routes,omitempty"` // TODO: Move to ConfigRevision?
amSimple map[string]interface{} `yaml:"-" json:"-"`
}
func (c *PostableUserConfig) GetMergedAlertmanagerConfig() (MergeResult, error) {
@@ -70,7 +70,8 @@ type NotificationPolicyExport struct {
// RouteExport is the provisioned file export of definitions.Route. This is needed to hide fields that aren't useable in
// provisioning file format. An alternative would be to define a custom MarshalJSON and MarshalYAML that excludes them.
type RouteExport struct {
Receiver string `yaml:"receiver,omitempty" json:"receiver,omitempty" hcl:"contact_point"`
Name *string `yaml:"name,omitempty" json:"name,omitempty" hcl:"name,optional"`
Receiver string `yaml:"receiver,omitempty" json:"receiver,omitempty" hcl:"contact_point"`
GroupByStr *[]string `yaml:"group_by,omitempty" json:"group_by,omitempty" hcl:"group_by"`
// Deprecated. Remove before v1.0 release.
+1 -1
View File
@@ -422,7 +422,7 @@ func (ng *AlertNG) init() error {
)
// Provisioning
policyService := provisioning.NewNotificationPolicyService(configStore, ng.store, ng.store, ng.Cfg.UnifiedAlerting, ng.Log)
policyService := provisioning.NewNotificationPolicyService(configStore, ng.store, ng.store, ng.Cfg.UnifiedAlerting, ng.FeatureToggles, ng.Log)
contactPointService := provisioning.NewContactPointService(configStore, ng.SecretsService, ng.store, ng.store, provisioningReceiverService, ng.Log, ng.store, ng.ResourcePermissions)
templateService := provisioning.NewTemplateService(configStore, ng.store, ng.store, ng.Log)
muteTimingService := provisioning.NewMuteTimingService(configStore, ng.store, ng.store, ng.Log, ng.store)
@@ -21,6 +21,7 @@ import (
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/metrics"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/setting"
@@ -336,6 +337,9 @@ func (am *alertmanager) applyConfig(ctx context.Context, cfg *apimodels.Postable
return false, fmt.Errorf("failed to decrypt external configurations: %w", err)
}
// Add managed routes to the configuration.
cfg.AlertmanagerConfig.Route = legacy_storage.WithManagedRoutes(cfg.AlertmanagerConfig.Route, cfg.ManagedRoutes)
mergeResult, err := cfg.GetMergedAlertmanagerConfig()
if err != nil {
return false, fmt.Errorf("failed to get full alertmanager configuration: %w", err)
@@ -12,6 +12,12 @@ var (
"Invalid receiver: '{{ .Public.Reason }}'",
errutil.WithPublic("Invalid receiver: '{{ .Public.Reason }}'"),
)
ErrRouteExists = errutil.Conflict("alerting.notifications.routes.exists", errutil.WithPublicMessage("Route with this name already exists. Use a different name or update an existing one."))
ErrRouteInvalidFormat = errutil.BadRequest("alerting.notifications.routes.invalidFormat").MustTemplate(
"Invalid format of the submitted route.",
errutil.WithPublic("Invalid format of the submitted route: {{.Public.Error}}. Correct the payload and try again."),
)
)
func makeErrBadAlertmanagerConfiguration(err error) error {
@@ -33,3 +39,12 @@ func MakeErrReceiverInvalid(err error) error {
}
return ErrReceiverInvalid.Build(data)
}
func MakeErrRouteInvalidFormat(err error) error {
return ErrRouteInvalidFormat.Build(errutil.TemplateData{
Public: map[string]any{
"Error": err.Error(),
},
Error: err,
})
}
@@ -0,0 +1,380 @@
package legacy_storage
import (
"encoding/binary"
"fmt"
"hash"
"hash/fnv"
"maps"
"slices"
"strings"
"unsafe"
"github.com/grafana/alerting/definition"
"github.com/prometheus/alertmanager/dispatch"
"github.com/prometheus/alertmanager/pkg/labels"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
)
const UserDefinedRoutingTreeName = "user-defined"
const NamedRouteMatcher = "__grafana_managed_route__"
type ManagedRoute struct {
Name string
Version string
Receiver string
GroupBy []string
GroupWait *model.Duration
GroupInterval *model.Duration
RepeatInterval *model.Duration
Routes []*definition.Route
Provenance models.Provenance
}
func (r *ManagedRoute) AsRoute() definition.Route {
// Only need to copy the fields that are valid for a root route.
return definition.Route{
Receiver: r.Receiver,
GroupByStr: r.GroupBy,
GroupWait: r.GroupWait,
GroupInterval: r.GroupInterval,
RepeatInterval: r.RepeatInterval,
Routes: r.Routes,
Provenance: definitions.Provenance(r.Provenance),
}
}
func (r *ManagedRoute) GeneratedSubRoute() *definition.Route {
amRoute := r.AsRoute()
// It's important that the generated sub-route is fully defined so that they will never rely on the values of the root.
defaultOpts := dispatch.DefaultRouteOpts
if amRoute.GroupWait == nil {
gw := model.Duration(defaultOpts.GroupWait)
amRoute.GroupWait = &gw
}
if amRoute.GroupInterval == nil {
gi := model.Duration(defaultOpts.GroupInterval)
amRoute.GroupInterval = &gi
}
if amRoute.RepeatInterval == nil {
ri := model.Duration(defaultOpts.RepeatInterval)
amRoute.RepeatInterval = &ri
}
if r.Name != UserDefinedRoutingTreeName {
// Set label matcher.
amRoute.ObjectMatchers = definitions.ObjectMatchers{managedRouteMatcher(r.Name)}
}
return &amRoute
}
func (r *ManagedRoute) ResourceType() string {
return (&definition.Route{}).ResourceType()
}
func (r *ManagedRoute) ResourceID() string {
if r.Name == UserDefinedRoutingTreeName {
// Backwards compatibility with legacy user-defined routing tree.
return ""
}
return r.Name
}
func NewManagedRoute(name string, r *definition.Route) *ManagedRoute {
return &ManagedRoute{
Name: name,
Version: CalculateRouteFingerprint(*r),
Receiver: r.Receiver,
GroupBy: r.GroupByStr,
GroupWait: r.GroupWait,
GroupInterval: r.GroupInterval,
RepeatInterval: r.RepeatInterval,
Routes: r.Routes,
Provenance: models.Provenance(r.Provenance),
}
}
func managedRouteMatcher(name string) *labels.Matcher {
return &labels.Matcher{
Type: labels.MatchEqual,
Name: NamedRouteMatcher,
Value: name,
}
}
type ManagedRoutes []*ManagedRoute
func (m ManagedRoutes) Sort() {
// Sort the keys of the map to ensure consistent ordering. Always ensure that the legacy user-defined routing tree is last.
slices.SortFunc(m, func(a, b *ManagedRoute) int {
if a.Name == UserDefinedRoutingTreeName {
return 1
}
if b.Name == UserDefinedRoutingTreeName {
return -1
}
return strings.Compare(a.Name, b.Name)
})
}
func WithManagedRoutes(root *definitions.Route, managedRoutes map[string]*definition.Route) *definitions.Route {
if len(managedRoutes) == 0 {
// If there are no managed routes, we just return the original root.
return root
}
newRoot := *root
newManagedRoutes := make([]*definition.Route, 0, len(newRoot.Routes)+len(managedRoutes))
for _, k := range slices.Sorted(maps.Keys(managedRoutes)) {
// On the off chance that the route is nil or invalid managed route with the restricted name, we skip it.
if managedRoutes[k] == nil || k == UserDefinedRoutingTreeName {
continue
}
newManagedRoutes = append(newManagedRoutes, NewManagedRoute(k, managedRoutes[k]).GeneratedSubRoute())
}
// Add the user-defined routing tree at the end.
newManagedRoutes = append(newManagedRoutes, newRoot.Routes...)
newRoot.Routes = newManagedRoutes
return &newRoot
}
func (rev *ConfigRevision) GetManagedRoute(name string) *ManagedRoute {
if name == UserDefinedRoutingTreeName {
return NewManagedRoute(UserDefinedRoutingTreeName, rev.Config.AlertmanagerConfig.Route)
}
route, ok := rev.Config.ManagedRoutes[name]
if !ok {
return nil
}
return NewManagedRoute(name, route)
}
func (rev *ConfigRevision) GetManagedRoutes() ManagedRoutes {
managedRoutes := make(ManagedRoutes, 0, len(rev.Config.ManagedRoutes)+1)
for _, k := range slices.Sorted(maps.Keys(rev.Config.ManagedRoutes)) {
// On the off chance that the route is nil or invalid managed route with the restricted name, we skip it.
if rev.Config.ManagedRoutes[k] == nil || k == UserDefinedRoutingTreeName {
continue
}
managedRoutes = append(managedRoutes, NewManagedRoute(k, rev.Config.ManagedRoutes[k]))
}
managedRoutes = append(managedRoutes, NewManagedRoute(UserDefinedRoutingTreeName, rev.Config.AlertmanagerConfig.Route))
return managedRoutes
}
func (rev *ConfigRevision) DeleteManagedRoute(name string) {
// Intentionally does not consider if name == UserDefinedRoutingTreeName as it should only be Reset via Update.
delete(rev.Config.ManagedRoutes, name)
}
func (rev *ConfigRevision) CreateManagedRoute(name string, subtree definitions.Route) (*ManagedRoute, error) {
if name == "" {
return nil, fmt.Errorf("route name is required")
}
if name == UserDefinedRoutingTreeName {
return nil, fmt.Errorf("cannot create a managed route with the name %q, this name is reserved for the user-defined routing tree", UserDefinedRoutingTreeName)
}
if _, exists := rev.Config.ManagedRoutes[name]; exists {
return nil, ErrRouteExists.Errorf("")
}
managedRoute := NewManagedRoute(name, &subtree)
amRoute := managedRoute.AsRoute()
err := rev.ValidateRoute(amRoute)
if err != nil {
return nil, MakeErrRouteInvalidFormat(err)
}
if rev.Config.ManagedRoutes == nil {
rev.Config.ManagedRoutes = make(map[string]*definition.Route, 1)
}
rev.Config.ManagedRoutes[name] = &amRoute
return managedRoute, nil
}
func (rev *ConfigRevision) UpdateNamedRoute(name string, subtree definitions.Route) (*ManagedRoute, error) {
if name == "" {
return nil, fmt.Errorf("route name is required")
}
if existing := rev.GetManagedRoute(name); existing == nil {
return nil, fmt.Errorf("managed route %q not found", name)
}
managedRoute := NewManagedRoute(name, &subtree)
amRoute := managedRoute.AsRoute()
err := rev.ValidateRoute(amRoute)
if err != nil {
return nil, MakeErrRouteInvalidFormat(err)
}
if name == UserDefinedRoutingTreeName {
rev.Config.AlertmanagerConfig.Route = &amRoute
} else {
if rev.Config.ManagedRoutes == nil {
rev.Config.ManagedRoutes = make(map[string]*definition.Route, 1)
}
rev.Config.ManagedRoutes[name] = &amRoute
}
return managedRoute, nil
}
func (rev *ConfigRevision) ResetUserDefinedRoute(defaultCfg *definitions.PostableUserConfig) (*ManagedRoute, error) {
// Ensure the new default receiver exists and if not, create it.
if err := rev.validateReceiverReferences(*defaultCfg.AlertmanagerConfig.Route); err != nil {
// Default receiver doesn't exist, create it.
var defaultRcv *definitions.PostableApiReceiver
for _, rcv := range defaultCfg.AlertmanagerConfig.Receivers {
if rcv.Name == defaultCfg.AlertmanagerConfig.Route.Receiver {
defaultRcv = rcv
break
}
}
if defaultRcv == nil {
return nil, fmt.Errorf("inconsistent default configuration: default receiver %q not found", defaultCfg.AlertmanagerConfig.Route.Receiver)
}
rev.Config.AlertmanagerConfig.Receivers = append(rev.Config.AlertmanagerConfig.Receivers, defaultRcv)
}
return rev.UpdateNamedRoute(UserDefinedRoutingTreeName, *defaultCfg.AlertmanagerConfig.Route)
}
func (rev *ConfigRevision) ValidateRoute(route definitions.Route) error {
err := route.Validate()
if err != nil {
return err
}
err = rev.validateReceiverReferences(route)
if err != nil {
return err
}
err = rev.validateTimeIntervalReferences(route)
if err != nil {
return err
}
return nil
}
func (rev *ConfigRevision) validateReceiverReferences(route definitions.Route) error {
receivers := rev.GetReceiversNames()
receivers[""] = struct{}{} // Allow empty receiver (inheriting from parent)
return route.ValidateReceivers(receivers)
}
func (rev *ConfigRevision) validateTimeIntervalReferences(route definitions.Route) error {
timeIntervals := map[string]struct{}{}
for _, mt := range rev.Config.AlertmanagerConfig.MuteTimeIntervals {
timeIntervals[mt.Name] = struct{}{}
}
for _, mt := range rev.Config.AlertmanagerConfig.TimeIntervals {
timeIntervals[mt.Name] = struct{}{}
}
return route.ValidateTimeIntervals(timeIntervals)
}
func CalculateRouteFingerprint(route definitions.Route) string {
sum := fnv.New64a()
writeToHash(sum, &route)
return fmt.Sprintf("%016x", sum.Sum64())
}
func writeToHash(sum hash.Hash, r *definitions.Route) {
writeBytes := func(b []byte) {
_, _ = sum.Write(b)
// add a byte sequence that cannot happen in UTF-8 strings.
_, _ = sum.Write([]byte{255})
}
writeString := func(s string) {
if len(s) == 0 {
writeBytes(nil)
return
}
// #nosec G103
// avoid allocation when converting string to byte slice
writeBytes(unsafe.Slice(unsafe.StringData(s), len(s)))
}
// this temp slice is used to convert ints to bytes.
tmp := make([]byte, 8)
writeInt := func(u int64) {
binary.LittleEndian.PutUint64(tmp, uint64(u))
writeBytes(tmp)
}
writeBool := func(b bool) {
if b {
writeInt(1)
} else {
writeInt(0)
}
}
writeDuration := func(d *model.Duration) {
if d == nil {
_, _ = sum.Write([]byte{255})
} else {
binary.LittleEndian.PutUint64(tmp, uint64(*d))
_, _ = sum.Write(tmp)
_, _ = sum.Write([]byte{255})
}
}
writeString(r.Receiver)
for _, s := range r.GroupByStr {
writeString(s)
}
for _, labelName := range r.GroupBy {
writeString(string(labelName))
}
writeBool(r.GroupByAll)
if len(r.Match) > 0 {
for _, key := range slices.Sorted(maps.Keys(r.Match)) {
writeString(key)
writeString(r.Match[key])
}
}
if len(r.MatchRE) > 0 {
for _, key := range slices.Sorted(maps.Keys(r.MatchRE)) {
writeString(key)
str, err := r.MatchRE[key].MarshalJSON()
if err != nil {
writeString(fmt.Sprintf("%+v", r.MatchRE))
}
writeBytes(str)
}
}
for _, matcher := range r.Matchers {
writeString(matcher.String())
}
for _, matcher := range r.ObjectMatchers {
writeString(matcher.String())
}
for _, timeInterval := range r.MuteTimeIntervals {
writeString(timeInterval)
}
for _, timeInterval := range r.ActiveTimeIntervals {
writeString(timeInterval)
}
writeBool(r.Continue)
writeDuration(r.GroupWait)
writeDuration(r.GroupInterval)
writeDuration(r.RepeatInterval)
for _, route := range r.Routes {
writeToHash(sum, route)
}
}
@@ -41,6 +41,8 @@ var (
ErrRouteConflictingMatchers = errutil.BadRequest("alerting.notifications.routes.conflictingMatchers").MustTemplate("Routing tree conflicts with the external configuration",
errutil.WithPublic("Cannot add\\update route: matchers conflict with an external routing tree merging matchers {{ .Public.Matchers }}, making the added\\updated route unreachable."),
)
ErrRouteNotFound = errutil.NotFound("alerting.notifications.routes.notFound", errutil.WithPublicMessage("Route not found"))
)
// MakeErrTimeIntervalInvalid creates an error with the ErrTimeIntervalInvalid template
@@ -2,19 +2,13 @@ package provisioning
import (
"context"
"encoding/binary"
"errors"
"fmt"
"hash"
"hash/fnv"
"slices"
"unsafe"
"github.com/grafana/alerting/definition"
"github.com/prometheus/common/model"
"golang.org/x/exp/maps"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
@@ -29,92 +23,138 @@ type NotificationPolicyService struct {
log log.Logger
settings setting.UnifiedAlertingSettings
validator validation.ProvenanceStatusTransitionValidator
FeatureToggles featuremgmt.FeatureToggles
}
func NewNotificationPolicyService(am alertmanagerConfigStore, prov ProvisioningStore,
xact TransactionManager, settings setting.UnifiedAlertingSettings, log log.Logger) *NotificationPolicyService {
func NewNotificationPolicyService(
am alertmanagerConfigStore,
prov ProvisioningStore,
xact TransactionManager,
settings setting.UnifiedAlertingSettings,
features featuremgmt.FeatureToggles,
log log.Logger,
) *NotificationPolicyService {
return &NotificationPolicyService{
configStore: am,
provenanceStore: prov,
xact: xact,
log: log,
settings: settings,
FeatureToggles: features,
validator: validation.ValidateProvenanceRelaxed,
}
}
func (nps *NotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
func (nps *NotificationPolicyService) GetManagedRoute(ctx context.Context, orgID int64, name string) (legacy_storage.ManagedRoute, error) {
// TODO: Keep this?
if name == "" {
name = legacy_storage.UserDefinedRoutingTreeName
}
// Backwards compatibility when managed routes FF is disabled. Only allow the default route.
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) && name != legacy_storage.UserDefinedRoutingTreeName {
return legacy_storage.ManagedRoute{}, ErrRouteNotFound.Errorf("route %q not found", name)
}
rev, err := nps.configStore.Get(ctx, orgID)
if err != nil {
return definitions.Route{}, "", err
return legacy_storage.ManagedRoute{}, err
}
if rev.Config.AlertmanagerConfig.Route == nil {
return definitions.Route{}, "", fmt.Errorf("no route present in current alertmanager config")
route := rev.GetManagedRoute(name)
if route == nil {
return legacy_storage.ManagedRoute{}, ErrRouteNotFound.Errorf("route %q not found", name)
}
provenance, err := nps.provenanceStore.GetProvenance(ctx, rev.Config.AlertmanagerConfig.Route, orgID)
provenance, err := nps.provenanceStore.GetProvenance(ctx, route, orgID)
if err != nil {
return definitions.Route{}, "", err
return legacy_storage.ManagedRoute{}, err
}
result := *rev.Config.AlertmanagerConfig.Route
result.Provenance = definitions.Provenance(provenance)
version := calculateRouteFingerprint(result)
return result, version, nil
route.Provenance = provenance
return *route, nil
}
func (nps *NotificationPolicyService) UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p models.Provenance, version string) (definitions.Route, string, error) {
err := tree.Validate()
func (nps *NotificationPolicyService) GetManagedRoutes(ctx context.Context, orgID int64) (legacy_storage.ManagedRoutes, error) {
rev, err := nps.configStore.Get(ctx, orgID)
if err != nil {
return definitions.Route{}, "", MakeErrRouteInvalidFormat(err)
return nil, err
}
provenances, err := nps.provenanceStore.GetProvenances(ctx, orgID, (&legacy_storage.ManagedRoute{}).ResourceType())
if err != nil {
return nil, err
}
managedRoutesDisabled := !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies)
managedRoutes := rev.GetManagedRoutes()
for _, mr := range managedRoutes {
// Backwards compatibility when managed routes FF is disabled. Don't include any custom managed routes.
if managedRoutesDisabled && mr.Name != legacy_storage.UserDefinedRoutingTreeName {
continue
}
provenance, ok := provenances[mr.ResourceID()]
if !ok {
provenance = models.ProvenanceNone
}
mr.Provenance = provenance
}
managedRoutes.Sort()
return managedRoutes, nil
}
func (nps *NotificationPolicyService) UpdateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p models.Provenance, version string) (*legacy_storage.ManagedRoute, error) {
// TODO: Keep this?
if name == "" {
name = legacy_storage.UserDefinedRoutingTreeName
}
// Backwards compatibility when managed routes FF is disabled. Only allow the default route.
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) && name != legacy_storage.UserDefinedRoutingTreeName {
return nil, ErrRouteNotFound.Errorf("route %q not found", name)
}
err := subtree.Validate()
if err != nil {
return nil, MakeErrRouteInvalidFormat(err)
}
revision, err := nps.configStore.Get(ctx, orgID)
if err != nil {
return definitions.Route{}, "", err
return nil, err
}
err = nps.checkOptimisticConcurrency(*revision.Config.AlertmanagerConfig.Route, p, version, "update")
existing := revision.GetManagedRoute(name)
if existing == nil {
return nil, ErrRouteNotFound.Errorf("route %q not found", name)
}
err = nps.checkOptimisticConcurrency(existing, p, version, "update")
if err != nil {
return definitions.Route{}, "", err
return nil, err
}
// check that provenance is not changed in an invalid way
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, &tree, orgID)
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, existing, orgID)
if err != nil {
return definitions.Route{}, "", err
return nil, err
}
if err := nps.validator(storedProvenance, p); err != nil {
return definitions.Route{}, "", err
return nil, err
}
receivers := revision.GetReceiversNames()
receivers[""] = struct{}{} // Allow empty receiver (inheriting from parent)
err = tree.ValidateReceivers(receivers)
updated, err := revision.UpdateNamedRoute(name, subtree)
if err != nil {
return definitions.Route{}, "", MakeErrRouteInvalidFormat(err)
return nil, err
}
timeIntervals := map[string]struct{}{}
for _, mt := range revision.Config.AlertmanagerConfig.MuteTimeIntervals {
timeIntervals[mt.Name] = struct{}{}
}
for _, mt := range revision.Config.AlertmanagerConfig.TimeIntervals {
timeIntervals[mt.Name] = struct{}{}
}
err = tree.ValidateTimeIntervals(timeIntervals)
if err != nil {
return definitions.Route{}, "", MakeErrRouteInvalidFormat(err)
}
revision.Config.AlertmanagerConfig.Route = &tree
updated.Provenance = storedProvenance
_, err = revision.Config.GetMergedAlertmanagerConfig()
if err != nil {
if errors.Is(err, definition.ErrSubtreeMatchersConflict) {
// TODO temporarily get the conflicting matchers
return definitions.Route{}, "", MakeErrRouteConflictingMatchers(fmt.Sprintf("%s", revision.Config.ExtraConfigs[0].MergeMatchers))
return nil, MakeErrRouteConflictingMatchers(fmt.Sprintf("%s", revision.Config.ExtraConfigs[0].MergeMatchers))
}
nps.log.Warn("Unable to validate the combined routing tree because of an error during merging. This could be a sign of broken external configuration. Skipping", "error", err)
}
@@ -123,169 +163,147 @@ func (nps *NotificationPolicyService) UpdatePolicyTree(ctx context.Context, orgI
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
return err
}
return nps.provenanceStore.SetProvenance(ctx, &tree, orgID, p)
return nps.provenanceStore.SetProvenance(ctx, updated, orgID, p)
})
if err != nil {
return definitions.Route{}, "", err
return nil, err
}
return tree, calculateRouteFingerprint(tree), nil
return updated, nil
}
func (nps *NotificationPolicyService) ResetPolicyTree(ctx context.Context, orgID int64, provenance models.Provenance) (definitions.Route, error) {
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, &definitions.Route{}, orgID)
if err != nil {
return definitions.Route{}, err
}
if err := nps.validator(storedProvenance, provenance); err != nil {
return definitions.Route{}, err
func (nps *NotificationPolicyService) DeleteManagedRoute(ctx context.Context, orgID int64, name string, p models.Provenance, version string) error {
// TODO: Keep this?
if name == "" {
name = legacy_storage.UserDefinedRoutingTreeName
}
defaultCfg, err := legacy_storage.DeserializeAlertmanagerConfig([]byte(nps.settings.DefaultConfiguration))
if err != nil {
nps.log.Error("Failed to parse default alertmanager config: %w", err)
return definitions.Route{}, fmt.Errorf("failed to parse default alertmanager config: %w", err)
// Backwards compatibility when managed routes FF is disabled. Only allow the default route.
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) && name != legacy_storage.UserDefinedRoutingTreeName {
return ErrRouteNotFound.Errorf("route %q not found", name)
}
route := defaultCfg.AlertmanagerConfig.Route
revision, err := nps.configStore.Get(ctx, orgID)
if err != nil {
return definitions.Route{}, err
return err
}
revision.Config.AlertmanagerConfig.Route = route
err = nps.ensureDefaultReceiverExists(revision.Config, defaultCfg)
existing := revision.GetManagedRoute(name)
if existing == nil {
return ErrRouteNotFound.Errorf("route %q not found", name)
}
err = nps.checkOptimisticConcurrency(existing, p, version, "delete")
if err != nil {
return definitions.Route{}, err
return err
}
storedProvenance, err := nps.provenanceStore.GetProvenance(ctx, existing, orgID)
if err != nil {
return err
}
if err := nps.validator(storedProvenance, p); err != nil {
return err
}
if name == legacy_storage.UserDefinedRoutingTreeName {
defaultCfg, err := legacy_storage.DeserializeAlertmanagerConfig([]byte(nps.settings.DefaultConfiguration))
if err != nil {
nps.log.Error("Failed to parse default alertmanager config: %w", err)
return fmt.Errorf("failed to parse default alertmanager config: %w", err)
}
_, err = revision.ResetUserDefinedRoute(defaultCfg)
if err != nil {
return err
}
} else {
revision.DeleteManagedRoute(name)
}
_, err = revision.Config.GetMergedAlertmanagerConfig()
if err != nil {
return fmt.Errorf("new routing tree is not compatible with extra configuration: %w", err)
}
return nps.xact.InTransaction(ctx, func(ctx context.Context) error {
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
return err
}
return nps.provenanceStore.DeleteProvenance(ctx, existing, orgID)
})
}
func (nps *NotificationPolicyService) CreateManagedRoute(ctx context.Context, orgID int64, name string, subtree definitions.Route, p models.Provenance) (*legacy_storage.ManagedRoute, error) {
// Backwards compatibility when managed routes FF is disabled. This is not allowed.
if !nps.FeatureToggles.IsEnabledGlobally(featuremgmt.FlagAlertingMultiplePolicies) {
return nil, fmt.Errorf("managed routes are not enabled, see feature toggle %s", featuremgmt.FlagAlertingMultiplePolicies)
}
err := subtree.Validate()
if err != nil {
return nil, MakeErrRouteInvalidFormat(err)
}
revision, err := nps.configStore.Get(ctx, orgID)
if err != nil {
return nil, err
}
created, err := revision.CreateManagedRoute(name, subtree)
if err != nil {
return nil, err
}
_, err = revision.Config.GetMergedAlertmanagerConfig()
if err != nil {
return nil, fmt.Errorf("new routing tree is not compatible with extra configuration: %w", err)
}
err = nps.xact.InTransaction(ctx, func(ctx context.Context) error {
if err := nps.configStore.Save(ctx, revision, orgID); err != nil {
return err
}
return nps.provenanceStore.DeleteProvenance(ctx, route, orgID)
return nps.provenanceStore.SetProvenance(ctx, created, orgID, p)
})
if err != nil {
return definitions.Route{}, nil
} // TODO should be error?
return *route, nil
return nil, err
}
return created, nil
}
func (nps *NotificationPolicyService) ensureDefaultReceiverExists(cfg *definitions.PostableUserConfig, defaultCfg *definitions.PostableUserConfig) error {
defaultRcv := cfg.AlertmanagerConfig.Route.Receiver
for _, rcv := range cfg.AlertmanagerConfig.Receivers {
if rcv.Name == defaultRcv {
return nil
}
// TODO: Remove this method once the all callers support named routes.
func (nps *NotificationPolicyService) GetPolicyTree(ctx context.Context, orgID int64) (definitions.Route, string, error) {
r, err := nps.GetManagedRoute(ctx, orgID, legacy_storage.UserDefinedRoutingTreeName)
if err != nil {
return definitions.Route{}, "", err
}
for _, rcv := range defaultCfg.AlertmanagerConfig.Receivers {
if rcv.Name == defaultRcv {
cfg.AlertmanagerConfig.Receivers = append(cfg.AlertmanagerConfig.Receivers, rcv)
return nil
}
}
nps.log.Error("Grafana Alerting has been configured with a default configuration that is internally inconsistent! The default configuration's notification policy must have a corresponding receiver.")
return fmt.Errorf("inconsistent default configuration")
return r.AsRoute(), r.Version, nil
}
func calculateRouteFingerprint(route definitions.Route) string {
sum := fnv.New64a()
writeToHash(sum, &route)
return fmt.Sprintf("%016x", sum.Sum64())
// TODO: Remove this method once the all callers support named routes.
func (nps *NotificationPolicyService) UpdatePolicyTree(ctx context.Context, orgID int64, tree definitions.Route, p models.Provenance, version string) (definitions.Route, string, error) {
r, err := nps.UpdateManagedRoute(ctx, orgID, legacy_storage.UserDefinedRoutingTreeName, tree, p, version)
if err != nil {
return definitions.Route{}, "", err
}
return r.AsRoute(), r.Version, nil
}
func writeToHash(sum hash.Hash, r *definitions.Route) {
writeBytes := func(b []byte) {
_, _ = sum.Write(b)
// add a byte sequence that cannot happen in UTF-8 strings.
_, _ = sum.Write([]byte{255})
// TODO: Remove this method once the all callers support named routes.
func (nps *NotificationPolicyService) ResetPolicyTree(ctx context.Context, orgID int64, provenance models.Provenance) (definitions.Route, error) {
err := nps.DeleteManagedRoute(ctx, orgID, legacy_storage.UserDefinedRoutingTreeName, provenance, "")
if err != nil {
return definitions.Route{}, err
}
writeString := func(s string) {
if len(s) == 0 {
writeBytes(nil)
return
}
// #nosec G103
// avoid allocation when converting string to byte slice
writeBytes(unsafe.Slice(unsafe.StringData(s), len(s)))
}
// this temp slice is used to convert ints to bytes.
tmp := make([]byte, 8)
writeInt := func(u int64) {
binary.LittleEndian.PutUint64(tmp, uint64(u))
writeBytes(tmp)
}
writeBool := func(b bool) {
if b {
writeInt(1)
} else {
writeInt(0)
}
}
writeDuration := func(d *model.Duration) {
if d == nil {
_, _ = sum.Write([]byte{255})
} else {
binary.LittleEndian.PutUint64(tmp, uint64(*d))
_, _ = sum.Write(tmp)
_, _ = sum.Write([]byte{255})
}
}
writeString(r.Receiver)
for _, s := range r.GroupByStr {
writeString(s)
}
for _, labelName := range r.GroupBy {
writeString(string(labelName))
}
writeBool(r.GroupByAll)
if len(r.Match) > 0 {
keys := maps.Keys(r.Match)
slices.Sort(keys)
for _, key := range keys {
writeString(key)
writeString(r.Match[key])
}
}
if len(r.MatchRE) > 0 {
keys := maps.Keys(r.MatchRE)
slices.Sort(keys)
for _, key := range keys {
writeString(key)
str, err := r.MatchRE[key].MarshalJSON()
if err != nil {
writeString(fmt.Sprintf("%+v", r.MatchRE))
}
writeBytes(str)
}
}
for _, matcher := range r.Matchers {
writeString(matcher.String())
}
for _, matcher := range r.ObjectMatchers {
writeString(matcher.String())
}
for _, timeInterval := range r.MuteTimeIntervals {
writeString(timeInterval)
}
for _, timeInterval := range r.ActiveTimeIntervals {
writeString(timeInterval)
}
writeBool(r.Continue)
writeDuration(r.GroupWait)
writeDuration(r.GroupInterval)
writeDuration(r.RepeatInterval)
for _, route := range r.Routes {
writeToHash(sum, route)
defaultCfg, err := legacy_storage.DeserializeAlertmanagerConfig([]byte(nps.settings.DefaultConfiguration))
if err != nil {
nps.log.Error("Failed to parse default alertmanager config: %w", err)
return definitions.Route{}, fmt.Errorf("failed to parse default alertmanager config: %w", err)
}
return *defaultCfg.AlertmanagerConfig.Route, nil
}
func (nps *NotificationPolicyService) checkOptimisticConcurrency(current definitions.Route, provenance models.Provenance, desiredVersion string, action string) error {
func (nps *NotificationPolicyService) checkOptimisticConcurrency(current *legacy_storage.ManagedRoute, provenance models.Provenance, desiredVersion string, action string) error {
if desiredVersion == "" {
if provenance != models.ProvenanceFile {
// if version is not specified and it's not a file provisioning, emit a log message to reflect that optimistic concurrency is disabled for this request
@@ -293,9 +311,8 @@ func (nps *NotificationPolicyService) checkOptimisticConcurrency(current definit
}
return nil
}
currentVersion := calculateRouteFingerprint(current)
if currentVersion != desiredVersion {
return ErrVersionConflict.Errorf("provided version %s of routing tree does not match current version %s", desiredVersion, currentVersion)
if current.Version != desiredVersion {
return ErrVersionConflict.Errorf("provided version %s of routing tree does not match current version %s", desiredVersion, current.Version)
}
return nil
}
@@ -16,6 +16,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
@@ -29,7 +30,7 @@ func TestGetPolicyTree(t *testing.T) {
rev := getDefaultConfigRevision()
expectedRoute := *rev.Config.AlertmanagerConfig.Route
expectedRoute.Provenance = definitions.Provenance(models.ProvenanceAPI)
expectedVersion := calculateRouteFingerprint(expectedRoute)
expectedVersion := legacy_storage.CalculateRouteFingerprint(expectedRoute)
sut, store, prov := createNotificationPolicyServiceSut()
store.GetFn = func(ctx context.Context, orgID int64) (*legacy_storage.ConfigRevision, error) {
@@ -52,7 +53,7 @@ func TestGetPolicyTree(t *testing.T) {
assert.Len(t, prov.Calls, 1)
assert.Equal(t, "GetProvenance", prov.Calls[0].MethodName)
assert.IsType(t, &definitions.Route{}, prov.Calls[0].Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), prov.Calls[0].Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, prov.Calls[0].Arguments[2])
}
@@ -60,7 +61,7 @@ func TestUpdatePolicyTree(t *testing.T) {
orgID := int64(1)
rev := getDefaultConfigRevision()
defaultVersion := calculateRouteFingerprint(*rev.Config.AlertmanagerConfig.Route)
defaultVersion := legacy_storage.CalculateRouteFingerprint(*rev.Config.AlertmanagerConfig.Route)
newRoute := definitions.Route{
Receiver: rev.Config.AlertmanagerConfig.Receivers[0].Name,
@@ -185,7 +186,7 @@ func TestUpdatePolicyTree(t *testing.T) {
assert.Len(t, prov.Calls, 1)
assert.Equal(t, "GetProvenance", prov.Calls[0].MethodName)
assert.IsType(t, &definitions.Route{}, prov.Calls[0].Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), prov.Calls[0].Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, prov.Calls[0].Arguments[2].(int64))
})
@@ -273,7 +274,7 @@ func TestUpdatePolicyTree(t *testing.T) {
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, route, models.ProvenanceAPI, defaultVersion)
require.NoError(t, err)
assert.Equal(t, route, result)
assert.Equal(t, calculateRouteFingerprint(route), version)
assert.Equal(t, legacy_storage.CalculateRouteFingerprint(route), version)
})
t.Run("updates Route and sets provenance in transaction if route is valid and version matches", func(t *testing.T) {
@@ -289,7 +290,7 @@ func TestUpdatePolicyTree(t *testing.T) {
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, newRoute, models.ProvenanceAPI, defaultVersion)
require.NoError(t, err)
assert.Equal(t, newRoute, result)
assert.Equal(t, calculateRouteFingerprint(newRoute), version)
assert.Equal(t, legacy_storage.CalculateRouteFingerprint(newRoute), version)
assert.Len(t, store.Calls, 2)
assert.Equal(t, "Save", store.Calls[1].Method)
@@ -298,12 +299,12 @@ func TestUpdatePolicyTree(t *testing.T) {
c := prov.Calls[0]
assert.Equal(t, "GetProvenance", c.MethodName)
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, c.Arguments[2].(int64))
c = prov.Calls[1]
assert.Equal(t, "SetProvenance", c.MethodName)
assertInTransaction(t, c.Arguments[0].(context.Context))
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, c.Arguments[2].(int64))
assert.Equal(t, models.ProvenanceAPI, c.Arguments[3].(models.Provenance))
})
@@ -321,7 +322,7 @@ func TestUpdatePolicyTree(t *testing.T) {
result, version, err := sut.UpdatePolicyTree(context.Background(), orgID, newRoute, models.ProvenanceAPI, "")
require.NoError(t, err)
assert.Equal(t, newRoute, result)
assert.Equal(t, calculateRouteFingerprint(newRoute), version)
assert.Equal(t, legacy_storage.CalculateRouteFingerprint(newRoute), version)
assert.Len(t, store.Calls, 2)
assert.Equal(t, "Save", store.Calls[1].Method)
@@ -332,7 +333,7 @@ func TestUpdatePolicyTree(t *testing.T) {
c := prov.Calls[1]
assert.Equal(t, "SetProvenance", c.MethodName)
assertInTransaction(t, c.Arguments[0].(context.Context))
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, c.Arguments[2].(int64))
assert.Equal(t, models.ProvenanceAPI, c.Arguments[3].(models.Provenance))
})
@@ -430,12 +431,12 @@ func TestResetPolicyTree(t *testing.T) {
assert.Len(t, prov.Calls, 2)
c := prov.Calls[0]
assert.Equal(t, "GetProvenance", c.MethodName)
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, c.Arguments[2].(int64))
c = prov.Calls[1]
assert.Equal(t, "DeleteProvenance", c.MethodName)
assertInTransaction(t, c.Arguments[0].(context.Context))
assert.IsType(t, &definitions.Route{}, c.Arguments[1])
assert.Equal(t, (&definitions.Route{}).ResourceType(), c.Arguments[1].(models.Provisionable).ResourceType())
assert.Equal(t, orgID, c.Arguments[2])
})
}
@@ -516,10 +517,10 @@ func TestRoute_Fingerprint(t *testing.T) {
t.Run("stable across code changes", func(t *testing.T) {
expectedFingerprint := "450c06a7f4a66675" // If this is a valid fingerprint generation change, update the expected value.
assert.Equal(t, expectedFingerprint, calculateRouteFingerprint(baseRouteGen()))
assert.Equal(t, expectedFingerprint, legacy_storage.CalculateRouteFingerprint(baseRouteGen()))
})
t.Run("unstable across field modification", func(t *testing.T) {
fingerprint := calculateRouteFingerprint(baseRouteGen())
fingerprint := legacy_storage.CalculateRouteFingerprint(baseRouteGen())
excludedFields := map[string]struct{}{
"Routes": {},
"Provenance": {},
@@ -548,7 +549,7 @@ func TestRoute_Fingerprint(t *testing.T) {
// Set the field to the value of the completelyDifferentRoute.
vf.Set(otherField)
f2 := calculateRouteFingerprint(cp)
f2 := legacy_storage.CalculateRouteFingerprint(cp)
assert.NotEqualf(t, fingerprint, f2, "Route field %s does not seem to be used in fingerprint", field)
}
})
@@ -573,6 +574,7 @@ func createNotificationPolicyServiceSut() (*NotificationPolicyService, *legacy_s
validator: func(from, to models.Provenance) error {
return nil
},
FeatureToggles: featuremgmt.WithFeatures(),
}, configStore, prov
}
@@ -2,6 +2,7 @@ package alerting
import (
"context"
"errors"
"fmt"
"github.com/grafana/grafana/pkg/infra/log"
@@ -31,7 +32,18 @@ func (c *defaultNotificationPolicyProvisioner) Provision(ctx context.Context,
files []*AlertingFile) error {
for _, file := range files {
for _, np := range file.Policies {
_, _, err := c.notificationPolicyService.UpdatePolicyTree(ctx, np.OrgID,
if _, err := c.notificationPolicyService.GetManagedRoute(ctx, np.OrgID, np.Name); err != nil {
if errors.Is(err, provisioning.ErrRouteNotFound) {
_, err := c.notificationPolicyService.CreateManagedRoute(ctx, np.OrgID, np.Name,
np.Policy, models.ProvenanceFile)
if err != nil {
return fmt.Errorf("%s: %w", file.Filename, err)
}
continue
}
return err
}
_, err := c.notificationPolicyService.UpdateManagedRoute(ctx, np.OrgID, np.Name,
np.Policy, models.ProvenanceFile, "")
if err != nil {
return fmt.Errorf("%s: %w", file.Filename, err)
@@ -44,8 +56,8 @@ func (c *defaultNotificationPolicyProvisioner) Provision(ctx context.Context,
func (c *defaultNotificationPolicyProvisioner) Unprovision(ctx context.Context,
files []*AlertingFile) error {
for _, file := range files {
for _, orgID := range file.ResetPolicies {
_, err := c.notificationPolicyService.ResetPolicyTree(ctx, int64(orgID), models.ProvenanceFile)
for _, deletePolicy := range file.DeletePolicies {
err := c.notificationPolicyService.DeleteManagedRoute(ctx, deletePolicy.OrgID, deletePolicy.Name, models.ProvenanceFile, "")
if err != nil {
return fmt.Errorf("%s: %w", file.Filename, err)
}
@@ -2,15 +2,19 @@ package alerting
import (
"encoding/json"
"errors"
"strings"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/services/provisioning/values"
)
type NotificiationPolicyV1 struct {
OrgID values.Int64Value `json:"orgId" yaml:"orgId"`
// We use JSONValue here, as we want to have interpolation the values.
Policy values.JSONValue `json:"-" yaml:"-"`
Policy values.JSONValue `json:"-" yaml:"-"`
Name values.StringValue `json:"name" yaml:"name"`
}
func (v1 *NotificiationPolicyV1) UnmarshalYAML(unmarshal func(any) error) error {
@@ -30,6 +34,10 @@ func (v1 *NotificiationPolicyV1) mapToModel() (NotificiationPolicy, error) {
if orgID < 1 {
orgID = 1
}
name := v1.Name.Value()
if name == "" {
name = legacy_storage.UserDefinedRoutingTreeName
}
var route definitions.Route
// We need the string json representation, so we marshal the policy back
// as a string and interpolate it at the same time.
@@ -48,10 +56,37 @@ func (v1 *NotificiationPolicyV1) mapToModel() (NotificiationPolicy, error) {
return NotificiationPolicy{
OrgID: orgID,
Policy: route,
Name: strings.TrimSpace(name),
}, nil
}
type NotificiationPolicy struct {
OrgID int64
Name string
Policy definitions.Route
}
type DeleteNotificationPolicyV1 struct {
OrgID values.Int64Value `json:"orgId" yaml:"orgId"`
Name values.StringValue `json:"name" yaml:"name"`
}
func (v1 DeleteNotificationPolicyV1) mapToModel() (DeleteNotificationPolicy, error) {
name := strings.TrimSpace(v1.Name.Value())
if name == "" {
return DeleteNotificationPolicy{}, errors.New("delete policy missing name")
}
orgID := v1.OrgID.Value()
if orgID < 1 {
orgID = 1
}
return DeleteNotificationPolicy{
OrgID: orgID,
Name: name,
}, nil
}
type DeleteNotificationPolicy struct {
OrgID int64
Name string
}
@@ -5,6 +5,8 @@ import (
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
)
func TestNotificationPolicy(t *testing.T) {
@@ -27,6 +29,33 @@ repeat_interval: ${NOTIFIER_EMAIL_REMINDER_FREQUENCY}
require.NoError(t, err)
require.Equal(t, int64(123), np.OrgID)
require.Equal(t, "test", np.Policy.Receiver)
require.Equal(t, legacy_storage.UserDefinedRoutingTreeName, np.Name)
require.True(t, np.Policy.Continue)
require.Equal(t, envValue, np.Policy.RepeatInterval.String())
}
func TestNotificationPolicyWithName(t *testing.T) {
const (
envKey = "NOTIFIER_EMAIL_REMINDER_FREQUENCY"
envValue = "4h"
)
t.Setenv(envKey, envValue)
data := `orgId: 123
receiver: test
continue: true
name: "test-policy"
repeat_interval: ${NOTIFIER_EMAIL_REMINDER_FREQUENCY}
`
var model NotificiationPolicyV1
err := yaml.Unmarshal([]byte(data), &model)
require.NoError(t, err)
np, err := model.mapToModel()
require.NoError(t, err)
require.Equal(t, int64(123), np.OrgID)
require.Equal(t, "test", np.Policy.Receiver)
require.Equal(t, "test-policy", np.Name)
require.True(t, np.Policy.Continue)
require.Equal(t, envValue, np.Policy.RepeatInterval.String())
}
+25 -12
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/services/provisioning/values"
)
@@ -21,7 +22,7 @@ type AlertingFile struct {
ContactPoints []ContactPoint
DeleteContactPoints []DeleteContactPoint
Policies []NotificiationPolicy
ResetPolicies []OrgID
DeletePolicies []DeleteNotificationPolicy
MuteTimes []MuteTime
DeleteMuteTimes []DeleteMuteTime
Templates []Template
@@ -31,16 +32,17 @@ type AlertingFile struct {
type AlertingFileV1 struct {
configVersion
Filename string
Groups []AlertRuleGroupV1 `json:"groups" yaml:"groups"`
DeleteRules []RuleDeleteV1 `json:"deleteRules" yaml:"deleteRules"`
ContactPoints []ContactPointV1 `json:"contactPoints" yaml:"contactPoints"`
DeleteContactPoints []DeleteContactPointV1 `json:"deleteContactPoints" yaml:"deleteContactPoints"`
Policies []NotificiationPolicyV1 `json:"policies" yaml:"policies"`
ResetPolicies []values.Int64Value `json:"resetPolicies" yaml:"resetPolicies"`
MuteTimes []MuteTimeV1 `json:"muteTimes" yaml:"muteTimes"`
DeleteMuteTimes []DeleteMuteTimeV1 `json:"deleteMuteTimes" yaml:"deleteMuteTimes"`
Templates []TemplateV1 `json:"templates" yaml:"templates"`
DeleteTemplates []DeleteTemplateV1 `json:"deleteTemplates" yaml:"deleteTemplates"`
Groups []AlertRuleGroupV1 `json:"groups" yaml:"groups"`
DeleteRules []RuleDeleteV1 `json:"deleteRules" yaml:"deleteRules"`
ContactPoints []ContactPointV1 `json:"contactPoints" yaml:"contactPoints"`
DeleteContactPoints []DeleteContactPointV1 `json:"deleteContactPoints" yaml:"deleteContactPoints"`
Policies []NotificiationPolicyV1 `json:"policies" yaml:"policies"`
ResetPolicies []values.Int64Value `json:"resetPolicies" yaml:"resetPolicies"` // Legacy field, use DeletePolicies instead.
DeletePolicies []DeleteNotificationPolicyV1 `json:"deletePolicies" yaml:"deletePolicies"`
MuteTimes []MuteTimeV1 `json:"muteTimes" yaml:"muteTimes"`
DeleteMuteTimes []DeleteMuteTimeV1 `json:"deleteMuteTimes" yaml:"deleteMuteTimes"`
Templates []TemplateV1 `json:"templates" yaml:"templates"`
DeleteTemplates []DeleteTemplateV1 `json:"deleteTemplates" yaml:"deleteTemplates"`
}
func (fileV1 *AlertingFileV1) MapToModel() (AlertingFile, error) {
@@ -101,7 +103,18 @@ func (fileV1 *AlertingFileV1) mapPolicies(alertingFile *AlertingFile) error {
alertingFile.Policies = append(alertingFile.Policies, np)
}
for _, orgIDV1 := range fileV1.ResetPolicies {
alertingFile.ResetPolicies = append(alertingFile.ResetPolicies, OrgID(orgIDV1.Value()))
alertingFile.DeletePolicies = append(alertingFile.DeletePolicies, DeleteNotificationPolicy{
OrgID: orgIDV1.Value(),
Name: legacy_storage.UserDefinedRoutingTreeName,
})
}
for _, deleteV1 := range fileV1.DeletePolicies {
delReq, err := deleteV1.mapToModel()
if err != nil {
return err
}
alertingFile.DeletePolicies = append(alertingFile.DeletePolicies, delReq)
}
return nil
}
+1 -1
View File
@@ -336,7 +336,7 @@ func (ps *ProvisioningServiceImpl) ProvisionAlerting(ctx context.Context) error
contactPointService := provisioning.NewContactPointService(configStore, ps.secretService,
ps.alertingStore, ps.SQLStore, receiverSvc, ps.log, ps.alertingStore, ps.resourcePermissions)
notificationPolicyService := provisioning.NewNotificationPolicyService(configStore,
ps.alertingStore, ps.SQLStore, ps.Cfg.UnifiedAlerting, ps.log)
ps.alertingStore, ps.SQLStore, ps.Cfg.UnifiedAlerting, ps.alertingStore.FeatureToggles, ps.log)
mutetimingsService := provisioning.NewMuteTimingService(configStore, ps.alertingStore, ps.alertingStore, ps.log, ps.alertingStore)
templateService := provisioning.NewTemplateService(configStore, ps.alertingStore, ps.alertingStore, ps.log)
cfg := prov_alerting.ProvisionerConfig{
@@ -23,7 +23,6 @@ import (
"k8s.io/apimachinery/pkg/types"
"github.com/grafana/alerting/notify"
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
"github.com/grafana/grafana/pkg/bus"
@@ -38,6 +37,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/api"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/tests/api/alerting"
@@ -809,7 +809,9 @@ func TestIntegrationInUseMetadata(t *testing.T) {
// Removing the new extra route should leave only 1.
amConfig.AlertmanagerConfig.Route.Routes = amConfig.AlertmanagerConfig.Route.Routes[:1]
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, *amConfig.AlertmanagerConfig.Route, "", func(int64) string { return "default" })
managedRoute := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
managedRoute.Version = "" // Avoid version conflict.
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, managedRoute, func(int64) string { return "default" })
require.NoError(t, err)
routeAdminClient := test_common.NewRoutingTreeClient(t, helper.Org1.Admin)
_, err = routeAdminClient.Update(ctx, v1Route, v1.UpdateOptions{})
@@ -831,7 +833,9 @@ func TestIntegrationInUseMetadata(t *testing.T) {
// Remove the remaining routes.
amConfig.AlertmanagerConfig.Route.Routes = nil
v1route, err := routingtree.ConvertToK8sResource(1, *amConfig.AlertmanagerConfig.Route, "", func(int64) string { return "default" })
managedRoute = legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
managedRoute.Version = "" // Avoid version conflict.
v1route, err := routingtree.ConvertToK8sResource(1, managedRoute, func(int64) string { return "default" })
require.NoError(t, err)
_, err = routeAdminClient.Update(ctx, v1route, v1.UpdateOptions{})
require.NoError(t, err)
@@ -1139,9 +1143,15 @@ func TestIntegrationReferentialIntegrity(t *testing.T) {
}
updatedRoute := legacyCli.GetRoute(t)
for _, route := range updatedRoute.Routes {
assert.Equalf(t, expectedTitle, route.Receiver, "time receiver in routes should have been renamed but it did not")
}
// Sanity check to make sure at least some titles updated.
assert.Error(t, updatedRoute.ValidateReceivers(map[string]struct{}{
"grafana-default-email": {},
}))
// Make sure all references are either to the default receiver or the renamed one.
assert.NoError(t, updatedRoute.ValidateReceivers(map[string]struct{}{
"grafana-default-email": {},
expectedTitle: {},
}))
actual, err = adminClient.Get(ctx, actual.Name, v1.GetOptions{})
require.NoError(t, err)
@@ -1498,7 +1508,9 @@ func persistInitialConfig(t *testing.T, amConfig definitions.PostableUserConfig)
nsMapper := func(_ int64) string { return "default" }
routeClient := test_common.NewRoutingTreeClient(t, helper.Org1.Admin)
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, *amConfig.AlertmanagerConfig.Route, "", nsMapper)
managedRoute := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
managedRoute.Version = "" // Avoid version conflict.
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.AdminServiceAccount.OrgId, managedRoute, nsMapper)
require.NoError(t, err)
_, err = routeClient.Update(ctx, v1route, v1.UpdateOptions{})
require.NoError(t, err)
@@ -18,6 +18,7 @@ import (
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1"
"github.com/grafana/grafana/pkg/registry/apps/alerting/notifications/routingtree"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/apps/alerting/notifications/pkg/apis/alertingnotifications/v0alpha1/fakes"
"github.com/grafana/grafana/pkg/bus"
@@ -48,6 +49,8 @@ func getTestHelper(t *testing.T) *apis.K8sTestHelper {
}
func TestIntegrationNotAllowedMethods(t *testing.T) {
// TODO: Add more tests.
t.Skip("No longer applies, need real tests.")
testutil.SkipIntegrationTestInShortMode(t)
ctx := context.Background()
@@ -387,7 +390,9 @@ func TestIntegrationDataConsistency(t *testing.T) {
createRoute := func(t *testing.T, route definitions.Route) {
t.Helper()
routeClient := common.NewRoutingTreeClient(t, helper.Org1.Admin)
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), route, "", func(int64) string { return "default" })
managedRoute := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, &route)
managedRoute.Version = "" // Avoid version conflict.
v1Route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), managedRoute, func(int64) string { return "default" })
require.NoError(t, err)
_, err = routeClient.Update(ctx, v1Route, v1.UpdateOptions{})
require.NoError(t, err)
@@ -30,6 +30,7 @@ import (
"github.com/grafana/grafana/pkg/services/folder/foldertest"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/legacy_storage"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/tests/api/alerting"
@@ -656,7 +657,9 @@ func TestIntegrationTimeIntervalReferentialIntegrity(t *testing.T) {
}
routeClient := common.NewRoutingTreeClient(t, helper.Org1.Admin)
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), *amConfig.AlertmanagerConfig.Route, "", func(int64) string { return "default" })
route := legacy_storage.NewManagedRoute(v0alpha1.UserDefinedRoutingTreeName, amConfig.AlertmanagerConfig.Route)
route.Version = "" // Avoid version conflict.
v1route, err := routingtree.ConvertToK8sResource(helper.Org1.Admin.Identity.GetOrgID(), route, func(int64) string { return "default" })
require.NoError(t, err)
_, err = routeClient.Update(ctx, v1route, v1.UpdateOptions{})
require.NoError(t, err)
+15
View File
@@ -85,6 +85,21 @@ export function getAlertingRoutes(cfg = config): RouteDescriptor[] {
)
),
},
{
path: '/alerting/notifications/routes/:name/edit',
roles: evaluateAccess([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsExternalRead,
...PERMISSIONS_NOTIFICATION_POLICIES_READ,
...PERMISSIONS_NOTIFICATION_POLICIES_MODIFY,
]),
component: importAlertingComponent(
() =>
import(
/* webpackChunkName: "EditRoutingTreePage" */ 'app/features/alerting/unified/components/notification-policies/EditRoutingTreePage'
)
),
},
{
path: '/alerting/silences',
roles: evaluateAccess([
@@ -32,7 +32,7 @@ import {
import { AccessControlAction } from 'app/types/accessControl';
import NotificationPolicies from './NotificationPoliciesPage';
import { findRoutesMatchingFilters } from './components/notification-policies/NotificationPoliciesList';
import { findRoutesMatchingFilters } from './components/notification-policies/NotificationPoliciesTree';
import {
grantUserPermissions,
mockDataSource,
@@ -1,19 +1,63 @@
import { css } from '@emotion/css';
import { useState } from 'react';
import { Fragment, useState } from 'react';
import { GrafanaTheme2, UrlQueryMap } from '@grafana/data';
import { t } from '@grafana/i18n';
import { Tab, TabContent, TabsBar, useStyles2 } from '@grafana/ui';
import {
Alert,
Button,
Dropdown,
EmptyState,
LinkButton,
LoadingPlaceholder,
Menu,
Pagination,
Stack,
Tab,
TabContent,
TabsBar,
Text,
Tooltip,
useStyles2,
} from '@grafana/ui';
import { useQueryParams } from 'app/core/hooks/useQueryParams';
import { useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { NotificationPoliciesList } from 'app/features/alerting/unified/components/notification-policies/NotificationPoliciesList';
import { AlertmanagerAction, useAlertmanagerAbility } from 'app/features/alerting/unified/hooks/useAbilities';
import { NotificationPoliciesTree } from 'app/features/alerting/unified/components/notification-policies/NotificationPoliciesTree';
import { MetadataRow } from 'app/features/alerting/unified/components/notification-policies/Policy';
import {
AlertmanagerAction,
useAlertmanagerAbilities,
useAlertmanagerAbility,
} from 'app/features/alerting/unified/hooks/useAbilities';
import { AlertmanagerPageWrapper } from './components/AlertingPageWrapper';
import { GrafanaAlertmanagerWarning } from './components/GrafanaAlertmanagerWarning';
import { TimeIntervalsTable } from './components/mute-timings/MuteTimingsTable';
import { useAlertmanager } from './state/AlertmanagerContext';
import { withPageErrorBoundary } from './withPageErrorBoundary';
import { AlertmanagerGroup, Receiver, Route, ROUTES_META_SYMBOL } from '../../../plugins/datasource/alertmanager/types';
import { stringifyErrorLike } from './utils/misc';
import {
useCreateRoutingTree,
useDeleteRoutingTree,
useListNotificationPolicyRoutes,
useRootRouteSearch,
} from './components/notification-policies/useNotificationPolicyRoute';
import { useURLSearchParams } from './hooks/useURLSearchParams';
import { usePagination } from './hooks/usePagination';
import { useCreateRoutingTreeModal, useDeleteRoutingTreeModal } from './components/notification-policies/components/Modals';
import { ALL_ROUTING_TREES, useExportRoutingTree } from './components/notification-policies/useExportRoutingTree';
import { K8sAnnotations, ROOT_ROUTE_NAME } from './utils/k8s/constants';
import ConditionalWrap from './components/ConditionalWrap';
import { ProvisioningBadge } from './components/Provisioning';
import { getAnnotation } from './utils/k8s/utils';
import { Spacer } from './components/Spacer';
import MoreButton from './components/MoreButton';
import { useGrafanaContactPoints } from './components/contact-points/useContactPoints';
import { useAlertGroupsModal } from './components/notification-policies/Modals';
import { normalizeMatchers } from './utils/matchers';
import { RoutingTreeFilter } from './components/notification-policies/components/RoutingTreeFilter';
import {config} from '@grafana/runtime';
enum ActiveTab {
NotificationPolicies = 'notification_policies',
@@ -73,17 +117,360 @@ const NotificationPoliciesTabs = () => {
)}
</TabsBar>
<TabContent className={styles.tabContent}>
{policyTreeTabActive && <NotificationPoliciesList />}
{policyTreeTabActive && <PolicyTreeTab />}
{muteTimingsTabActive && <TimeIntervalsTable />}
</TabContent>
</>
);
};
const PolicyTreeTab = () => {
const { isGrafanaAlertmanager } = useAlertmanager();
const useMultiplePoliciesView = config.featureToggles.alertingMultiplePolicies;
if (!isGrafanaAlertmanager || !useMultiplePoliciesView) {
return <NotificationPoliciesTree />;
}
return <Stack direction="column">
<PolicyTreeTabContents />
</Stack>
}
const DEFAULT_PAGE_SIZE = 10;
const PolicyTreeTabContents = () => {
const [queryParams] = useURLSearchParams();
const [[createPoliciesSupported, createPoliciesAllowed], [exportPoliciesSupported, exportPoliciesAllowed]] =
useAlertmanagerAbilities([
AlertmanagerAction.CreateNotificationPolicy,
AlertmanagerAction.ExportNotificationPolicies,
]);
const {
currentData: allPolicies,
isLoading,
error: fetchPoliciesError,
} = useListNotificationPolicyRoutes();
const [ExportDrawer, showExportDrawer] = useExportRoutingTree();
const [createTrigger] = useCreateRoutingTree();
const [CreateModal, showCreateModal] = useCreateRoutingTreeModal(createTrigger.execute);
const search = queryParams.get('search');
const [contactPointsSupported, canSeeContactPoints] = useAlertmanagerAbility(AlertmanagerAction.ViewContactPoint);
const shouldFetchContactPoints = contactPointsSupported && canSeeContactPoints;
const { contactPoints: receivers } = useGrafanaContactPoints({
skip: !shouldFetchContactPoints,
fetchStatuses: false,
fetchPolicies: false,
});
if (isLoading) {
return <LoadingPlaceholder text={'Loading...'} />;
}
return (
<>
{/* TODO we can add some additional info here with a ToggleTip */}
<Stack direction="row" alignItems="end" justifyContent="space-between">
<RoutingTreeFilter />
<Stack direction="row" gap={1}>
{createPoliciesSupported && (
<Button
icon="plus"
aria-label={'add policy'}
variant="primary"
disabled={!createPoliciesAllowed}
onClick={() => showCreateModal()}
>
Create policy
</Button>
)}
{exportPoliciesSupported && (
<Button
icon="download-alt"
variant="secondary"
aria-label={'export all'}
disabled={!exportPoliciesAllowed}
onClick={() => showExportDrawer(ALL_ROUTING_TREES)}
>
Export all
</Button>
)}
</Stack>
</Stack>
{fetchPoliciesError ? (
<Alert title={'Failed to fetch policies'}>{stringifyErrorLike(fetchPoliciesError)}</Alert>
) : (
<RoutingTreeList
policies={allPolicies ?? []}
search={search}
pageSize={DEFAULT_PAGE_SIZE}
receivers={receivers}
/>
)}
{CreateModal}
{ExportDrawer}
</>
);
};
interface RoutingTreeListProps {
policies: Route[];
search?: string | null;
pageSize: number;
receivers?: Receiver[];
}
const RoutingTreeList = ({ policies, search, pageSize = DEFAULT_PAGE_SIZE, receivers }: RoutingTreeListProps) => {
const searchResults = useRootRouteSearch(policies, search);
const { page, pageItems, numberOfPages, onPageChange } = usePagination(searchResults, 1, pageSize);
if (pageItems.length === 0) {
return <EmptyState variant="not-found" message={'No policies found'} />;
}
return (
<>
{pageItems.map((policy, index) => {
const key = `${policy.name}-${index}`;
return <RoutingTree key={key} route={policy} receivers={receivers} />;
})}
<Pagination currentPage={page} numberOfPages={numberOfPages} onNavigate={onPageChange} hideWhenSinglePage />
</>
);
};
interface RoutingTreeProps {
route: Route;
receivers?: Receiver[];
}
export const RoutingTree = ({ route, receivers }: RoutingTreeProps) => {
const styles = useStyles2(getStyles);
const { selectedAlertmanager } = useAlertmanager();
const [deleteTrigger] = useDeleteRoutingTree();
const [DeleteModal, showDeleteModal] = useDeleteRoutingTreeModal(deleteTrigger.execute);
const [alertInstancesModal, showAlertGroupsModal] = useAlertGroupsModal(selectedAlertmanager ?? '');
const matchingInstancesPreview = { enabled: false }; // Placeholder for matching instances preview logic
const numberOfAlertInstances = undefined; // Placeholder for number of alert instances logic
const matchingAlertGroups: AlertmanagerGroup[] | undefined = []; // Placeholder for matching alert groups logic
const matchers = normalizeMatchers(route);
return (
<div className={styles.routingTreeWrapper} data-testid="contact-point">
<Stack direction="column" gap={0}>
<RoutingTreeHeader
route={route}
onDelete={(routeToDelete) =>
showDeleteModal({
name: routeToDelete[ROUTES_META_SYMBOL]?.name ?? '',
resourceVersion: routeToDelete[ROUTES_META_SYMBOL]?.resourceVersion,
})
}
/>
<div className={styles.routingTreeMetadataWrapper}>
<Stack direction="column" gap={0.5}>
<MetadataRow
matchingInstancesPreview={matchingInstancesPreview}
numberOfAlertInstances={numberOfAlertInstances}
contactPoint={route.receiver ?? undefined}
groupBy={route.group_by ?? []}
muteTimings={route.mute_time_intervals ?? []}
activeTimings={route.active_time_intervals ?? []}
timingOptions={{
group_wait: route.group_wait,
group_interval: route.group_interval,
repeat_interval: route.repeat_interval,
}}
alertManagerSourceName={selectedAlertmanager ?? ''}
receivers={receivers ?? []}
matchingAlertGroups={matchingAlertGroups}
matchers={matchers}
isDefaultPolicy={true}
onShowAlertInstances={showAlertGroupsModal}
/>
</Stack>
</div>
</Stack>
{DeleteModal}
{alertInstancesModal}
</div>
);
};
interface RoutingTreeHeaderProps {
route: Route;
onDelete: (route: Route) => void;
}
export const RoutingTreeHeader = ({ route, onDelete }: RoutingTreeHeaderProps) => {
const provisioned = route[ROUTES_META_SYMBOL]?.provisioned ?? false;
const styles = useStyles2(getStyles);
const [
[updatePoliciesSupported, updatePoliciesAllowed],
[deletePoliciesSupported, deletePoliciesAllowed],
[exportPoliciesSupported, exportPoliciesAllowed],
] = useAlertmanagerAbilities([
AlertmanagerAction.UpdateNotificationPolicyTree,
AlertmanagerAction.DeleteNotificationPolicy,
AlertmanagerAction.ExportNotificationPolicies,
]);
const canEdit = updatePoliciesSupported && updatePoliciesAllowed && !provisioned;
const [ExportDrawer, showExportDrawer] = useExportRoutingTree();
const menuActions: JSX.Element[] = [];
if (exportPoliciesSupported) {
menuActions.push(
<Fragment key="export-contact-point">
<Menu.Item
icon="download-alt"
label={t('alerting.use-create-dropdown-menu-actions.label-export', 'Export')}
ariaLabel="export"
disabled={!exportPoliciesAllowed}
data-testid="export"
onClick={() => showExportDrawer(route.name ?? '')}
/>
<Menu.Divider />
</Fragment>
);
}
if (deletePoliciesSupported) {
const canBeDeleted = deletePoliciesAllowed && !provisioned;
const isDefaultPolicy = route.name === ROOT_ROUTE_NAME;
const cannotDeleteNoPermissions = `You do not have the required permission to ${isDefaultPolicy ? 'reset' : 'delete'} this routing tree`;
const cannotDeleteProvisioned = `Routing tree is provisioned and cannot be ${isDefaultPolicy ? 'reset' : 'deleted'} via the UI`;
const reasonsDeleteIsDisabled = [
!deletePoliciesAllowed ? cannotDeleteNoPermissions : '',
provisioned ? cannotDeleteProvisioned : '',
].filter(Boolean);
const deleteTooltipContent = (
<>
{`Routing tree cannot be ${isDefaultPolicy ? 'reset' : 'deleted'} for the following reasons:`}
<br />
{reasonsDeleteIsDisabled.map((reason) => (
<li key={reason}>{reason}</li>
))}
</>
);
menuActions.push(
<ConditionalWrap
key="delete-routing-tree"
shouldWrap={!canBeDeleted}
wrap={(children) => (
<Tooltip content={deleteTooltipContent} placement="top">
<span>{children}</span>
</Tooltip>
)}
>
<Menu.Item
label={route.name === ROOT_ROUTE_NAME ? "Reset" : t('alerting.use-create-dropdown-menu-actions.label-delete', 'Delete')}
ariaLabel="delete"
icon="trash-alt"
destructive
disabled={!canBeDeleted}
onClick={() => onDelete(route)}
/>
</ConditionalWrap>
);
}
const routeName = route.name === ROOT_ROUTE_NAME || !route.name ? 'Default Policy' : route.name;
const numberOfPolicies = countPolicies(route);
return (
<div className={styles.headerWrapper}>
<Stack direction="row" alignItems="center" gap={1}>
<Stack alignItems="center" gap={1} minWidth={0}>
<Text element="h2" variant="body" weight="medium" truncate>
{routeName}
</Text>
</Stack>
{numberOfPolicies > 0 && <>{`Contains ${numberOfPolicies} polic${numberOfPolicies > 1 ? 'ies' : 'y'}`}</>}
{provisioned && (
<ProvisioningBadge
tooltip
provenance={getAnnotation(route[ROUTES_META_SYMBOL] ?? {}, K8sAnnotations.Provenance)}
/>
)}
<Spacer />
<LinkButton
tooltipPlacement="top"
tooltip={provisioned ? 'Provisioned routing trees cannot be edited in the UI' : undefined}
variant="secondary"
size="sm"
icon={canEdit ? 'pen' : 'eye'}
type="button"
data-testid={`${canEdit ? 'edit' : 'view'}-action`}
href={`/alerting/notifications/routes/${encodeURIComponent(route.name ?? '')}/edit`}
>
{canEdit ? 'Edit' : 'View'}
</LinkButton>
{menuActions.length > 0 && (
<Dropdown overlay={<Menu>{menuActions}</Menu>}>
<MoreButton aria-label={`More actions for routing tree "${route.name ?? ''}"`} />
</Dropdown>
)}
</Stack>
{ExportDrawer}
</div>
);
};
function countPolicies(route: Route): number {
let count = 0;
if (route.routes) {
count += route.routes.length;
route.routes.forEach((subRoute) => {
count += countPolicies(subRoute);
});
}
return count;
}
const getStyles = (theme: GrafanaTheme2) => ({
tabContent: css({
marginTop: theme.spacing(2),
}),
routingTreeWrapper: css({
borderRadius: theme.shape.radius.default,
border: `solid 1px ${theme.colors.border.weak}`,
borderBottom: 'none',
}),
headerWrapper: css({
background: `${theme.colors.background.secondary}`,
padding: `${theme.spacing(1)} ${theme.spacing(1.5)}`,
borderBottom: `solid 1px ${theme.colors.border.weak}`,
borderTopLeftRadius: `${theme.shape.radius.default}`,
borderTopRightRadius: `${theme.shape.radius.default}`,
}),
routingTreeMetadataWrapper: css({
position: 'relative',
background: `${theme.colors.background.primary}`,
padding: `${theme.spacing(1)} ${theme.spacing(1.5)}`,
borderBottom: `solid 1px ${theme.colors.border.weak}`,
}),
});
interface QueryParamValues {
@@ -402,10 +402,10 @@ export const alertRuleApi = alertingApi.injectEndpoints({
}),
keepUnusedDataFor: 0,
}),
exportPolicies: build.query<string, { format: ExportFormats }>({
query: ({ format }) => ({
exportPolicies: build.query<string, { routeName?: string, format: ExportFormats }>({
query: ({ routeName, format }) => ({
url: `/api/v1/provisioning/policies/export/`,
params: { format: format },
params: { format: format, routeName: routeName },
responseType: 'text',
}),
keepUnusedDataFor: 0,
@@ -9,12 +9,14 @@ import { FileExportPreview } from './FileExportPreview';
import { GrafanaExportDrawer } from './GrafanaExportDrawer';
import { ExportFormats, allGrafanaExportProviders } from './providers';
interface GrafanaPoliciesPreviewProps {
routeName?: string;
exportFormat: ExportFormats;
onClose: () => void;
}
const GrafanaPoliciesExporterPreview = ({ exportFormat, onClose }: GrafanaPoliciesPreviewProps) => {
const GrafanaPoliciesExporterPreview = ({ routeName = '', exportFormat, onClose }: GrafanaPoliciesPreviewProps) => {
const { currentData: policiesDefinition = '', isFetching } = alertRuleApi.useExportPoliciesQuery({
routeName: routeName,
format: exportFormat,
});
@@ -35,10 +37,11 @@ const GrafanaPoliciesExporterPreview = ({ exportFormat, onClose }: GrafanaPolici
};
interface GrafanaPoliciesExporterProps {
routeName?: string;
onClose: () => void;
}
export const GrafanaPoliciesExporter = ({ onClose }: GrafanaPoliciesExporterProps) => {
export const GrafanaPoliciesExporter = ({ routeName = '', onClose }: GrafanaPoliciesExporterProps) => {
const [activeTab, setActiveTab] = useState<ExportFormats>('yaml');
return (
@@ -48,7 +51,7 @@ export const GrafanaPoliciesExporter = ({ onClose }: GrafanaPoliciesExporterProp
onClose={onClose}
formatProviders={Object.values(allGrafanaExportProviders)}
>
<GrafanaPoliciesExporterPreview exportFormat={activeTab} onClose={onClose} />
<GrafanaPoliciesExporterPreview exportFormat={activeTab} onClose={onClose} routeName={routeName}/>
</GrafanaExportDrawer>
);
};
@@ -3,7 +3,7 @@ import { Controller, useForm } from 'react-hook-form';
import { ContactPointSelector as GrafanaManagedContactPointSelector } from '@grafana/alerting/unstable';
import { Trans, t } from '@grafana/i18n';
import { Collapse, Field, Link, MultiSelect, useStyles2 } from '@grafana/ui';
import { Collapse, Field, Input, Link, MultiSelect, useStyles2 } from '@grafana/ui';
import { ExternalAlertmanagerContactPointSelector } from 'app/features/alerting/unified/components/notification-policies/ContactPointSelector';
import { handleContactPointSelect } from 'app/features/alerting/unified/components/notification-policies/utils';
import { RouteWithID } from 'app/plugins/datasource/alertmanager/types';
@@ -30,9 +30,10 @@ export interface AmRootRouteFormProps {
actionButtons: ReactNode;
onSubmit: (route: Partial<FormAmRoute>) => void;
route: RouteWithID;
showNameField?: boolean;
}
export const AmRootRouteForm = ({ actionButtons, alertManagerSourceName, onSubmit, route }: AmRootRouteFormProps) => {
export const AmRootRouteForm = ({ actionButtons, alertManagerSourceName, onSubmit, route, showNameField }: AmRootRouteFormProps) => {
const styles = useStyles2(getFormStyles);
const [isTimingOptionsExpanded, setIsTimingOptionsExpanded] = useState(false);
const { isGrafanaAlertmanager } = useAlertmanager();
@@ -55,6 +56,30 @@ export const AmRootRouteForm = ({ actionButtons, alertManagerSourceName, onSubmi
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
{showNameField && (<Field
required
label={t('alerting.am-root-route-form.name', 'Name')}
description={t(
'alerting.am-root-route-form.description-unique-route',
'A unique name for the routing tree'
)}
invalid={!!errors.name}
error={errors.name?.message}
>
<Input
{...register('name', {
required: true,
validate: (value) => {
if (!value || value.trim().length === 0) {
return 'Name is required';
}
return true
},
})}
className={styles.input}
data-testid="routing-tree-name"
/>
</Field>)}
<Field
label={t('alerting.am-root-route-form.label-default-contact-point', 'Default contact point')}
invalid={Boolean(errors.receiver) ? true : undefined}
@@ -0,0 +1,39 @@
import { useParams } from 'react-router-dom-v5-compat';
import { Alert } from '@grafana/ui';
import { withPageErrorBoundary } from '../../withPageErrorBoundary';
import { AlertmanagerPageWrapper } from '../AlertingPageWrapper';
import { NotificationPoliciesTree } from './NotificationPoliciesTree';
import { ROOT_ROUTE_NAME } from '../../utils/k8s/constants';
const EditRoutingTree = () => {
const { name = '' } = useParams();
const routeName = decodeURIComponent(name);
if (!routeName) {
return (
<Alert severity="error" title={'Routing tree not found'}>
{'Sorry, this routing tree does not seem to exist.'}
</Alert>
);
}
return <NotificationPoliciesTree routeName={routeName} />;
};
function EditRoutingTreePage() {
const { name = '' } = useParams();
const routeName = name === ROOT_ROUTE_NAME ? "Default Policy" : decodeURIComponent(name);
const pageNav = {
text: routeName,
};
return (
<AlertmanagerPageWrapper navId="am-routes" pageNav={pageNav} accessType="notification">
<EditRoutingTree />
</AlertmanagerPageWrapper>
);
}
export default withPageErrorBoundary(EditRoutingTreePage);
@@ -298,10 +298,10 @@ const useAlertGroupsModal = (
return [modalElement, handleShow, handleDismiss];
};
const UpdatingModal: FC<Pick<ModalProps, 'isOpen'>> = ({ isOpen }) => (
export const UpdatingModal: FC<Pick<ModalProps, 'isOpen' | 'onDismiss'>> = ({ isOpen, onDismiss = () => {}} ) => (
<Modal
isOpen={isOpen}
onDismiss={() => {}}
onDismiss={onDismiss}
closeOnBackdropClick={false}
closeOnEscape={false}
ariaLabel={t('alerting.policies.update.updating', 'Updating...')}
@@ -33,7 +33,11 @@ import {
useUpdateExistingNotificationPolicy,
} from './useNotificationPolicyRoute';
export const NotificationPoliciesList = () => {
interface NotificationPoliciesTreeProps {
routeName?: string;
}
export const NotificationPoliciesTree = ({ routeName }: NotificationPoliciesTreeProps) => {
const appNotification = useAppNotification();
const [contactPointsSupported, canSeeContactPoints] = useAlertmanagerAbility(AlertmanagerAction.ViewContactPoint);
@@ -53,16 +57,11 @@ export const NotificationPoliciesList = () => {
);
const {
currentData,
currentData: defaultPolicy,
isLoading,
error: fetchPoliciesError,
refetch: refetchNotificationPolicyRoute,
} = useNotificationPolicyRoute({ alertmanager: selectedAlertmanager ?? '' });
// We make the assumption that the first policy is the default one
// At the time of writing, this will be always the case for the AM config response, and the K8S API
// TODO in the future: Generalise the component to support any number of "root" policies
const [defaultPolicy] = currentData ?? [];
} = useNotificationPolicyRoute({ alertmanager: selectedAlertmanager ?? '' }, routeName);
// deleting policies
const [deleteNotificationPolicy, deleteNotificationPolicyState] = useDeleteNotificationPolicy({
@@ -140,7 +139,7 @@ export const NotificationPoliciesList = () => {
}
async function handleDelete(route: RouteWithID) {
await deleteNotificationPolicy.execute(route.id);
await deleteNotificationPolicy.execute(route);
handleActionResult({ error: deleteNotificationPolicyState.error });
}
@@ -151,7 +150,7 @@ export const NotificationPoliciesList = () => {
) {
await addNotificationPolicy.execute({
partialRoute,
referenceRouteIdentifier: referenceRoute.id,
referenceRoute: referenceRoute,
insertPosition,
});
handleActionResult({ error: addNotificationPolicyState.error });
@@ -49,8 +49,9 @@ import { Spacer } from '../Spacer';
import { GrafanaPoliciesExporter } from '../export/GrafanaPoliciesExporter';
import { Matchers } from './Matchers';
import { RoutesMatchingFilters } from './NotificationPoliciesList';
import { RoutesMatchingFilters } from './NotificationPoliciesTree';
import { TimingOptions } from './timingOptions';
import { ROOT_ROUTE_NAME } from '../../utils/k8s/constants';
const POLICIES_PER_PAGE = 20;
@@ -81,6 +82,7 @@ interface PolicyComponentProps {
) => void;
isAutoGenerated?: boolean;
isDefaultPolicy?: boolean;
hideChildren? : boolean;
}
const Policy = (props: PolicyComponentProps) => {
@@ -103,6 +105,7 @@ const Policy = (props: PolicyComponentProps) => {
onShowAlertInstances,
isAutoGenerated = false,
isDefaultPolicy = false,
hideChildren = false,
} = props;
const styles = useStyles2(getStyles);
@@ -134,7 +137,7 @@ const Policy = (props: PolicyComponentProps) => {
const actualContactPoint = contactPoint ?? inheritedProperties?.receiver ?? '';
const contactPointErrors = contactPointsState ? getContactPointErrors(actualContactPoint, contactPointsState) : [];
const allChildPolicies = currentRoute.routes ?? [];
const allChildPolicies = hideChildren ? []: currentRoute.routes ?? [];
// filter child policies that match
const childPolicies = filtersApplied
@@ -239,7 +242,7 @@ const Policy = (props: PolicyComponentProps) => {
/>
) : null}
{isImmutablePolicy && (
<>{isAutogeneratedPolicyRoot ? <AutogeneratedRootIndicator /> : <DefaultPolicyIndicator />}</>
<>{isAutogeneratedPolicyRoot ? <AutogeneratedRootIndicator /> : <DefaultPolicyIndicator route={currentRoute} />}</>
)}
{!isImmutablePolicy && (
<>
@@ -395,7 +398,7 @@ const Policy = (props: PolicyComponentProps) => {
</>
)}
</div>
{showExportDrawer && <GrafanaPoliciesExporter onClose={toggleShowExportDrawer} />}
{showExportDrawer && <GrafanaPoliciesExporter routeName={currentRoute.name == ROOT_ROUTE_NAME || !currentRoute.name ? "" : currentRoute.name} onClose={toggleShowExportDrawer} />}
</Stack>
);
};
@@ -421,7 +424,7 @@ interface MetadataRowProps {
) => void;
}
function MetadataRow({
export function MetadataRow({
numberOfAlertInstances,
isDefaultPolicy,
timingOptions,
@@ -691,17 +694,23 @@ const AllMatchesIndicator: FC = () => {
);
};
export function DefaultPolicyIndicator() {
type DefaultPolicyIndicatorProps = { route?: RouteWithID };
export const DefaultPolicyIndicator: FC<DefaultPolicyIndicatorProps> = ({route={}}) => {
const styles = useStyles2(getStyles);
return (
<>
<Text element="h2" variant="body" weight="medium">
<Trans i18nKey="alerting.policies.default-policy.title">Default policy</Trans>
{ route.name == ROOT_ROUTE_NAME || !route.name ?
<Trans i18nKey="alerting.policies.default-policy.title">Default policy</Trans> :
`Default policy for '${route.name}'`
}
</Text>
<span className={styles.metadata}>
<Trans i18nKey="alerting.policies.default-policy.description">
All alert instances will be handled by the default policy if no other matching policies are found.
</Trans>
{ route.name == ROOT_ROUTE_NAME || !route.name ?
<Trans i18nKey="alerting.policies.default-policy.description">All alert instances will be handled by the default policy if no other matching policies are found.</Trans> :
"All alert instances associated with this Route will be handled by this default policy if no other matching policies are found."
}
</span>
</>
);
@@ -0,0 +1,192 @@
import { useCallback, useMemo, useState } from 'react';
import { Trans, t } from '@grafana/i18n';
import { Button, Modal, ModalProps, useStyles2 } from '@grafana/ui';
import { stringifyErrorLike } from '../../../utils/misc';
import { FormAmRoute } from '../../../types/amroutes';
import { AmRootRouteForm } from '../EditDefaultPolicyForm';
import { UpdatingModal } from '../Modals';
import { getFormStyles } from '../formStyles';
import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
import { RouteWithID } from '../../../../../../plugins/datasource/alertmanager/types';
import { defaultGroupBy } from '../../../utils/amroutes';
/**
* This hook controls the delete modal for routing trees, showing loading and error states when appropriate
*/
export const useDeleteRoutingTreeModal = (
handleDelete: ({ name, resourceVersion }: { name: string; resourceVersion?: string }) => Promise<unknown>
) => {
const [showModal, setShowModal] = useState(false);
const [routingTree, setRoutingTree] = useState<{ name: string; resourceVersion?: string }>();
const [error, setError] = useState<unknown | undefined>();
const [isLoading, setIsLoading] = useState(false);
const handleDismiss = useCallback(() => {
if (isLoading) {
return;
}
setRoutingTree(undefined);
setShowModal(false);
setError(undefined);
}, [isLoading]);
const handleShow = useCallback(({ name, resourceVersion }: { name: string; resourceVersion?: string }) => {
setRoutingTree({ name, resourceVersion });
setShowModal(true);
setError(undefined);
}, []);
const handleSubmit = useCallback(() => {
if (routingTree) {
setIsLoading(true);
handleDelete(routingTree)
.then(() => setShowModal(false))
.catch(setError)
.finally(() => {
setIsLoading(false);
});
}
}, [handleDelete, routingTree]);
const modalElement = useMemo(() => {
if (error) {
return <ErrorModal isOpen={showModal} onDismiss={handleDismiss} error={error} />;
}
return (
<Modal
isOpen={showModal}
onDismiss={handleDismiss}
closeOnBackdropClick={!isLoading}
closeOnEscape={!isLoading}
title={'Delete routing tree'}
>
<p>Deleting this routing tree will permanently remove it.</p>
<p>Are you sure you want to delete this routing tree?</p>
<Modal.ButtonRow>
<Button type="button" variant="destructive" onClick={handleSubmit} disabled={isLoading}>
{isLoading ? 'Deleting...' : 'Yes, delete routing tree'}
</Button>
<Button type="button" variant="secondary" onClick={handleDismiss} disabled={isLoading}>
<Trans i18nKey="alerting.common.cancel">Cancel</Trans>
</Button>
</Modal.ButtonRow>
</Modal>
);
}, [error, handleDismiss, handleSubmit, isLoading, showModal]);
return [modalElement, handleShow, handleDismiss] as const;
};
const emptyRouteWithID = {
id: '',
name: '',
group_by: defaultGroupBy,
}
/**
* This hook controls the create modal for routing trees, showing loading and error states when appropriate
*/
export const useCreateRoutingTreeModal = (handleCreate: (route: Partial<FormAmRoute>) => Promise<unknown>) => {
const styles = useStyles2(getFormStyles);
const [showModal, setShowModal] = useState(false);
const [route, setRoute] = useState<RouteWithID>(emptyRouteWithID);
const [error, setError] = useState<unknown | undefined>();
const [isLoading, setIsLoading] = useState(false);
const handleDismiss = useCallback(() => {
if (isLoading) {
return;
}
setShowModal(false);
setError(undefined);
setRoute(emptyRouteWithID);
}, [isLoading]);
const handleShow = useCallback(() => {
setShowModal(true);
setError(undefined);
setRoute(emptyRouteWithID);
}, []);
const handleSubmit = useCallback(
(newRoute: Partial<FormAmRoute>) => {
if (newRoute) {
setIsLoading(true);
handleCreate(newRoute)
.then(() => setShowModal(false))
.catch(setError)
.finally(() => {
setIsLoading(false);
});
}
},
[handleCreate]
);
const modalElement = useMemo(() => {
if (error) {
return <ErrorModal isOpen={showModal} onDismiss={handleDismiss} error={error} />;
}
if (isLoading) {
return <UpdatingModal isOpen={showModal} onDismiss={handleDismiss} />;
}
return (
<Modal
isOpen={showModal}
onDismiss={handleDismiss}
closeOnBackdropClick={true}
closeOnEscape={true}
title={'Create routing tree'}
>
<AmRootRouteForm
route={route}
showNameField={true}
onSubmit={handleSubmit}
alertManagerSourceName={GRAFANA_RULES_SOURCE_NAME}
actionButtons={
<Modal.ButtonRow>
<Button type="button" variant="secondary" onClick={handleDismiss} fill="outline">
<Trans i18nKey="alerting.common.cancel">Cancel</Trans>
</Button>
<Button type="submit">
<Trans i18nKey="alerting.policies.save-policy">Add routing tree</Trans>
</Button>
</Modal.ButtonRow>
}
/>
</Modal>
);
}, [route, error, handleSubmit, handleDismiss, isLoading, showModal, styles.input]);
return [modalElement, handleShow, handleDismiss] as const;
};
interface ErrorModalProps extends Pick<ModalProps, 'isOpen' | 'onDismiss'> {
error: unknown;
}
const ErrorModal = ({ isOpen, onDismiss, error }: ErrorModalProps) => {
return (
<Modal
isOpen={isOpen}
onDismiss={onDismiss}
closeOnBackdropClick={true}
closeOnEscape={true}
title={t('alerting.error-modal.title-something-went-wrong', 'Something went wrong')}
>
<p>
<Trans i18nKey="alerting.error-modal.failed-to-update-your-configuration">
Failed to update your configuration:
</Trans>
</p>
<pre>
<code>{stringifyErrorLike(error)}</code>
</pre>
</Modal>
);
};
@@ -0,0 +1,70 @@
import { css } from '@emotion/css';
import { useCallback, useState } from 'react';
import { useDebounce } from 'react-use';
import { Trans, t } from '@grafana/i18n';
import { Button, Field, Icon, Input, Stack, useStyles2 } from '@grafana/ui';
import { useURLSearchParams } from '../../../hooks/useURLSearchParams';
const RoutingTreeFilter = () => {
const styles = useStyles2(getStyles);
const [searchParams, setSearchParams] = useURLSearchParams();
const defaultValue = searchParams.get('search') ?? '';
const [searchValue, setSearchValue] = useState(defaultValue);
const [_, cancel] = useDebounce(
() => {
setSearchParams({ search: searchValue }, true);
},
300,
[setSearchParams, searchValue]
);
const clear = useCallback(() => {
cancel();
setSearchValue('');
setSearchParams({ search: '' }, true);
}, [cancel, setSearchParams]);
const hasInput = Boolean(defaultValue);
return (
<Stack direction="row" alignItems="end" gap={0.5}>
<Field
className={styles.noBottom}
label={'Search by name or receiver'}
>
<Input
aria-label={'search routing trees'}
placeholder={t('alerting.contact-points-filter.placeholder-search', 'Search')}
width={46}
prefix={<Icon name="search" />}
onChange={(event) => {
setSearchValue(event.currentTarget.value);
}}
value={searchValue}
/>
</Field>
<Button
variant="secondary"
icon="times"
onClick={() => clear()}
disabled={!hasInput}
aria-label={t('alerting.contact-points-filter.aria-label-clear', 'clear')}
>
<Trans i18nKey="alerting.contact-points-filter.clear">Clear</Trans>
</Button>
</Stack>
);
};
const getStyles = () => ({
noBottom: css({
marginBottom: 0,
}),
});
export { RoutingTreeFilter };
@@ -0,0 +1,39 @@
import { useCallback, useMemo, useState } from 'react';
import { useToggle } from 'react-use';
import { GrafanaPoliciesExporter } from '../export/GrafanaPoliciesExporter';
export const ALL_ROUTING_TREES = Symbol('all routing trees');
type ExportProps = [JSX.Element | null, (routeName: string | typeof ALL_ROUTING_TREES) => void];
export const useExportRoutingTree = (): ExportProps => {
const [routeName, setRouteName] = useState<string | typeof ALL_ROUTING_TREES | null>(null);
const [isExportDrawerOpen, toggleShowExportDrawer] = useToggle(false);
const handleClose = useCallback(() => {
setRouteName(null);
toggleShowExportDrawer(false);
}, [toggleShowExportDrawer]);
const handleOpen = (routeName: string | typeof ALL_ROUTING_TREES) => {
setRouteName(routeName);
toggleShowExportDrawer(true);
};
const drawer = useMemo(() => {
if (!routeName || !isExportDrawerOpen) {
return null;
}
if (routeName === ALL_ROUTING_TREES) {
// use this drawer when we want to export all policies
return <GrafanaPoliciesExporter onClose={handleClose} />;
} else {
// use this one for exporting a single policy
return <GrafanaPoliciesExporter routeName={routeName} onClose={handleClose} />;
}
}, [isExportDrawerOpen, handleClose, routeName]);
return [drawer, handleOpen];
};
@@ -24,6 +24,7 @@ test('k8sSubRouteToRoute', () => {
};
const expected: Route = {
name: 'test-name',
continue: false,
group_by: ['label1'],
group_interval: '5m',
@@ -35,6 +36,7 @@ test('k8sSubRouteToRoute', () => {
repeat_interval: '4h',
routes: [
{
name: 'test-name',
receiver: 'receiver2',
matchers: undefined,
object_matchers: [['label2', MatcherOperator.notEqual, 'value2']],
@@ -43,7 +45,7 @@ test('k8sSubRouteToRoute', () => {
],
};
expect(k8sSubRouteToRoute(input)).toStrictEqual(expected);
expect(k8sSubRouteToRoute(input, 'test-name')).toStrictEqual(expected);
});
test('routeToK8sSubRoute', () => {
@@ -1,18 +1,18 @@
import { pick } from 'lodash';
import { pick, uniq } from 'lodash';
import memoize from 'micro-memoize';
import { INHERITABLE_KEYS, type InheritableProperties } from '@grafana/alerting/internal';
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { MatcherOperator, ROUTES_META_SYMBOL, Route } from 'app/plugins/datasource/alertmanager/types';
import { ROUTES_META_SYMBOL, Route, RouteWithID, MatcherOperator } from 'app/plugins/datasource/alertmanager/types';
import { getAPINamespace } from '../../../../../api/utils';
import { alertmanagerApi } from '../../api/alertmanagerApi';
import { useAsync } from '../../hooks/useAsync';
import { useProduceNewAlertmanagerConfiguration } from '../../hooks/useProduceNewAlertmanagerConfig';
import {
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults,
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
generatedRoutesApi as routingTreeApi,
} from '../../openapi/routesApi.gen';
import {
@@ -32,30 +32,47 @@ import {
mergePartialAmRouteWithRouteTree,
omitRouteFromRouteTree,
} from '../../utils/routeTree';
const k8sRoutesToRoutesMemoized = memoize(k8sRoutesToRoutes, { maxSize: 1 });
import uFuzzy from '@leeoniya/ufuzzy';
import { useMemo } from 'react';
const {
useCreateNamespacedRoutingTreeMutation,
useDeleteNamespacedRoutingTreeMutation,
useListNamespacedRoutingTreeQuery,
useReplaceNamespacedRoutingTreeMutation,
useLazyListNamespacedRoutingTreeQuery,
useLazyReadNamespacedRoutingTreeQuery,
useReadNamespacedRoutingTreeQuery,
} = routingTreeApi;
const { useGetAlertmanagerConfigurationQuery } = alertmanagerApi;
export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArgs, { skip }: Skippable = {}) => {
export const useNotificationPolicyRoute = (
{ alertmanager }: BaseAlertmanagerArgs,
routeName: string = ROOT_ROUTE_NAME,
{ skip }: Skippable = {}
) => {
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const k8sRouteQuery = useListNamespacedRoutingTreeQuery(
{ namespace: getAPINamespace() },
const k8sRouteQuery = useReadNamespacedRoutingTreeQuery(
{ namespace: getAPINamespace(), name: routeName },
{
skip: skip || !k8sApiSupported,
selectFromResult: (result) => {
return {
...result,
currentData: result.currentData ? k8sRoutesToRoutesMemoized(result.currentData.items) : undefined,
data: result.data ? k8sRoutesToRoutesMemoized(result.data.items) : undefined,
};
const { data, currentData, ...rest } = result;
const transformed = useMemo(() => {
return data ? k8sRouteToRoute(data) : data;
}, [data]);
const transformedCurrent = useMemo(() => {
return currentData ? k8sRouteToRoute(currentData) : currentData;
}, [currentData]);
return {
...rest,
data: transformed,
currentData: transformedCurrent,
};
},
}
);
@@ -66,10 +83,10 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
return {
...result,
currentData: result.currentData?.alertmanager_config?.route
? [parseAmConfigRoute(result.currentData.alertmanager_config.route)]
? parseAmConfigRoute(result.currentData.alertmanager_config.route)
: undefined,
data: result.data?.alertmanager_config?.route
? [parseAmConfigRoute(result.data.alertmanager_config.route)]
? parseAmConfigRoute(result.data.alertmanager_config.route)
: undefined,
};
},
@@ -78,6 +95,32 @@ export const useNotificationPolicyRoute = ({ alertmanager }: BaseAlertmanagerArg
return k8sApiSupported ? k8sRouteQuery : amConfigQuery;
};
export const useListNotificationPolicyRoutes = ({ skip }: Skippable = {}) => {
return useListNamespacedRoutingTreeQuery(
{ namespace: getAPINamespace() },
{
skip: skip,
selectFromResult: (result) => {
const { data, currentData, ...rest } = result;
const transformed = useMemo(() => {
return data ? data.items.map(k8sRouteToRoute) : data;
}, [data]);
const transformedCurrent = useMemo(() => {
return currentData ? currentData.items.map(k8sRouteToRoute) : currentData;
}, [currentData]);
return {
...rest,
data: transformed,
currentData: transformedCurrent,
};
},
}
);
};
const parseAmConfigRoute = memoize((route: Route): Route => {
return {
...route,
@@ -91,25 +134,26 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
const updateUsingK8sApi = useAsync(async (update: Partial<FormAmRoute>) => {
const namespace = getAPINamespace();
const result = await listNamespacedRoutingTree({ namespace });
const name = update.name ?? ROOT_ROUTE_NAME;
const result = await readNamespacedRoutingTree({ namespace, name: name });
const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
const rootTree = result.data;
if (!rootTree) {
throw new Error(`no root route found for namespace ${namespace}`);
throw new Error(`no root route found for namespace ${namespace} and name ${name}`);
}
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
const newRouteTree = mergePartialAmRouteWithRouteTree(alertmanager, update, rootRouteWithIdentifiers);
// Create the K8s route object
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
return updatedNamespacedRoute({
name: ROOT_ROUTE_NAME,
name: name,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
}).unwrap();
@@ -126,33 +170,34 @@ export function useUpdateExistingNotificationPolicy({ alertmanager }: BaseAlertm
export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
const deleteFromK8sApi = useAsync(async (id: string) => {
const deleteFromK8sApi = useAsync(async (route: RouteWithID) => {
const namespace = getAPINamespace();
const result = await listNamespacedRoutingTree({ namespace });
const name = route.name ?? ROOT_ROUTE_NAME;
const result = await readNamespacedRoutingTree({ namespace, name: name });
const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
const rootTree = result.data;
if (!rootTree) {
throw new Error(`no root route found for namespace ${namespace}`);
}
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
const newRouteTree = omitRouteFromRouteTree(id, rootRouteWithIdentifiers);
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
const newRouteTree = omitRouteFromRouteTree(route.id, rootRouteWithIdentifiers);
// Create the K8s route object
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
return updatedNamespacedRoute({
name: ROOT_ROUTE_NAME,
name: name,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: routeObject,
}).unwrap();
});
const deleteFromAlertmanagerConfiguration = useAsync(async (id: string) => {
const action = deleteRouteAction({ id });
const deleteFromAlertmanagerConfiguration = useAsync(async (route: RouteWithID) => {
const action = deleteRouteAction({ id: route.id });
return produceNewAlertmanagerConfiguration(action);
});
@@ -162,32 +207,33 @@ export function useDeleteNotificationPolicy({ alertmanager }: BaseAlertmanagerAr
export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs) {
const k8sApiSupported = shouldUseK8sApi(alertmanager);
const [produceNewAlertmanagerConfiguration] = useProduceNewAlertmanagerConfiguration();
const [listNamespacedRoutingTree] = useLazyListNamespacedRoutingTreeQuery();
const [readNamespacedRoutingTree] = useLazyReadNamespacedRoutingTreeQuery();
const [updatedNamespacedRoute] = useReplaceNamespacedRoutingTreeMutation();
const addToK8sApi = useAsync(
async ({
partialRoute,
referenceRouteIdentifier,
referenceRoute,
insertPosition,
}: {
partialRoute: Partial<FormAmRoute>;
referenceRouteIdentifier: string;
referenceRoute: RouteWithID;
insertPosition: InsertPosition;
}) => {
const namespace = getAPINamespace();
const result = await listNamespacedRoutingTree({ namespace });
const name = referenceRoute.name ?? ROOT_ROUTE_NAME;
const result = await readNamespacedRoutingTree({ namespace, name: name });
const [rootTree] = result.data ? k8sRoutesToRoutesMemoized(result.data.items) : [];
const rootTree = result.data;
if (!rootTree) {
throw new Error(`no root route found for namespace ${namespace}`);
}
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(rootTree);
const rootRouteWithIdentifiers = addUniqueIdentifierToRoute(k8sRouteToRoute(rootTree));
const newRouteTree = addRouteToReferenceRoute(
alertmanager ?? '',
partialRoute,
referenceRouteIdentifier,
referenceRoute.id,
rootRouteWithIdentifiers,
insertPosition
);
@@ -196,7 +242,7 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
const routeObject = createKubernetesRoutingTreeSpec(newRouteTree);
return updatedNamespacedRoute({
name: ROOT_ROUTE_NAME,
name: name,
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
}).unwrap();
@@ -206,16 +252,16 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
const addToAlertmanagerConfiguration = useAsync(
async ({
partialRoute,
referenceRouteIdentifier,
referenceRoute,
insertPosition,
}: {
partialRoute: Partial<FormAmRoute>;
referenceRouteIdentifier: string;
referenceRoute: RouteWithID;
insertPosition: InsertPosition;
}) => {
const action = addRouteAction({
partialRoute,
referenceRouteIdentifier,
referenceRouteIdentifier: referenceRoute.id,
insertPosition,
alertmanager,
});
@@ -226,29 +272,161 @@ export function useAddNotificationPolicy({ alertmanager }: BaseAlertmanagerArgs)
return k8sApiSupported ? addToK8sApi : addToAlertmanagerConfiguration;
}
function k8sRoutesToRoutes(routes: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree[]): Route[] {
return routes?.map((route) => {
return {
...route.spec.defaults,
routes: route.spec.routes?.map(k8sSubRouteToRoute),
[ROUTES_META_SYMBOL]: {
provisioned: isK8sEntityProvisioned(route),
resourceVersion: route.metadata.resourceVersion,
name: route.metadata.name,
},
};
type DeleteRoutingTreeArgs = { name: string; resourceVersion?: string };
export function useDeleteRoutingTree() {
const [deleteNamespacedRoutingTree] = useDeleteNamespacedRoutingTreeMutation();
return useAsync(async ({ name, resourceVersion }: DeleteRoutingTreeArgs) => {
const namespace = getAPINamespace();
return deleteNamespacedRoutingTree({
name: name,
namespace,
ioK8SApimachineryPkgApisMetaV1DeleteOptions: { preconditions: { resourceVersion } },
}).unwrap();
});
}
export function useCreateRoutingTree() {
const [createNamespacedRoutingTree] = useCreateNamespacedRoutingTreeMutation();
return useAsync(async (partialFormRoute: Partial<FormAmRoute>) => {
const namespace = getAPINamespace();
const {
name,
overrideGrouping,
groupBy,
overrideTimings,
groupWaitValue,
groupIntervalValue,
repeatIntervalValue,
receiver,
} = partialFormRoute;
// This does not "inherit" from any existing route, as this is a new routing tree. If not set, it will use the system
// defaults. Currently supported by group_by, group_wait, group_interval, and repeat_interval
const USE_DEFAULTS = undefined;
const newRoute: Route = {
name: name,
group_by: overrideGrouping ? groupBy : USE_DEFAULTS,
group_wait: overrideTimings && groupWaitValue ? groupWaitValue : USE_DEFAULTS,
group_interval: overrideTimings && groupIntervalValue ? groupIntervalValue : USE_DEFAULTS,
repeat_interval: overrideTimings && repeatIntervalValue ? repeatIntervalValue : USE_DEFAULTS,
receiver: receiver,
};
// defaults(newRoute, TIMING_OPTIONS_DEFAULTS)
// Create the K8s route object
const routeObject = createKubernetesRoutingTreeSpec(newRoute);
return createNamespacedRoutingTree({
namespace,
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: cleanKubernetesRouteIDs(routeObject),
}).unwrap();
});
}
const fuzzyFinder = new uFuzzy({
intraMode: 1,
intraIns: 1,
intraSub: 1,
intraDel: 1,
intraTrn: 1,
});
export const useRootRouteSearch = (policies: Route[], search?: string | null): Route[] => {
const nameHaystack = useMemo(() => {
return policies.map((policy) => policy.name ?? '');
}, [policies]);
const receiverHaystack = useMemo(() => {
return policies.map((policy) => policy.receiver ?? '');
}, [policies]);
if (!search) {
return policies;
}
const nameHits = fuzzyFinder.filter(nameHaystack, search) ?? [];
const typeHits = fuzzyFinder.filter(receiverHaystack, search) ?? [];
const hits = [...nameHits, ...typeHits];
return uniq(hits).map((id) => policies[id]) ?? [];
};
/**
* Convert Route to K8s compatible format. Make sure we aren't sending any additional properties the API doesn't recognize
* because it will reply with excess properties in the HTTP headers
*/
export function createKubernetesRoutingTreeSpec(
rootRoute: Route
): ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree {
const inheritableDefaultProperties: InheritableProperties = pick(routeAdapter.toPackage(rootRoute), INHERITABLE_KEYS);
const name = rootRoute.name ?? ROOT_ROUTE_NAME;
const defaults: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults = {
...inheritableDefaultProperties,
// TODO: Fix types in k8s API? Fix our types to not allow empty receiver? TBC
receiver: rootRoute.receiver ?? '',
};
const routes = rootRoute.routes?.map(routeToK8sSubRoute) ?? [];
const spec = {
defaults,
routes,
};
return {
spec: spec,
metadata: {
name: name,
resourceVersion: rootRoute[ROUTES_META_SYMBOL]?.resourceVersion,
},
};
}
export const NAMED_ROOT_LABEL_NAME = '__grafana_managed_route__';
function k8sRouteToRoute(route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree): Route {
return {
...route.spec.defaults,
name: route.metadata.name,
routes: route.spec.routes?.map((subroute) => k8sSubRouteToRoute(subroute, route.metadata.name)),
// This assumes if a `NAMED_ROOT_LABEL_NAME` label exists, it will NOT go to the default route, which is a fair but
// not perfect assumption since we don't yet protect the label.
object_matchers:
route.metadata.name == ROOT_ROUTE_NAME || !route.metadata.name
? [[NAMED_ROOT_LABEL_NAME, MatcherOperator.equal, '']]
: [[NAMED_ROOT_LABEL_NAME, MatcherOperator.equal, route.metadata.name]],
[ROUTES_META_SYMBOL]: {
provisioned: isK8sEntityProvisioned(route),
resourceVersion: route.metadata.resourceVersion,
name: route.metadata.name,
metadata: route.metadata,
},
};
}
/** Helper to provide type safety for matcher operators from API */
function isValidMatcherOperator(type: string): type is MatcherOperator {
return Object.values<string>(MatcherOperator).includes(type);
}
export function k8sSubRouteToRoute(route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route): Route {
export function k8sSubRouteToRoute(
route: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
rootName?: string
): Route {
return {
...route,
routes: route.routes?.map(k8sSubRouteToRoute),
name: rootName,
routes: route.routes?.map((subroute) => k8sSubRouteToRoute(subroute, rootName)),
matchers: undefined,
object_matchers: route.matchers?.map(({ label, type, value }) => {
if (!isValidMatcherOperator(type)) {
@@ -272,34 +450,3 @@ export function routeToK8sSubRoute(route: Route): ComGithubGrafanaGrafanaPkgApis
routes: route.routes?.map(routeToK8sSubRoute),
};
}
/**
* Convert Route to K8s compatible format. Make sure we aren't sending any additional properties the API doesn't recognize
* because it will reply with excess properties in the HTTP headers
*/
export function createKubernetesRoutingTreeSpec(
rootRoute: Route
): ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree {
const inheritableDefaultProperties: InheritableProperties = pick(routeAdapter.toPackage(rootRoute), INHERITABLE_KEYS);
const defaults: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RouteDefaults = {
...inheritableDefaultProperties,
// TODO: Fix types in k8s API? Fix our types to not allow empty receiver? TBC
receiver: rootRoute.receiver ?? '',
};
const routes = rootRoute.routes?.map(routeToK8sSubRoute) ?? [];
const spec = {
defaults,
routes,
};
return {
spec: spec,
metadata: {
name: ROOT_ROUTE_NAME,
resourceVersion: rootRoute[ROUTES_META_SYMBOL]?.resourceVersion,
},
};
}
@@ -97,7 +97,7 @@ export function NotificationPolicyDrawer({
)}
</Stack>
<TextLink href={createRelativeUrl('/alerting/routes')} external inline={false}>
<TextLink href={createRelativeUrl(`/alerting/notifications/routes/${encodeURIComponent(policyName ?? '')}/edit`)} external inline={false}>
<Trans i18nKey="alerting.notification-policy-drawer.view-notification-policy-tree">
View notification policy tree
</Trans>
@@ -1,7 +1,10 @@
import { useMemo } from 'react';
import { useAsync } from 'react-use';
import { useNotificationPolicyRoute } from 'app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute';
import {
NAMED_ROOT_LABEL_NAME,
useNotificationPolicyRoute,
} from 'app/features/alerting/unified/components/notification-policies/useNotificationPolicyRoute';
import { Labels } from '../../../../../../types/unified-alerting-dto';
import { useRouteGroupsMatcher } from '../../../useRouteGroupsMatcher';
@@ -10,16 +13,21 @@ import { GRAFANA_RULES_SOURCE_NAME } from '../../../utils/datasource';
import { normalizeRoute } from '../../../utils/notification-policies';
export const useAlertmanagerNotificationRoutingPreview = (alertmanager: string, instances: Labels[]) => {
// if a NAMED_ROOT_LABEL_NAME label exists, then we only match to that route.
const routeName = useMemo(() => {
const routeNameLabel = instances.find((instance) => instance[NAMED_ROOT_LABEL_NAME]);
return routeNameLabel?.[NAMED_ROOT_LABEL_NAME];
}, [instances]);
const {
data: currentData,
data: defaultPolicy,
isLoading: isPoliciesLoading,
error: policiesError,
} = useNotificationPolicyRoute({ alertmanager });
} = useNotificationPolicyRoute({ alertmanager }, routeName);
// this function will use a web worker to compute matching routes
const { matchInstancesToRoutes } = useRouteGroupsMatcher();
const [defaultPolicy] = currentData ?? [];
const rootRoute = useMemo(() => {
if (!defaultPolicy) {
return;
@@ -25,6 +25,32 @@ const injectedRtkApi = api
}),
providesTags: ['RoutingTree'],
}),
createNamespacedRoutingTree: build.mutation<
CreateNamespacedRoutingTreeApiResponse,
CreateNamespacedRoutingTreeApiArg
>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees`,
method: 'POST',
body: queryArg.comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree,
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
fieldManager: queryArg.fieldManager,
fieldValidation: queryArg.fieldValidation,
},
}),
invalidatesTags: ['RoutingTree'],
}),
readNamespacedRoutingTree: build.query<ReadNamespacedRoutingTreeApiResponse, ReadNamespacedRoutingTreeApiArg>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees/${queryArg.name}`,
params: {
pretty: queryArg.pretty,
},
}),
providesTags: ['RoutingTree'],
}),
replaceNamespacedRoutingTree: build.mutation<
ReplaceNamespacedRoutingTreeApiResponse,
ReplaceNamespacedRoutingTreeApiArg
@@ -42,6 +68,24 @@ const injectedRtkApi = api
}),
invalidatesTags: ['RoutingTree'],
}),
deleteNamespacedRoutingTree: build.mutation<
DeleteNamespacedRoutingTreeApiResponse,
DeleteNamespacedRoutingTreeApiArg
>({
query: (queryArg) => ({
url: `/apis/notifications.alerting.grafana.app/v0alpha1/namespaces/${queryArg['namespace']}/routingtrees/${queryArg.name}`,
method: 'DELETE',
params: {
pretty: queryArg.pretty,
dryRun: queryArg.dryRun,
gracePeriodSeconds: queryArg.gracePeriodSeconds,
ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential,
orphanDependents: queryArg.orphanDependents,
propagationPolicy: queryArg.propagationPolicy,
},
}),
invalidatesTags: ['RoutingTree'],
}),
}),
overrideExisting: false,
});
@@ -56,7 +100,7 @@ export type ListNamespacedRoutingTreeApiArg = {
/** 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. */
@@ -64,19 +108,19 @@ export type ListNamespacedRoutingTreeApiArg = {
/** 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
@@ -86,7 +130,7 @@ export type ListNamespacedRoutingTreeApiArg = {
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. */
@@ -94,6 +138,33 @@ export type ListNamespacedRoutingTreeApiArg = {
/** 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 CreateNamespacedRoutingTreeApiResponse = /** status 200 OK */
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
| /** status 202 Accepted */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
export type CreateNamespacedRoutingTreeApiArg = {
/** object name and auth scope, such as for teams and projects */
namespace: 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;
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
};
export type ReadNamespacedRoutingTreeApiResponse =
/** status 200 OK */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
export type ReadNamespacedRoutingTreeApiArg = {
/** name of the RoutingTree */
name: string;
/** object name and auth scope, such as for teams and projects */
namespace: 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 ReplaceNamespacedRoutingTreeApiResponse = /** status 200 OK */
| ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree
| /** status 201 Created */ ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
@@ -112,6 +183,28 @@ export type ReplaceNamespacedRoutingTreeApiArg = {
fieldValidation?: string;
comGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTree;
};
export type DeleteNamespacedRoutingTreeApiResponse = /** status 200 OK */
| IoK8SApimachineryPkgApisMetaV1Status
| /** status 202 Accepted */ IoK8SApimachineryPkgApisMetaV1Status;
export type DeleteNamespacedRoutingTreeApiArg = {
/** name of the RoutingTree */
name: string;
/** object name and auth scope, such as for teams and projects */
namespace: 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;
ioK8SApimachineryPkgApisMetaV1DeleteOptions: IoK8SApimachineryPkgApisMetaV1DeleteOptions;
};
export type IoK8SApimachineryPkgApisMetaV1Time = string;
export type IoK8SApimachineryPkgApisMetaV1FieldsV1 = object;
export type IoK8SApimachineryPkgApisMetaV1ManagedFieldsEntry = {
@@ -150,21 +243,21 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = {
[key: string]: string;
};
/** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.
Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
creationTimestamp?: IoK8SApimachineryPkgApisMetaV1Time;
/** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */
deletionGracePeriodSeconds?: number;
/** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.
Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
deletionTimestamp?: IoK8SApimachineryPkgApisMetaV1Time;
/** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */
finalizers?: string[];
/** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
If this field is specified and the generated name exists, the server will return a 409.
Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */
generateName?: string;
/** A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. */
@@ -178,19 +271,19 @@ export type IoK8SApimachineryPkgApisMetaV1ObjectMeta = {
/** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
name?: string;
/** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */
namespace?: string;
/** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */
ownerReferences?: IoK8SApimachineryPkgApisMetaV1OwnerReference[];
/** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.
Populated by the system. Read-only. Value must be treated as opaque by clients and . 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;
/** UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
uid?: string;
};
@@ -207,6 +300,7 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Matcher =
value: string;
};
export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route = {
active_time_intervals?: string[];
continue?: boolean;
group_by?: string[];
group_interval?: string;
@@ -227,6 +321,7 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTr
/** 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: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
/** Spec is the spec of the RoutingTree */
spec: ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTreeSpec;
};
export type IoK8SApimachineryPkgApisMetaV1ListMeta = {
@@ -247,3 +342,69 @@ export type ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1RoutingTr
kind?: string;
metadata: IoK8SApimachineryPkgApisMetaV1ListMeta;
};
export type IoK8SApimachineryPkgApisMetaV1StatusCause = {
/** 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 IoK8SApimachineryPkgApisMetaV1StatusDetails = {
/** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */
causes?: IoK8SApimachineryPkgApisMetaV1StatusCause[];
/** 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 IoK8SApimachineryPkgApisMetaV1Status = {
/** 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?: IoK8SApimachineryPkgApisMetaV1StatusDetails;
/** 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?: IoK8SApimachineryPkgApisMetaV1ListMeta;
/** 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 IoK8SApimachineryPkgApisMetaV1Preconditions = {
/** Specifies the target ResourceVersion */
resourceVersion?: string;
/** Specifies the target UID. */
uid?: string;
};
export type IoK8SApimachineryPkgApisMetaV1DeleteOptions = {
/** 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;
/** 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;
/** 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;
/** 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;
/** Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned. */
preconditions?: IoK8SApimachineryPkgApisMetaV1Preconditions;
/** 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;
};
@@ -52,7 +52,7 @@ export const routeGroupsMatcher = {
.map((matchDetails) => ({
route,
routeTree: {
metadata: { name: 'user-defined' },
metadata: { name: routeTree.name },
expandedSpec: expandedTree,
},
matchDetails,
@@ -2,6 +2,7 @@ import { MatcherFieldValue } from './silence-form';
export interface FormAmRoute {
id: string;
name?: string;
object_matchers: MatcherFieldValue[];
continue: boolean;
receiver: string;
@@ -49,6 +49,7 @@ export const commonGroupByOptions = [
export const emptyRoute: FormAmRoute = {
id: '',
name: '',
overrideGrouping: false,
groupBy: defaultGroupBy,
object_matchers: [],
@@ -63,9 +64,13 @@ export const emptyRoute: FormAmRoute = {
activeTimeIntervals: [],
};
export function addUniqueIdentifierToRoutes(routes: Route[]): RouteWithID[] {
return routes.map((policy, index) => addUniqueIdentifierToRoute(policy, policy.name ?? index.toString()));
}
// add unique identifiers to each route in the route tree, that way we can figure out what route we've edited / deleted
// ⚠️ make sure this function uses _stable_ identifiers!
export function addUniqueIdentifierToRoute(route: Route, position = '0'): RouteWithID {
export function addUniqueIdentifierToRoute(route: Route, position = route.name ?? '0'): RouteWithID {
const routeHash = hashRoute(route);
const routes = route.routes ?? [];
@@ -112,6 +117,7 @@ export const amRouteToFormAmRoute = (route: RouteWithID | undefined): FormAmRout
return {
id,
name: route.name ?? '',
// Frontend migration to use object_matchers instead of matchers, match, and match_re
object_matchers: [
...matchers,
@@ -153,13 +153,14 @@ export function findRouteInTree(
export function cleanRouteIDs<
T extends RouteWithID | Route | ComGithubGrafanaGrafanaPkgApisAlertingNotificationsV0Alpha1Route,
>(route: T): Omit<T, 'id'> {
>(route: T): Omit<T, 'id' | 'name'> {
return omit(
{
...route,
routes: route.routes?.map((route) => cleanRouteIDs(route)),
},
'id'
'id',
'name'
);
}
@@ -198,6 +199,7 @@ export function hashRoute(route: Route): string {
*/
export function stabilizeRoute(route: Route): Required<Route> {
const result: Required<Route> = {
name: route.name ?? '',
receiver: route.receiver ?? '',
group_by: route.group_by ? [...route.group_by].sort() : [],
continue: route.continue ?? false,
@@ -61,7 +61,7 @@ function useGetConfigurationForApps() {
const { data: rootRoute, isLoading: isLoadingDefaultContactPoint } = useNotificationPolicyRoute({
alertmanager: GRAFANA_RULES_SOURCE_NAME,
});
const defaultContactpoint = rootRoute?.[0].receiver || '';
const defaultContactpoint = rootRoute?.receiver || '';
const { isDone: isCreateAlertRuleDone, isLoading: isLoadingAlertCreatedDone } = useIsCreateAlertRuleDone();
// configuration checks for incidents
const {
@@ -105,4 +105,32 @@ describe('ScopesNavigationTreeLink', () => {
expect(matchingLink).toHaveAttribute('aria-current', 'page');
expect(otherLink).not.toHaveAttribute('aria-current');
});
it('shows correct icon for grafana-metricsdrilldown-app with query parameters', () => {
renderWithRouter(
<ScopesNavigationTreeLink
to="/a/grafana-metricsdrilldown-app?from=now-1h&to=now"
title="Metrics Drilldown"
id="metrics-drilldown"
/>
);
const link = screen.getByTestId('scopes-dashboards-metrics-drilldown');
// Icon should be rendered (check for SVG element which is how Icon renders)
const icon = link.querySelector('svg');
expect(icon).toBeInTheDocument();
// The link should contain the title text
expect(link).toHaveTextContent('Metrics Drilldown');
});
it('shows correct icon for grafana-metricsdrilldown-app without trailing slash', () => {
renderWithRouter(
<ScopesNavigationTreeLink to="/a/grafana-metricsdrilldown-app" title="Metrics Drilldown" id="metrics-drilldown" />
);
const link = screen.getByTestId('scopes-dashboards-metrics-drilldown');
const icon = link.querySelector('svg');
expect(icon).toBeInTheDocument();
expect(link).toHaveTextContent('Metrics Drilldown');
});
});
@@ -5,7 +5,7 @@ import { Link, useLocation } from 'react-router-dom-v5-compat';
import { GrafanaTheme2, IconName, locationUtil } from '@grafana/data';
import { Icon, useStyles2 } from '@grafana/ui';
import { isCurrentPath } from './scopeNavgiationUtils';
import { isCurrentPath, normalizePath } from './scopeNavgiationUtils';
export interface ScopesNavigationTreeLinkProps {
to: string;
@@ -36,25 +36,30 @@ export function ScopesNavigationTreeLink({ to, title, id }: ScopesNavigationTree
}
function getLinkIcon(to: string) {
// Strip base URL and normalize path
const normalizedPath = locationUtil.stripBaseFromUrl(to);
for (const [key, value] of linkMap.entries()) {
if (normalizedPath.startsWith(key)) {
return value;
}
// Check for external links before stripping base (stripBaseFromUrl removes http:// for same-origin URLs)
if (to.startsWith('http')) {
return 'external-link-alt';
}
return 'link';
// Strip base URL and normalize path (remove query params and hash)
const baseStripped = locationUtil.stripBaseFromUrl(to);
const normalizedPath = normalizePath(baseStripped);
// Check for dashboard paths with startsWith (e.g., /d/dashboard-id)
if (normalizedPath.startsWith('/d')) {
return 'apps';
}
// Use direct Map lookup for exact path matches
return linkMap.get(normalizedPath) ?? 'link';
}
const linkMap = new Map<string, IconName>([
['http', 'external-link-alt'],
['/d', 'apps'],
['/explore/metrics', 'drilldown'],
['/a/grafana-metricsdrilldown-app/', 'drilldown'],
['/a/grafana-lokiexplore-app/', 'drilldown'],
['/a/grafana-exploretraces-app/', 'drilldown'],
['/a/grafana-pyroscope-app/', 'drilldown'],
['/a/grafana-metricsdrilldown-app', 'drilldown'],
['/a/grafana-lokiexplore-app', 'drilldown'],
['/a/grafana-exploretraces-app', 'drilldown'],
['/a/grafana-pyroscope-app', 'drilldown'],
]);
const getStyles = (theme: GrafanaTheme2) => {
@@ -1,6 +1,6 @@
//DOCS: https://prometheus.io/docs/alerting/latest/configuration/
import { DataSourceJsonData, WithAccessControlMetadata } from '@grafana/data';
import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/unified/openapi/receiversApi.gen';
import { IoK8SApimachineryPkgApisMetaV1ObjectMeta } from 'app/features/alerting/unified/openapi/routesApi.gen';
import { ExtraConfiguration } from 'app/features/alerting/unified/utils/alertmanager/extraConfigs';
export const ROUTES_META_SYMBOL = Symbol('routes_metadata');
@@ -123,6 +123,7 @@ export type Receiver = GrafanaManagedContactPoint | AlertmanagerReceiver;
export type ObjectMatcher = [name: string, operator: MatcherOperator, value: string];
export type Route = {
name?: string;
receiver?: string | null;
group_by?: string[];
continue?: boolean;
@@ -147,6 +148,7 @@ export type Route = {
provisioned?: boolean;
resourceVersion?: string;
name?: string;
metadata?: IoK8SApimachineryPkgApisMetaV1ObjectMeta;
};
};
+3 -1
View File
@@ -67,8 +67,10 @@ const config: ConfigFile = {
apiImport: 'alertingApi',
filterEndpoints: [
'listNamespacedRoutingTree',
'createNamespacedRoutingTree',
'readNamespacedRoutingTree',
'replaceNamespacedRoutingTree',
'deleteCollectionNamespacedRoutingTree',
'deleteNamespacedRoutingTree',
],
exportName: 'generatedRoutesApi',
flattenArg: false,