Compare commits
19 Commits
dual-write
...
feat/mt-ap
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ef277d550 | ||
|
|
987c1fc6b6 | ||
|
|
170ac31c5a | ||
|
|
0d1e0bc21c | ||
|
|
afd84f0335 | ||
|
|
d680537ea1 | ||
|
|
78d507d285 | ||
|
|
9d1d0e72c2 | ||
|
|
fd955f90ac | ||
|
|
ccb032f376 | ||
|
|
cf452c167b | ||
|
|
39c34f85f4 | ||
|
|
9e4e93bf5e | ||
|
|
8df2debd34 | ||
|
|
d146d2c539 | ||
|
|
1bd36486e9 | ||
|
|
b99639fe7a | ||
|
|
719d779171 | ||
|
|
09d98402c4 |
1
.github/CODEOWNERS
vendored
1
.github/CODEOWNERS
vendored
@@ -1328,6 +1328,7 @@ embed.go @grafana/grafana-as-code
|
||||
/conf/provisioning/datasources/ @grafana/plugins-platform-backend
|
||||
/conf/provisioning/plugins/ @grafana/plugins-platform-backend
|
||||
/conf/provisioning/sample/ @grafana/grafana-git-ui-sync-team
|
||||
/conf/apiextensions.ini @grafana/grafana-app-platform-squad
|
||||
|
||||
# Security
|
||||
/relyance.yaml @grafana/security-team
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -135,6 +135,10 @@ profile.cov
|
||||
/pkg/operators/enterprise_*
|
||||
/pkg/operators/**/enterprise_*
|
||||
|
||||
# Enterprise apiextensions server
|
||||
pkg/registry/apis/apiextensions/*
|
||||
!pkg/registry/apis/apiextensions/register.go
|
||||
|
||||
debug.test
|
||||
/examples/*/dist
|
||||
/packaging/**/*.rpm
|
||||
|
||||
@@ -28,7 +28,7 @@ type check struct {
|
||||
PluginStore pluginstore.Store
|
||||
PluginContextProvider PluginContextProvider
|
||||
PluginClient plugins.Client
|
||||
PluginRepo repo.Service
|
||||
PluginRepo checks.PluginInfoGetter
|
||||
GrafanaVersion string
|
||||
pluginCanBeInstalledCache map[string]bool
|
||||
pluginExistsCacheMu sync.RWMutex
|
||||
@@ -39,7 +39,7 @@ func New(
|
||||
pluginStore pluginstore.Store,
|
||||
pluginContextProvider PluginContextProvider,
|
||||
pluginClient plugins.Client,
|
||||
pluginRepo repo.Service,
|
||||
pluginRepo checks.PluginInfoGetter,
|
||||
grafanaVersion string,
|
||||
) checks.Check {
|
||||
return &check{
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
type missingPluginStep struct {
|
||||
PluginStore pluginstore.Store
|
||||
PluginRepo repo.Service
|
||||
PluginRepo checks.PluginInfoGetter
|
||||
GrafanaVersion string
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/grafana/grafana-app-sdk/logging"
|
||||
advisorv0alpha1 "github.com/grafana/grafana/apps/advisor/pkg/apis/advisor/v0alpha1"
|
||||
"github.com/grafana/grafana/pkg/plugins/repo"
|
||||
)
|
||||
|
||||
// Check returns metadata about the check being executed and the list of Steps
|
||||
@@ -37,3 +38,10 @@ type Step interface {
|
||||
// Run executes the step for an item and returns a report
|
||||
Run(ctx context.Context, log logging.Logger, obj *advisorv0alpha1.CheckSpec, item any) ([]advisorv0alpha1.CheckReportFailure, error)
|
||||
}
|
||||
|
||||
// PluginInfoGetter is a minimal interface for retrieving plugin information from a repository.
|
||||
// It contains only the GetPluginsInfo method used by plugincheck and datasourcecheck.
|
||||
type PluginInfoGetter interface {
|
||||
// GetPluginsInfo will return a list of plugins from grafana.com/api/plugins.
|
||||
GetPluginsInfo(ctx context.Context, options repo.GetPluginsInfoOptions, compatOpts repo.CompatOpts) ([]repo.PluginInfo, error)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ const (
|
||||
|
||||
func New(
|
||||
pluginStore pluginstore.Store,
|
||||
pluginRepo repo.Service,
|
||||
pluginRepo checks.PluginInfoGetter,
|
||||
updateChecker pluginchecker.PluginUpdateChecker,
|
||||
pluginErrorResolver plugins.ErrorResolver,
|
||||
grafanaVersion string,
|
||||
@@ -33,7 +33,7 @@ func New(
|
||||
|
||||
type check struct {
|
||||
PluginStore pluginstore.Store
|
||||
PluginRepo repo.Service
|
||||
PluginRepo checks.PluginInfoGetter
|
||||
updateChecker pluginchecker.PluginUpdateChecker
|
||||
pluginErrorResolver plugins.ErrorResolver
|
||||
GrafanaVersion string
|
||||
|
||||
53
conf/apiextensions.ini
Normal file
53
conf/apiextensions.ini
Normal file
@@ -0,0 +1,53 @@
|
||||
; Run locally unified storage with SQLite to test
|
||||
; new API registration changes
|
||||
app_mode = development
|
||||
target = all
|
||||
|
||||
[log]
|
||||
level = debug
|
||||
|
||||
[server]
|
||||
; HTTPS is required for kubectl (but HTTP works for testing with curl)
|
||||
protocol = https
|
||||
http_port = 1111
|
||||
|
||||
[feature_toggles]
|
||||
; Enable the apiextensions feature
|
||||
apiExtensions = true
|
||||
; Enable unified storage globally
|
||||
unifiedStorage = true
|
||||
; Enable search indexing for unified storage
|
||||
unifiedStorageSearch = true
|
||||
; Enable the grafana-apiserver explicitly
|
||||
grafanaAPIServer = true
|
||||
; Enable K8s aggregator for API discovery aggregation
|
||||
; NOTE: This is an enterprise-only feature that requires TLS certificates
|
||||
; This will surface the new registered group APIs to the `/apis` endpoint.
|
||||
kubernetesAggregator = true
|
||||
|
||||
[grafana-apiserver]
|
||||
; Use unified storage backed by SQL (uses your Grafana database)
|
||||
storage_type = unified
|
||||
; Certificates for the Kubernetes aggregator (generated by hack/make-aggregator-pki.sh)
|
||||
proxy_client_cert_file = data/grafana-aggregator/client.crt
|
||||
proxy_client_key_file = data/grafana-aggregator/client.key
|
||||
|
||||
; Configure dashboards to use unified storage
|
||||
[unified_storage.dashboards.dashboard.grafana.app]
|
||||
dualWriterMode = 5
|
||||
|
||||
; Configure folders to use unified storage (required for dashboards)
|
||||
[unified_storage.folders.folder.grafana.app]
|
||||
dualWriterMode = 5
|
||||
|
||||
[database]
|
||||
; SQLite database for testing
|
||||
type = sqlite3
|
||||
path = grafana.db
|
||||
high_availability = false
|
||||
|
||||
; Will only be used for the MT grafana
|
||||
; apiextensions service
|
||||
; [auth.extended_jwt]
|
||||
; enabled = true
|
||||
; jwks_url = "http://localhost:6481/jwks"
|
||||
@@ -83,6 +83,7 @@ Most [generally available](https://grafana.com/docs/release-life-cycle/#general-
|
||||
| `reportingRetries` | Enables rendering retries for the reporting feature |
|
||||
| `externalServiceAccounts` | Automatic service account and token setup for plugins |
|
||||
| `cloudWatchBatchQueries` | Runs CloudWatch metrics queries as separate batches |
|
||||
| `dashboardNewLayouts` | Enables new dashboard layouts |
|
||||
| `pdfTables` | Enables generating table data as PDF in reporting |
|
||||
| `canvasPanelPanZoom` | Allow pan and zoom in canvas panel |
|
||||
| `alertingSaveStateCompressed` | Enables the compressed protobuf-based alert state storage. Default is enabled. |
|
||||
|
||||
@@ -30,7 +30,9 @@ refs:
|
||||
|
||||
# Datagrid
|
||||
|
||||
{{< docs/experimental product="The datagrid visualization" featureFlag="`enableDatagridEditing`" >}}
|
||||
{{< admonition type="caution" >}}
|
||||
Starting with Grafana 12.4, Datagrid is deprecated. It will be removed in version 13.0.
|
||||
{{< /admonition >}}
|
||||
|
||||
Datagrids offer you the ability to create, edit, and fine-tune data within Grafana. As such, this panel can act as a data source for other panels
|
||||
inside a dashboard.
|
||||
|
||||
2
go.mod
2
go.mod
@@ -646,7 +646,7 @@ require (
|
||||
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/apiextensions-apiserver v0.34.3 // indirect
|
||||
k8s.io/apiextensions-apiserver v0.34.3
|
||||
k8s.io/kms v0.34.3 // indirect
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
|
||||
17
go.work.sum
17
go.work.sum
@@ -737,6 +737,7 @@ github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRr
|
||||
github.com/emicklei/go-restful/v3 v3.12.1/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
|
||||
github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
|
||||
github.com/emicklei/proto v1.10.0/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A=
|
||||
github.com/emicklei/proto v1.13.2/go.mod h1:rn1FgRS/FANiZdD2djyH7TMA9jdRDcYQ9IEN9yvjX0A=
|
||||
github.com/envoyproxy/go-control-plane v0.13.4/go.mod h1:kDfuBlDVsSj2MjrLEtRWtHlsWIFcGyB2RMO44Dc5GZA=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.32.3/go.mod h1:F6hWupPfh75TBXGKA++MCT/CZHFq5r9/uwt/kQYkZfE=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw=
|
||||
@@ -992,6 +993,7 @@ github.com/grafana/nanogit v0.0.0-20250616082354-5e94194d02ed/go.mod h1:OIAAKNgG
|
||||
github.com/grafana/nanogit v0.0.0-20250619160700-ebf70d342aa5 h1:MAQ2B0cu0V1S91ZjVa7NomNZFjaR2SmdtvdwhqBtyhU=
|
||||
github.com/grafana/nanogit v0.0.0-20250619160700-ebf70d342aa5/go.mod h1:tN93IZUaAmnSWgL0IgnKdLv6DNeIhTJGvl1wvQMrWco=
|
||||
github.com/grafana/nanogit v0.0.0-20250723104447-68f58f5ecec0/go.mod h1:ToqLjIdvV3AZQa3K6e5m9hy/nsGaUByc2dWQlctB9iA=
|
||||
github.com/grafana/nanogit v0.0.0-20251106115617-c622d3e0fc4b/go.mod h1:ToqLjIdvV3AZQa3K6e5m9hy/nsGaUByc2dWQlctB9iA=
|
||||
github.com/grafana/prometheus-alertmanager v0.25.1-0.20240930132144-b5e64e81e8d3 h1:6D2gGAwyQBElSrp3E+9lSr7k8gLuP3Aiy20rweLWeBw=
|
||||
github.com/grafana/prometheus-alertmanager v0.25.1-0.20240930132144-b5e64e81e8d3/go.mod h1:YeND+6FDA7OuFgDzYODN8kfPhXLCehcpxe4T9mdnpCY=
|
||||
github.com/grafana/prometheus-alertmanager v0.25.1-0.20250331083058-4563aec7a975 h1:4/BZkGObFWZf4cLbE2Vqg/1VTz67Q0AJ7LHspWLKJoQ=
|
||||
@@ -1465,6 +1467,7 @@ github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiy
|
||||
github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g=
|
||||
github.com/schollz/progressbar/v3 v3.14.6 h1:GyjwcWBAf+GFDMLziwerKvpuS7ZF+mNTAXIB2aspiZs=
|
||||
github.com/schollz/progressbar/v3 v3.14.6/go.mod h1:Nrzpuw3Nl0srLY0VlTvC4V6RL50pcEymjy6qyJAaLa0=
|
||||
github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8=
|
||||
github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM=
|
||||
github.com/segmentio/asm v1.1.4/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/fasthash v1.0.3 h1:EI9+KE1EwvMLBWwjpRDc+fEM+prwxDYbslddQGtrmhM=
|
||||
@@ -1498,6 +1501,7 @@ github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB
|
||||
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
|
||||
github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
|
||||
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
@@ -1647,10 +1651,13 @@ go.etcd.io/etcd v0.5.0-alpha.5.0.20200910180754-dd1b699fc489 h1:1JFLBqwIgdyHN1Zt
|
||||
go.etcd.io/etcd v3.3.25+incompatible h1:V1RzkZJj9LqsJRy+TUBgpWSbZXITLB819lstuTFoZOY=
|
||||
go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI=
|
||||
go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
|
||||
go.etcd.io/etcd/api/v3 v3.6.4/go.mod h1:eFhhvfR8Px1P6SEuLT600v+vrhdDTdcfMzmnxVXXSbk=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.4/go.mod h1:sbdzr2cl3HzVmxNw//PH7aLGVtY4QySjQFuaCgcRFAI=
|
||||
go.etcd.io/etcd/client/v2 v2.305.4 h1:Dcx3/MYyfKcPNLpR4VVQUP5KgYrBeJtktBwEKkw08Ao=
|
||||
go.etcd.io/etcd/client/v2 v2.305.5/go.mod h1:zQjKllfqfBVyVStbt4FaosoX2iYd8fV/GRy/PbowgP4=
|
||||
go.etcd.io/etcd/client/v3 v3.5.0/go.mod h1:AIKXXVX/DQXtfTEqBryiLTUXwON+GuvO6Z7lLS/oTh0=
|
||||
go.etcd.io/etcd/client/v3 v3.6.4/go.mod h1:jaNNHCyg2FdALyKWnd7hxZXZxZANb0+KGY+YQaEMISo=
|
||||
go.etcd.io/etcd/raft/v3 v3.5.5/go.mod h1:76TA48q03g1y1VpTue92jZLr9lIHKUNcYdZOOGyx8rI=
|
||||
go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA=
|
||||
go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o=
|
||||
@@ -1975,6 +1982,7 @@ golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sU
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
|
||||
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
|
||||
golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
|
||||
golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8/go.mod h1:CQ1k9gNrJ50XIzaKCRR2hssIjF07kZFEiieALBM/ARQ=
|
||||
@@ -2257,24 +2265,30 @@ k8s.io/api v0.26.2/go.mod h1:1kjMQsFE+QHPfskEcVNgL3+Hp88B80uj0QtSOlj8itU=
|
||||
k8s.io/api v0.33.3/go.mod h1:01Y/iLUjNBM3TAvypct7DIj0M0NIZc+PzAHCIo0CYGE=
|
||||
k8s.io/api v0.34.0/go.mod h1:YzgkIzOOlhl9uwWCZNqpw6RJy9L2FK4dlJeayUoydug=
|
||||
k8s.io/api v0.34.1/go.mod h1:SB80FxFtXn5/gwzCoN6QCtPD7Vbu5w2n1S0J5gFfTYk=
|
||||
k8s.io/api v0.34.2/go.mod h1:MMBPaWlED2a8w4RSeanD76f7opUoypY8TFYkSM+3XHw=
|
||||
k8s.io/apiextensions-apiserver v0.33.3/go.mod h1:oROuctgo27mUsyp9+Obahos6CWcMISSAPzQ77CAQGz8=
|
||||
k8s.io/apiextensions-apiserver v0.34.1/go.mod h1:hP9Rld3zF5Ay2Of3BeEpLAToP+l4s5UlxiHfqRaRcMc=
|
||||
k8s.io/apiextensions-apiserver v0.34.2/go.mod h1:398CJrsgXF1wytdaanynDpJ67zG4Xq7yj91GrmYN2SE=
|
||||
k8s.io/apimachinery v0.26.2/go.mod h1:ats7nN1LExKHvJ9TmwootT00Yz05MuYqPXEXaVeOy5I=
|
||||
k8s.io/apimachinery v0.33.3/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM=
|
||||
k8s.io/apimachinery v0.34.0/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw=
|
||||
k8s.io/apimachinery v0.34.1/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw=
|
||||
k8s.io/apimachinery v0.34.2/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw=
|
||||
k8s.io/apiserver v0.26.2/go.mod h1:GHcozwXgXsPuOJ28EnQ/jXEM9QeG6HT22YxSNmpYNh8=
|
||||
k8s.io/apiserver v0.33.3/go.mod h1:05632ifFEe6TxwjdAIrwINHWE2hLwyADFk5mBsQa15E=
|
||||
k8s.io/apiserver v0.34.1/go.mod h1:eOOc9nrVqlBI1AFCvVzsob0OxtPZUCPiUJL45JOTBG0=
|
||||
k8s.io/apiserver v0.34.2/go.mod h1:gqJQy2yDOB50R3JUReHSFr+cwJnL8G1dzTA0YLEqAPI=
|
||||
k8s.io/client-go v0.26.2/go.mod h1:u5EjOuSyBa09yqqyY7m3abZeovO/7D/WehVVlZ2qcqU=
|
||||
k8s.io/client-go v0.33.3/go.mod h1:luqKBQggEf3shbxHY4uVENAxrDISLOarxpTKMiUuujg=
|
||||
k8s.io/client-go v0.34.0/go.mod h1:ozgMnEKXkRjeMvBZdV1AijMHLTh3pbACPvK7zFR+QQY=
|
||||
k8s.io/client-go v0.34.1/go.mod h1:kA8v0FP+tk6sZA0yKLRG67LWjqufAoSHA2xVGKw9Of8=
|
||||
k8s.io/client-go v0.34.2/go.mod h1:2VYDl1XXJsdcAxw7BenFslRQX28Dxz91U9MWKjX97fE=
|
||||
k8s.io/code-generator v0.34.3 h1:6ipJKsJZZ9q21BO8I2jEj4OLN3y8/1n4aihKN0xKmQk=
|
||||
k8s.io/code-generator v0.34.3/go.mod h1:oW73UPYpGLsbRN8Ozkhd6ZzkF8hzFCiYmvEuWZDroI4=
|
||||
k8s.io/component-base v0.26.2/go.mod h1:DxbuIe9M3IZPRxPIzhch2m1eT7uFrSBJUBuVCQEBivs=
|
||||
k8s.io/component-base v0.33.3/go.mod h1:ktBVsBzkI3imDuxYXmVxZ2zxJnYTZ4HAsVj9iF09qp4=
|
||||
k8s.io/component-base v0.34.1/go.mod h1:mknCpLlTSKHzAQJJnnHVKqjxR7gBeHRv0rPXA7gdtQ0=
|
||||
k8s.io/component-base v0.34.2/go.mod h1:9xw2FHJavUHBFpiGkZoKuYZ5pdtLKe97DEByaA+hHbM=
|
||||
k8s.io/cri-api v0.27.1/go.mod h1:+Ts/AVYbIo04S86XbTD73UPp/DkTiYxtsFeOFEu32L0=
|
||||
k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6 h1:4s3/R4+OYYYUKptXPhZKjQ04WJ6EhQQVFdjOFvCazDk=
|
||||
k8s.io/gengo/v2 v2.0.0-20250604051438-85fd79dbfd9f h1:SLb+kxmzfA87x4E4brQzB33VBbT2+x7Zq9ROIHmGn9Q=
|
||||
@@ -2288,7 +2302,9 @@ k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y=
|
||||
k8s.io/klog/v2 v2.80.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
|
||||
k8s.io/klog/v2 v2.90.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
|
||||
k8s.io/kms v0.34.1/go.mod h1:s1CFkLG7w9eaTYvctOxosx88fl4spqmixnNpys0JAtM=
|
||||
k8s.io/kms v0.34.2/go.mod h1:s1CFkLG7w9eaTYvctOxosx88fl4spqmixnNpys0JAtM=
|
||||
k8s.io/kube-aggregator v0.34.1/go.mod h1:RU8j+5ERfp0h+gIvWtxRPfsa5nK7rboDm8RST8BJfYQ=
|
||||
k8s.io/kube-aggregator v0.34.2/go.mod h1:/tp4cc/1p2AvICsS4mjjSJakdrbhcGbRmj0mdHTdR2Q=
|
||||
k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8=
|
||||
k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b/go.mod h1:UZ2yyWbFTpuhSbFhv24aGNOdoRdJZgsIObGBUaYVsts=
|
||||
k8s.io/utils v0.0.0-20230220204549-a5ecb0141aa5/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
|
||||
@@ -2324,6 +2340,7 @@ rsc.io/binaryregexp v0.2.0 h1:HfqmD5MEmC0zvwBuF187nq9mdnXjXsSivRiXN7SmRkE=
|
||||
rsc.io/pdf v0.1.1 h1:k1MczvYDUvJBe93bYd7wrZLLUEcLZAuF824/I4e5Xr4=
|
||||
rsc.io/quote/v3 v3.1.0 h1:9JKUTTIUgS6kzR9mK1YuGKv6Nl+DijDNIc0ghT58FaY=
|
||||
rsc.io/sampler v1.3.0 h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/QiW4=
|
||||
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw=
|
||||
sigs.k8s.io/controller-runtime v0.22.1 h1:Ah1T7I+0A7ize291nJZdS1CabF/lB4E++WizgV24Eqg=
|
||||
sigs.k8s.io/controller-runtime v0.22.1/go.mod h1:FwiwRjkRPbiN+zp2QRp7wlTCzbUXxZ/D4OzuQUDwBHY=
|
||||
sigs.k8s.io/controller-runtime v0.22.4 h1:GEjV7KV3TY8e+tJ2LCTxUTanW4z/FmNB7l327UfMq9A=
|
||||
|
||||
@@ -293,8 +293,8 @@
|
||||
"@grafana/plugin-ui": "^0.11.1",
|
||||
"@grafana/prometheus": "workspace:*",
|
||||
"@grafana/runtime": "workspace:*",
|
||||
"@grafana/scenes": "v6.52.1",
|
||||
"@grafana/scenes-react": "v6.52.1",
|
||||
"@grafana/scenes": "6.52.2",
|
||||
"@grafana/scenes-react": "6.52.2",
|
||||
"@grafana/schema": "workspace:*",
|
||||
"@grafana/sql": "workspace:*",
|
||||
"@grafana/ui": "workspace:*",
|
||||
|
||||
@@ -844,7 +844,6 @@ export {
|
||||
DataLinkConfigOrigin,
|
||||
SupportedTransformationType,
|
||||
type InternalDataLink,
|
||||
type LinkTarget,
|
||||
type LinkModel,
|
||||
type LinkModelSupplier,
|
||||
VariableOrigin,
|
||||
@@ -852,6 +851,7 @@ export {
|
||||
VariableSuggestionsScope,
|
||||
OneClickMode,
|
||||
} from './types/dataLink';
|
||||
export { type LinkTarget } from './types/linkTarget';
|
||||
export {
|
||||
type Action,
|
||||
type ActionModel,
|
||||
|
||||
@@ -13,7 +13,10 @@
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": ["light", "dark"]
|
||||
"enum": [
|
||||
"light",
|
||||
"dark"
|
||||
]
|
||||
},
|
||||
"primary": {
|
||||
"type": "object",
|
||||
@@ -385,7 +388,13 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": ["super-light-red", "light-red", "red", "semi-dark-red", "dark-red"]
|
||||
"enum": [
|
||||
"super-light-red",
|
||||
"light-red",
|
||||
"red",
|
||||
"semi-dark-red",
|
||||
"dark-red"
|
||||
]
|
||||
},
|
||||
"aliases": {
|
||||
"type": "array",
|
||||
@@ -397,12 +406,18 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": ["color", "name"],
|
||||
"required": [
|
||||
"color",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["name", "shades"],
|
||||
"required": [
|
||||
"name",
|
||||
"shades"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
@@ -422,7 +437,13 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": ["super-light-orange", "light-orange", "orange", "semi-dark-orange", "dark-orange"]
|
||||
"enum": [
|
||||
"super-light-orange",
|
||||
"light-orange",
|
||||
"orange",
|
||||
"semi-dark-orange",
|
||||
"dark-orange"
|
||||
]
|
||||
},
|
||||
"aliases": {
|
||||
"type": "array",
|
||||
@@ -434,12 +455,18 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": ["color", "name"],
|
||||
"required": [
|
||||
"color",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["name", "shades"],
|
||||
"required": [
|
||||
"name",
|
||||
"shades"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
@@ -459,7 +486,13 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": ["super-light-yellow", "light-yellow", "yellow", "semi-dark-yellow", "dark-yellow"]
|
||||
"enum": [
|
||||
"super-light-yellow",
|
||||
"light-yellow",
|
||||
"yellow",
|
||||
"semi-dark-yellow",
|
||||
"dark-yellow"
|
||||
]
|
||||
},
|
||||
"aliases": {
|
||||
"type": "array",
|
||||
@@ -471,12 +504,18 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": ["color", "name"],
|
||||
"required": [
|
||||
"color",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["name", "shades"],
|
||||
"required": [
|
||||
"name",
|
||||
"shades"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
@@ -496,7 +535,13 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": ["super-light-green", "light-green", "green", "semi-dark-green", "dark-green"]
|
||||
"enum": [
|
||||
"super-light-green",
|
||||
"light-green",
|
||||
"green",
|
||||
"semi-dark-green",
|
||||
"dark-green"
|
||||
]
|
||||
},
|
||||
"aliases": {
|
||||
"type": "array",
|
||||
@@ -508,12 +553,18 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": ["color", "name"],
|
||||
"required": [
|
||||
"color",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["name", "shades"],
|
||||
"required": [
|
||||
"name",
|
||||
"shades"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
@@ -533,7 +584,13 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": ["super-light-blue", "light-blue", "blue", "semi-dark-blue", "dark-blue"]
|
||||
"enum": [
|
||||
"super-light-blue",
|
||||
"light-blue",
|
||||
"blue",
|
||||
"semi-dark-blue",
|
||||
"dark-blue"
|
||||
]
|
||||
},
|
||||
"aliases": {
|
||||
"type": "array",
|
||||
@@ -545,12 +602,18 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": ["color", "name"],
|
||||
"required": [
|
||||
"color",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["name", "shades"],
|
||||
"required": [
|
||||
"name",
|
||||
"shades"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
@@ -570,7 +633,13 @@
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": ["super-light-purple", "light-purple", "purple", "semi-dark-purple", "dark-purple"]
|
||||
"enum": [
|
||||
"super-light-purple",
|
||||
"light-purple",
|
||||
"purple",
|
||||
"semi-dark-purple",
|
||||
"dark-purple"
|
||||
]
|
||||
},
|
||||
"aliases": {
|
||||
"type": "array",
|
||||
@@ -582,12 +651,18 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": ["color", "name"],
|
||||
"required": [
|
||||
"color",
|
||||
"name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["name", "shades"],
|
||||
"required": [
|
||||
"name",
|
||||
"shades"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
@@ -603,6 +678,9 @@
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["name", "id"],
|
||||
"required": [
|
||||
"name",
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ScopedVars } from './ScopedVars';
|
||||
import { ExploreCorrelationHelperData, ExplorePanelsState } from './explore';
|
||||
import { LinkTarget } from './linkTarget';
|
||||
import { InterpolateFunction } from './panel';
|
||||
import { DataQuery } from './query';
|
||||
import { TimeRange } from './time';
|
||||
@@ -88,8 +89,6 @@ export interface InternalDataLink<T extends DataQuery = any> {
|
||||
range?: TimeRange;
|
||||
}
|
||||
|
||||
export type LinkTarget = '_blank' | '_self' | undefined;
|
||||
|
||||
/**
|
||||
* Processed Link Model. The values are ready to use
|
||||
*/
|
||||
|
||||
@@ -356,7 +356,7 @@ export interface FeatureToggles {
|
||||
*/
|
||||
dashboardScene?: boolean;
|
||||
/**
|
||||
* Enables experimental new dashboard layouts
|
||||
* Enables new dashboard layouts
|
||||
*/
|
||||
dashboardNewLayouts?: boolean;
|
||||
/**
|
||||
@@ -474,6 +474,10 @@ export interface FeatureToggles {
|
||||
*/
|
||||
kubernetesAggregatorCapTokenAuth?: boolean;
|
||||
/**
|
||||
* Enable Kubernetes CustomResourceDefinition (CRD) support with dynamic API registration
|
||||
*/
|
||||
apiExtensions?: boolean;
|
||||
/**
|
||||
* Enable groupBy variable support in scenes dashboards
|
||||
*/
|
||||
groupByVariable?: boolean;
|
||||
@@ -531,6 +535,10 @@ export interface FeatureToggles {
|
||||
*/
|
||||
alertingListViewV2?: boolean;
|
||||
/**
|
||||
* Enables the new Alerting navigation structure with improved menu grouping
|
||||
*/
|
||||
alertingNavigationV2?: boolean;
|
||||
/**
|
||||
* Enables saved searches for alert rules list
|
||||
*/
|
||||
alertingSavedSearches?: boolean;
|
||||
@@ -1251,4 +1259,8 @@ export interface FeatureToggles {
|
||||
* Enables profiles exemplars support in profiles drilldown
|
||||
*/
|
||||
profilesExemplars?: boolean;
|
||||
/**
|
||||
* Use synchronized dispatch timer to minimize duplicate notifications across alertmanager HA pods
|
||||
*/
|
||||
alertingSyncDispatchTimer?: boolean;
|
||||
}
|
||||
|
||||
4
packages/grafana-data/src/types/linkTarget.ts
Normal file
4
packages/grafana-data/src/types/linkTarget.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Target for links - controls whether link opens in new tab or same tab
|
||||
*/
|
||||
export type LinkTarget = '_blank' | '_self' | undefined;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ComponentType } from 'react';
|
||||
|
||||
import { LinkTarget } from './dataLink';
|
||||
import { IconName } from './icon';
|
||||
import { LinkTarget } from './linkTarget';
|
||||
|
||||
export interface NavLinkDTO {
|
||||
id?: string;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { DataFrame } from './dataFrame';
|
||||
import { DataQueryError, DataQueryRequest, DataQueryTimings } from './datasource';
|
||||
import { FieldConfigSource } from './fieldOverrides';
|
||||
import { IconName } from './icon';
|
||||
import { LinkTarget } from './linkTarget';
|
||||
import { OptionEditorConfig } from './options';
|
||||
import { PluginMeta } from './plugin';
|
||||
import { AbsoluteTimeRange, TimeRange, TimeZone } from './time';
|
||||
@@ -191,6 +192,7 @@ export interface PanelMenuItem {
|
||||
onClick?: (event: React.MouseEvent) => void;
|
||||
shortcut?: string;
|
||||
href?: string;
|
||||
target?: LinkTarget;
|
||||
subMenu?: PanelMenuItem[];
|
||||
}
|
||||
|
||||
|
||||
@@ -163,6 +163,7 @@ var serviceIdentityTokenPermissions = []string{
|
||||
"plugins.grafana.app:*",
|
||||
"historian.alerting.grafana.app:*",
|
||||
"advisor.grafana.app:*",
|
||||
"apiextensions.grafana.app:*",
|
||||
|
||||
// Secrets Manager uses a custom verb for secret decryption, and its authorizer does not allow wildcard permissions.
|
||||
"secret.grafana.app/securevalues:decrypt",
|
||||
|
||||
@@ -131,19 +131,31 @@ func NamespaceKeyFunc(gr schema.GroupResource) func(ctx context.Context, name st
|
||||
}
|
||||
}
|
||||
|
||||
// NoNamespaceKeyFunc is the default function for constructing storage paths
|
||||
// to a resource relative to the given prefix without a namespace.
|
||||
func NoNamespaceKeyFunc(ctx context.Context, prefix string, gr schema.GroupResource, name string) (string, error) {
|
||||
if len(name) == 0 {
|
||||
return "", apierrors.NewBadRequest("Name parameter required.")
|
||||
// ClusterScopedKeyFunc constructs storage paths for cluster-scoped resources (no namespace).
|
||||
func ClusterScopedKeyFunc(gr schema.GroupResource) func(ctx context.Context, name string) (string, error) {
|
||||
return func(ctx context.Context, name string) (string, error) {
|
||||
if len(name) == 0 {
|
||||
return "", apierrors.NewBadRequest("Name parameter required.")
|
||||
}
|
||||
if msgs := path.IsValidPathSegmentName(name); len(msgs) != 0 {
|
||||
return "", apierrors.NewBadRequest(fmt.Sprintf("Name parameter invalid: %q: %s", name, strings.Join(msgs, ";")))
|
||||
}
|
||||
key := &Key{
|
||||
Group: gr.Group,
|
||||
Resource: gr.Resource,
|
||||
Name: name,
|
||||
}
|
||||
return key.String(), nil
|
||||
}
|
||||
}
|
||||
|
||||
// ClusterScopedKeyRootFunc is used by the generic registry store for cluster-scoped resources.
|
||||
func ClusterScopedKeyRootFunc(gr schema.GroupResource) func(ctx context.Context) string {
|
||||
return func(ctx context.Context) string {
|
||||
key := &Key{
|
||||
Group: gr.Group,
|
||||
Resource: gr.Resource,
|
||||
}
|
||||
return key.String()
|
||||
}
|
||||
if msgs := path.IsValidPathSegmentName(name); len(msgs) != 0 {
|
||||
return "", apierrors.NewBadRequest(fmt.Sprintf("Name parameter invalid: %q: %s", name, strings.Join(msgs, ";")))
|
||||
}
|
||||
key := &Key{
|
||||
Group: gr.Group,
|
||||
Resource: gr.Resource,
|
||||
Name: name,
|
||||
}
|
||||
return prefix + key.String(), nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package generic
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"k8s.io/apimachinery/pkg/fields"
|
||||
"k8s.io/apimachinery/pkg/labels"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
@@ -28,10 +30,21 @@ func NewRegistryStoreWithSelectableFields(scheme *runtime.Scheme, resourceInfo u
|
||||
gv := resourceInfo.GroupVersion()
|
||||
gv.Version = runtime.APIVersionInternal
|
||||
strategy := NewStrategy(scheme, gv)
|
||||
|
||||
gr := resourceInfo.GroupResource()
|
||||
var keyRootFunc func(ctx context.Context) string
|
||||
var keyFunc func(ctx context.Context, name string) (string, error)
|
||||
|
||||
if resourceInfo.IsClusterScoped() {
|
||||
strategy = strategy.WithClusterScope()
|
||||
keyRootFunc = ClusterScopedKeyRootFunc(gr)
|
||||
keyFunc = ClusterScopedKeyFunc(gr)
|
||||
} else {
|
||||
keyRootFunc = KeyRootFunc(gr)
|
||||
keyFunc = NamespaceKeyFunc(gr)
|
||||
}
|
||||
|
||||
|
||||
// Use custom GetAttrs if provided, otherwise use default
|
||||
var attrFunc storage.AttrFunc
|
||||
var predicateFunc func(label labels.Selector, field fields.Selector) storage.SelectionPredicate
|
||||
@@ -47,10 +60,10 @@ func NewRegistryStoreWithSelectableFields(scheme *runtime.Scheme, resourceInfo u
|
||||
store := ®istry.Store{
|
||||
NewFunc: resourceInfo.NewFunc,
|
||||
NewListFunc: resourceInfo.NewListFunc,
|
||||
KeyRootFunc: KeyRootFunc(resourceInfo.GroupResource()),
|
||||
KeyFunc: NamespaceKeyFunc(resourceInfo.GroupResource()),
|
||||
KeyRootFunc: keyRootFunc,
|
||||
KeyFunc: keyFunc,
|
||||
PredicateFunc: predicateFunc,
|
||||
DefaultQualifiedResource: resourceInfo.GroupResource(),
|
||||
DefaultQualifiedResource: gr,
|
||||
SingularQualifiedResource: resourceInfo.SingularGroupResource(),
|
||||
TableConvertor: resourceInfo.TableConverter(),
|
||||
CreateStrategy: strategy,
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
_ "github.com/Azure/azure-sdk-for-go/services/keyvault/v7.1/keyvault"
|
||||
_ "github.com/Azure/go-autorest/autorest"
|
||||
_ "github.com/Azure/go-autorest/autorest/adal"
|
||||
_ "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
|
||||
_ "github.com/beevik/etree"
|
||||
_ "github.com/blugelabs/bluge"
|
||||
_ "github.com/blugelabs/bluge_segment_api"
|
||||
|
||||
@@ -42,7 +42,7 @@ func (r *converter) asDataSource(ds *datasources.DataSource) (*datasourceV0.Data
|
||||
Generation: int64(ds.Version),
|
||||
},
|
||||
Spec: datasourceV0.UnstructuredSpec{},
|
||||
Secure: ToInlineSecureValues("", ds.UID, maps.Keys(ds.SecureJsonData)),
|
||||
Secure: ToInlineSecureValues(ds.Type, ds.UID, maps.Keys(ds.SecureJsonData)),
|
||||
}
|
||||
obj.UID = gapiutil.CalculateClusterWideUID(obj)
|
||||
obj.Spec.SetTitle(ds.Name).
|
||||
@@ -82,11 +82,18 @@ func (r *converter) asDataSource(ds *datasources.DataSource) (*datasourceV0.Data
|
||||
|
||||
// ToInlineSecureValues converts secure json into InlineSecureValues with reference names
|
||||
// The names are predictable and can be used while we implement dual writing for secrets
|
||||
func ToInlineSecureValues(_ string, dsUID string, keys iter.Seq[string]) common.InlineSecureValues {
|
||||
func ToInlineSecureValues(dsType string, dsUID string, keys iter.Seq[string]) common.InlineSecureValues {
|
||||
values := make(common.InlineSecureValues)
|
||||
for k := range keys {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(dsType)) // plugin id
|
||||
h.Write([]byte("|"))
|
||||
h.Write([]byte(dsUID)) // unique identifier
|
||||
h.Write([]byte("|"))
|
||||
h.Write([]byte(k)) // property name
|
||||
n := hex.EncodeToString(h.Sum(nil))
|
||||
values[k] = common.InlineSecureValue{
|
||||
Name: getLegacySecureValueName(dsUID, k),
|
||||
Name: "ds-" + n[0:10], // predictable name for dual writing
|
||||
}
|
||||
}
|
||||
if len(values) == 0 {
|
||||
@@ -95,15 +102,6 @@ func ToInlineSecureValues(_ string, dsUID string, keys iter.Seq[string]) common.
|
||||
return values
|
||||
}
|
||||
|
||||
func getLegacySecureValueName(dsUID string, key string) string {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(dsUID)) // unique identifier
|
||||
h.Write([]byte("|"))
|
||||
h.Write([]byte(key)) // property name
|
||||
n := hex.EncodeToString(h.Sum(nil))
|
||||
return "ds-" + n[0:10] // predictable name for dual writing
|
||||
}
|
||||
|
||||
func (r *converter) toAddCommand(ds *datasourceV0.DataSource) (*datasources.AddDataSourceCommand, error) {
|
||||
if r.group != "" && ds.APIVersion != "" && !strings.HasPrefix(ds.APIVersion, r.group) {
|
||||
return nil, fmt.Errorf("expecting APIGroup: %s", r.group)
|
||||
|
||||
@@ -11,11 +11,9 @@ import (
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apiserver/pkg/registry/rest"
|
||||
|
||||
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
|
||||
"github.com/grafana/grafana/pkg/apimachinery/utils"
|
||||
"github.com/grafana/grafana/pkg/apis/datasource/v0alpha1"
|
||||
"github.com/grafana/grafana/pkg/infra/metrics/metricutil"
|
||||
"github.com/grafana/grafana/pkg/storage/legacysql/dualwrite"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -92,20 +90,6 @@ func (s *legacyStorage) Create(ctx context.Context, obj runtime.Object, createVa
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expected a datasource object")
|
||||
}
|
||||
|
||||
// Verify the secure value commands
|
||||
for _, v := range ds.Secure {
|
||||
if v.Create.IsZero() {
|
||||
return nil, fmt.Errorf("secure values must use create when creating a new datasource")
|
||||
}
|
||||
if v.Remove {
|
||||
return nil, fmt.Errorf("secure values can not use remove when creating a new datasource")
|
||||
}
|
||||
if v.Name != "" {
|
||||
return nil, fmt.Errorf("secure values can not specify a name when creating a new datasource")
|
||||
}
|
||||
}
|
||||
|
||||
return s.datasources.CreateDataSource(ctx, ds)
|
||||
}
|
||||
|
||||
@@ -138,26 +122,6 @@ func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.Up
|
||||
return nil, false, fmt.Errorf("expected a datasource object (old)")
|
||||
}
|
||||
|
||||
// Expose any secure value changes to the dual writer
|
||||
var secureChanges common.InlineSecureValues
|
||||
for k, v := range ds.Secure {
|
||||
if v.Remove || v.Create != "" {
|
||||
if secureChanges == nil {
|
||||
secureChanges = make(common.InlineSecureValues)
|
||||
}
|
||||
secureChanges[k] = v
|
||||
dualwrite.SetUpdatedSecureValues(ctx, ds.Secure)
|
||||
continue
|
||||
}
|
||||
|
||||
// The legacy store must use fixed names generated by the internal system
|
||||
// we can not support external shared secrets when using the SQL backing for datasources
|
||||
validName := getLegacySecureValueName(name, k)
|
||||
if v.Name != validName {
|
||||
return nil, false, fmt.Errorf("invalid secure value name %q, expected %q", v.Name, validName)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep all the old secure values
|
||||
if len(oldDS.Secure) > 0 {
|
||||
for k, v := range oldDS.Secure {
|
||||
|
||||
@@ -30,7 +30,6 @@ import (
|
||||
"github.com/grafana/grafana/pkg/services/accesscontrol"
|
||||
"github.com/grafana/grafana/pkg/services/apiserver/builder"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
"github.com/grafana/grafana/pkg/storage/unified/apistore"
|
||||
"github.com/grafana/grafana/pkg/tsdb/grafana-testdata-datasource/kinds"
|
||||
)
|
||||
|
||||
@@ -103,10 +102,10 @@ func RegisterAPIService(
|
||||
datasources.GetDatasourceProvider(pluginJSON),
|
||||
contextProvider,
|
||||
accessControl,
|
||||
//nolint:staticcheck // not yet migrated to OpenFeature
|
||||
DataSourceAPIBuilderConfig{
|
||||
//nolint:staticcheck // not yet migrated to OpenFeature
|
||||
LoadQueryTypes: features.IsEnabledGlobally(featuremgmt.FlagDatasourceQueryTypes),
|
||||
UseDualWriter: features.IsEnabledGlobally(featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs),
|
||||
UseDualWriter: false,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
@@ -225,12 +224,6 @@ func (b *DataSourceAPIBuilder) AllowedV0Alpha1Resources() []string {
|
||||
}
|
||||
|
||||
func (b *DataSourceAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.APIGroupInfo, opts builder.APIGroupOptions) error {
|
||||
opts.StorageOptsRegister(b.datasourceResourceInfo.GroupResource(), apistore.StorageOptions{
|
||||
EnableFolderSupport: false,
|
||||
|
||||
Scheme: opts.Scheme, // allows for generic Type applied to multiple groups
|
||||
})
|
||||
|
||||
storage := map[string]rest.Storage{}
|
||||
|
||||
// Register the raw datasource connection
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"secure": {
|
||||
"password": {
|
||||
"name": "ds-0d27eff323"
|
||||
"name": "ds-d5c1b093af"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,10 +22,10 @@
|
||||
},
|
||||
"secure": {
|
||||
"extra": {
|
||||
"name": "ds-6ed1b76e5d"
|
||||
"name": "ds-bb8b5d8b32"
|
||||
},
|
||||
"password": {
|
||||
"name": "ds-edc8fde0ac"
|
||||
"name": "ds-973a1eb29d"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ func (s *LocalInlineSecureValueService) CanReference(ctx context.Context, owner
|
||||
}
|
||||
|
||||
if owner.APIGroup == "" || owner.APIVersion == "" || owner.Kind == "" || owner.Name == "" {
|
||||
return fmt.Errorf("owner reference must have a valid API group, API version, kind and name [CanReference]")
|
||||
return fmt.Errorf("owner reference must have a valid API group, API version, kind and name")
|
||||
}
|
||||
|
||||
if len(names) == 0 {
|
||||
@@ -167,7 +167,7 @@ func (s *LocalInlineSecureValueService) verifyOwnerAndAuth(ctx context.Context,
|
||||
}
|
||||
|
||||
if owner.Namespace == "" || owner.APIGroup == "" || owner.APIVersion == "" || owner.Kind == "" || owner.Name == "" {
|
||||
return nil, fmt.Errorf("owner reference must have a valid API group, API version, kind, namespace and name [verifyOwnerAndAuth:%+v]", owner)
|
||||
return nil, fmt.Errorf("owner reference must have a valid API group, API version, kind, namespace and name")
|
||||
}
|
||||
|
||||
return authInfo, nil
|
||||
|
||||
@@ -3,6 +3,7 @@ package aggregatorrunner
|
||||
import (
|
||||
"context"
|
||||
|
||||
apiextensionsinformers "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
genericapiserver "k8s.io/apiserver/pkg/server"
|
||||
|
||||
@@ -21,6 +22,10 @@ func (n NoopAggregatorConfigurator) Run(ctx context.Context, transport *options.
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (n *NoopAggregatorConfigurator) SetCRDInformer(_ apiextensionsinformers.CustomResourceDefinitionInformer) {
|
||||
// noop
|
||||
}
|
||||
|
||||
func ProvideNoopAggregatorConfigurator() AggregatorRunner {
|
||||
return &NoopAggregatorConfigurator{}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package aggregatorrunner
|
||||
import (
|
||||
"context"
|
||||
|
||||
apiextensionsinformers "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
genericapiserver "k8s.io/apiserver/pkg/server"
|
||||
|
||||
@@ -21,4 +22,8 @@ type AggregatorRunner interface {
|
||||
|
||||
// Run starts the complete apiserver chain, expects it executes any logic inside a goroutine and doesn't block. Returns the running server.
|
||||
Run(ctx context.Context, transport *options.RoundTripperFunc, stoppedCh chan error) (*genericapiserver.GenericAPIServer, error)
|
||||
|
||||
// SetCRDInformer sets the CRD informer for auto-registering APIServices for CRDs.
|
||||
// This should be called before Configure if CRD API is enabled.
|
||||
SetCRDInformer(informer apiextensionsinformers.CustomResourceDefinitionInformer)
|
||||
}
|
||||
|
||||
@@ -346,6 +346,7 @@ func (s *service) start(ctx context.Context) error {
|
||||
serverConfig.MaxRequestBodyBytes = MaxRequestBodyBytes
|
||||
|
||||
var optsregister apistore.StorageOptionsRegister
|
||||
var restOptsGetter *apistore.RESTOptionsGetter
|
||||
|
||||
if o.StorageOptions.StorageType == grafanaapiserveroptions.StorageTypeEtcd {
|
||||
if err := o.RecommendedOptions.Etcd.Validate(); len(err) > 0 {
|
||||
@@ -355,9 +356,9 @@ func (s *service) start(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
getter := apistore.NewRESTOptionsGetterForClient(s.unified, s.secrets, o.RecommendedOptions.Etcd.StorageConfig, s.restConfigProvider)
|
||||
optsregister = getter.RegisterOptions
|
||||
serverConfig.RESTOptionsGetter = getter
|
||||
restOptsGetter = apistore.NewRESTOptionsGetterForClient(s.unified, s.secrets, o.RecommendedOptions.Etcd.StorageConfig, s.restConfigProvider)
|
||||
optsregister = restOptsGetter.RegisterOptions
|
||||
serverConfig.RESTOptionsGetter = restOptsGetter
|
||||
}
|
||||
|
||||
defGetters := []common.GetOpenAPIDefinitions{
|
||||
@@ -398,8 +399,11 @@ func (s *service) start(ctx context.Context) error {
|
||||
return fmt.Errorf("failed to register post start hooks for app installers: %w", err)
|
||||
}
|
||||
|
||||
// Create the server
|
||||
server, err := serverConfig.Complete().New("grafana-apiserver", genericapiserver.NewEmptyDelegateWithCustomHandler(notFoundHandler))
|
||||
// Determine the delegate for the main server
|
||||
var delegationTarget = genericapiserver.NewEmptyDelegateWithCustomHandler(notFoundHandler)
|
||||
|
||||
// Create the main Grafana API server
|
||||
server, err := serverConfig.Complete().New("grafana-apiserver", delegationTarget)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -671,4 +675,4 @@ func useNamespaceFromPath(path string, user *user.SignedInUser) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -574,8 +574,8 @@ var (
|
||||
},
|
||||
{
|
||||
Name: "dashboardNewLayouts",
|
||||
Description: "Enables experimental new dashboard layouts",
|
||||
Stage: FeatureStageExperimental,
|
||||
Description: "Enables new dashboard layouts",
|
||||
Stage: FeatureStagePublicPreview,
|
||||
FrontendOnly: false, // The restore backend feature changes behavior based on this flag
|
||||
Owner: grafanaDashboardsSquad,
|
||||
},
|
||||
@@ -777,6 +777,13 @@ var (
|
||||
Owner: grafanaAppPlatformSquad,
|
||||
RequiresRestart: true,
|
||||
},
|
||||
{
|
||||
Name: "apiExtensions",
|
||||
Description: "Enable Kubernetes CustomResourceDefinition (CRD) support with dynamic API registration (Enterprise + MT-only)",
|
||||
Stage: FeatureStageExperimental,
|
||||
Owner: grafanaAppPlatformSquad,
|
||||
RequiresRestart: true,
|
||||
},
|
||||
{
|
||||
Name: "groupByVariable",
|
||||
Description: "Enable groupBy variable support in scenes dashboards",
|
||||
@@ -879,6 +886,13 @@ var (
|
||||
Owner: grafanaAlertingSquad,
|
||||
FrontendOnly: true,
|
||||
},
|
||||
{
|
||||
Name: "alertingNavigationV2",
|
||||
Description: "Enables the new Alerting navigation structure with improved menu grouping",
|
||||
Stage: FeatureStageExperimental,
|
||||
Owner: grafanaAlertingSquad,
|
||||
FrontendOnly: false,
|
||||
},
|
||||
{
|
||||
Name: "alertingSavedSearches",
|
||||
Description: "Enables saved searches for alert rules list",
|
||||
@@ -981,7 +995,8 @@ var (
|
||||
Stage: FeatureStageDeprecated,
|
||||
Owner: grafanaPartnerPluginsSquad,
|
||||
Expression: "true", // Enabled by default for now
|
||||
}, {
|
||||
},
|
||||
{
|
||||
Name: "alertingFilterV2",
|
||||
Description: "Enable the new alerting search experience",
|
||||
Stage: FeatureStageExperimental,
|
||||
@@ -2069,6 +2084,14 @@ var (
|
||||
Owner: grafanaObservabilityTracesAndProfilingSquad,
|
||||
FrontendOnly: false,
|
||||
},
|
||||
{
|
||||
Name: "alertingSyncDispatchTimer",
|
||||
Description: "Use synchronized dispatch timer to minimize duplicate notifications across alertmanager HA pods",
|
||||
Stage: FeatureStageExperimental,
|
||||
Owner: grafanaAlertingSquad,
|
||||
RequiresRestart: true,
|
||||
HideFromDocs: true,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
5
pkg/services/featuremgmt/toggles_gen.csv
generated
5
pkg/services/featuremgmt/toggles_gen.csv
generated
@@ -79,7 +79,7 @@ annotationPermissionUpdate,GA,@grafana/identity-access-team,false,false,false
|
||||
dashboardSceneForViewers,GA,@grafana/dashboards-squad,false,false,true
|
||||
dashboardSceneSolo,GA,@grafana/dashboards-squad,false,false,true
|
||||
dashboardScene,GA,@grafana/dashboards-squad,false,false,true
|
||||
dashboardNewLayouts,experimental,@grafana/dashboards-squad,false,false,false
|
||||
dashboardNewLayouts,preview,@grafana/dashboards-squad,false,false,false
|
||||
dashboardUndoRedo,experimental,@grafana/dashboards-squad,false,false,true
|
||||
unlimitedLayoutsNesting,experimental,@grafana/dashboards-squad,false,false,true
|
||||
drilldownRecommendations,experimental,@grafana/dashboards-squad,false,false,true
|
||||
@@ -107,6 +107,7 @@ sqlExpressions,preview,@grafana/grafana-datasources-core-services,false,false,fa
|
||||
sqlExpressionsColumnAutoComplete,experimental,@grafana/datapro,false,false,true
|
||||
kubernetesAggregator,experimental,@grafana/grafana-app-platform-squad,false,true,false
|
||||
kubernetesAggregatorCapTokenAuth,experimental,@grafana/grafana-app-platform-squad,false,true,false
|
||||
apiExtensions,experimental,@grafana/grafana-app-platform-squad,false,true,false
|
||||
groupByVariable,experimental,@grafana/dashboards-squad,false,false,false
|
||||
scopeFilters,experimental,@grafana/dashboards-squad,false,false,false
|
||||
oauthRequireSubClaim,experimental,@grafana/identity-access-team,false,false,false
|
||||
@@ -121,6 +122,7 @@ dashboardLibrary,experimental,@grafana/sharing-squad,false,false,false
|
||||
suggestedDashboards,experimental,@grafana/sharing-squad,false,false,false
|
||||
dashboardTemplates,preview,@grafana/sharing-squad,false,false,false
|
||||
alertingListViewV2,privatePreview,@grafana/alerting-squad,false,false,true
|
||||
alertingNavigationV2,experimental,@grafana/alerting-squad,false,false,false
|
||||
alertingSavedSearches,experimental,@grafana/alerting-squad,false,false,true
|
||||
alertingDisableSendAlertsExternal,experimental,@grafana/alerting-squad,false,false,false
|
||||
preserveDashboardStateWhenNavigating,experimental,@grafana/dashboards-squad,false,false,false
|
||||
@@ -280,3 +282,4 @@ multiPropsVariables,experimental,@grafana/dashboards-squad,false,false,true
|
||||
smoothingTransformation,experimental,@grafana/datapro,false,false,true
|
||||
secretsManagementAppPlatformAwsKeeper,experimental,@grafana/grafana-operator-experience-squad,false,false,false
|
||||
profilesExemplars,experimental,@grafana/observability-traces-and-profiling,false,false,false
|
||||
alertingSyncDispatchTimer,experimental,@grafana/alerting-squad,false,true,false
|
||||
|
||||
|
14
pkg/services/featuremgmt/toggles_gen.go
generated
14
pkg/services/featuremgmt/toggles_gen.go
generated
@@ -260,7 +260,7 @@ const (
|
||||
FlagAnnotationPermissionUpdate = "annotationPermissionUpdate"
|
||||
|
||||
// FlagDashboardNewLayouts
|
||||
// Enables experimental new dashboard layouts
|
||||
// Enables new dashboard layouts
|
||||
FlagDashboardNewLayouts = "dashboardNewLayouts"
|
||||
|
||||
// FlagPdfTables
|
||||
@@ -319,6 +319,10 @@ const (
|
||||
// Enable CAP token based authentication in grafana's embedded kube-aggregator
|
||||
FlagKubernetesAggregatorCapTokenAuth = "kubernetesAggregatorCapTokenAuth"
|
||||
|
||||
// FlagApiExtensions
|
||||
// Enable Kubernetes CustomResourceDefinition (CRD) support with dynamic API registration
|
||||
FlagApiExtensions = "apiExtensions"
|
||||
|
||||
// FlagGroupByVariable
|
||||
// Enable groupBy variable support in scenes dashboards
|
||||
FlagGroupByVariable = "groupByVariable"
|
||||
@@ -371,6 +375,10 @@ const (
|
||||
// Enables a flow to get started with a new dashboard from a template
|
||||
FlagDashboardTemplates = "dashboardTemplates"
|
||||
|
||||
// FlagAlertingNavigationV2
|
||||
// Enables the new Alerting navigation structure with improved menu grouping
|
||||
FlagAlertingNavigationV2 = "alertingNavigationV2"
|
||||
|
||||
// FlagAlertingDisableSendAlertsExternal
|
||||
// Disables the ability to send alerts to an external Alertmanager datasource.
|
||||
FlagAlertingDisableSendAlertsExternal = "alertingDisableSendAlertsExternal"
|
||||
@@ -789,4 +797,8 @@ const (
|
||||
// FlagProfilesExemplars
|
||||
// Enables profiles exemplars support in profiles drilldown
|
||||
FlagProfilesExemplars = "profilesExemplars"
|
||||
|
||||
// FlagAlertingSyncDispatchTimer
|
||||
// Use synchronized dispatch timer to minimize duplicate notifications across alertmanager HA pods
|
||||
FlagAlertingSyncDispatchTimer = "alertingSyncDispatchTimer"
|
||||
)
|
||||
|
||||
53
pkg/services/featuremgmt/toggles_gen.json
generated
53
pkg/services/featuremgmt/toggles_gen.json
generated
@@ -348,6 +348,18 @@
|
||||
"expression": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"metadata": {
|
||||
"name": "alertingNavigationV2",
|
||||
"resourceVersion": "1768320918269",
|
||||
"creationTimestamp": "2026-01-13T16:15:18Z"
|
||||
},
|
||||
"spec": {
|
||||
"description": "Enables the new Alerting navigation structure with improved menu grouping",
|
||||
"stage": "experimental",
|
||||
"codeowner": "@grafana/alerting-squad"
|
||||
}
|
||||
},
|
||||
{
|
||||
"metadata": {
|
||||
"name": "alertingNotificationHistory",
|
||||
@@ -511,6 +523,20 @@
|
||||
"frontend": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"metadata": {
|
||||
"name": "alertingSyncDispatchTimer",
|
||||
"resourceVersion": "1766161788928",
|
||||
"creationTimestamp": "2025-12-19T16:29:48Z"
|
||||
},
|
||||
"spec": {
|
||||
"description": "Use synchronized dispatch timer to minimize duplicate notifications across alertmanager HA pods",
|
||||
"stage": "experimental",
|
||||
"codeowner": "@grafana/alerting-squad",
|
||||
"requiresRestart": true,
|
||||
"hideFromDocs": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"metadata": {
|
||||
"name": "alertingTriage",
|
||||
@@ -632,6 +658,19 @@
|
||||
"expression": "true"
|
||||
}
|
||||
},
|
||||
{
|
||||
"metadata": {
|
||||
"name": "apiExtensions",
|
||||
"resourceVersion": "1764159104213",
|
||||
"creationTimestamp": "2025-11-26T12:11:44Z"
|
||||
},
|
||||
"spec": {
|
||||
"description": "Enable Kubernetes CustomResourceDefinition (CRD) support with dynamic API registration",
|
||||
"stage": "experimental",
|
||||
"codeowner": "@grafana/grafana-app-platform-squad",
|
||||
"requiresRestart": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"metadata": {
|
||||
"name": "appPlatformGrpcClientAuth",
|
||||
@@ -662,7 +701,8 @@
|
||||
"metadata": {
|
||||
"name": "auditLoggingAppPlatform",
|
||||
"resourceVersion": "1767013056996",
|
||||
"creationTimestamp": "2025-12-29T12:57:36Z"
|
||||
"creationTimestamp": "2025-12-29T12:57:36Z",
|
||||
"deletionTimestamp": "2026-01-06T09:18:36Z"
|
||||
},
|
||||
"spec": {
|
||||
"description": "Enable audit logging with Kubernetes under app platform",
|
||||
@@ -1015,12 +1055,15 @@
|
||||
{
|
||||
"metadata": {
|
||||
"name": "dashboardNewLayouts",
|
||||
"resourceVersion": "1764664939750",
|
||||
"creationTimestamp": "2024-10-23T08:55:45Z"
|
||||
"resourceVersion": "1768382835527",
|
||||
"creationTimestamp": "2024-10-23T08:55:45Z",
|
||||
"annotations": {
|
||||
"grafana.app/updatedTimestamp": "2026-01-14 09:27:15.527103 +0000 UTC"
|
||||
}
|
||||
},
|
||||
"spec": {
|
||||
"description": "Enables experimental new dashboard layouts",
|
||||
"stage": "experimental",
|
||||
"description": "Enables new dashboard layouts",
|
||||
"stage": "preview",
|
||||
"codeowner": "@grafana/dashboards-squad"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -54,8 +54,7 @@ func (s *ServiceImpl) getAdminNode(c *contextmodel.ReqContext) (*navtree.NavLink
|
||||
}
|
||||
//nolint:staticcheck // not yet migrated to OpenFeature
|
||||
if c.HasRole(identity.RoleAdmin) &&
|
||||
(s.cfg.StackID == "" || // show OnPrem even when provisioning is disabled
|
||||
s.features.IsEnabledGlobally(featuremgmt.FlagProvisioning)) {
|
||||
s.features.IsEnabledGlobally(featuremgmt.FlagProvisioning) {
|
||||
generalNodeLinks = append(generalNodeLinks, &navtree.NavLink{
|
||||
Text: "Provisioning",
|
||||
Id: "provisioning",
|
||||
|
||||
@@ -213,6 +213,9 @@ func (ng *AlertNG) init() error {
|
||||
SkipVerify: ng.Cfg.Smtp.SkipVerify,
|
||||
StaticHeaders: ng.Cfg.Smtp.StaticHeaders,
|
||||
}
|
||||
runtimeConfig := remoteClient.RuntimeConfig{
|
||||
DispatchTimer: notifier.GetDispatchTimer(ng.FeatureToggles).String(),
|
||||
}
|
||||
|
||||
cfg := remote.AlertmanagerConfig{
|
||||
BasicAuthPassword: ng.Cfg.UnifiedAlerting.RemoteAlertmanager.Password,
|
||||
@@ -222,6 +225,7 @@ func (ng *AlertNG) init() error {
|
||||
ExternalURL: ng.Cfg.AppURL,
|
||||
SmtpConfig: smtpCfg,
|
||||
Timeout: ng.Cfg.UnifiedAlerting.RemoteAlertmanager.Timeout,
|
||||
RuntimeConfig: runtimeConfig,
|
||||
}
|
||||
autogenFn := func(ctx context.Context, logger log.Logger, orgID int64, cfg *definitions.PostableApiAlertingConfig, invalidReceiverAction notifier.InvalidReceiversAction) error {
|
||||
return notifier.AddAutogenConfig(ctx, logger, ng.store, orgID, cfg, invalidReceiverAction, ng.FeatureToggles)
|
||||
|
||||
@@ -33,6 +33,9 @@ const (
|
||||
|
||||
// How long we keep silences in the kvstore after they've expired.
|
||||
silenceRetention = 5 * 24 * time.Hour
|
||||
|
||||
// How long we keep flushes in the kvstore after they've expired.
|
||||
flushRetention = 5 * 24 * time.Hour
|
||||
)
|
||||
|
||||
type AlertingStore interface {
|
||||
@@ -44,8 +47,10 @@ type AlertingStore interface {
|
||||
type stateStore interface {
|
||||
SaveSilences(ctx context.Context, st alertingNotify.State) (int64, error)
|
||||
SaveNotificationLog(ctx context.Context, st alertingNotify.State) (int64, error)
|
||||
SaveFlushLog(ctx context.Context, st alertingNotify.State) (int64, error)
|
||||
GetSilences(ctx context.Context) (string, error)
|
||||
GetNotificationLog(ctx context.Context) (string, error)
|
||||
GetFlushLog(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
type alertmanager struct {
|
||||
@@ -101,6 +106,10 @@ func NewAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flushLog, err := stateStore.GetFlushLog(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
silencesOptions := maintenanceOptions{
|
||||
initialState: silences,
|
||||
@@ -123,12 +132,29 @@ func NewAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A
|
||||
}
|
||||
l := log.New("ngalert.notifier")
|
||||
|
||||
dispatchTimer := GetDispatchTimer(featureToggles)
|
||||
|
||||
var flushLogOptions *maintenanceOptions
|
||||
if dispatchTimer == alertingNotify.DispatchTimerSync {
|
||||
flushLogOptions = &maintenanceOptions{
|
||||
initialState: flushLog,
|
||||
retention: flushRetention,
|
||||
maintenanceFrequency: maintenanceInterval,
|
||||
maintenanceFunc: func(state alertingNotify.State) (int64, error) {
|
||||
// Detached context here is to make sure that when the service is shut down the persist operation is executed.
|
||||
return stateStore.SaveFlushLog(context.Background(), state)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
opts := alertingNotify.GrafanaAlertmanagerOpts{
|
||||
ExternalURL: cfg.AppURL,
|
||||
AlertStoreCallback: nil,
|
||||
PeerTimeout: cfg.UnifiedAlerting.HAPeerTimeout,
|
||||
Silences: silencesOptions,
|
||||
Nflog: nflogOptions,
|
||||
FlushLog: flushLogOptions,
|
||||
DispatchTimer: dispatchTimer,
|
||||
Limits: alertingNotify.Limits{
|
||||
MaxSilences: cfg.UnifiedAlerting.AlertmanagerMaxSilencesCount,
|
||||
MaxSilenceSizeBytes: cfg.UnifiedAlerting.AlertmanagerMaxSilenceSizeBytes,
|
||||
|
||||
16
pkg/services/ngalert/notifier/dispatch_timer.go
Normal file
16
pkg/services/ngalert/notifier/dispatch_timer.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
alertingNotify "github.com/grafana/alerting/notify"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
)
|
||||
|
||||
// GetDispatchTimer returns the appropriate dispatch timer based on feature toggles.
|
||||
func GetDispatchTimer(features featuremgmt.FeatureToggles) (dt alertingNotify.DispatchTimer) {
|
||||
//nolint:staticcheck // not yet migrated to OpenFeature
|
||||
enabled := features.IsEnabledGlobally(featuremgmt.FlagAlertingSyncDispatchTimer)
|
||||
if enabled {
|
||||
dt = alertingNotify.DispatchTimerSync
|
||||
}
|
||||
return
|
||||
}
|
||||
36
pkg/services/ngalert/notifier/dispatch_timer_test.go
Normal file
36
pkg/services/ngalert/notifier/dispatch_timer_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
alertingNotify "github.com/grafana/alerting/notify"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetDispatchTimer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
featureFlagValue bool
|
||||
expected alertingNotify.DispatchTimer
|
||||
}{
|
||||
{
|
||||
name: "feature flag enabled returns sync timer",
|
||||
featureFlagValue: true,
|
||||
expected: alertingNotify.DispatchTimerSync,
|
||||
},
|
||||
{
|
||||
name: "feature flag disabled returns default timer",
|
||||
featureFlagValue: false,
|
||||
expected: alertingNotify.DispatchTimerDefault,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
features := featuremgmt.WithFeatures(featuremgmt.FlagAlertingSyncDispatchTimer, tt.featureFlagValue)
|
||||
result := GetDispatchTimer(features)
|
||||
require.Equal(t, tt.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ const (
|
||||
KVNamespace = "alertmanager"
|
||||
NotificationLogFilename = "notifications"
|
||||
SilencesFilename = "silences"
|
||||
FlushLogFilename = "flushes"
|
||||
)
|
||||
|
||||
// FileStore is in charge of persisting the alertmanager files to the database.
|
||||
@@ -42,6 +43,10 @@ func (fileStore *FileStore) GetNotificationLog(ctx context.Context) (string, err
|
||||
return fileStore.contentFor(ctx, NotificationLogFilename)
|
||||
}
|
||||
|
||||
func (fileStore *FileStore) GetFlushLog(ctx context.Context) (string, error) {
|
||||
return fileStore.contentFor(ctx, FlushLogFilename)
|
||||
}
|
||||
|
||||
// contentFor returns the content for the given Alertmanager kvstore key.
|
||||
func (fileStore *FileStore) contentFor(ctx context.Context, filename string) (string, error) {
|
||||
// Then, let's attempt to read it from the database.
|
||||
@@ -74,6 +79,11 @@ func (fileStore *FileStore) SaveNotificationLog(ctx context.Context, st alerting
|
||||
return fileStore.persist(ctx, NotificationLogFilename, st)
|
||||
}
|
||||
|
||||
// SaveFlushLog saves the flush log to the database and returns the size of the unencoded state.
|
||||
func (fileStore *FileStore) SaveFlushLog(ctx context.Context, st alertingNotify.State) (int64, error) {
|
||||
return fileStore.persist(ctx, FlushLogFilename, st)
|
||||
}
|
||||
|
||||
// persist takes care of persisting the binary representation of internal state to the database as a base64 encoded string.
|
||||
func (fileStore *FileStore) persist(ctx context.Context, filename string, st alertingNotify.State) (int64, error) {
|
||||
var size int64
|
||||
|
||||
@@ -106,3 +106,48 @@ func TestFileStore_NotificationLog(t *testing.T) {
|
||||
t.Errorf("Unexpected Diff: %v", cmp.Diff(newState, decoded))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileStore_FlushLog(t *testing.T) {
|
||||
store := fakes.NewFakeKVStore(t)
|
||||
ctx := context.Background()
|
||||
var orgId int64 = 1
|
||||
|
||||
// Initialize kvstore with empty flush log state.
|
||||
initialState := flushLogState{} // FlushLog uses the same structure as nflog
|
||||
decodedState, err := initialState.MarshalBinary()
|
||||
require.NoError(t, err)
|
||||
encodedState := base64.StdEncoding.EncodeToString(decodedState)
|
||||
err = store.Set(ctx, orgId, KVNamespace, FlushLogFilename, encodedState)
|
||||
require.NoError(t, err)
|
||||
|
||||
fs := NewFileStore(orgId, store)
|
||||
|
||||
// Load initial (empty).
|
||||
flushLog, err := fs.GetFlushLog(ctx)
|
||||
require.NoError(t, err)
|
||||
decoded, err := decodeFlushLogState(strings.NewReader(flushLog))
|
||||
require.NoError(t, err)
|
||||
if !cmp.Equal(initialState, decoded) {
|
||||
t.Errorf("Unexpected Diff: %v", cmp.Diff(initialState, decoded))
|
||||
}
|
||||
|
||||
// Save new flush log state.
|
||||
now := time.Now()
|
||||
oneHour := now.Add(time.Hour)
|
||||
|
||||
v1 := createFlushLog(1, now, oneHour)
|
||||
v2 := createFlushLog(2, now, oneHour)
|
||||
newState := flushLogState{1: v1, 2: v2}
|
||||
size, err := fs.SaveFlushLog(ctx, newState)
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, size, int64(0))
|
||||
|
||||
// Load new.
|
||||
flushLog, err = fs.GetFlushLog(ctx)
|
||||
require.NoError(t, err)
|
||||
decoded, err = decodeFlushLogState(strings.NewReader(flushLog))
|
||||
require.NoError(t, err)
|
||||
if !cmp.Equal(newState, decoded) {
|
||||
t.Errorf("Unexpected Diff: %v", cmp.Diff(newState, decoded))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ type Alertmanager interface {
|
||||
type ExternalState struct {
|
||||
Silences []byte
|
||||
Nflog []byte
|
||||
FlushLog []byte
|
||||
}
|
||||
|
||||
// StateMerger describes a type that is able to merge external state (nflog, silences) with its own.
|
||||
@@ -378,7 +379,7 @@ func (moa *MultiOrgAlertmanager) SyncAlertmanagersForOrgs(ctx context.Context, o
|
||||
func (moa *MultiOrgAlertmanager) cleanupOrphanLocalOrgState(ctx context.Context,
|
||||
activeOrganizations map[int64]struct{},
|
||||
) {
|
||||
storedFiles := []string{NotificationLogFilename, SilencesFilename}
|
||||
storedFiles := []string{NotificationLogFilename, SilencesFilename, FlushLogFilename}
|
||||
for _, fileName := range storedFiles {
|
||||
keys, err := moa.kvStore.Keys(ctx, kvstore.AllOrganizations, KVNamespace, fileName)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,5 +5,8 @@ func (am *alertmanager) MergeState(state ExternalState) error {
|
||||
if err := am.Base.MergeNflog(state.Nflog); err != nil {
|
||||
return err
|
||||
}
|
||||
return am.Base.MergeSilences(state.Silences)
|
||||
if err := am.Base.MergeSilences(state.Silences); err != nil {
|
||||
return err
|
||||
}
|
||||
return am.Base.MergeFlushLog(state.FlushLog)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/matttproud/golang_protobuf_extensions/pbutil"
|
||||
"github.com/prometheus/alertmanager/flushlog/flushlogpb"
|
||||
"github.com/prometheus/alertmanager/nflog/nflogpb"
|
||||
"github.com/prometheus/alertmanager/silence/silencepb"
|
||||
"github.com/prometheus/common/model"
|
||||
@@ -228,15 +229,13 @@ func (f *FakeOrgStore) FetchOrgIds(_ context.Context) ([]int64, error) {
|
||||
return f.orgs, nil
|
||||
}
|
||||
|
||||
type NoValidation struct {
|
||||
}
|
||||
type NoValidation struct{}
|
||||
|
||||
func (n NoValidation) Validate(_ models.NotificationSettings) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type RejectingValidation struct {
|
||||
}
|
||||
type RejectingValidation struct{}
|
||||
|
||||
func (n RejectingValidation) Validate(s models.NotificationSettings) error {
|
||||
return ErrorReceiverDoesNotExist{ErrorReferenceInvalid: ErrorReferenceInvalid{Reference: s.Receiver}}
|
||||
@@ -365,6 +364,51 @@ func createNotificationLog(groupKey string, receiverName string, sentAt, expires
|
||||
}
|
||||
}
|
||||
|
||||
// https://github.com/grafana/prometheus-alertmanager/blob/main/flushlog/flushlog.go#L136-L136
|
||||
type flushLogState map[uint64]*flushlogpb.MeshFlushLog
|
||||
|
||||
func (s flushLogState) MarshalBinary() ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
for _, e := range s {
|
||||
if _, err := pbutil.WriteDelimited(&buf, e); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func createFlushLog(groupFingerprint uint64, ts, expiresAt time.Time) *flushlogpb.MeshFlushLog {
|
||||
return &flushlogpb.MeshFlushLog{
|
||||
FlushLog: &flushlogpb.FlushLog{
|
||||
GroupFingerprint: groupFingerprint,
|
||||
Timestamp: ts,
|
||||
},
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
// decodeFlushLogState copied from decodeState in prometheus-alertmanager/flushlog/flushlog.go
|
||||
func decodeFlushLogState(r io.Reader) (flushLogState, error) {
|
||||
st := flushLogState{}
|
||||
for {
|
||||
var e flushlogpb.MeshFlushLog
|
||||
_, err := pbutil.ReadDelimited(r, &e)
|
||||
if err == nil {
|
||||
if e.FlushLog == nil || e.FlushLog.GroupFingerprint == 0 || e.FlushLog.Timestamp.IsZero() {
|
||||
return nil, errInvalidState
|
||||
}
|
||||
st[e.FlushLog.GroupFingerprint] = &e
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
type call struct {
|
||||
Method string
|
||||
Args []interface{}
|
||||
|
||||
@@ -47,6 +47,7 @@ import (
|
||||
type stateStore interface {
|
||||
GetSilences(ctx context.Context) (string, error)
|
||||
GetNotificationLog(ctx context.Context) (string, error)
|
||||
GetFlushLog(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// AutogenFn is a function that adds auto-generated routes to a configuration.
|
||||
@@ -86,6 +87,8 @@ type Alertmanager struct {
|
||||
|
||||
promoteConfig bool
|
||||
externalURL string
|
||||
|
||||
runtimeConfig remoteClient.RuntimeConfig
|
||||
}
|
||||
|
||||
type AlertmanagerConfig struct {
|
||||
@@ -111,6 +114,9 @@ type AlertmanagerConfig struct {
|
||||
|
||||
// Timeout for the HTTP client.
|
||||
Timeout time.Duration
|
||||
|
||||
// RuntimeConfig specifies runtime behavior settings for the remote Alertmanager.
|
||||
RuntimeConfig remoteClient.RuntimeConfig
|
||||
}
|
||||
|
||||
func (cfg *AlertmanagerConfig) Validate() error {
|
||||
@@ -203,6 +209,7 @@ func NewAlertmanager(ctx context.Context, cfg AlertmanagerConfig, store stateSto
|
||||
externalURL: cfg.ExternalURL,
|
||||
promoteConfig: cfg.PromoteConfig,
|
||||
smtp: cfg.SmtpConfig,
|
||||
runtimeConfig: cfg.RuntimeConfig,
|
||||
}
|
||||
|
||||
// Parse the default configuration once and remember its hash so we can compare it later.
|
||||
@@ -331,10 +338,11 @@ func (am *Alertmanager) buildConfiguration(ctx context.Context, raw []byte, crea
|
||||
AlertmanagerConfig: mergeResult.Config,
|
||||
Templates: templates,
|
||||
},
|
||||
CreatedAt: createdAtEpoch,
|
||||
Promoted: am.promoteConfig,
|
||||
ExternalURL: am.externalURL,
|
||||
SmtpConfig: am.smtp,
|
||||
CreatedAt: createdAtEpoch,
|
||||
Promoted: am.promoteConfig,
|
||||
ExternalURL: am.externalURL,
|
||||
SmtpConfig: am.smtp,
|
||||
RuntimeConfig: am.runtimeConfig,
|
||||
}
|
||||
|
||||
cfgHash, err := calculateUserGrafanaConfigHash(payload)
|
||||
@@ -388,6 +396,8 @@ func (am *Alertmanager) GetRemoteState(ctx context.Context) (notifier.ExternalSt
|
||||
rs.Silences = p.Data
|
||||
case "nfl":
|
||||
rs.Nflog = p.Data
|
||||
case "fls":
|
||||
rs.FlushLog = p.Data
|
||||
default:
|
||||
return rs, fmt.Errorf("unknown part key %q", p.Key)
|
||||
}
|
||||
@@ -677,6 +687,12 @@ func (am *Alertmanager) getFullState(ctx context.Context) (string, error) {
|
||||
}
|
||||
parts = append(parts, alertingClusterPB.Part{Key: notifier.NotificationLogFilename, Data: []byte(notificationLog)})
|
||||
|
||||
flushLog, err := am.state.GetFlushLog(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error getting flush log: %w", err)
|
||||
}
|
||||
parts = append(parts, alertingClusterPB.Part{Key: notifier.FlushLogFilename, Data: []byte(flushLog)})
|
||||
|
||||
fs := alertingClusterPB.FullState{
|
||||
Parts: parts,
|
||||
}
|
||||
|
||||
@@ -29,6 +29,10 @@ func (u *GrafanaAlertmanagerConfig) MarshalJSON() ([]byte, error) {
|
||||
return definition.MarshalJSONWithSecrets((*cfg)(u))
|
||||
}
|
||||
|
||||
type RuntimeConfig struct {
|
||||
DispatchTimer string `json:"dispatch_timer"`
|
||||
}
|
||||
|
||||
type UserGrafanaConfig struct {
|
||||
GrafanaAlertmanagerConfig GrafanaAlertmanagerConfig `json:"configuration"`
|
||||
Hash string `json:"configuration_hash"`
|
||||
@@ -37,6 +41,7 @@ type UserGrafanaConfig struct {
|
||||
Promoted bool `json:"promoted"`
|
||||
ExternalURL string `json:"external_url"`
|
||||
SmtpConfig SmtpConfig `json:"smtp_config"`
|
||||
RuntimeConfig RuntimeConfig `json:"runtime_config"`
|
||||
}
|
||||
|
||||
func (mc *Mimir) GetGrafanaAlertmanagerConfig(ctx context.Context) (*UserGrafanaConfig, error) {
|
||||
|
||||
@@ -600,6 +600,7 @@ type Cfg struct {
|
||||
IndexRebuildInterval time.Duration
|
||||
IndexCacheTTL time.Duration
|
||||
IndexMinUpdateInterval time.Duration // Don't update index if it was updated less than this interval ago.
|
||||
IndexScoringModel string // Note: Temporary config to switch the index scoring model and will be removed soon.
|
||||
MaxFileIndexAge time.Duration // Max age of file-based indexes. Index older than this will be rebuilt asynchronously.
|
||||
MinFileIndexBuildVersion string // Minimum version of Grafana that built the file-based index. If index was built with older Grafana, it will be rebuilt asynchronously.
|
||||
EnableSharding bool
|
||||
|
||||
@@ -123,6 +123,10 @@ func (cfg *Cfg) setUnifiedStorageConfig() {
|
||||
cfg.IndexRebuildInterval = section.Key("index_rebuild_interval").MustDuration(24 * time.Hour)
|
||||
cfg.IndexCacheTTL = section.Key("index_cache_ttl").MustDuration(10 * time.Minute)
|
||||
cfg.IndexMinUpdateInterval = section.Key("index_min_update_interval").MustDuration(0)
|
||||
cfg.IndexScoringModel = section.Key("index_scoring_model").MustString("")
|
||||
if cfg.IndexScoringModel != "" {
|
||||
cfg.Logger.Info("Index scoring model set", "model", cfg.IndexScoringModel)
|
||||
}
|
||||
cfg.SprinklesApiServer = section.Key("sprinkles_api_server").String()
|
||||
cfg.SprinklesApiServerPageLimit = section.Key("sprinkles_api_server_page_limit").MustInt(10000)
|
||||
cfg.CACertPath = section.Key("ca_cert_path").String()
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package dualwrite
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
|
||||
)
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
type dualWriteContext struct {
|
||||
updatedSecureValues common.InlineSecureValues
|
||||
}
|
||||
|
||||
func addToContext(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, &dualWriteContext{})
|
||||
}
|
||||
|
||||
// Get the Requester from context
|
||||
func SetUpdatedSecureValues(ctx context.Context, sv common.InlineSecureValues) {
|
||||
u, ok := ctx.Value(ctxKey{}).(*dualWriteContext)
|
||||
if !ok || u == nil {
|
||||
return // OK, this can happen when things are in mode 0 (legacy only)
|
||||
}
|
||||
u.updatedSecureValues = sv
|
||||
}
|
||||
|
||||
// Get the Requester from context
|
||||
func getUpdatedSecureValues(ctx context.Context) common.InlineSecureValues {
|
||||
u, ok := ctx.Value(ctxKey{}).(*dualWriteContext)
|
||||
if !ok || u == nil {
|
||||
return nil
|
||||
}
|
||||
return u.updatedSecureValues
|
||||
}
|
||||
@@ -16,15 +16,14 @@ import (
|
||||
"k8s.io/apiserver/pkg/registry/rest"
|
||||
|
||||
"github.com/grafana/grafana-app-sdk/logging"
|
||||
common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
|
||||
|
||||
"github.com/grafana/grafana/pkg/apimachinery/utils"
|
||||
grafanarest "github.com/grafana/grafana/pkg/apiserver/rest"
|
||||
)
|
||||
|
||||
var (
|
||||
_ grafanarest.Storage = (*dualWriter)(nil)
|
||||
|
||||
tracer = otel.Tracer("github.com/grafana/grafana/pkg/storage/legacysql/dualwrite")
|
||||
_ grafanarest.Storage = (*dualWriter)(nil)
|
||||
tracer = otel.Tracer("github.com/grafana/grafana/pkg/storage/legacysql/dualwrite")
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -204,7 +203,7 @@ func (d *dualWriter) Create(ctx context.Context, in runtime.Object, createValida
|
||||
|
||||
log := logging.FromContext(ctx).With("method", "Create")
|
||||
|
||||
accIn, err := utils.MetaAccessor(in)
|
||||
accIn, err := meta.Accessor(in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -217,19 +216,19 @@ func (d *dualWriter) Create(ctx context.Context, in runtime.Object, createValida
|
||||
return nil, fmt.Errorf("name or generatename have to be set")
|
||||
}
|
||||
|
||||
secure, err := accIn.GetSecureValues()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to read secure values %w", err)
|
||||
}
|
||||
|
||||
readFromUnifiedWriteToBothStorages := d.readUnified && d.legacy != nil && d.unified != nil
|
||||
|
||||
permissions := ""
|
||||
if readFromUnifiedWriteToBothStorages {
|
||||
objIn, err := utils.MetaAccessor(in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// keep permissions, we will set it back after the object is created
|
||||
permissions = accIn.GetAnnotation(utils.AnnoKeyGrantPermissions)
|
||||
permissions = objIn.GetAnnotation(utils.AnnoKeyGrantPermissions)
|
||||
if permissions != "" {
|
||||
accIn.SetAnnotation(utils.AnnoKeyGrantPermissions, "") // remove the annotation for now
|
||||
objIn.SetAnnotation(utils.AnnoKeyGrantPermissions, "") // remove the annotation for now
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,36 +241,35 @@ func (d *dualWriter) Create(ctx context.Context, in runtime.Object, createValida
|
||||
}
|
||||
|
||||
createdCopy := createdFromLegacy.DeepCopyObject()
|
||||
accCreated, err := utils.MetaAccessor(createdCopy)
|
||||
accCreated, err := meta.Accessor(createdCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accCreated.SetResourceVersion("")
|
||||
accCreated.SetUID("")
|
||||
if secure != nil {
|
||||
if err = accCreated.SetSecureValues(secure); err != nil {
|
||||
return nil, fmt.Errorf("unable to set secure values on duplicate object %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if readFromUnifiedWriteToBothStorages {
|
||||
objCopy, err := utils.MetaAccessor(createdCopy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// restore the permissions annotation, as we removed it before creating in legacy
|
||||
if permissions != "" {
|
||||
accCreated.SetAnnotation(utils.AnnoKeyGrantPermissions, permissions)
|
||||
objCopy.SetAnnotation(utils.AnnoKeyGrantPermissions, permissions)
|
||||
}
|
||||
|
||||
// Propagate annotations and labels to the object saved in
|
||||
// unified storage, making sure the `deprecatedID` is saved
|
||||
// as well as provisioning metadata, when present.
|
||||
for name, val := range accIn.GetAnnotations() {
|
||||
accCreated.SetAnnotation(name, val)
|
||||
objCopy.SetAnnotation(name, val)
|
||||
}
|
||||
|
||||
legacyAcc, err := meta.Accessor(createdFromLegacy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accCreated.SetLabels(legacyAcc.GetLabels())
|
||||
objCopy.SetLabels(legacyAcc.GetLabels())
|
||||
}
|
||||
|
||||
// If unified storage is the primary storage, let's just create it in the foreground and return it.
|
||||
@@ -386,7 +384,6 @@ func (d *dualWriter) Update(ctx context.Context, name string, objInfo rest.Updat
|
||||
// but legacy failed, the user would get a failure, but see the update did apply to the source
|
||||
// of truth, and be less likely to retry to save (and get the stores in sync again)
|
||||
|
||||
ctx = addToContext(ctx)
|
||||
legacyInfo := objInfo
|
||||
legacyForceCreate := forceAllowCreate
|
||||
unifiedInfo := objInfo
|
||||
@@ -420,14 +417,6 @@ func (d *dualWriter) Update(ctx context.Context, name string, objInfo rest.Updat
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate secure values from the update request to the unified storage update.
|
||||
if secure := getUpdatedSecureValues(ctx); secure != nil {
|
||||
wrapped, ok := unifiedInfo.(*wrappedUpdateInfo)
|
||||
if ok {
|
||||
wrapped.updatedSecureValues = secure
|
||||
}
|
||||
}
|
||||
|
||||
if d.readUnified {
|
||||
return d.unified.Update(ctx, name, unifiedInfo, createValidation, updateValidation, unifiedForceCreate, options)
|
||||
} else if d.errorIsOK {
|
||||
@@ -526,10 +515,9 @@ func (d *dualWriter) ConvertToTable(ctx context.Context, object runtime.Object,
|
||||
}
|
||||
|
||||
type wrappedUpdateInfo struct {
|
||||
objInfo rest.UpdatedObjectInfo
|
||||
legacyLabels map[string]string
|
||||
legacyAnnotations map[string]string
|
||||
updatedSecureValues common.InlineSecureValues
|
||||
objInfo rest.UpdatedObjectInfo
|
||||
legacyLabels map[string]string
|
||||
legacyAnnotations map[string]string
|
||||
}
|
||||
|
||||
// Preconditions implements rest.UpdatedObjectInfo.
|
||||
@@ -572,13 +560,6 @@ func (w *wrappedUpdateInfo) UpdatedObject(ctx context.Context, oldObj runtime.Ob
|
||||
|
||||
meta.SetResourceVersion("")
|
||||
meta.SetUID("")
|
||||
|
||||
if w.updatedSecureValues != nil {
|
||||
if err = meta.SetSecureValues(w.updatedSecureValues); err != nil {
|
||||
return nil, fmt.Errorf("unable to set secure values on duplicate object %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return obj, err
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,8 @@ package apistore
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
@@ -85,9 +83,6 @@ func (s *Storage) prepareObjectForStorage(ctx context.Context, newObject runtime
|
||||
if !ok {
|
||||
return v, errors.New("missing auth info")
|
||||
}
|
||||
if err := s.checkGVK(newObject); err != nil {
|
||||
return v, err
|
||||
}
|
||||
|
||||
obj, err := utils.MetaAccessor(newObject)
|
||||
if err != nil {
|
||||
@@ -143,7 +138,8 @@ func (s *Storage) prepareObjectForStorage(ctx context.Context, newObject runtime
|
||||
return v, err
|
||||
}
|
||||
|
||||
if err = s.encode(newObject, &v.raw); err == nil {
|
||||
err = s.codec.Encode(newObject, &v.raw)
|
||||
if err == nil {
|
||||
err = s.handleLargeResources(ctx, obj, &v.raw)
|
||||
}
|
||||
return v, err
|
||||
@@ -156,9 +152,6 @@ func (s *Storage) prepareObjectForUpdate(ctx context.Context, updateObject runti
|
||||
if !ok {
|
||||
return v, errors.New("missing auth info")
|
||||
}
|
||||
if err := s.checkGVK(updateObject); err != nil {
|
||||
return v, err
|
||||
}
|
||||
|
||||
obj, err := utils.MetaAccessor(updateObject)
|
||||
if err != nil {
|
||||
@@ -240,7 +233,8 @@ func (s *Storage) prepareObjectForUpdate(ctx context.Context, updateObject runti
|
||||
obj.SetAnnotation(utils.AnnoKeyUpdatedTimestamp, previous.GetAnnotation(utils.AnnoKeyUpdatedTimestamp))
|
||||
}
|
||||
|
||||
if err = s.encode(updateObject, &v.raw); err == nil {
|
||||
err = s.codec.Encode(updateObject, &v.raw)
|
||||
if err == nil {
|
||||
err = s.handleLargeResources(ctx, obj, &v.raw)
|
||||
}
|
||||
return v, err
|
||||
@@ -274,51 +268,7 @@ func (s *Storage) handleLargeResources(ctx context.Context, obj utils.GrafanaMet
|
||||
}
|
||||
|
||||
// Now encode the smaller version
|
||||
return s.encode(orig, buf)
|
||||
return s.codec.Encode(orig, buf)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Storage) checkGVK(obj runtime.Object) error {
|
||||
if s.opts.Scheme == nil {
|
||||
return nil // we can not do anything
|
||||
}
|
||||
|
||||
// Ensure group+version+kind are configured
|
||||
info := obj.GetObjectKind()
|
||||
gvk := info.GroupVersionKind()
|
||||
if gvk.Group == "" || gvk.Kind == "" || gvk.Version == "" {
|
||||
gvks, _, err := s.opts.Scheme.ObjectKinds(obj)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unknown object kind %w", err)
|
||||
}
|
||||
for _, v := range gvks {
|
||||
if v.Group != s.gr.Group {
|
||||
continue // skip values not in this group
|
||||
}
|
||||
gvk.Group = v.Group
|
||||
gvk.Kind = v.Kind
|
||||
if gvk.Version == "" {
|
||||
gvk.Version = v.Version
|
||||
}
|
||||
info.SetGroupVersionKind(gvk)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Storage) encode(obj runtime.Object, w io.Writer) error {
|
||||
// The standard encoder is fine when only one type maps to a group
|
||||
if s.opts.Scheme == nil {
|
||||
return s.codec.Encode(obj, w)
|
||||
}
|
||||
if err := s.checkGVK(obj); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// This will always write the saved GVK, unlike:
|
||||
// https://github.com/kubernetes/kubernetes/blob/v1.34.3/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go#L267
|
||||
// that picks an arbitrary GVK that may not match the same group!
|
||||
return json.NewEncoder(w).Encode(obj)
|
||||
}
|
||||
|
||||
@@ -33,11 +33,9 @@ func TestPrepareObjectForStorage(t *testing.T) {
|
||||
node, err := snowflake.NewNode(rand.Int64N(1024))
|
||||
require.NoError(t, err)
|
||||
s := &Storage{
|
||||
gr: dashv1.DashboardResourceInfo.GroupResource(),
|
||||
codec: apitesting.TestCodec(rtcodecs, dashv1.DashboardResourceInfo.GroupVersion()),
|
||||
snowflake: node,
|
||||
opts: StorageOptions{
|
||||
Scheme: rtscheme,
|
||||
EnableFolderSupport: true,
|
||||
LargeObjectSupport: nil,
|
||||
MaximumNameLength: 100,
|
||||
|
||||
@@ -57,8 +57,6 @@ type DefaultPermissionSetter = func(ctx context.Context, key *resourcepb.Resourc
|
||||
|
||||
// Optional settings that apply to a single resource
|
||||
type StorageOptions struct {
|
||||
Scheme *runtime.Scheme
|
||||
|
||||
// ????: should we constrain this to only dashboards for now?
|
||||
// Not yet clear if this is a good general solution, or just a stop-gap
|
||||
LargeObjectSupport LargeObjectSupport
|
||||
|
||||
@@ -177,6 +177,7 @@ func (c authzLimitedClient) Compile(ctx context.Context, id claims.AuthInfo, req
|
||||
return true
|
||||
}, claims.NoopZookie{}, nil
|
||||
}
|
||||
|
||||
if !claims.NamespaceMatches(id.GetNamespace(), req.Namespace) {
|
||||
span.SetAttributes(attribute.Bool("allowed", false))
|
||||
span.SetStatus(codes.Error, "Namespace mismatch")
|
||||
|
||||
@@ -81,6 +81,11 @@ type BleveOptions struct {
|
||||
// Indexes that are not owned by current instance are eligible for cleanup.
|
||||
// If nil, all indexes are owned by the current instance.
|
||||
OwnsIndex func(key resource.NamespacedResource) (bool, error)
|
||||
|
||||
// ScoringModel defines the scoring model used for the bleve indexes
|
||||
// Default: index.TFIDFScoring
|
||||
// Supported values: index.TFIDFScoring and index.BM25Scoring
|
||||
ScoringModel string
|
||||
}
|
||||
|
||||
type bleveBackend struct {
|
||||
@@ -368,7 +373,7 @@ func (b *bleveBackend) BuildIndex(
|
||||
attribute.String("reason", indexBuildReason),
|
||||
)
|
||||
|
||||
mapper, err := GetBleveMappings(fields)
|
||||
mapper, err := GetBleveMappings(b.opts.ScoringModel, fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/storage/unified/resource"
|
||||
@@ -19,6 +20,7 @@ func TestBleveSearchBackend(t *testing.T) {
|
||||
backend, err := NewBleveBackend(BleveOptions{
|
||||
Root: tempDir,
|
||||
FileThreshold: 5,
|
||||
ScoringModel: index.BM25Scoring,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, backend)
|
||||
@@ -52,3 +54,32 @@ func TestSearchBackendBenchmark(t *testing.T) {
|
||||
|
||||
unitest.BenchmarkSearchBackend(t, backend, opts)
|
||||
}
|
||||
|
||||
func BenchmarkScoringModels(b *testing.B) {
|
||||
models := []string{index.TFIDFScoring, index.BM25Scoring}
|
||||
|
||||
for _, model := range models {
|
||||
b.Run(model, func(b *testing.B) {
|
||||
tempDir := b.TempDir()
|
||||
|
||||
backend, err := NewBleveBackend(BleveOptions{
|
||||
Root: tempDir,
|
||||
ScoringModel: model,
|
||||
}, nil)
|
||||
require.NoError(b, err)
|
||||
require.NotNil(b, backend)
|
||||
|
||||
b.Cleanup(backend.Stop)
|
||||
|
||||
opts := &unitest.BenchmarkOptions{
|
||||
NumResources: 1000,
|
||||
Concurrency: 4,
|
||||
NumNamespaces: 10,
|
||||
NumGroups: 10,
|
||||
NumResourceTypes: 10,
|
||||
}
|
||||
|
||||
unitest.BenchmarkSearchBackend(b, backend, opts)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,15 @@ import (
|
||||
"github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
|
||||
"github.com/blevesearch/bleve/v2/analysis/analyzer/standard"
|
||||
"github.com/blevesearch/bleve/v2/mapping"
|
||||
|
||||
"github.com/grafana/grafana/pkg/storage/unified/resource"
|
||||
"github.com/grafana/grafana/pkg/storage/unified/resourcepb"
|
||||
)
|
||||
|
||||
func GetBleveMappings(fields resource.SearchableDocumentFields) (mapping.IndexMapping, error) {
|
||||
func GetBleveMappings(scoringModel string, fields resource.SearchableDocumentFields) (mapping.IndexMapping, error) {
|
||||
mapper := bleve.NewIndexMapping()
|
||||
if scoringModel != "" {
|
||||
mapper.ScoringModel = scoringModel
|
||||
}
|
||||
|
||||
err := RegisterCustomAnalyzers(mapper)
|
||||
if err != nil {
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func TestDocumentMapping(t *testing.T) {
|
||||
mappings, err := search.GetBleveMappings(nil)
|
||||
mappings, err := search.GetBleveMappings("", nil)
|
||||
require.NoError(t, err)
|
||||
data := resource.IndexableDocument{
|
||||
Title: "title",
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/blevesearch/bleve/v2"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/apimachinery/identity"
|
||||
@@ -258,6 +259,7 @@ func newTestDashboardsIndex(t testing.TB, threshold int64, size int64, writer re
|
||||
backend, err := search.NewBleveBackend(search.BleveOptions{
|
||||
Root: t.TempDir(),
|
||||
FileThreshold: threshold, // use in-memory for tests
|
||||
ScoringModel: index.BM25Scoring,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/blevesearch/bleve/v2"
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -50,6 +51,7 @@ func TestBleveBackend(t *testing.T) {
|
||||
backend, err := NewBleveBackend(BleveOptions{
|
||||
Root: tmpdir,
|
||||
FileThreshold: 5, // with more than 5 items we create a file on disk
|
||||
ScoringModel: index.BM25Scoring,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(backend.Stop)
|
||||
@@ -773,6 +775,7 @@ func setupBleveBackend(t *testing.T, options ...setupOption) (*bleveBackend, pro
|
||||
IndexCacheTTL: defaultIndexCacheTTL,
|
||||
Logger: log.NewNopLogger(),
|
||||
BuildVersion: buildVersion,
|
||||
ScoringModel: index.BM25Scoring,
|
||||
}
|
||||
for _, opt := range options {
|
||||
opt(&opts)
|
||||
|
||||
@@ -46,6 +46,7 @@ func NewSearchOptions(
|
||||
BuildVersion: cfg.BuildVersion,
|
||||
OwnsIndex: ownsIndexFn,
|
||||
IndexMinUpdateInterval: cfg.IndexMinUpdateInterval,
|
||||
ScoringModel: cfg.IndexScoringModel,
|
||||
}, indexMetrics)
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
index "github.com/blevesearch/bleve_index_api"
|
||||
"github.com/go-jose/go-jose/v4/jwt"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -129,21 +130,28 @@ func TestIntegrationSearchAndStorage(t *testing.T) {
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a new bleve backend
|
||||
search, err := search.NewBleveBackend(search.BleveOptions{
|
||||
FileThreshold: 0,
|
||||
Root: t.TempDir(),
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, search)
|
||||
t.Cleanup(search.Stop)
|
||||
scoringModels := []string{index.TFIDFScoring, index.BM25Scoring}
|
||||
|
||||
// Create a new resource backend
|
||||
storage, _ := newTestBackend(t, false, 0)
|
||||
require.NotNil(t, storage)
|
||||
for _, model := range scoringModels {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
// Create a new bleve backend
|
||||
search, err := search.NewBleveBackend(search.BleveOptions{
|
||||
FileThreshold: 0,
|
||||
Root: t.TempDir(),
|
||||
ScoringModel: model,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, search)
|
||||
t.Cleanup(search.Stop)
|
||||
|
||||
// Run the shared storage and search tests
|
||||
unitest.RunTestSearchAndStorage(t, ctx, storage, search)
|
||||
// Create a new resource backend
|
||||
storage, _ := newTestBackend(t, false, 0)
|
||||
require.NotNil(t, storage)
|
||||
|
||||
// Run the shared storage and search tests
|
||||
unitest.RunTestSearchAndStorage(t, ctx, storage, search)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientServer(t *testing.T) {
|
||||
|
||||
@@ -209,7 +209,7 @@
|
||||
"path": "public/plugins/grafana-azure-monitor-datasource/img/azure_monitor_cpu.png"
|
||||
}
|
||||
],
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": [
|
||||
"azure",
|
||||
@@ -589,7 +589,7 @@
|
||||
"hasUpdate": false,
|
||||
"defaultNavUrl": "/plugins/datagrid/",
|
||||
"category": "",
|
||||
"state": "beta",
|
||||
"state": "deprecated",
|
||||
"signature": "internal",
|
||||
"signatureType": "",
|
||||
"signatureOrg": "",
|
||||
@@ -880,7 +880,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -934,7 +934,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": [
|
||||
"grafana",
|
||||
@@ -1000,7 +1000,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -1217,7 +1217,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -1325,7 +1325,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -1375,7 +1375,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -1425,7 +1425,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -1575,7 +1575,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -1629,7 +1629,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": [
|
||||
"grafana",
|
||||
@@ -1734,7 +1734,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -2042,7 +2042,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -2092,7 +2092,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
@@ -2445,7 +2445,7 @@
|
||||
},
|
||||
"build": {},
|
||||
"screenshots": null,
|
||||
"version": "12.3.0-pre",
|
||||
"version": "12.4.0-pre",
|
||||
"updated": "",
|
||||
"keywords": null
|
||||
},
|
||||
|
||||
@@ -5,8 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -15,11 +13,9 @@ import (
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
|
||||
"github.com/grafana/grafana/pkg/apimachinery/utils"
|
||||
grafanarest "github.com/grafana/grafana/pkg/apiserver/rest"
|
||||
"github.com/grafana/grafana/pkg/components/simplejson"
|
||||
"github.com/grafana/grafana/pkg/services/datasources"
|
||||
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/grafana/grafana/pkg/tests/apis"
|
||||
"github.com/grafana/grafana/pkg/tests/testinfra"
|
||||
"github.com/grafana/grafana/pkg/tests/testsuite"
|
||||
@@ -32,192 +28,112 @@ func TestMain(m *testing.M) {
|
||||
|
||||
func TestIntegrationTestDatasource(t *testing.T) {
|
||||
testutil.SkipIntegrationTestInShortMode(t)
|
||||
expectedAPIVersion := "grafana-testdata-datasource.datasource.grafana.app/v0alpha1"
|
||||
|
||||
for _, mode := range []grafanarest.DualWriterMode{
|
||||
grafanarest.Mode0, // Legacy only
|
||||
grafanarest.Mode2, // write both, read legacy
|
||||
grafanarest.Mode3, // write both, read unified
|
||||
grafanarest.Mode5, // Unified only
|
||||
} {
|
||||
t.Run(fmt.Sprintf("testdata (mode:%d)", mode), func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{
|
||||
DisableAnonymous: true,
|
||||
EnableFeatureToggles: []string{
|
||||
featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, // Required to start the datasource api servers
|
||||
featuremgmt.FlagQueryServiceWithConnections, // enables CRUD endpoints
|
||||
},
|
||||
UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{
|
||||
"datasources.grafana-testdata-datasource.datasource.grafana.app": {
|
||||
DualWriterMode: mode,
|
||||
},
|
||||
},
|
||||
})
|
||||
helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{
|
||||
AppModeProduction: false, // dev mode required for datasource connections
|
||||
DisableAnonymous: true,
|
||||
EnableFeatureToggles: []string{
|
||||
featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, // Required to start the example service
|
||||
},
|
||||
})
|
||||
|
||||
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
|
||||
Group: "grafana-testdata-datasource.datasource.grafana.app",
|
||||
Version: "v0alpha1",
|
||||
Resource: "datasources",
|
||||
}).Namespace("default")
|
||||
// Create a single datasource
|
||||
ds := helper.CreateDS(&datasources.AddDataSourceCommand{
|
||||
Name: "test",
|
||||
Type: datasources.DS_TESTDATA,
|
||||
UID: "test",
|
||||
OrgID: int64(1),
|
||||
|
||||
t.Run("create", func(t *testing.T) {
|
||||
out, err := client.Create(ctx, &unstructured.Unstructured{
|
||||
Object: map[string]any{
|
||||
"apiVersion": "grafana-testdata-datasource.datasource.grafana.app/v0alpha1",
|
||||
"kind": "DataSource",
|
||||
"metadata": map[string]any{
|
||||
"name": "test",
|
||||
},
|
||||
"spec": map[string]any{
|
||||
"title": "test",
|
||||
},
|
||||
"secure": map[string]any{
|
||||
"aaa": map[string]any{
|
||||
"create": "AAA",
|
||||
},
|
||||
"bbb": map[string]any{
|
||||
"create": "BBB",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, metav1.CreateOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "test", out.GetName())
|
||||
require.Equal(t, expectedAPIVersion, out.GetAPIVersion())
|
||||
// These settings are not actually used, but testing that they get saved
|
||||
Database: "testdb",
|
||||
URL: "http://fake.url",
|
||||
Access: datasources.DS_ACCESS_PROXY,
|
||||
User: "example",
|
||||
ReadOnly: true,
|
||||
JsonData: simplejson.NewFromAny(map[string]any{
|
||||
"hello": "world",
|
||||
}),
|
||||
SecureJsonData: map[string]string{
|
||||
"aaa": "AAA",
|
||||
"bbb": "BBB",
|
||||
},
|
||||
})
|
||||
require.Equal(t, "test", ds.UID)
|
||||
|
||||
obj, err := utils.MetaAccessor(out)
|
||||
require.NoError(t, err)
|
||||
t.Run("Admin configs", func(t *testing.T) {
|
||||
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
|
||||
Group: "grafana-testdata-datasource.datasource.grafana.app",
|
||||
Version: "v0alpha1",
|
||||
Resource: "datasources",
|
||||
}).Namespace("default")
|
||||
ctx := context.Background()
|
||||
|
||||
secure, err := obj.GetSecureValues()
|
||||
require.NoError(t, err)
|
||||
list, err := client.List(ctx, metav1.ListOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, list.Items, 1, "expected a single connection")
|
||||
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
|
||||
|
||||
keys := slices.Collect(maps.Keys(secure))
|
||||
require.ElementsMatch(t, []string{"aaa", "bbb"}, keys)
|
||||
})
|
||||
spec, _, _ := unstructured.NestedMap(list.Items[0].Object, "spec")
|
||||
jj, _ := json.MarshalIndent(spec, "", " ")
|
||||
fmt.Printf("%s\n", string(jj))
|
||||
require.JSONEq(t, `{
|
||||
"access": "proxy",
|
||||
"database": "testdb",
|
||||
"isDefault": true,
|
||||
"jsonData": {
|
||||
"hello": "world"
|
||||
},
|
||||
"readOnly": true,
|
||||
"title": "test",
|
||||
"url": "http://fake.url",
|
||||
"user": "example"
|
||||
}`, string(jj))
|
||||
})
|
||||
|
||||
t.Run("update", func(t *testing.T) {
|
||||
out, err := client.Update(ctx, &unstructured.Unstructured{
|
||||
Object: map[string]any{
|
||||
"apiVersion": "grafana-testdata-datasource.datasource.grafana.app/v0alpha1",
|
||||
"metadata": map[string]any{
|
||||
"name": "test",
|
||||
},
|
||||
"spec": map[string]any{
|
||||
"title": "test",
|
||||
"database": "testdb",
|
||||
"url": "http://fake.url",
|
||||
"access": datasources.DS_ACCESS_PROXY,
|
||||
"user": "example",
|
||||
"isDefault": true,
|
||||
"readOnly": true,
|
||||
"jsonData": map[string]any{
|
||||
"hello": "world",
|
||||
},
|
||||
},
|
||||
"secure": map[string]any{
|
||||
// "aaa": map[string]any{
|
||||
// "remove": true, // remove does not really remove in legacy!
|
||||
// },
|
||||
"ccc": map[string]any{
|
||||
"create": "CCC", // add a third value
|
||||
},
|
||||
},
|
||||
},
|
||||
}, metav1.UpdateOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "test", out.GetName())
|
||||
require.Equal(t, expectedAPIVersion, out.GetAPIVersion())
|
||||
t.Run("Call subresources", func(t *testing.T) {
|
||||
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
|
||||
Group: "grafana-testdata-datasource.datasource.grafana.app",
|
||||
Version: "v0alpha1",
|
||||
Resource: "datasources",
|
||||
}).Namespace("default")
|
||||
ctx := context.Background()
|
||||
|
||||
obj, err := utils.MetaAccessor(out)
|
||||
require.NoError(t, err)
|
||||
list, err := client.List(ctx, metav1.ListOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, list.Items, 1, "expected a single connection")
|
||||
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
|
||||
|
||||
secure, err := obj.GetSecureValues()
|
||||
require.NoError(t, err)
|
||||
_, err = client.Get(ctx, "test", metav1.GetOptions{}, "health")
|
||||
// endpoint is disabled currently because it has not been
|
||||
// sufficiently tested.
|
||||
// for more info see pkg/registry/apis/datasource/sub_health.go
|
||||
require.Error(t, err)
|
||||
var statusErr *apierrors.StatusError
|
||||
require.True(t, errors.As(err, &statusErr))
|
||||
require.Equal(t, int32(501), statusErr.ErrStatus.Code)
|
||||
// require.NoError(t, err)
|
||||
// body, err := rsp.MarshalJSON()
|
||||
// require.NoError(t, err)
|
||||
// //fmt.Printf("GOT: %v\n", string(body))
|
||||
// require.JSONEq(t, `{
|
||||
// "apiVersion": "testdata.datasource.grafana.app/v0alpha1",
|
||||
// "code": 1,
|
||||
// "kind": "HealthCheckResult",
|
||||
// "message": "Data source is working",
|
||||
// "status": "OK"
|
||||
// }
|
||||
// `, string(body))
|
||||
|
||||
keys := slices.Collect(maps.Keys(secure))
|
||||
require.ElementsMatch(t, []string{"aaa", "bbb", "ccc"}, keys)
|
||||
})
|
||||
|
||||
t.Run("list", func(t *testing.T) {
|
||||
list, err := client.List(ctx, metav1.ListOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, expectedAPIVersion, list.GetAPIVersion())
|
||||
require.Len(t, list.Items, 1, "expected a single datasource")
|
||||
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
|
||||
|
||||
spec, _, _ := unstructured.NestedMap(list.Items[0].Object, "spec")
|
||||
jj, _ := json.MarshalIndent(spec, "", " ")
|
||||
// fmt.Printf("%s\n", string(jj))
|
||||
require.JSONEq(t, `{
|
||||
"access": "proxy",
|
||||
"database": "testdb",
|
||||
"isDefault": true,
|
||||
"jsonData": {
|
||||
"hello": "world"
|
||||
},
|
||||
"readOnly": true,
|
||||
"title": "test",
|
||||
"url": "http://fake.url",
|
||||
"user": "example"
|
||||
}`, string(jj))
|
||||
})
|
||||
|
||||
t.Run("execute", func(t *testing.T) {
|
||||
client := helper.Org1.Admin.ResourceClient(t, schema.GroupVersionResource{
|
||||
Group: "grafana-testdata-datasource.datasource.grafana.app",
|
||||
Version: "v0alpha1",
|
||||
Resource: "datasources",
|
||||
}).Namespace("default")
|
||||
ctx := context.Background()
|
||||
|
||||
list, err := client.List(ctx, metav1.ListOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, list.Items, 1, "expected a single connection")
|
||||
require.Equal(t, "test", list.Items[0].GetName(), "with the test uid")
|
||||
|
||||
_, err = client.Get(ctx, "test", metav1.GetOptions{}, "health")
|
||||
// endpoint is disabled currently because it has not been
|
||||
// sufficiently tested.
|
||||
// for more info see pkg/registry/apis/datasource/sub_health.go
|
||||
require.Error(t, err)
|
||||
var statusErr *apierrors.StatusError
|
||||
require.True(t, errors.As(err, &statusErr))
|
||||
require.Equal(t, int32(501), statusErr.ErrStatus.Code)
|
||||
// require.NoError(t, err)
|
||||
// body, err := rsp.MarshalJSON()
|
||||
// require.NoError(t, err)
|
||||
// //fmt.Printf("GOT: %v\n", string(body))
|
||||
// require.JSONEq(t, `{
|
||||
// "apiVersion": "grafana-testdata-datasource.datasource.grafana.app/v0alpha1",
|
||||
// "code": 1,
|
||||
// "kind": "HealthCheckResult",
|
||||
// "message": "Data source is working",
|
||||
// "status": "OK"
|
||||
// }
|
||||
// `, string(body))
|
||||
|
||||
// Test connecting to non-JSON marshaled data
|
||||
raw := apis.DoRequest[any](helper, apis.RequestParams{
|
||||
User: helper.Org1.Admin,
|
||||
Method: "GET",
|
||||
Path: "/apis/grafana-testdata-datasource.datasource.grafana.app/v0alpha1/namespaces/default/datasources/test/resource",
|
||||
}, nil)
|
||||
// endpoint is disabled currently because it has not been
|
||||
// sufficiently tested.
|
||||
// for more info see pkg/registry/apis/datasource/sub_resource.go
|
||||
require.Equal(t, int32(501), raw.Status.Code)
|
||||
// require.Equal(t, `Hello world from test datasource!`, string(raw.Body))
|
||||
})
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
err := client.Delete(ctx, "test", metav1.DeleteOptions{})
|
||||
require.NoError(t, err)
|
||||
|
||||
list, err := client.List(ctx, metav1.ListOptions{})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, list.Items)
|
||||
})
|
||||
})
|
||||
}
|
||||
// Test connecting to non-JSON marshaled data
|
||||
raw := apis.DoRequest[any](helper, apis.RequestParams{
|
||||
User: helper.Org1.Admin,
|
||||
Method: "GET",
|
||||
Path: "/apis/grafana-testdata-datasource.datasource.grafana.app/v0alpha1/namespaces/default/datasources/test/resource",
|
||||
}, nil)
|
||||
// endpoint is disabled currently because it has not been
|
||||
// sufficiently tested.
|
||||
// for more info see pkg/registry/apis/datasource/sub_resource.go
|
||||
require.Equal(t, int32(501), raw.Status.Code)
|
||||
// require.Equal(t, `Hello world from test datasource!`, string(raw.Body))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -103,98 +103,6 @@
|
||||
],
|
||||
"description": "list objects of kind DataSource",
|
||||
"operationId": "listDataSource",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "allowWatchBookmarks",
|
||||
"in": "query",
|
||||
"description": "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "continue",
|
||||
"in": "query",
|
||||
"description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldSelector",
|
||||
"in": "query",
|
||||
"description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "labelSelector",
|
||||
"in": "query",
|
||||
"description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "resourceVersion",
|
||||
"in": "query",
|
||||
"description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "resourceVersionMatch",
|
||||
"in": "query",
|
||||
"description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sendInitialEvents",
|
||||
"in": "query",
|
||||
"description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "timeoutSeconds",
|
||||
"in": "query",
|
||||
"description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "watch",
|
||||
"in": "query",
|
||||
"description": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
@@ -234,285 +142,52 @@
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"tags": [
|
||||
"DataSource"
|
||||
],
|
||||
"description": "create a DataSource",
|
||||
"operationId": "createDataSource",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "dryRun",
|
||||
"in": "query",
|
||||
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldManager",
|
||||
"in": "query",
|
||||
"description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldValidation",
|
||||
"in": "query",
|
||||
"description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"202": {
|
||||
"description": "Accepted",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"x-kubernetes-action": "post",
|
||||
"x-kubernetes-group-version-kind": {
|
||||
"group": "grafana-testdata-datasource.datasource.grafana.app",
|
||||
"version": "v0alpha1",
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"DataSource"
|
||||
],
|
||||
"description": "delete collection of DataSource",
|
||||
"operationId": "deletecollectionDataSource",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "continue",
|
||||
"in": "query",
|
||||
"description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "dryRun",
|
||||
"in": "query",
|
||||
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldSelector",
|
||||
"in": "query",
|
||||
"description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "gracePeriodSeconds",
|
||||
"in": "query",
|
||||
"description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "ignoreStoreReadErrorWithClusterBreakingPotential",
|
||||
"in": "query",
|
||||
"description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "labelSelector",
|
||||
"in": "query",
|
||||
"description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "orphanDependents",
|
||||
"in": "query",
|
||||
"description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "propagationPolicy",
|
||||
"in": "query",
|
||||
"description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "resourceVersion",
|
||||
"in": "query",
|
||||
"description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "resourceVersionMatch",
|
||||
"in": "query",
|
||||
"description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sendInitialEvents",
|
||||
"in": "query",
|
||||
"description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "timeoutSeconds",
|
||||
"in": "query",
|
||||
"description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"x-kubernetes-action": "deletecollection",
|
||||
"x-kubernetes-group-version-kind": {
|
||||
"group": "grafana-testdata-datasource.datasource.grafana.app",
|
||||
"version": "v0alpha1",
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "allowWatchBookmarks",
|
||||
"in": "query",
|
||||
"description": "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "continue",
|
||||
"in": "query",
|
||||
"description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldSelector",
|
||||
"in": "query",
|
||||
"description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "labelSelector",
|
||||
"in": "query",
|
||||
"description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "namespace",
|
||||
"in": "path",
|
||||
@@ -531,6 +206,51 @@
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "resourceVersion",
|
||||
"in": "query",
|
||||
"description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "resourceVersionMatch",
|
||||
"in": "query",
|
||||
"description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sendInitialEvents",
|
||||
"in": "query",
|
||||
"description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "timeoutSeconds",
|
||||
"in": "query",
|
||||
"description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "watch",
|
||||
"in": "query",
|
||||
"description": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -570,330 +290,6 @@
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"tags": [
|
||||
"DataSource"
|
||||
],
|
||||
"description": "replace the specified DataSource",
|
||||
"operationId": "replaceDataSource",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "dryRun",
|
||||
"in": "query",
|
||||
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldManager",
|
||||
"in": "query",
|
||||
"description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldValidation",
|
||||
"in": "query",
|
||||
"description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"x-kubernetes-action": "put",
|
||||
"x-kubernetes-group-version-kind": {
|
||||
"group": "grafana-testdata-datasource.datasource.grafana.app",
|
||||
"version": "v0alpha1",
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"tags": [
|
||||
"DataSource"
|
||||
],
|
||||
"description": "delete a DataSource",
|
||||
"operationId": "deleteDataSource",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "dryRun",
|
||||
"in": "query",
|
||||
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "gracePeriodSeconds",
|
||||
"in": "query",
|
||||
"description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "ignoreStoreReadErrorWithClusterBreakingPotential",
|
||||
"in": "query",
|
||||
"description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "orphanDependents",
|
||||
"in": "query",
|
||||
"description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "propagationPolicy",
|
||||
"in": "query",
|
||||
"description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"202": {
|
||||
"description": "Accepted",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"x-kubernetes-action": "delete",
|
||||
"x-kubernetes-group-version-kind": {
|
||||
"group": "grafana-testdata-datasource.datasource.grafana.app",
|
||||
"version": "v0alpha1",
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"tags": [
|
||||
"DataSource"
|
||||
],
|
||||
"description": "partially update the specified DataSource",
|
||||
"operationId": "updateDataSource",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "dryRun",
|
||||
"in": "query",
|
||||
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldManager",
|
||||
"in": "query",
|
||||
"description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fieldValidation",
|
||||
"in": "query",
|
||||
"description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"uniqueItems": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"in": "query",
|
||||
"description": "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.",
|
||||
"schema": {
|
||||
"type": "boolean",
|
||||
"uniqueItems": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/apply-patch+yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
|
||||
}
|
||||
},
|
||||
"application/json-patch+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
|
||||
}
|
||||
},
|
||||
"application/merge-patch+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
|
||||
}
|
||||
},
|
||||
"application/strategic-merge-patch+json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/vnd.kubernetes.protobuf": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
},
|
||||
"application/yaml": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apis.datasource.v0alpha1.DataSource"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"x-kubernetes-action": "patch",
|
||||
"x-kubernetes-group-version-kind": {
|
||||
"group": "grafana-testdata-datasource.datasource.grafana.app",
|
||||
"version": "v0alpha1",
|
||||
"kind": "DataSource"
|
||||
}
|
||||
},
|
||||
"parameters": [
|
||||
{
|
||||
"name": "name",
|
||||
@@ -1550,54 +946,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions": {
|
||||
"description": "DeleteOptions may be provided when deleting an API object.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"apiVersion": {
|
||||
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
|
||||
"type": "string"
|
||||
},
|
||||
"dryRun": {
|
||||
"description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"default": ""
|
||||
},
|
||||
"x-kubernetes-list-type": "atomic"
|
||||
},
|
||||
"gracePeriodSeconds": {
|
||||
"description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
"ignoreStoreReadErrorWithClusterBreakingPotential": {
|
||||
"description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it",
|
||||
"type": "boolean"
|
||||
},
|
||||
"kind": {
|
||||
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
|
||||
"type": "string"
|
||||
},
|
||||
"orphanDependents": {
|
||||
"description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"preconditions": {
|
||||
"description": "Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions"
|
||||
}
|
||||
]
|
||||
},
|
||||
"propagationPolicy": {
|
||||
"description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1": {
|
||||
"description": "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:\u003cname\u003e', where \u003cname\u003e is the name of a field in a struct, or key in a map 'v:\u003cvalue\u003e', where \u003cvalue\u003e is the exact json formatted value of a list item 'i:\u003cindex\u003e', where \u003cindex\u003e is position of a item in a list 'k:\u003ckeys\u003e', where \u003ckeys\u003e is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff",
|
||||
"type": "object"
|
||||
@@ -1821,131 +1169,6 @@
|
||||
},
|
||||
"x-kubernetes-map-type": "atomic"
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.Patch": {
|
||||
"description": "Patch is provided to give a concrete name and type to the Kubernetes PATCH request body.",
|
||||
"type": "object"
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.Preconditions": {
|
||||
"description": "Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"resourceVersion": {
|
||||
"description": "Specifies the target ResourceVersion",
|
||||
"type": "string"
|
||||
},
|
||||
"uid": {
|
||||
"description": "Specifies the target UID.",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.Status": {
|
||||
"description": "Status is a return value for calls that don't return other objects.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"apiVersion": {
|
||||
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
|
||||
"type": "string"
|
||||
},
|
||||
"code": {
|
||||
"description": "Suggested HTTP return code for this status, 0 if not set.",
|
||||
"type": "integer",
|
||||
"format": "int32"
|
||||
},
|
||||
"details": {
|
||||
"description": "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.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.StatusDetails"
|
||||
}
|
||||
],
|
||||
"x-kubernetes-list-type": "atomic"
|
||||
},
|
||||
"kind": {
|
||||
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
|
||||
"type": "string"
|
||||
},
|
||||
"message": {
|
||||
"description": "A human-readable description of the status of this operation.",
|
||||
"type": "string"
|
||||
},
|
||||
"metadata": {
|
||||
"description": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
|
||||
"default": {},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta"
|
||||
}
|
||||
]
|
||||
},
|
||||
"reason": {
|
||||
"description": "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.",
|
||||
"type": "string"
|
||||
},
|
||||
"status": {
|
||||
"description": "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",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.StatusCause": {
|
||||
"description": "StatusCause provides more information about an api.Status failure, including cases when multiple errors are encountered.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"field": {
|
||||
"description": "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.\n\nExamples:\n \"name\" - the field \"name\" on the current resource\n \"items[0].name\" - the field \"name\" on the first array entry in \"items\"",
|
||||
"type": "string"
|
||||
},
|
||||
"message": {
|
||||
"description": "A human-readable description of the cause of the error. This field may be presented as-is to a reader.",
|
||||
"type": "string"
|
||||
},
|
||||
"reason": {
|
||||
"description": "A machine-readable description of the cause of the error. If this value is empty there is no information available.",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.StatusDetails": {
|
||||
"description": "StatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"causes": {
|
||||
"description": "The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"default": {},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.StatusCause"
|
||||
}
|
||||
]
|
||||
},
|
||||
"x-kubernetes-list-type": "atomic"
|
||||
},
|
||||
"group": {
|
||||
"description": "The group attribute of the resource associated with the status StatusReason.",
|
||||
"type": "string"
|
||||
},
|
||||
"kind": {
|
||||
"description": "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",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"description": "The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described).",
|
||||
"type": "string"
|
||||
},
|
||||
"retryAfterSeconds": {
|
||||
"description": "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.",
|
||||
"type": "integer",
|
||||
"format": "int32"
|
||||
},
|
||||
"uid": {
|
||||
"description": "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",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"io.k8s.apimachinery.pkg.apis.meta.v1.Time": {
|
||||
"description": "Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.",
|
||||
"type": "string",
|
||||
|
||||
@@ -108,7 +108,9 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
|
||||
}),
|
||||
|
||||
grafanaNotifiers: build.query<NotifierDTO[], void>({
|
||||
query: () => ({ url: '/api/alert-notifiers' }),
|
||||
// NOTE: version=2 parameter required for versioned schema (PR #109969)
|
||||
// This parameter will be removed in future when v2 becomes default
|
||||
query: () => ({ url: '/api/alert-notifiers?version=2' }),
|
||||
transformResponse: (response: NotifierDTO[]) => {
|
||||
const populateSecureFieldKey = (
|
||||
option: NotificationChannelOption,
|
||||
@@ -121,11 +123,16 @@ export const alertmanagerApi = alertingApi.injectEndpoints({
|
||||
),
|
||||
});
|
||||
|
||||
// Keep versions array intact for version-specific options lookup
|
||||
// Transform options with secureFieldKey population
|
||||
return response.map((notifier) => ({
|
||||
...notifier,
|
||||
options: notifier.options.map((option) => {
|
||||
return populateSecureFieldKey(option, '');
|
||||
}),
|
||||
options: (notifier.options || []).map((option) => populateSecureFieldKey(option, '')),
|
||||
// Also transform options within each version
|
||||
versions: notifier.versions?.map((version) => ({
|
||||
...version,
|
||||
options: (version.options || []).map((option) => populateSecureFieldKey(option, '')),
|
||||
})),
|
||||
}));
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -46,6 +46,7 @@ export type GrafanaPromRulesOptions = Omit<PromRulesOptions, 'ruleSource' | 'nam
|
||||
state?: PromAlertingRuleState[];
|
||||
title?: string;
|
||||
searchGroupName?: string;
|
||||
searchFolder?: string;
|
||||
type?: 'alerting' | 'recording';
|
||||
ruleMatchers?: string[];
|
||||
plugins?: 'hide' | 'only';
|
||||
@@ -103,6 +104,7 @@ export const prometheusApi = alertingApi.injectEndpoints({
|
||||
title,
|
||||
datasources,
|
||||
searchGroupName,
|
||||
searchFolder,
|
||||
dashboardUid,
|
||||
ruleMatchers,
|
||||
plugins,
|
||||
@@ -123,6 +125,7 @@ export const prometheusApi = alertingApi.injectEndpoints({
|
||||
datasource_uid: datasources,
|
||||
'search.rule_name': title,
|
||||
'search.rule_group': searchGroupName,
|
||||
'search.folder': searchFolder,
|
||||
dashboard_uid: dashboardUid,
|
||||
rule_matcher: ruleMatchers,
|
||||
plugins: plugins,
|
||||
|
||||
@@ -36,6 +36,24 @@ export const ProvisioningAlert = ({ resource, ...rest }: ProvisioningAlertProps)
|
||||
);
|
||||
};
|
||||
|
||||
export const ImportedContactPointAlert = (props: ExtraAlertProps) => {
|
||||
return (
|
||||
<Alert
|
||||
title={t(
|
||||
'alerting.provisioning.title-imported',
|
||||
'This contact point was imported and cannot be edited through the UI'
|
||||
)}
|
||||
severity="info"
|
||||
{...props}
|
||||
>
|
||||
<Trans i18nKey="alerting.provisioning.body-imported">
|
||||
This contact point contains integrations that were imported from an external Alertmanager and is currently
|
||||
read-only. The integrations will become editable after the migration process is complete.
|
||||
</Trans>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
|
||||
export const ProvisioningBadge = ({
|
||||
tooltip,
|
||||
provenance,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import 'core-js/stable/structured-clone';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
import { clickSelectOption } from 'test/helpers/selectOptionInTest';
|
||||
import { render } from 'test/test-utils';
|
||||
import { render, screen } from 'test/test-utils';
|
||||
import { byRole, byTestId } from 'testing-library-selector';
|
||||
|
||||
import { grafanaAlertNotifiers } from 'app/features/alerting/unified/mockGrafanaNotifiers';
|
||||
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
|
||||
import { NotifierDTO } from 'app/features/alerting/unified/types/alerting';
|
||||
|
||||
import { ChannelSubForm } from './ChannelSubForm';
|
||||
import { GrafanaCommonChannelSettings } from './GrafanaCommonChannelSettings';
|
||||
@@ -16,6 +17,7 @@ type TestChannelValues = {
|
||||
type: string;
|
||||
settings: Record<string, unknown>;
|
||||
secureFields: Record<string, boolean>;
|
||||
version?: string;
|
||||
};
|
||||
|
||||
type TestReceiverFormValues = {
|
||||
@@ -246,4 +248,241 @@ describe('ChannelSubForm', () => {
|
||||
expect(slackUrl).toBeEnabled();
|
||||
expect(slackUrl).toHaveValue('');
|
||||
});
|
||||
|
||||
describe('version-specific options display', () => {
|
||||
// Create a mock notifier with different options for v0 and v1
|
||||
const legacyOptions = [
|
||||
{
|
||||
element: 'input' as const,
|
||||
inputType: 'text',
|
||||
label: 'Legacy URL',
|
||||
description: 'The legacy endpoint URL',
|
||||
placeholder: '',
|
||||
propertyName: 'legacyUrl',
|
||||
required: true,
|
||||
secure: false,
|
||||
showWhen: { field: '', is: '' },
|
||||
validationRule: '',
|
||||
dependsOn: '',
|
||||
},
|
||||
];
|
||||
|
||||
const webhookWithVersions: NotifierDTO = {
|
||||
...grafanaAlertNotifiers.webhook,
|
||||
versions: [
|
||||
{
|
||||
version: 'v0mimir1',
|
||||
label: 'Webhook (Legacy)',
|
||||
description: 'Legacy webhook from Mimir',
|
||||
canCreate: false,
|
||||
options: legacyOptions,
|
||||
},
|
||||
{
|
||||
version: 'v0mimir2',
|
||||
label: 'Webhook (Legacy v2)',
|
||||
description: 'Legacy webhook v2 from Mimir',
|
||||
canCreate: false,
|
||||
options: legacyOptions,
|
||||
},
|
||||
{
|
||||
version: 'v1',
|
||||
label: 'Webhook',
|
||||
description: 'Sends HTTP POST request',
|
||||
canCreate: true,
|
||||
options: grafanaAlertNotifiers.webhook.options,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const versionedNotifiers: Notifier[] = [
|
||||
{ dto: webhookWithVersions, meta: { enabled: true, order: 1 } },
|
||||
{ dto: grafanaAlertNotifiers.slack, meta: { enabled: true, order: 2 } },
|
||||
];
|
||||
|
||||
function VersionedTestFormWrapper({
|
||||
defaults,
|
||||
initial,
|
||||
}: {
|
||||
defaults: TestChannelValues;
|
||||
initial?: TestChannelValues;
|
||||
}) {
|
||||
const form = useForm<TestReceiverFormValues>({
|
||||
defaultValues: {
|
||||
name: 'test-contact-point',
|
||||
items: [defaults],
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<AlertmanagerProvider accessType="notification">
|
||||
<FormProvider {...form}>
|
||||
<ChannelSubForm
|
||||
defaultValues={defaults}
|
||||
initialValues={initial}
|
||||
pathPrefix={`items.0.`}
|
||||
integrationIndex={0}
|
||||
notifiers={versionedNotifiers}
|
||||
onDuplicate={jest.fn()}
|
||||
commonSettingsComponent={GrafanaCommonChannelSettings}
|
||||
isEditable={true}
|
||||
isTestable={false}
|
||||
canEditProtectedFields={true}
|
||||
/>
|
||||
</FormProvider>
|
||||
</AlertmanagerProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function renderVersionedForm(defaults: TestChannelValues, initial?: TestChannelValues) {
|
||||
return render(<VersionedTestFormWrapper defaults={defaults} initial={initial} />);
|
||||
}
|
||||
|
||||
it('should display v1 options when integration has v1 version', () => {
|
||||
const webhookV1: TestChannelValues = {
|
||||
__id: 'id-0',
|
||||
type: 'webhook',
|
||||
version: 'v1',
|
||||
settings: { url: 'https://example.com' },
|
||||
secureFields: {},
|
||||
};
|
||||
|
||||
renderVersionedForm(webhookV1, webhookV1);
|
||||
|
||||
// Should show v1 URL field (from default options)
|
||||
expect(ui.settings.webhook.url.get()).toBeInTheDocument();
|
||||
// Should NOT show legacy URL field
|
||||
expect(screen.queryByRole('textbox', { name: /Legacy URL/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display v0 options when integration has legacy version', () => {
|
||||
const webhookV0: TestChannelValues = {
|
||||
__id: 'id-0',
|
||||
type: 'webhook',
|
||||
version: 'v0mimir1',
|
||||
settings: { legacyUrl: 'https://legacy.example.com' },
|
||||
secureFields: {},
|
||||
};
|
||||
|
||||
renderVersionedForm(webhookV0, webhookV0);
|
||||
|
||||
// Should show legacy URL field (from v0 options)
|
||||
expect(screen.getByRole('textbox', { name: /Legacy URL/i })).toBeInTheDocument();
|
||||
// Should NOT show v1 URL field
|
||||
expect(ui.settings.webhook.url.query()).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display "Legacy" badge for v0mimir1 integration', () => {
|
||||
const webhookV0: TestChannelValues = {
|
||||
__id: 'id-0',
|
||||
type: 'webhook',
|
||||
version: 'v0mimir1',
|
||||
settings: { legacyUrl: 'https://legacy.example.com' },
|
||||
secureFields: {},
|
||||
};
|
||||
|
||||
renderVersionedForm(webhookV0, webhookV0);
|
||||
|
||||
// Should show "Legacy" badge for v0mimir1 integrations
|
||||
expect(screen.getByText('Legacy')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display "Legacy v2" badge for v0mimir2 integration', () => {
|
||||
const webhookV0v2: TestChannelValues = {
|
||||
__id: 'id-0',
|
||||
type: 'webhook',
|
||||
version: 'v0mimir2',
|
||||
settings: { legacyUrl: 'https://legacy.example.com' },
|
||||
secureFields: {},
|
||||
};
|
||||
|
||||
renderVersionedForm(webhookV0v2, webhookV0v2);
|
||||
|
||||
// Should show "Legacy v2" badge for v0mimir2 integrations
|
||||
expect(screen.getByText('Legacy v2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT display version badge for v1 integration', () => {
|
||||
const webhookV1: TestChannelValues = {
|
||||
__id: 'id-0',
|
||||
type: 'webhook',
|
||||
version: 'v1',
|
||||
settings: { url: 'https://example.com' },
|
||||
secureFields: {},
|
||||
};
|
||||
|
||||
renderVersionedForm(webhookV1, webhookV1);
|
||||
|
||||
// Should NOT show version badge for non-legacy v1 integrations
|
||||
expect(screen.queryByText('v1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should filter out notifiers with canCreate: false from dropdown', () => {
|
||||
// Create a notifier that only has v0 versions (cannot be created)
|
||||
const legacyOnlyNotifier: NotifierDTO = {
|
||||
type: 'wechat',
|
||||
name: 'WeChat',
|
||||
heading: 'WeChat settings',
|
||||
description: 'Sends notifications to WeChat',
|
||||
options: [],
|
||||
versions: [
|
||||
{
|
||||
version: 'v0mimir1',
|
||||
label: 'WeChat (Legacy)',
|
||||
description: 'Legacy WeChat',
|
||||
canCreate: false,
|
||||
options: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const notifiersWithLegacyOnly: Notifier[] = [
|
||||
{ dto: webhookWithVersions, meta: { enabled: true, order: 1 } },
|
||||
{ dto: legacyOnlyNotifier, meta: { enabled: true, order: 2 } },
|
||||
];
|
||||
|
||||
function LegacyOnlyTestWrapper({ defaults }: { defaults: TestChannelValues }) {
|
||||
const form = useForm<TestReceiverFormValues>({
|
||||
defaultValues: {
|
||||
name: 'test-contact-point',
|
||||
items: [defaults],
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<AlertmanagerProvider accessType="notification">
|
||||
<FormProvider {...form}>
|
||||
<ChannelSubForm
|
||||
defaultValues={defaults}
|
||||
pathPrefix={`items.0.`}
|
||||
integrationIndex={0}
|
||||
notifiers={notifiersWithLegacyOnly}
|
||||
onDuplicate={jest.fn()}
|
||||
commonSettingsComponent={GrafanaCommonChannelSettings}
|
||||
isEditable={true}
|
||||
isTestable={false}
|
||||
canEditProtectedFields={true}
|
||||
/>
|
||||
</FormProvider>
|
||||
</AlertmanagerProvider>
|
||||
);
|
||||
}
|
||||
|
||||
render(
|
||||
<LegacyOnlyTestWrapper
|
||||
defaults={{
|
||||
__id: 'id-0',
|
||||
type: 'webhook',
|
||||
settings: {},
|
||||
secureFields: {},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
// Webhook should be in dropdown (has v1 with canCreate: true)
|
||||
expect(ui.typeSelector.get()).toHaveTextContent('Webhook');
|
||||
|
||||
// WeChat should NOT be in the options (only has v0 with canCreate: false)
|
||||
// We can't easily check dropdown options without opening it, but the filter should work
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Controller, FieldErrors, useFormContext } from 'react-hook-form';
|
||||
|
||||
import { GrafanaTheme2, SelectableValue } from '@grafana/data';
|
||||
import { Trans, t } from '@grafana/i18n';
|
||||
import { Alert, Button, Field, Select, Stack, Text, useStyles2 } from '@grafana/ui';
|
||||
import { Alert, Badge, Button, Field, Select, Stack, Text, useStyles2 } from '@grafana/ui';
|
||||
import { NotificationChannelOption } from 'app/features/alerting/unified/types/alerting';
|
||||
|
||||
import {
|
||||
@@ -16,6 +16,12 @@ import {
|
||||
GrafanaChannelValues,
|
||||
ReceiverFormValues,
|
||||
} from '../../../types/receiver-form';
|
||||
import {
|
||||
canCreateNotifier,
|
||||
getLegacyVersionLabel,
|
||||
getOptionsForVersion,
|
||||
isLegacyVersion,
|
||||
} from '../../../utils/notifier-versions';
|
||||
import { OnCallIntegrationType } from '../grafanaAppReceivers/onCall/useOnCallIntegration';
|
||||
|
||||
import { ChannelOptions } from './ChannelOptions';
|
||||
@@ -62,6 +68,7 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
|
||||
const channelFieldPath = `items.${integrationIndex}` as const;
|
||||
const typeFieldPath = `${channelFieldPath}.type` as const;
|
||||
const versionFieldPath = `${channelFieldPath}.version` as const;
|
||||
const settingsFieldPath = `${channelFieldPath}.settings` as const;
|
||||
const secureFieldsPath = `${channelFieldPath}.secureFields` as const;
|
||||
|
||||
@@ -104,6 +111,9 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
|
||||
setValue(settingsFieldPath, defaultNotifierSettings);
|
||||
setValue(secureFieldsPath, {});
|
||||
|
||||
// Reset version when changing type - backend will use its default
|
||||
setValue(versionFieldPath, undefined);
|
||||
}
|
||||
|
||||
// Restore initial value of an existing oncall integration
|
||||
@@ -123,6 +133,7 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
setValue,
|
||||
settingsFieldPath,
|
||||
typeFieldPath,
|
||||
versionFieldPath,
|
||||
secureFieldsPath,
|
||||
getValues,
|
||||
watch,
|
||||
@@ -164,24 +175,30 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
setValue(`${settingsFieldPath}.${fieldPath}`, undefined);
|
||||
};
|
||||
|
||||
const typeOptions = useMemo(
|
||||
(): SelectableValue[] =>
|
||||
sortBy(notifiers, ({ dto, meta }) => [meta?.order ?? 0, dto.name]).map<SelectableValue>(
|
||||
({ dto: { name, type }, meta }) => ({
|
||||
// @ts-expect-error ReactNode is supported
|
||||
const typeOptions = useMemo((): SelectableValue[] => {
|
||||
// Filter out notifiers that can't be created (e.g., v0-only integrations like WeChat)
|
||||
// These are legacy integrations that only exist in Mimir and can't be created in Grafana
|
||||
const creatableNotifiers = notifiers.filter(({ dto }) => canCreateNotifier(dto));
|
||||
|
||||
return sortBy(creatableNotifiers, ({ dto, meta }) => [meta?.order ?? 0, dto.name]).map<SelectableValue>(
|
||||
({ dto: { name, type }, meta }) => {
|
||||
return {
|
||||
// ReactNode is supported in Select label, but types don't reflect it
|
||||
/* eslint-disable @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any */
|
||||
label: (
|
||||
<Stack alignItems="center" gap={1}>
|
||||
{name}
|
||||
{meta?.badge}
|
||||
</Stack>
|
||||
),
|
||||
) as any,
|
||||
/* eslint-enable @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any */
|
||||
value: type,
|
||||
description: meta?.description,
|
||||
isDisabled: meta ? !meta.enabled : false,
|
||||
})
|
||||
),
|
||||
[notifiers]
|
||||
);
|
||||
};
|
||||
}
|
||||
);
|
||||
}, [notifiers]);
|
||||
|
||||
const handleTest = async () => {
|
||||
await trigger();
|
||||
@@ -198,10 +215,21 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
// Cloud AM takes no value at all
|
||||
const isParseModeNone = parse_mode === 'None' || !parse_mode;
|
||||
const showTelegramWarning = isTelegram && !isParseModeNone;
|
||||
|
||||
// Check if current integration is a legacy version (canCreate: false)
|
||||
// Legacy integrations are read-only and cannot be edited
|
||||
// Read version from existing integration data (stored in receiver config)
|
||||
const integrationVersion = initialValues?.version || defaultValues.version;
|
||||
const isLegacy = notifier ? isLegacyVersion(notifier.dto, integrationVersion) : false;
|
||||
|
||||
// Get the correct options based on the integration's version
|
||||
// This ensures legacy (v0) integrations display the correct schema
|
||||
const versionedOptions = notifier ? getOptionsForVersion(notifier.dto, integrationVersion) : [];
|
||||
|
||||
// if there are mandatory options defined, optional options will be hidden by a collapse
|
||||
// if there aren't mandatory options, all options will be shown without collapse
|
||||
const mandatoryOptions = notifier?.dto.options.filter((o) => o.required) ?? [];
|
||||
const optionalOptions = notifier?.dto.options.filter((o) => !o.required) ?? [];
|
||||
const mandatoryOptions = versionedOptions.filter((o) => o.required);
|
||||
const optionalOptions = versionedOptions.filter((o) => !o.required);
|
||||
|
||||
const contactPointTypeInputId = `contact-point-type-${pathPrefix}`;
|
||||
return (
|
||||
@@ -214,21 +242,35 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
data-testid={`${pathPrefix}type`}
|
||||
noMargin
|
||||
>
|
||||
<Controller
|
||||
name={typeFieldPath}
|
||||
control={control}
|
||||
defaultValue={defaultValues.type}
|
||||
render={({ field: { ref, onChange, ...field } }) => (
|
||||
<Select
|
||||
disabled={!isEditable}
|
||||
inputId={contactPointTypeInputId}
|
||||
{...field}
|
||||
width={37}
|
||||
options={typeOptions}
|
||||
onChange={(value) => onChange(value?.value)}
|
||||
<Stack direction="row" alignItems="center" gap={1}>
|
||||
<Controller
|
||||
name={typeFieldPath}
|
||||
control={control}
|
||||
defaultValue={defaultValues.type}
|
||||
render={({ field: { ref, onChange, ...field } }) => (
|
||||
<Select
|
||||
disabled={!isEditable}
|
||||
inputId={contactPointTypeInputId}
|
||||
{...field}
|
||||
width={37}
|
||||
options={typeOptions}
|
||||
onChange={(value) => onChange(value?.value)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{isLegacy && integrationVersion && (
|
||||
<Badge
|
||||
text={getLegacyVersionLabel(integrationVersion)}
|
||||
color="orange"
|
||||
icon="exclamation-triangle"
|
||||
tooltip={t(
|
||||
'alerting.channel-sub-form.tooltip-legacy-version',
|
||||
'This is a legacy integration (version: {{version}}). It cannot be modified.',
|
||||
{ version: integrationVersion }
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
</Field>
|
||||
</div>
|
||||
<div className={styles.buttons}>
|
||||
@@ -292,7 +334,7 @@ export function ChannelSubForm<R extends ChannelValues>({
|
||||
name: notifier.dto.name,
|
||||
})}
|
||||
>
|
||||
{notifier.dto.info !== '' && (
|
||||
{notifier.dto.info && (
|
||||
<Alert title="" severity="info">
|
||||
{notifier.dto.info}
|
||||
</Alert>
|
||||
|
||||
@@ -18,12 +18,13 @@ import {
|
||||
|
||||
import { alertmanagerApi } from '../../../api/alertmanagerApi';
|
||||
import { GrafanaChannelValues, ReceiverFormValues } from '../../../types/receiver-form';
|
||||
import { hasLegacyIntegrations } from '../../../utils/notifier-versions';
|
||||
import {
|
||||
formChannelValuesToGrafanaChannelConfig,
|
||||
formValuesToGrafanaReceiver,
|
||||
grafanaReceiverToFormValues,
|
||||
} from '../../../utils/receiver-form';
|
||||
import { ProvisionedResource, ProvisioningAlert } from '../../Provisioning';
|
||||
import { ImportedContactPointAlert, ProvisionedResource, ProvisioningAlert } from '../../Provisioning';
|
||||
import { ReceiverTypes } from '../grafanaAppReceivers/onCall/onCall';
|
||||
import { useOnCallIntegration } from '../grafanaAppReceivers/onCall/useOnCallIntegration';
|
||||
|
||||
@@ -39,6 +40,8 @@ const defaultChannelValues: GrafanaChannelValues = Object.freeze({
|
||||
secureFields: {},
|
||||
disableResolveMessage: false,
|
||||
type: 'email',
|
||||
// version is intentionally not set here - it will be determined by the notifier's currentVersion
|
||||
// when the integration is created/type is changed. The backend will use its default if not provided.
|
||||
});
|
||||
|
||||
interface Props {
|
||||
@@ -67,7 +70,6 @@ export const GrafanaReceiverForm = ({ contactPoint, readOnly = false, editMode }
|
||||
} = useOnCallIntegration();
|
||||
|
||||
const { data: grafanaNotifiers = [], isLoading: isLoadingNotifiers } = useGrafanaNotifiersQuery();
|
||||
|
||||
const [testReceivers, setTestReceivers] = useState<Receiver[]>();
|
||||
|
||||
// transform receiver DTO to form values
|
||||
@@ -135,15 +137,20 @@ export const GrafanaReceiverForm = ({ contactPoint, readOnly = false, editMode }
|
||||
);
|
||||
}
|
||||
|
||||
// Map notifiers to Notifier[] format for ReceiverForm
|
||||
// The grafanaNotifiers include version-specific options via the versions array from the backend
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/consistent-type-assertions
|
||||
const notifiers: Notifier[] = grafanaNotifiers.map((n) => {
|
||||
if (n.type === ReceiverTypes.OnCall) {
|
||||
return {
|
||||
dto: extendOnCallNotifierFeatures(n),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/consistent-type-assertions
|
||||
dto: extendOnCallNotifierFeatures(n as any) as any,
|
||||
meta: onCallNotifierMeta,
|
||||
};
|
||||
}
|
||||
|
||||
return { dto: n };
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/consistent-type-assertions
|
||||
return { dto: n as any };
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -163,7 +170,12 @@ export const GrafanaReceiverForm = ({ contactPoint, readOnly = false, editMode }
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{contactPoint?.provisioned && <ProvisioningAlert resource={ProvisionedResource.ContactPoint} />}
|
||||
{contactPoint?.provisioned && hasLegacyIntegrations(contactPoint, grafanaNotifiers) && (
|
||||
<ImportedContactPointAlert />
|
||||
)}
|
||||
{contactPoint?.provisioned && !hasLegacyIntegrations(contactPoint, grafanaNotifiers) && (
|
||||
<ProvisioningAlert resource={ProvisionedResource.ContactPoint} />
|
||||
)}
|
||||
|
||||
<ReceiverForm<GrafanaChannelValues>
|
||||
contactPointId={contactPoint?.id}
|
||||
|
||||
@@ -455,6 +455,25 @@ describe('grafana-managed rules', () => {
|
||||
expect(frontendFilter.ruleMatches(regularRule)).toBe(true);
|
||||
expect(frontendFilter.ruleMatches(pluginRule)).toBe(true);
|
||||
});
|
||||
|
||||
it('should include searchFolder in backend filter when namespace is provided', () => {
|
||||
const { backendFilter } = getGrafanaFilter(getFilter({ namespace: 'my-folder' }));
|
||||
|
||||
expect(backendFilter.searchFolder).toBe('my-folder');
|
||||
});
|
||||
|
||||
it('should skip namespace filtering on frontend when backend filtering is enabled', () => {
|
||||
const group: PromRuleGroupDTO = {
|
||||
name: 'Test Group',
|
||||
file: 'production/alerts',
|
||||
rules: [],
|
||||
interval: 60,
|
||||
};
|
||||
|
||||
const { frontendFilter } = getGrafanaFilter(getFilter({ namespace: 'staging' }));
|
||||
// Should return true because namespace filter is null (handled by backend)
|
||||
expect(frontendFilter.groupMatches(group)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when alertingUIUseBackendFilters is disabled', () => {
|
||||
@@ -537,6 +556,12 @@ describe('grafana-managed rules', () => {
|
||||
expect(backendFilter.searchGroupName).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not include searchFolder in backend filter', () => {
|
||||
const { backendFilter } = getGrafanaFilter(getFilter({ namespace: 'my-folder' }));
|
||||
|
||||
expect(backendFilter.searchFolder).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should perform groupName filtering on frontend', () => {
|
||||
const group: PromRuleGroupDTO = {
|
||||
name: 'CPU Usage Alerts',
|
||||
@@ -706,8 +731,8 @@ describe('grafana-managed rules', () => {
|
||||
expect(frontendFilter.groupMatches(group)).toBe(true);
|
||||
});
|
||||
|
||||
it('should still apply always-frontend filters (namespace)', () => {
|
||||
// Namespace filter should still work
|
||||
it('should skip namespace filtering on frontend', () => {
|
||||
// Namespace filter should be handled by backend
|
||||
const group: PromRuleGroupDTO = {
|
||||
name: 'Test Group',
|
||||
file: 'production/alerts',
|
||||
@@ -719,7 +744,7 @@ describe('grafana-managed rules', () => {
|
||||
expect(nsFilter.groupMatches(group)).toBe(true);
|
||||
|
||||
const { frontendFilter: nsFilter2 } = getGrafanaFilter(getFilter({ namespace: 'staging' }));
|
||||
expect(nsFilter2.groupMatches(group)).toBe(false);
|
||||
expect(nsFilter2.groupMatches(group)).toBe(true);
|
||||
});
|
||||
|
||||
it('should skip dataSourceNames filtering on frontend (handled by backend)', () => {
|
||||
@@ -807,8 +832,8 @@ describe('grafana-managed rules', () => {
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ labels: ['severity=critical'] }))).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true for client-side only filters', () => {
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(true);
|
||||
it('should return false for namespace filter (handled by backend)', () => {
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for plugins filter (handled by backend when feature toggle is enabled)', () => {
|
||||
@@ -862,8 +887,8 @@ describe('grafana-managed rules', () => {
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ ruleHealth: RuleHealth.Ok }))).toBe(false);
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ contactPoint: 'my-contact-point' }))).toBe(false);
|
||||
|
||||
// Should return true for: always-frontend filters only (namespace)
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(true);
|
||||
// Should return false for: namespace (handled by backend)
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(false);
|
||||
|
||||
// plugins is backend-handled when both feature toggles are enabled
|
||||
expect(hasGrafanaClientSideFilters(getFilter({ plugins: 'hide' }))).toBe(false);
|
||||
|
||||
@@ -96,6 +96,7 @@ export function getGrafanaFilter(filterState: Partial<RulesFilter>) {
|
||||
datasources: ruleFilterConfig.dataSourceNames ? undefined : datasourceUids,
|
||||
ruleMatchers: ruleMatchersBackendFilter,
|
||||
plugins: ruleFilterConfig.plugins ? undefined : normalizedFilterState.plugins,
|
||||
searchFolder: groupFilterConfig.namespace ? undefined : normalizedFilterState.namespace,
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -134,7 +135,7 @@ function buildGrafanaFilterConfigs() {
|
||||
};
|
||||
|
||||
const groupFilterConfig: GroupFilterConfig = {
|
||||
namespace: namespaceFilter,
|
||||
namespace: useBackendFilters ? null : namespaceFilter,
|
||||
groupName: useBackendFilters ? null : groupNameFilter,
|
||||
};
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ interface GrafanaPromApiFilter {
|
||||
contactPoint?: string;
|
||||
title?: string;
|
||||
searchGroupName?: string;
|
||||
searchFolder?: string;
|
||||
type?: 'alerting' | 'recording';
|
||||
dashboardUid?: string;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ describe('paginationLimits', () => {
|
||||
{ contactPoint: 'slack' },
|
||||
{ dataSourceNames: ['prometheus'] },
|
||||
{ labels: ['severity=critical'] },
|
||||
{ namespace: 'production' },
|
||||
])(
|
||||
'should return rule limit for grafana + large limit for datasource when only backend filters are used: %p',
|
||||
(filterState) => {
|
||||
@@ -84,16 +85,6 @@ describe('paginationLimits', () => {
|
||||
expect(datasourceManagedLimit).toEqual({ groupLimit: FILTERED_GROUPS_LARGE_API_PAGE_SIZE });
|
||||
}
|
||||
);
|
||||
|
||||
it.each<Partial<RulesFilter>>([
|
||||
{ namespace: 'production' },
|
||||
{ ruleState: PromAlertingRuleState.Firing, namespace: 'production' },
|
||||
])('should return large limits for both when frontend filters are used: %p', (filterState) => {
|
||||
const { grafanaManagedLimit, datasourceManagedLimit } = getFilteredRulesLimits(getFilter(filterState));
|
||||
|
||||
expect(grafanaManagedLimit).toEqual({ groupLimit: FILTERED_GROUPS_LARGE_API_PAGE_SIZE });
|
||||
expect(datasourceManagedLimit).toEqual({ groupLimit: FILTERED_GROUPS_LARGE_API_PAGE_SIZE });
|
||||
});
|
||||
});
|
||||
|
||||
describe('when alertingUIUseFullyCompatBackendFilters is enabled', () => {
|
||||
@@ -158,6 +149,7 @@ describe('paginationLimits', () => {
|
||||
{ contactPoint: 'slack' },
|
||||
{ dataSourceNames: ['prometheus'] },
|
||||
{ labels: ['severity=critical'] },
|
||||
{ namespace: 'production' },
|
||||
])(
|
||||
'should return rule limit for grafana + large limit for datasource when only backend filters are used: %p',
|
||||
(filterState) => {
|
||||
@@ -167,16 +159,6 @@ describe('paginationLimits', () => {
|
||||
expect(datasourceManagedLimit).toEqual({ groupLimit: FILTERED_GROUPS_LARGE_API_PAGE_SIZE });
|
||||
}
|
||||
);
|
||||
|
||||
it.each<Partial<RulesFilter>>([{ namespace: 'production' }])(
|
||||
'should return large limits for both when frontend filters are used: %p',
|
||||
(filterState) => {
|
||||
const { grafanaManagedLimit, datasourceManagedLimit } = getFilteredRulesLimits(getFilter(filterState));
|
||||
|
||||
expect(grafanaManagedLimit).toEqual({ groupLimit: FILTERED_GROUPS_LARGE_API_PAGE_SIZE });
|
||||
expect(datasourceManagedLimit).toEqual({ groupLimit: FILTERED_GROUPS_LARGE_API_PAGE_SIZE });
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -80,6 +80,20 @@ export type CloudNotifierType =
|
||||
| 'jira';
|
||||
|
||||
export type NotifierType = GrafanaNotifierType | CloudNotifierType;
|
||||
|
||||
/**
|
||||
* Represents a specific version of a notifier integration
|
||||
* Used for integration versioning during Single Alert Manager migration
|
||||
*/
|
||||
export interface NotifierVersion {
|
||||
version: string;
|
||||
label: string;
|
||||
description: string;
|
||||
options: NotificationChannelOption[];
|
||||
/** Whether this version can be used to create new integrations */
|
||||
canCreate?: boolean;
|
||||
}
|
||||
|
||||
export interface NotifierDTO<T = NotifierType> {
|
||||
name: string;
|
||||
description: string;
|
||||
@@ -88,6 +102,23 @@ export interface NotifierDTO<T = NotifierType> {
|
||||
options: NotificationChannelOption[];
|
||||
info?: string;
|
||||
secure?: boolean;
|
||||
/**
|
||||
* Available versions for this notifier from the backend
|
||||
* Each version contains version-specific options and metadata
|
||||
*/
|
||||
versions?: NotifierVersion[];
|
||||
/**
|
||||
* The default version that the backend will use when creating new integrations.
|
||||
* Returned by the backend from /api/alert-notifiers?version=2
|
||||
*
|
||||
* - "v1" for most notifiers (modern Grafana version)
|
||||
* - "v0mimir1" for legacy-only notifiers (e.g., WeChat)
|
||||
*
|
||||
* Note: Currently not used in the frontend. The backend handles version
|
||||
* selection automatically. Could be used in the future to display
|
||||
* version information or validate notifier capabilities.
|
||||
*/
|
||||
currentVersion?: string;
|
||||
}
|
||||
|
||||
export interface NotificationChannelType {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ControlledField } from '../hooks/useControlledFieldArray';
|
||||
export interface ChannelValues {
|
||||
__id: string; // used to correlate form values to original DTOs
|
||||
type: string;
|
||||
version?: string; // Integration version (e.g. "v0" for Mimir legacy, "v1" for Grafana)
|
||||
settings: Record<string, any>;
|
||||
secureFields: Record<string, boolean | ''>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
import { GrafanaManagedContactPoint } from 'app/plugins/datasource/alertmanager/types';
|
||||
|
||||
import { NotificationChannelOption, NotifierDTO, NotifierVersion } from '../types/alerting';
|
||||
|
||||
import {
|
||||
canCreateNotifier,
|
||||
getLegacyVersionLabel,
|
||||
getOptionsForVersion,
|
||||
hasLegacyIntegrations,
|
||||
isLegacyVersion,
|
||||
} from './notifier-versions';
|
||||
|
||||
// Helper to create a minimal NotifierDTO for testing
|
||||
function createNotifier(overrides: Partial<NotifierDTO> = {}): NotifierDTO {
|
||||
return {
|
||||
name: 'Test Notifier',
|
||||
description: 'Test description',
|
||||
type: 'webhook',
|
||||
heading: 'Test heading',
|
||||
options: [
|
||||
{
|
||||
element: 'input',
|
||||
inputType: 'text',
|
||||
label: 'Default Option',
|
||||
description: 'Default option description',
|
||||
placeholder: '',
|
||||
propertyName: 'defaultOption',
|
||||
required: true,
|
||||
secure: false,
|
||||
showWhen: { field: '', is: '' },
|
||||
validationRule: '',
|
||||
dependsOn: '',
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to create a NotifierVersion for testing
|
||||
function createVersion(overrides: Partial<NotifierVersion> = {}): NotifierVersion {
|
||||
return {
|
||||
version: 'v1',
|
||||
label: 'Test Version',
|
||||
description: 'Test version description',
|
||||
options: [
|
||||
{
|
||||
element: 'input',
|
||||
inputType: 'text',
|
||||
label: 'Version Option',
|
||||
description: 'Version option description',
|
||||
placeholder: '',
|
||||
propertyName: 'versionOption',
|
||||
required: true,
|
||||
secure: false,
|
||||
showWhen: { field: '', is: '' },
|
||||
validationRule: '',
|
||||
dependsOn: '',
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('notifier-versions utilities', () => {
|
||||
describe('canCreateNotifier', () => {
|
||||
it('should return true if notifier has no versions array', () => {
|
||||
const notifier = createNotifier({ versions: undefined });
|
||||
expect(canCreateNotifier(notifier)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if notifier has empty versions array', () => {
|
||||
const notifier = createNotifier({ versions: [] });
|
||||
expect(canCreateNotifier(notifier)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if at least one version has canCreate: true', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v1', canCreate: true }),
|
||||
],
|
||||
});
|
||||
expect(canCreateNotifier(notifier)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if at least one version has canCreate: undefined (defaults to true)', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v1', canCreate: undefined }),
|
||||
],
|
||||
});
|
||||
expect(canCreateNotifier(notifier)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false if all versions have canCreate: false', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v0mimir2', canCreate: false }),
|
||||
],
|
||||
});
|
||||
expect(canCreateNotifier(notifier)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for notifiers like WeChat that only have legacy versions', () => {
|
||||
const wechatNotifier = createNotifier({
|
||||
name: 'WeChat',
|
||||
type: 'wechat',
|
||||
versions: [createVersion({ version: 'v0mimir1', canCreate: false })],
|
||||
});
|
||||
expect(canCreateNotifier(wechatNotifier)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLegacyVersion', () => {
|
||||
it('should return false if no version is specified', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [createVersion({ version: 'v0mimir1', canCreate: false })],
|
||||
});
|
||||
expect(isLegacyVersion(notifier, undefined)).toBe(false);
|
||||
expect(isLegacyVersion(notifier, '')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if notifier has no versions array', () => {
|
||||
const notifier = createNotifier({ versions: undefined });
|
||||
expect(isLegacyVersion(notifier, 'v0mimir1')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if notifier has empty versions array', () => {
|
||||
const notifier = createNotifier({ versions: [] });
|
||||
expect(isLegacyVersion(notifier, 'v0mimir1')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if version is not found in versions array', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [createVersion({ version: 'v1', canCreate: true })],
|
||||
});
|
||||
expect(isLegacyVersion(notifier, 'v0mimir1')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if version has canCreate: true', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [createVersion({ version: 'v1', canCreate: true })],
|
||||
});
|
||||
expect(isLegacyVersion(notifier, 'v1')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if version has canCreate: undefined', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [createVersion({ version: 'v1', canCreate: undefined })],
|
||||
});
|
||||
expect(isLegacyVersion(notifier, 'v1')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if version has canCreate: false', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v1', canCreate: true }),
|
||||
],
|
||||
});
|
||||
expect(isLegacyVersion(notifier, 'v0mimir1')).toBe(true);
|
||||
});
|
||||
|
||||
it('should correctly identify legacy versions in a mixed notifier', () => {
|
||||
const notifier = createNotifier({
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v0mimir2', canCreate: false }),
|
||||
createVersion({ version: 'v1', canCreate: true }),
|
||||
],
|
||||
});
|
||||
expect(isLegacyVersion(notifier, 'v0mimir1')).toBe(true);
|
||||
expect(isLegacyVersion(notifier, 'v0mimir2')).toBe(true);
|
||||
expect(isLegacyVersion(notifier, 'v1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOptionsForVersion', () => {
|
||||
const defaultOptions: NotificationChannelOption[] = [
|
||||
{
|
||||
element: 'input',
|
||||
inputType: 'text',
|
||||
label: 'Default URL',
|
||||
description: 'Default URL description',
|
||||
placeholder: '',
|
||||
propertyName: 'url',
|
||||
required: true,
|
||||
secure: false,
|
||||
showWhen: { field: '', is: '' },
|
||||
validationRule: '',
|
||||
dependsOn: '',
|
||||
},
|
||||
];
|
||||
|
||||
const v0Options: NotificationChannelOption[] = [
|
||||
{
|
||||
element: 'input',
|
||||
inputType: 'text',
|
||||
label: 'Legacy URL',
|
||||
description: 'Legacy URL description',
|
||||
placeholder: '',
|
||||
propertyName: 'legacyUrl',
|
||||
required: true,
|
||||
secure: false,
|
||||
showWhen: { field: '', is: '' },
|
||||
validationRule: '',
|
||||
dependsOn: '',
|
||||
},
|
||||
];
|
||||
|
||||
const v1Options: NotificationChannelOption[] = [
|
||||
{
|
||||
element: 'input',
|
||||
inputType: 'text',
|
||||
label: 'Modern URL',
|
||||
description: 'Modern URL description',
|
||||
placeholder: '',
|
||||
propertyName: 'modernUrl',
|
||||
required: true,
|
||||
secure: false,
|
||||
showWhen: { field: '', is: '' },
|
||||
validationRule: '',
|
||||
dependsOn: '',
|
||||
},
|
||||
];
|
||||
|
||||
it('should return options from default creatable version if no version is specified', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: [createVersion({ version: 'v1', options: v1Options, canCreate: true })],
|
||||
});
|
||||
// When no version specified, should use options from the default creatable version
|
||||
expect(getOptionsForVersion(notifier, undefined)).toBe(v1Options);
|
||||
});
|
||||
|
||||
it('should return default options if no version is specified and empty string is passed', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: [createVersion({ version: 'v1', options: v1Options, canCreate: true })],
|
||||
});
|
||||
// Empty string is still a falsy version, so should use default creatable version
|
||||
expect(getOptionsForVersion(notifier, '')).toBe(v1Options);
|
||||
});
|
||||
|
||||
it('should return default options if notifier has no versions array', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: undefined,
|
||||
});
|
||||
expect(getOptionsForVersion(notifier, 'v1')).toBe(defaultOptions);
|
||||
});
|
||||
|
||||
it('should return default options if notifier has empty versions array', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: [],
|
||||
});
|
||||
expect(getOptionsForVersion(notifier, 'v1')).toBe(defaultOptions);
|
||||
});
|
||||
|
||||
it('should return default options if version is not found', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: [createVersion({ version: 'v1', options: v1Options })],
|
||||
});
|
||||
expect(getOptionsForVersion(notifier, 'v0mimir1')).toBe(defaultOptions);
|
||||
});
|
||||
|
||||
it('should return version-specific options when version is found', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', options: v0Options }),
|
||||
createVersion({ version: 'v1', options: v1Options }),
|
||||
],
|
||||
});
|
||||
expect(getOptionsForVersion(notifier, 'v0mimir1')).toBe(v0Options);
|
||||
expect(getOptionsForVersion(notifier, 'v1')).toBe(v1Options);
|
||||
});
|
||||
|
||||
it('should return default options if version found but has no options', () => {
|
||||
const notifier = createNotifier({
|
||||
options: defaultOptions,
|
||||
versions: [
|
||||
{
|
||||
version: 'v1',
|
||||
label: 'V1',
|
||||
description: 'V1 description',
|
||||
options: undefined as unknown as NotificationChannelOption[],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(getOptionsForVersion(notifier, 'v1')).toBe(defaultOptions);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasLegacyIntegrations', () => {
|
||||
// Helper to create a minimal contact point for testing
|
||||
function createContactPoint(overrides: Partial<GrafanaManagedContactPoint> = {}): GrafanaManagedContactPoint {
|
||||
return {
|
||||
name: 'Test Contact Point',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// Create notifiers with version info for testing
|
||||
const notifiersWithVersions: NotifierDTO[] = [
|
||||
createNotifier({
|
||||
type: 'slack',
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v1', canCreate: true }),
|
||||
],
|
||||
}),
|
||||
createNotifier({
|
||||
type: 'webhook',
|
||||
versions: [
|
||||
createVersion({ version: 'v0mimir1', canCreate: false }),
|
||||
createVersion({ version: 'v0mimir2', canCreate: false }),
|
||||
createVersion({ version: 'v1', canCreate: true }),
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
it('should return false if contact point is undefined', () => {
|
||||
expect(hasLegacyIntegrations(undefined, notifiersWithVersions)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if notifiers is undefined', () => {
|
||||
const contactPoint = createContactPoint({
|
||||
grafana_managed_receiver_configs: [{ type: 'slack', settings: {}, version: 'v0mimir1' }],
|
||||
});
|
||||
expect(hasLegacyIntegrations(contactPoint, undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if contact point has no integrations', () => {
|
||||
const contactPoint = createContactPoint({ grafana_managed_receiver_configs: undefined });
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if contact point has empty integrations array', () => {
|
||||
const contactPoint = createContactPoint({ grafana_managed_receiver_configs: [] });
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if all integrations have v1 version (canCreate: true)', () => {
|
||||
const contactPoint = createContactPoint({
|
||||
grafana_managed_receiver_configs: [
|
||||
{ type: 'slack', settings: {}, version: 'v1' },
|
||||
{ type: 'webhook', settings: {}, version: 'v1' },
|
||||
],
|
||||
});
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if all integrations have no version', () => {
|
||||
const contactPoint = createContactPoint({
|
||||
grafana_managed_receiver_configs: [
|
||||
{ type: 'slack', settings: {} },
|
||||
{ type: 'webhook', settings: {} },
|
||||
],
|
||||
});
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true if any integration has a legacy version (canCreate: false)', () => {
|
||||
const contactPoint = createContactPoint({
|
||||
grafana_managed_receiver_configs: [
|
||||
{ type: 'slack', settings: {}, version: 'v0mimir1' },
|
||||
{ type: 'webhook', settings: {}, version: 'v1' },
|
||||
],
|
||||
});
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if all integrations have legacy versions', () => {
|
||||
const contactPoint = createContactPoint({
|
||||
grafana_managed_receiver_configs: [
|
||||
{ type: 'slack', settings: {}, version: 'v0mimir1' },
|
||||
{ type: 'webhook', settings: {}, version: 'v0mimir2' },
|
||||
],
|
||||
});
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false if notifier type is not found in notifiers array', () => {
|
||||
const contactPoint = createContactPoint({
|
||||
grafana_managed_receiver_configs: [{ type: 'unknown', settings: {}, version: 'v0mimir1' }],
|
||||
});
|
||||
expect(hasLegacyIntegrations(contactPoint, notifiersWithVersions)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getLegacyVersionLabel', () => {
|
||||
it('should return "Legacy" for undefined version', () => {
|
||||
expect(getLegacyVersionLabel(undefined)).toBe('Legacy');
|
||||
});
|
||||
|
||||
it('should return "Legacy" for empty string version', () => {
|
||||
expect(getLegacyVersionLabel('')).toBe('Legacy');
|
||||
});
|
||||
|
||||
it('should return "Legacy" for v0mimir1', () => {
|
||||
expect(getLegacyVersionLabel('v0mimir1')).toBe('Legacy');
|
||||
});
|
||||
|
||||
it('should return "Legacy v2" for v0mimir2', () => {
|
||||
expect(getLegacyVersionLabel('v0mimir2')).toBe('Legacy v2');
|
||||
});
|
||||
|
||||
it('should return "Legacy v3" for v0mimir3', () => {
|
||||
expect(getLegacyVersionLabel('v0mimir3')).toBe('Legacy v3');
|
||||
});
|
||||
|
||||
it('should return "Legacy" for v1 (trailing 1)', () => {
|
||||
expect(getLegacyVersionLabel('v1')).toBe('Legacy');
|
||||
});
|
||||
|
||||
it('should return "Legacy v2" for v2 (trailing 2)', () => {
|
||||
expect(getLegacyVersionLabel('v2')).toBe('Legacy v2');
|
||||
});
|
||||
|
||||
it('should return "Legacy" for version strings without trailing number', () => {
|
||||
expect(getLegacyVersionLabel('legacy')).toBe('Legacy');
|
||||
});
|
||||
});
|
||||
});
|
||||
126
public/app/features/alerting/unified/utils/notifier-versions.ts
Normal file
126
public/app/features/alerting/unified/utils/notifier-versions.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Utilities for integration versioning
|
||||
*
|
||||
* These utilities help get version-specific options from the backend response
|
||||
* (via /api/alert-notifiers?version=2)
|
||||
*/
|
||||
|
||||
import { GrafanaManagedContactPoint } from 'app/plugins/datasource/alertmanager/types';
|
||||
|
||||
import { NotificationChannelOption, NotifierDTO } from '../types/alerting';
|
||||
|
||||
/**
|
||||
* Checks if a notifier can be used to create new integrations.
|
||||
* A notifier can be created if it has at least one version with canCreate: true,
|
||||
* or if it has no versions array (legacy behavior).
|
||||
*
|
||||
* @param notifier - The notifier DTO to check
|
||||
* @returns True if the notifier can be used to create new integrations
|
||||
*/
|
||||
export function canCreateNotifier(notifier: NotifierDTO): boolean {
|
||||
// If no versions array, assume it can be created (legacy behavior)
|
||||
if (!notifier.versions || notifier.versions.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if any version has canCreate: true (or undefined, which defaults to true)
|
||||
return notifier.versions.some((v) => v.canCreate !== false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a specific version is legacy (cannot be created).
|
||||
* A version is legacy if it has canCreate: false in the notifier's versions array.
|
||||
*
|
||||
* @param notifier - The notifier DTO containing versions array
|
||||
* @param version - The version string to check (e.g., 'v0mimir1', 'v1')
|
||||
* @returns True if the version is legacy (canCreate: false)
|
||||
*/
|
||||
export function isLegacyVersion(notifier: NotifierDTO, version?: string): boolean {
|
||||
// If no version specified or no versions array, it's not legacy
|
||||
if (!version || !notifier.versions || notifier.versions.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Find the matching version and check its canCreate property
|
||||
const versionData = notifier.versions.find((v) => v.version === version);
|
||||
|
||||
// A version is legacy if canCreate is explicitly false
|
||||
return versionData?.canCreate === false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the options for a specific version of a notifier.
|
||||
* Used to display the correct form fields based on integration version.
|
||||
*
|
||||
* @param notifier - The notifier DTO containing versions array
|
||||
* @param version - The version to get options for (e.g., 'v0', 'v1')
|
||||
* @returns The options for the specified version, or default options if version not found
|
||||
*/
|
||||
export function getOptionsForVersion(notifier: NotifierDTO, version?: string): NotificationChannelOption[] {
|
||||
// If no versions array, use default options
|
||||
if (!notifier.versions || notifier.versions.length === 0) {
|
||||
return notifier.options;
|
||||
}
|
||||
|
||||
// If version is specified, find the matching version
|
||||
if (version) {
|
||||
const versionData = notifier.versions.find((v) => v.version === version);
|
||||
// Return version-specific options if found, otherwise fall back to default
|
||||
return versionData?.options ?? notifier.options;
|
||||
}
|
||||
|
||||
// If no version specified, find the default creatable version (canCreate !== false)
|
||||
const defaultVersion = notifier.versions.find((v) => v.canCreate !== false);
|
||||
return defaultVersion?.options ?? notifier.options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a contact point has any legacy (imported) integrations.
|
||||
* A contact point has legacy integrations if any of its integrations uses a version
|
||||
* with canCreate: false in the corresponding notifier's versions array.
|
||||
*
|
||||
* @param contactPoint - The contact point to check
|
||||
* @param notifiers - Array of notifier DTOs to look up version info
|
||||
* @returns True if the contact point has at least one legacy/imported integration
|
||||
*/
|
||||
export function hasLegacyIntegrations(contactPoint?: GrafanaManagedContactPoint, notifiers?: NotifierDTO[]): boolean {
|
||||
if (!contactPoint?.grafana_managed_receiver_configs || !notifiers) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return contactPoint.grafana_managed_receiver_configs.some((config) => {
|
||||
const notifier = notifiers.find((n) => n.type === config.type);
|
||||
return notifier ? isLegacyVersion(notifier, config.version) : false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a user-friendly label for a legacy version.
|
||||
* Extracts the version number from the version string and formats it as:
|
||||
* - "Legacy" for version 1 (e.g., v0mimir1)
|
||||
* - "Legacy v2" for version 2 (e.g., v0mimir2)
|
||||
* - etc.
|
||||
*
|
||||
* Precondition: This function assumes the version is already known to be legacy
|
||||
* (i.e., canCreate: false). Use isLegacyVersion() to check before calling this.
|
||||
*
|
||||
* @param version - The version string (e.g., 'v0mimir1', 'v0mimir2')
|
||||
* @returns A user-friendly label like "Legacy" or "Legacy v2"
|
||||
*/
|
||||
export function getLegacyVersionLabel(version?: string): string {
|
||||
if (!version) {
|
||||
return 'Legacy';
|
||||
}
|
||||
|
||||
// Extract trailing number from version string (e.g., v0mimir1 → 1, v0mimir2 → 2)
|
||||
const match = version.match(/(\d+)$/);
|
||||
if (match) {
|
||||
const num = parseInt(match[1], 10);
|
||||
if (num === 1) {
|
||||
return 'Legacy';
|
||||
}
|
||||
return `Legacy v${num}`;
|
||||
}
|
||||
|
||||
return 'Legacy';
|
||||
}
|
||||
@@ -185,6 +185,7 @@ function grafanaChannelConfigToFormChannelValues(
|
||||
const values: GrafanaChannelValues = {
|
||||
__id: id,
|
||||
type: channel.type as NotifierType,
|
||||
version: channel.version,
|
||||
provenance: channel.provenance,
|
||||
settings: { ...channel.settings },
|
||||
secureFields: { ...channel.secureFields },
|
||||
@@ -239,6 +240,7 @@ export function formChannelValuesToGrafanaChannelConfig(
|
||||
}),
|
||||
secureFields: secureFieldsFromValues,
|
||||
type: values.type,
|
||||
version: values.version ?? existing?.version,
|
||||
name,
|
||||
disableResolveMessage:
|
||||
values.disableResolveMessage ?? existing?.disableResolveMessage ?? defaults.disableResolveMessage,
|
||||
|
||||
@@ -141,6 +141,7 @@ export const getPluginExtensions: GetExtensions = ({
|
||||
description: overrides?.description || addedLink.description || '',
|
||||
path: isString(path) ? getLinkExtensionPathWithTracking(pluginId, path, extensionPointId) : undefined,
|
||||
category: overrides?.category || addedLink.category,
|
||||
openInNewTab: overrides?.openInNewTab ?? addedLink.openInNewTab,
|
||||
};
|
||||
|
||||
extensions.push(extension);
|
||||
|
||||
@@ -420,6 +420,7 @@ export function createExtensionSubMenu(extensions: PluginExtensionLink[]): Panel
|
||||
href: extension.path,
|
||||
onClick: extension.onClick,
|
||||
iconClassName: extension.icon,
|
||||
target: extension.openInNewTab ? '_blank' : undefined,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -433,6 +434,7 @@ export function createExtensionSubMenu(extensions: PluginExtensionLink[]): Panel
|
||||
href: extension.path,
|
||||
onClick: extension.onClick,
|
||||
iconClassName: extension.icon,
|
||||
target: extension.openInNewTab ? '_blank' : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { FeatureToggles } from '@grafana/data';
|
||||
import { config } from '@grafana/runtime';
|
||||
import { RepositoryViewList } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
export const requiredFeatureToggles: Array<keyof FeatureToggles> = ['provisioning', 'kubernetesDashboards'];
|
||||
export const requiredFeatureToggles: Array<keyof FeatureToggles> = ['kubernetesDashboards'];
|
||||
|
||||
/**
|
||||
* Checks if all required feature toggles are enabled
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { config } from '@grafana/runtime';
|
||||
import { SafeDynamicImport } from 'app/core/components/DynamicImports/SafeDynamicImport';
|
||||
import { RouteDescriptor } from 'app/core/navigation/types';
|
||||
import { DashboardRoutes } from 'app/types/dashboard';
|
||||
@@ -6,6 +7,11 @@ import { checkRequiredFeatures } from '../GettingStarted/features';
|
||||
import { CONNECTIONS_URL, CONNECT_URL, GETTING_STARTED_URL, PROVISIONING_URL } from '../constants';
|
||||
|
||||
export function getProvisioningRoutes(): RouteDescriptor[] {
|
||||
const featureToggles = config.featureToggles || {};
|
||||
if (!featureToggles.provisioning) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!checkRequiredFeatures()) {
|
||||
return [
|
||||
{
|
||||
|
||||
@@ -85,6 +85,10 @@ export type GrafanaManagedReceiverConfig = {
|
||||
// SecureSettings?: GrafanaManagedReceiverConfigSettings<boolean>;
|
||||
settings: GrafanaManagedReceiverConfigSettings;
|
||||
type: string;
|
||||
/**
|
||||
* Version of the integration (e.g. "v0" for Mimir legacy, "v1" for Grafana)
|
||||
*/
|
||||
version?: string;
|
||||
/**
|
||||
* Name of the _receiver_, which in most cases will be the
|
||||
* same as the contact point's name. This should not be used, and is optional because the
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"type": "panel",
|
||||
"name": "Datagrid",
|
||||
"id": "datagrid",
|
||||
"state": "beta",
|
||||
"state": "deprecated",
|
||||
|
||||
"info": {
|
||||
"author": {
|
||||
|
||||
@@ -807,7 +807,8 @@
|
||||
"label-integration": "Integration",
|
||||
"label-notification-settings": "Notification settings",
|
||||
"label-section": "Optional {{name}} settings",
|
||||
"test": "Test"
|
||||
"test": "Test",
|
||||
"tooltip-legacy-version": "This is a legacy integration (version: {{version}}). It cannot be modified."
|
||||
},
|
||||
"classic-condition-viewer": {
|
||||
"of": "OF",
|
||||
@@ -2176,7 +2177,9 @@
|
||||
"provisioning": {
|
||||
"badge-tooltip-provenance": "This resource has been provisioned via {{provenance}} and cannot be edited through the UI",
|
||||
"badge-tooltip-standard": "This resource has been provisioned and cannot be edited through the UI",
|
||||
"body-imported": "This contact point contains integrations that were imported from an external Alertmanager and is currently read-only. The integrations will become editable after the migration process is complete.",
|
||||
"body-provisioned": "This {{resource}} has been provisioned, that means it was created by config. Please contact your server admin to update this {{resource}}.",
|
||||
"title-imported": "This contact point was imported and cannot be edited through the UI",
|
||||
"title-provisioned": "This {{resource}} cannot be edited through the UI"
|
||||
},
|
||||
"provisioning-badge": {
|
||||
|
||||
22
yarn.lock
22
yarn.lock
@@ -3789,11 +3789,11 @@ __metadata:
|
||||
languageName: unknown
|
||||
linkType: soft
|
||||
|
||||
"@grafana/scenes-react@npm:v6.52.1":
|
||||
version: 6.52.1
|
||||
resolution: "@grafana/scenes-react@npm:6.52.1"
|
||||
"@grafana/scenes-react@npm:6.52.2":
|
||||
version: 6.52.2
|
||||
resolution: "@grafana/scenes-react@npm:6.52.2"
|
||||
dependencies:
|
||||
"@grafana/scenes": "npm:6.52.1"
|
||||
"@grafana/scenes": "npm:6.52.2"
|
||||
lru-cache: "npm:^10.2.2"
|
||||
react-use: "npm:^17.4.0"
|
||||
peerDependencies:
|
||||
@@ -3805,7 +3805,7 @@ __metadata:
|
||||
react: ^18.0.0
|
||||
react-dom: ^18.0.0
|
||||
react-router-dom: ^6.28.0
|
||||
checksum: 10/2f7c6ca8e26befd331808afb0cb934e2991e889a4de78be1122c536219676261c59c6204510761a1d4250fd44a3767818f0f225d23b2e7243cfc17baf8ca6ca3
|
||||
checksum: 10/c393faf6612e78254dab79b15cc970448d74ba9784ccda623953c5dbc21d91a8da94b7ad7d0d294eac51314cc193c419a7cb48295fd50b1f9c4472699669eb3e
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
@@ -3835,9 +3835,9 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"@grafana/scenes@npm:6.52.1, @grafana/scenes@npm:v6.52.1":
|
||||
version: 6.52.1
|
||||
resolution: "@grafana/scenes@npm:6.52.1"
|
||||
"@grafana/scenes@npm:6.52.2":
|
||||
version: 6.52.2
|
||||
resolution: "@grafana/scenes@npm:6.52.2"
|
||||
dependencies:
|
||||
"@floating-ui/react": "npm:^0.26.16"
|
||||
"@leeoniya/ufuzzy": "npm:^1.0.16"
|
||||
@@ -3857,7 +3857,7 @@ __metadata:
|
||||
react: ^18.0.0
|
||||
react-dom: ^18.0.0
|
||||
react-router-dom: ^6.28.0
|
||||
checksum: 10/d6172b51121e03c7dcbf30046772f99fc45922c1f7b360a7c3d2c0391300e378f306cb78251dda3b30895679379c38db30e4d52fee67a56cd95f18f38aadf3fb
|
||||
checksum: 10/f6dbe20db78bb1aa09cc38025534917887713d73119a172febb44700837ed859363ee0436b5f4bda6bc063f9432115e32519ab4c8da7834cf1fc22d43fea7711
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
@@ -19790,8 +19790,8 @@ __metadata:
|
||||
"@grafana/plugin-ui": "npm:^0.11.1"
|
||||
"@grafana/prometheus": "workspace:*"
|
||||
"@grafana/runtime": "workspace:*"
|
||||
"@grafana/scenes": "npm:v6.52.1"
|
||||
"@grafana/scenes-react": "npm:v6.52.1"
|
||||
"@grafana/scenes": "npm:6.52.2"
|
||||
"@grafana/scenes-react": "npm:6.52.2"
|
||||
"@grafana/schema": "workspace:*"
|
||||
"@grafana/sql": "workspace:*"
|
||||
"@grafana/test-utils": "workspace:*"
|
||||
|
||||
Reference in New Issue
Block a user