Commit Graph

1313 Commits

Author SHA1 Message Date
Jean-Philippe Quéméner
eb7e1216a1
feat(alerting): add async state persister (#80763) 2024-01-22 13:07:11 +01:00
Julien Duchesne
40312c527b
ngalert openapi: Fix ObjectMatchers definition (#79477)
These don't get marshalled and unmarshalled in the same way as they are represented in Go
This PR changes the OpenAPI spec to reflect what the API accepts and sends back
2024-01-19 14:37:11 -05:00
Alexander Weaver
18b9c8fd5f
Alerting: Nilcheck JitterStrategyFrom so it can be used in contexts without feature toggles (#80841)
Nilcheck so tests can have a nil feature toggles
2024-01-18 15:43:41 -06:00
Alexander Weaver
00a260effa
Alerting: Add setting to distribute rule group evaluations over time (#80766)
* Simple, per-base-interval jitter

* Add log just for test purposes

* Add strategy approach, allow choosing between group or rule

* Add flag to jitter rules

* Add second toggle for jittering within a group

* Wire up toggles to strategy

* Slightly improve comment ordering

* Add tests for offset generation

* Rename JitterStrategyFrom

* Improve debug log message

* Use grafana SDK labels rather than prometheus labels
2024-01-18 12:48:11 -06:00
Julien Duchesne
c9211fbd69
ngalert openapi: Use same basePath as rest of Grafana (#79025)
* ngalert openapi: Use same `basePath` as rest of Grafana
Currently, there are two issues that prevent easily merging `ngalert` and grafana openapi specs:
- The basePath is different. `grafana` has `/api` and `ngalert` has `/api/v1`. I changed `ngalert` to use `/api`
- The `ngalert` endpoints have their basePath in the each operation path. The basePath should actually be omitted
---------

Co-authored-by: Yuriy Tseretyan <yuriy.tseretyan@grafana.com>
2024-01-17 11:53:16 -05:00
Jean-Philippe Quéméner
82638d059f
feat(alerting): add state persister interface (#80384) 2024-01-17 13:33:13 +01:00
Santiago
3217a0dc05
Alerting: Fix state sync errors counter increment (#80702) 2024-01-17 11:04:27 +01:00
Sofia Papagiannaki
d1dab5828d
Alerting: Update rule API to address folders by UID (#74600)
* Change ruler API to expect the folder UID as namespace

* Update example requests

* Fix tests

* Update swagger

* Modify FIle field in /api/prometheus/grafana/api/v1/rules

* Fix ruler export

* Modify folder in responses to be formatted as <parent UID>/<title>

* Add alerting test with nested folders

* Apply suggestion from code review

* Alerting: use folder UID instead of title in rule API (#77166)

Co-authored-by: Sonia Aguilar <soniaaguilarpeiron@gmail.com>

* Drop a few more latent uses of namespace_id

* move getNamespaceKey to models package

* switch GetAlertRulesForScheduling to use folder table

* update GetAlertRulesForScheduling to return folder titles in format `parent_uid/title`.

* fi tests

* add tests for GetAlertRulesForScheduling when parent uid

* fix integration tests after merge

* fix test after merge

* change format of the namespace to JSON array

this is needed for forward compatibility, when we migrate to full paths

* update EF code to decode nested folder

---------

Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
Co-authored-by: Virginia Cepeda <virginia.cepeda@grafana.com>
Co-authored-by: Sonia Aguilar <soniaaguilarpeiron@gmail.com>
Co-authored-by: Alex Weaver <weaver.alex.d@gmail.com>
Co-authored-by: Gilles De Mey <gilles.de.mey@gmail.com>
2024-01-17 11:07:39 +02:00
Alexander Weaver
3c796ecc8f
Alerting: Add metric counting rule groups per org (#80669)
* Refactor, fix bad map hint

* Count groups per org
2024-01-16 16:35:56 -06:00
Santiago
3afd94185c
Alerting: Add metric to check for default AM configurations (#80225)
* Alerting: Add metric to check for default AM configurations

* Use a gauge for the config hash

* don't go out of bounds when converting uint64 to float64

* expose metric for config hash

* update metrics after applying config
2024-01-16 17:12:24 +01:00
Yuri Tseretyan
4b071f5452
Alerting: Fix MuteTiming Get API to return provenance status (#80494) 2024-01-13 00:16:54 +02:00
Julien Duchesne
2fb03dfa56
fix(swagger): Mute Timing PUT OK status is 202 (#80459) 2024-01-12 16:58:20 -05:00
Yuri Tseretyan
4479e7218d
Alerting: MuteTiming service return errutil + GetTiming by name (#79772)
* add get mute timing by name to MuteTimingService
* update get mute timing request handler to use the service method

* replace validation, uniqueness and used errors with errutils
* update mute timing methods return errutil responses
* use the term "time interval" in errors bevause mute timings are deprecated in Alertmanager and will be replaced by time intervals in the future.

* update create and update methods to return struct instead of pointer
2024-01-12 21:23:44 +02:00
idafurjes
cb419e799b
Remove folderid service test (#80433)
* Remove FolderID from service tests

* Add models

* Add folderID pack to publicdashboard tests

* Remove folderID from dashboard tests

* Remove folderID from folders

* Remove folderID from ngalert tests

* Remove nolint comment

* Add back some tests after rebase
2024-01-12 16:43:39 +01:00
Yuri Tseretyan
77db6a9ca4
Alerting: Fix GetAlertRulesForScheduling to use folder table and join by org_id (#80330) 2024-01-11 09:21:03 -05:00
Santiago
6c87d9a1e7
Alerting: Stop retries on 4xx status code responses (remote Alertmanager readiness check) (#80350) 2024-01-11 12:12:35 +01:00
William Wernert
48b5ac779b
Alerting/Annotations: Add annotation backend for Loki alert state history (#78156)
* Move scope type vars to testutil package

* Expose parts of state historian for use in annotation backend

* Implement Loki ASH Annotation store

This store will only implement the `Get` method of a RepositoryImpl since alert state history
writes to Loki elsewhere.

* Use interface for Loki HTTP Client

* Add tests for Loki ASH Annotation store

* Add missing test

* Fix lint

* Organize tests

* Add filter tests

* Improve tests

* Move filter logic into outer function

* Fix lint

* Add comment

* Fix tests

* Fix lint

* Rename historian store + refactor

* Cleanup historian store

* Fix tests

* Minor cleanup

* Use new `ShouldRecordAnnotation` filter

* Fix logic and add tests for this check

* Fix typos, remove unused variables, `< 1` -> `== 0`

* More closely mimic RBAC filter from xorm to ensure correct logic

* Move off weaveworks client

* Address PR comments
2024-01-10 18:42:35 -05:00
Matthew Jacobson
afa33f12b2
Alerting: Create alertingQueryOptimization feature flag for alert query optimization (#78932)
* Alerting: Create feature flag for alert query optimization

Adds a feature flag alertingQueryOptimization for an already existing 
functionality: alert query optimization. This feature flag will now be disabled 
by default.
2024-01-10 15:52:58 -05:00
Matthew Jacobson
f365d35cf8
Alerting: Show warning when query optimized (#78751)
* Alerting: Show warning when query optimized

* Use frame.AppendNotices

* Improve warning to include why and a prompt for action
2024-01-10 14:40:00 -05:00
Santiago
9e78faa7ba
Alerting: Add metrics to the remote Alertmanager struct (#79835)
* Alerting: Add metrics to the remote Alertmanager struct

* rephrase http_requests_failed description

* make linter happy

* remove unnecessary metrics

* extract timed client to separate package

* use histogram collector from dskit

* remove weaveworks dependency

* capture metrics for all requests to the remote Alertmanager (both clients)

* use the timed client in the MimirAuthRoundTripper

* HTTPRequestsDuration -> HTTPRequestDuration, clean up mimir client factory function

* refactor

* less git diff

* gauge for last readiness check in seconds

* initialize LastReadinesCheck to 0, tweak metric names and descriptions

* add counters for sync attempts/errors

* last config sync and last state sync timestamps (gauges)

* change latency metric name

* metric for remote Alertmanager mode

* code review comments

* move label constants to metrics package
2024-01-10 11:18:24 +01:00
Matthew Jacobson
1d4419fbe4
Alerting: Fix NoData & Error alerts not resolving when rule is reset (#80184)
* Alerting: Fix NoData & Error alerts not resolving when rule is reset

On rule reset, when creating the PostableAlerts StateToPostableAlert did not
attach the correct NoData/Error alertname and rulename labels to expire/resolve
the active alerts when the previous cached state was NoData/Error.
2024-01-09 14:47:19 -05:00
Alexander Weaver
542741f748
Alerting: Log scheduler maxAttempts, guard against invalid retry counts, log retry errors (#80234)
* Log maxAttempts, add guard, log retry errors

* fix whitespace

* Initialize evaluator in TestProcessTicks
2024-01-09 13:19:37 -06:00
Matthew Jacobson
aa03b8f8a7
Alerting: Guided legacy alerting upgrade dry-run (#80071)
This PR has two steps that together create a functional dry-run capability for the migration.

By enabling the feature flag alertingPreviewUpgrade when on legacy alerting it will:
    a. Allow all Grafana Alerting background services except for the scheduler to start (multiorg alertmanager, state manager, routes, …).
    b. Allow the UI to show Grafana Alerting pages alongside legacy ones (with appropriate in-app warnings that UA is not actually running).
    c. Show a new “Alerting Upgrade” page and register associated /api/v1/upgrade endpoints that will allow the user to upgrade their organization live without restart and present a summary of the upgrade in a table.
2024-01-05 18:19:12 -05:00
Yuri Tseretyan
72182e02a4
Alerting: Mute timing service tests (#79817)
split tests for mute timing service to functions for each method this makes it clear the scope of tests
2024-01-06 00:26:15 +02:00
Yuri Tseretyan
494f36e0bd
Alerting: Update provisioning services that handle Alertmanager configuraiton to access config via storage (#79814)
* extract get and save operations to a alertmanagerConfigStore. this removes duplicated code in service (currently only mute timings) and improves testing
* replace generic errors with errutils one with better messages.
* update provisioning services to use new store

---------

Co-authored-by: Alexander Weaver <weaver.alex.d@gmail.com>
2024-01-05 16:15:18 -05:00
Alexander Weaver
a8fb01a502
Swap weaveworks/common utilities for equivalents in grafana/dskit (#80051)
* Replace histogram collector and grpc injectors

* Extract request timing utility

* Also vendor test file

* Suppress erroneous linter warn
2024-01-05 10:08:38 -06:00
Matthew Jacobson
3537c5440f
Alerting: Refactor migration to return pairs of legacy and upgraded structs (#79719)
Some refactoring that will simplify next changes for dry-run PRs. This should be no-op as far as the created ngalert resources and database state, though it does change some logs.

The key change here is to modify migrateOrg to return pairs of legacy struct + ngalert struct instead of actually persisting the alerts and alertmanager config. This will allow us to capture error information during dry-run migration.

It also moves most persistence-related operations such as title deduplication and folder creation to the right before we persist. This will simplify eventual partial migrations (individual alerts, dashboards, channels, ...).

Additionally it changes channel code to deal with PostableGrafanaReceiver instead of PostableApiReceiver (integration instead of contact point).
2024-01-05 05:37:13 -05:00
Santiago
1f6575e65e
Alerting: Test MOA in remote secondary mode (#79828) 2024-01-05 11:05:27 +01:00
Alexander Weaver
90d4704cd7
Alerting: Fix URL timestamp conversion in historian API in annotation mode (#80026)
Fix timestamp conversion when calling annotation store
2024-01-04 12:40:21 -06:00
Yuri Tseretyan
f6a46744a6
Alerting: Support hysteresis command expression (#75189)
Backend: 

* Update the Grafana Alerting engine to provide feedback to HysteresisCommand. The feedback information is stored in state.Manager as a fingerprint of each state. The fingerprint is persisted to the database. Only fingerprints that belong to Pending and Alerting states are considered as "loaded" and provided back to the command.
   - add ResultFingerprint to state.State. It's different from other fingerprints we store in the state because it is calculated from the result labels.
  -  add rule_fingerprint column to alert_instance
   - update alerting evaluator to accept AlertingResultsReader via context, and update scheduler to provide it.
   - add AlertingResultsFromRuleState that implements the new interface in eval package
   - update getExprRequest to patch the hysteresis command.

* Only one "Recovery Threshold" query is allowed to be used in the alert rule and it must be the Condition.


Frontend:

* Add hysteresis option to Threshold in UI. It's called "Recovery Threshold"
* Add test for getUnloadEvaluatorTypeFromCondition
* Hide hysteresis in panel expressions

* Refactor isInvalid and add test for it
* Remove unnecesary React.memo
* Add tests for updateEvaluatorConditions

---------

Co-authored-by: Sonia Aguilar <soniaaguilarpeiron@gmail.com>
2024-01-04 11:47:13 -05:00
Santiago
a77ba40ed4
Alerting: Use the forked Alertmanager for remote secondary mode (#79646)
* (WIP) Alerting: Use the forked Alertmanager for remote secondary mode

* fall back to using internal AM in case of error

* remove TODOs, clean up .ini file, add orgId as part of remote AM config struct

* log warnings and errors, fall back to remoteSecondary, fall back to internal AM only

* extract logic to decide remote Alertmanager mode to a separate function, switch on mode

* tests

* make linter happy

* remove func to decide remote Alertmanager mode

* refactor factory function and options

* add default case to switch statement

* remove ineffectual assignment
2023-12-21 15:26:31 +01:00
Santiago
c46da8ea9b
Alerting: Update alerting package and imports from cluster and clusterpb (#79786)
* Alerting: Update alerting package

* update to latest commit

* alias for imports
2023-12-21 12:34:48 +01:00
Matthew Jacobson
0424d44b39
Alerting: In migration, create one label per channel (#76527)
* In migration, create one label per channel

This PR changes how routing is done by the legacy alerting migration.

Previously, we created a single label on each alert rule that contained an array of contact point names. Ex: __contact__="slack legacy testing","slack legacy testing2"

This label was then routed against a series of regex-matching policies with continue=true. Ex: __contacts__ =~ .*"slack legacy testing".*

In the case of many contact points, this array could quickly become difficult to manage and difficult to grok at-a-glance.

This PR replaces the single __contact__ label with multiple __legacy_c_{contactname}__ labels and simple equality-matching policies. These channel-specific policies are nested in a single route under the top-level route which matches against __legacy_use_channels__ = true for ease of organization.

This should improve the experience for users wanting to keep the default migrated routing strategy but who also want to modify which contact points an alert sends to.
2023-12-19 13:25:13 -05:00
Santiago
9945514baa
Alerting: Validate configuration for the remote Alertmanager struct (#79691)
* Alerting: Validate configuration for the remote Alertmanager struct

* add TenantID to test

* add OrgID to config struct in tests
2023-12-19 18:41:48 +01:00
Alexander Weaver
65ecde6eed
Alerting: Don't record annotations for mapped NoData transitions, when NoData is mapped to OK (#77164)
* Exclude mapped nodata transitions when nodata mapped to OK

* Fix processEvalResults test

* Don't check NoDataState when filtering transition

* Add comment to explain purpose of separate function

---------

Co-authored-by: William Wernert <william.wernert@grafana.com>
2023-12-18 16:59:32 -05:00
Santiago
f7248efff5
Alerting: Fix panic when creating a new Alertmanager returns an error (#79641)
Alerting: Fix panic after error creating new Alertmanager
2023-12-18 15:33:07 +01:00
Alexander Weaver
cf8e8852c3
Alerting: Drop NamespaceID from responses on unstable ngalert API endpoints in favor of NamespaceUID (#79359)
* Drop from API response

* Drop from swagger docs

* Drop from integration tests

* regenerate public swagger docs

* Drop from frontend

* Drop asserts for namespaceID field
2023-12-15 11:06:53 -06:00
William Wernert
9171bf92bb
Alerting: Add rule ID and title to alert state history Loki entry (#79481)
* Add rule ID and title to Loki entry

* Combine related tests
2023-12-14 13:06:23 -05:00
Santiago
23b4568597
Alerting: Send configuration and state to the remote Alertmanager on shutdown (#78682)
* Alerting: Send configuration and state to the remote Alertmanager on shutdown

* Alerting: Add a sync interval for ApplyConfig in remote secondary mode

* add routine to sync states and configs

* pass a cancellable context to syncRoutine(), remove tests for ApplyConfig, cache last config in memory

* extract logic to update config and state in the remote Alertmanager

* get latest config from the database

* avoid using separate goroutine for updating state and config

* clean up PR

* refactor, comments, tests

* update tests

* remove canceled context from calls to StopAndWait()

* create context with timeout and send config and state to remote Alertmanager

* update tests

* address code review comments
2023-12-13 22:53:09 +01:00
Julien Duchesne
884e0427e6
ngalert openapi: Add X-Disable-Provenance to missing operations (#79278)
Swagger(ngalert): Add `X-Disable-Provenance` to missing operations
I added all functions that call the `determineProvenance` function

Schema changes are from:
`make` in `pkg/services/ngalert/api/tooling`
`make swagger-clean && make openapi3-gen` in root
2023-12-13 10:55:59 -05:00
Santiago
91836e7832
Alerting: Add time-based convergence in remote secondary mode (#78809)
* Alerting: Add a sync interval for ApplyConfig in remote secondary mode

* add routine to sync states and configs

* pass a cancellable context to syncRoutine(), remove tests for ApplyConfig, cache last config in memory

* extract logic to update config and state in the remote Alertmanager

* get latest config from the database

* avoid using separate goroutine for updating state and config

* clean up PR

* refactor, comments, tests

* update tests

* add config struct for remote secondary forked Alertmanager

* use errgroups for sync operations

* use waitgroup instead of errgroup

* remove helper method to sync AMs

* check for errors instead of bool syncErr
2023-12-13 13:36:17 +01:00
William Wernert
62bdbe5b44
Annotations/Alerting: Add Loki historian store stub (#78363)
* Add Loki historian store stub

* Add composite store

* Use composite store if Loki historian enabled

* Split store interface into read/write

* Make composite + historian stores read only

* Use variadic constructor for composite

* Modify Loki store enable logic

* Use dskit.concurrency.ForEachJob for parallelism
2023-12-12 17:43:09 -05:00
Alexander Weaver
aa63e91a43
Alerting: Use mux router to match hooks, add support for path variables and methods (#79345)
* Use a router inside hooks rather than plain string matching

* Add test for mismatched method
2023-12-12 14:43:11 -06:00
Julien Duchesne
f977e3faf5
ngalert swagger: Fix status code (#79415)
This endpoint returns a 202, not a 204
Let me know if we should instead change the response of the API
2023-12-12 13:40:36 -05:00
Santiago
1a5c2cb55b
Alerting: Check whether the internal Alertmanager is ready in remote secondary mode (#79406)
Alerting: Check whether the internal Alertmanager is ready in remote secondary
2023-12-12 18:33:11 +01:00
gotjosh
cc3c0a2cc2
Alerting: Refactor readiness check (#78799)
* Alerting: Refactor readiness check

Moves the readiness check to the mimir client and removes the need to assert that we have senders - it already has a queue and can hold notifications until we're ready to send them.
---------

Signed-off-by: gotjosh <josue.abreu@gmail.com>
2023-12-12 15:34:54 +00:00
Santiago
57e0d6bcb5
Chore: Simplify function signature for GetLatestAlertmanagerConfiguration (#79392) 2023-12-12 13:49:54 +01:00
Yuri Tseretyan
8af08d0df2
Alerting: Add export of mute timings to file provisioning formats (#79225)
* add export of mute timings to file provisioning formats
* support export of mute timings to HCL
2023-12-11 21:36:51 -05:00
Alexander Weaver
b867505bd4
alerting: Add tests for hooks (#79284)
Add tests for hooks
2023-12-11 13:20:48 -06:00
Yuri Tseretyan
2be7605794
Alerting: Fix fine-grained rule access control to use 403 for authorization error (#79239)
* use 403 for authorization error
* update silences API
* add ForbiddenError to rule API responses
2023-12-07 13:43:58 -05:00
gotjosh
c631261681
Alerting: Attempt to retry retryable errors (#79161)
* Alerting: Attempt to retry retryable errors

Retrying has been broken for a good while now (at least since version 9.4) - this change attempts to re-introduce them in their simplest and safest form possible.

I first introduced #79095 to make sure we don't disrupt or put additional load on our customer's data sources with this change in a patch release. Paired with this change, retries can now work as expected.

There's two small differences between how retries work now and how they used to work in legacy alerting.

Retries only occur for valid alert definitions - if we suspect that that error comes from a malformed alert definition we skip retrying.
We have added a constant backoff of 1s in between retries.

---------

Signed-off-by: gotjosh <josue.abreu@gmail.com>
2023-12-06 20:45:08 +00:00
gotjosh
07915703fe
Revert "Alerting: Attempt to retry retryable errors" (#79158)
Revert "Alerting: Attempt to retry retryable errors (#79037)"

This reverts commit 3e51cf0949.
2023-12-06 19:12:01 +00:00
gotjosh
3e51cf0949
Alerting: Attempt to retry retryable errors (#79037)
* Alerting: Attempt to retry retryable errors

Currently in a draft state, but this was the minimal diff I could put together to exemplify how could achieve this.

Signed-off-by: gotjosh <josue.abreu@gmail.com>

---------

Signed-off-by: gotjosh <josue.abreu@gmail.com>
2023-12-06 16:35:22 +00:00
Yuri Tseretyan
7e331c8507
Alerting: Support for condition field in /api/v1/eval (#79032)
Co-authored-by: Sonia Aguilar <soniaaguilarpeiron@gmail.com>
2023-12-06 11:28:43 -05:00
Alexander Zobnin
959ebf82da
Folders: Show dashboards and folders with directly assigned permissions in "Shared" folder (#78465)
* Folders: Show folders user has access to at the root level

* Refactor

* Refactor

* Hide parent folders user has no access to

* Skip expensive computation if possible

* Fix tests

* Fix potential nil access

* Fix duplicated folders

* Fix linter error

* Fix querying folders if no managed permissions set

* Update benchmark

* Add special shared with me folder and fetch available non-root folders on demand

* Fix parents query

* Improve db query for folders

* Reset benchmark changes

* Fix permissions for shared with me folder

* Simplify dedup

* Add option to include shared folder permission to user's permissions

* Fix nil UID

* Remove duplicated folders from shared list

* Folders: Fix fetching empty folder

* Nested folders: Show dashboards with directly assigned permissions

* Fix slow dashboards fetch

* Refactor

* Fix cycle dependencies

* Move shared folder to models

* Fix shared folder links

* Refactor

* Use feature flag for permissions

* Use feature flag

* Review comments

* Expose shared folder UID through frontend settings

* Add frontend type for sharedWithMeFolderUID option

* Refactor: apply review suggestions

* Fix parent uid for shared folder

* Fix listing shared dashboards for users with access to all folders

* Prevent creating folder with "shared" UID

* Add tests for shared folders

* Add test for shared dashboards

* Fix linter

* Add metrics for shared with me folder

* Add metrics for shared with me dashboards

* Fix tests

* Tests: add metrics as a dependency

* Fix access control metadata for shared with me folder

* Use constant for shared with me

* Optimize parent folders access check, fetch all folders in one query.

* Use labels for metrics
2023-12-05 16:13:31 +01:00
Rodrigo Villablanca
ab83bc7346
Alerting: Fix export of notification policy to JSON (#78021)
* Export Notification Policy correctly (#78020)

The JSON version of an exported Notification Policy now
inline correctly the policy in the same way the Yaml version
does.

Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
2023-12-04 16:57:37 -05:00
Julien Duchesne
3c51190392
ngalert make: Support GNU install on Darwin (#78482)
* ngalert `make`: Support GNU install on Darwin
Currently, the Makefile assumes that Darwin is using the Mac version of `sed`
I have the GNU version, so it failed. With this PR, it checks which version is installed
I also called `make` and there are some changes that came out of it

* swagger-gen
2023-12-04 10:11:39 -05:00
Sofia Papagiannaki
6d4625ad52
Alerting: Fix deleting rules in a folder with matching UID in another organization (#78258)
* Remove usage of obsolete function for deleting alert rules under folder

* Apply suggestion from code review

* Update tests
2023-12-04 11:34:38 +02:00
Yuri Tseretyan
64feeddc23
Alerting: Update rule access control to return errutil errors (#78284)
* update rule access control to return errutil errors
* use alerting in msgID
2023-12-02 01:42:11 +02:00
Alexander Weaver
ab0ef5276f
Alerting: Decouple quota configuration logic from API interfaces and add tests (#78930)
* Separate usage reporter from API

* Extract quota registration

* Decouple from API store interface

* Move to ngalert package and add tests

* linter
2023-12-01 10:47:19 -06:00
Steve Simpson
520c927931
Alerting: Only warm alert state cache if execute_alerts=true. (#78895)
* Alerting: Only warm alert state cache if execute_alerts=true.

If the Grafana instance is not executing alerts, then Warm()-ing the state
manager is wasteful and could lead to misleading rule status queries, as the
status returned will be always based on the state loaded from the database at
startup, and not the most recent evaluation state.

* Move Warm() down to shared conditional.
2023-12-01 10:17:32 +01:00
Matthew Jacobson
5a80962de9
Alerting: Add clean_upgrade config and deprecate force_migration (#78324)
* Alerting: Add clean_upgrade config and deprecate force_migration

Upgrading to UA and rolling back will no longer delete any data by default. 
Instead, each set of tables will remain unchanged when switching between 
legacy and UA. As such, the force_migration config has been deprecated 
and no extra configuration is required to roll back to legacy anymore.

If clean_upgrade is set to true when upgrading from legacy alerting to Unified
Alerting, grafana will first delete all existing Unified Alerting resources,
thus re-upgrading all organizations from scratch. If false or unset,
organizations that have previously upgraded will not lose their existing Unified
 Alerting data when switching between legacy and Unified Alerting.

 Similar to force_migration, it should be kept false when not needed as it may
 cause unintended data-loss if left enabled.

---------

Co-authored-by: Christopher Moyer <35463610+chri2547@users.noreply.github.com>
2023-11-30 11:01:11 -05:00
Matthew Jacobson
cdad712547
Alerting: Keep track of individual org migration status (#78369)
* Alerting: Keep track of individual org migration status

Save migration status per migrated org.

Change the meaning (and key/value) of the org_id=0 entry 
to store the current (previous) config value used by alerting. 
This is so we can know when to upgrade/downgrade by 
comparing with the new config value in 
UnifiedAlerting.IsEnabled.
2023-11-30 10:25:59 -05:00
Santiago
d64c2b6f4e
Alerting: Implement ApplyConfig in the forked Alertmanager (#78684)
* Alerting: Add a sync interval for ApplyConfig in remote secondary mode

* remove out of scope code

* remove parentheses after CleanUp for consistency in test comments

* Add comment to ApplyConfig
2023-11-30 15:36:41 +01:00
Santiago
316c8b50bc
Alerting: Add SaveAndApply methods to the forked Alertmanager (remote secondary) (#78827)
* Alerting: Add configuration methods to the forked Alertmanager for remote secondary modes

* update comments
2023-11-30 15:18:56 +01:00
Matthew Jacobson
2b51f0e263
Alerting: In migration improve deduplication of title and group (#78351)
* Alerting: In migration improve deduplication of title and group

This change improves alert titles generated in the legacy migration 
that occur when we need to deduplicate titles. Now when duplicate 
titles are detected we will first attempt to append a sequential index, 
falling back to a random uid if none are unique within 10 attempts. 
This should cause shorter and more easily readable deduplicated 
titles in most cases.

In addition, groups are no longer deduplicated. Instead we set them 
to a combination of truncated dashboard name and humanized alert 
frequency. This way, alerts from the same dashboard share a group 
if they have the same evaluation interval. In the event that truncation 
causes overlap, it won't be a big issue as all alerts will still be in a 
group with the correct evaluation interval.
2023-11-29 10:05:00 -05:00
Santiago
73776f37eb
Alerting: Send state to the remote Alertmanager (#78538)
* Alerting: Introduce a Mimir client as part of the Remote Alertmanager

Mimir client that understands the new APIs developed for mimir. Very much a WIP still.

* more wip

* appease the linter

* more linting

* add more code

* get state from kvstore, encode, send

* send state to the remote Alertmanager, extract fullstate logic into its own function

* pass kvstore to remote.NewAlertmanager()

* refactor

* add fake kvstore to tests

* tests

* use FileStore to get state

* always log 'completed state upload'

* refactor compareRemoteConfig

* base64-encode the state in the file store

* export silences and nflog filenames, refactor

* log 'completed state/config upload...' regardless of outcome

* add values to the state store in tests

* address code review comments

* log error from filestore

---------

Co-authored-by: gotjosh <josue.abreu@gmail.com>
2023-11-29 12:49:39 +01:00
Matthew Jacobson
ce90a1f2be
Alerting: Apply query optimization to eval endpoints (#78566)
* Alerting: Apply query optimization to eval endpoints

Previously, query optimization was applied to alert queries when scheduled but
not when ran through `api/v1/eval` or `/api/v1/rule/test/grafana`. This could
lead to discrepancies between preview and scheduled alert results.
2023-11-28 19:44:28 -05:00
Santiago
01d274852c
Alerting: Add GetFullState method to FileStore (#78701)
* Alerting: Add GetFullState method to FileStore

* make tests compile, create stateStore in NewAlertmanager

* return errors instead of logging, accept an arbitrary number of strings

* make NewAlertmanager() accept a stateStore
2023-11-28 15:34:45 +01:00
William Wernert
f7bf818527
Alerting: Make alert state history Loki http client public (#78291)
* Make state history Loki client public

* Make historian metrics subsystem configurable
2023-11-27 09:20:50 -05:00
Matthew Jacobson
4b439b7f52
Alerting: In migration, fallback to '1s' for malformed min interval (#78614)
* Alerting: In migration, fallback to '1s' for malformed min interval

During legacy migration, when we encounter an alert datasource query 
with a min interval (interval field in the query model) that is not 
parseable, instead of failing the migration we fallback to a min interval 
of 1s and continue.

The reason for this is a bug in legacy alerting (existing for a few major 
versions) which allows arbitrary dashboard variables to be used as the 
min interval, even though those variables do not work and will cause 
the legacy alert to fail with `interval calculation failed: time: invalid 
duration`.
2023-11-24 11:27:44 -05:00
gotjosh
8120306fea
Remote Alertmanager(refactor): Only parse the URL once (#78631)
* Remote Alertmanager(refactor): Only parse the URL once

Exactly what it says in the tin.

Signed-off-by: gotjosh <josue.abreu@gmail.com>

* use the existing tests

Signed-off-by: gotjosh <josue.abreu@gmail.com>

---------

Signed-off-by: gotjosh <josue.abreu@gmail.com>
2023-11-24 11:05:13 +00:00
Jean-Philippe Quéméner
11d4f604f5
fix(alerting): proper handling for queries with multiple conditions in migration (#78591)
fix(alerting): proper handling for queries with multiple conditions
2023-11-23 18:05:44 +01:00
gotjosh
23fe8f4e9c
Alerting: Introduce a Mimir client as part of the Remote Alertmanager (#78357)
* Alerting: Introduce a Mimir client as part of the Remote Alertmanager

This is our first attempt at making Grafana communicate use Mimir as a backend - it uses a new set of APIs that we've developed on the Mimir side to upload the grafana configuration and alertmanager state so that it can then be ported over.

Codewise, we've introduced a couple of things:

A client to isolate in its own package all the communication that happens with Mimir
A few changes to the remote/alertmanager to include uploading the configuration and state when it starts
A few refactors that align a bit better with the design approach that we're thinking
An integration tests again these newly developed APIs using a custom image

---------

Signed-off-by: gotjosh <josue.abreu@gmail.com>
Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>
2023-11-23 16:59:36 +00:00
Jo
0de66a8099
Authz: Remove use of SignedInUser copy for permission evaluation (#78448)
* remove use of SignedInUserCopies

* add extra safety to not cross assign permissions

unwind circular dependency

dashboardacl->dashboardaccess

fix missing import

* correctly set teams for permissions

* fix missing inits

* nit: check err

* exit early for api keys
2023-11-22 14:20:22 +01:00
Tania
39754ba2d6
Nested Folders: Wrap create/update operations with transactions (#78000)
* Nested Folders: Add transaction to create and update methods

* Update tests

* Make IncreaseVersionForAllRulesInNamespace synchronous

* Resolve merge conflicts
2023-11-21 23:06:20 +02:00
Kat Yang
2f2ce3edbb
Chore: Deprecate ID from Folder (#78281)
* Chore: Deprecate ID from Folder

* chore: add more linter comments

* chore: add missing lint comment
2023-11-20 15:44:51 -05:00
Matthew Jacobson
893839d27b
Alerting: Move general alert rule validation from db-layer to model (#78325)
Alerting: Move general alert rule validation to model
2023-11-17 11:20:50 -05:00
Jean-Philippe Quéméner
2d2e058563
refactor: use constant for prometheus datasource type (#78287) 2023-11-17 01:07:35 +01:00
Yuri Tseretyan
7cec741bae
Alerting: Extract alerting rules authorization logic to a service (#77006)
* extract alerting authorization logic to separate package
* convert authorization logic to service
2023-11-15 18:54:54 +02:00
Kat Yang
3a2e96b0db
Chore: Deprecate FolderID from Dashboard (#77823)
* Chore: Deprecate FolderID from Dashboard

* chore: add two missing nolint comments
2023-11-15 10:28:50 -05:00
Ryan McKinley
f69fd3726b
FeatureToggles: Add context and and an explicit global check (#78081) 2023-11-14 12:50:27 -08:00
Jo
580477bf8e
NGAlerting: Use identity.Requester interface instead of SignedInUser (#76360)
* unfurl SignedInUserAttrs services

* replace signedInUser with Requester

replace signedInUser with requester

* fix tests

* linting

---------

Co-authored-by: Ieva <ieva.vasiljeva@grafana.com>
2023-11-14 14:47:34 +00:00
Santiago
4a152a0e35
Alerting: Add lifecycle methods to the forked Alertmanager (#77741)
* Alerting: Add an empty Forked Alertmanager

* Alerting: Add methods for silences to the forked Alertmanager

* check for errors in tests

* make linter happy

* Alerting: Add methods for alerts to the forked Alertmanager

* Alerting: Add methods for receivers to the forked Alertmanager

* Alerting: Add TestTemplate method to the forked Alertmanager

* make linter happy

* separate into both forked AMs

* fix tests

* Alerting: Add lifecycle methods to the forked Alertmanager
2023-11-14 11:17:17 +01:00
Ryan McKinley
dec9a07738
Settings: Actually deprecate access to feature flags (#78073) 2023-11-13 11:39:01 -08:00
Ryan McKinley
3509a5abb9
FeatureFlags: Cleanup usage of cfg.IsFeatureToggleEnabled (#78014) 2023-11-13 07:55:15 -08:00
Santiago
8b751eb216
Alerting: Add TestTemplate method to the forked Alertmanager (#77577)
* Alerting: Add an empty Forked Alertmanager

* Alerting: Add methods for silences to the forked Alertmanager

* check for errors in tests

* make linter happy

* Alerting: Add methods for alerts to the forked Alertmanager

* Alerting: Add methods for receivers to the forked Alertmanager

* Alerting: Add TestTemplate method to the forked Alertmanager

* make linter happy

* separate into both forked AMs

* fix tests
2023-11-09 12:35:24 +01:00
Santiago
ba51c371ec
Alerting: Add methods for receivers to the forked Alertmanager (#77574)
* Alerting: Add an empty Forked Alertmanager

* Alerting: Add methods for silences to the forked Alertmanager

* check for errors in tests

* make linter happy

* Alerting: Add methods for alerts to the forked Alertmanager

* Alerting: Add methods for receivers to the forked Alertmanager

* make linter happy

* separate into both forked AMs

* fix tests

* rename testErr -> expErr
2023-11-09 11:38:16 +01:00
Santiago
e24fe96d90
Alerting: Add methods for alerts to the forked Alertmanager (#77571)
* Alerting: Add an empty Forked Alertmanager

* Alerting: Add methods for silences to the forked Alertmanager

* check for errors in tests

* make linter happy

* Alerting: Add methods for alerts to the forked Alertmanager

* make linter happy

* separate into both forked AMs

* rename testErr -> expErr
2023-11-08 13:52:04 +01:00
Santiago
197f0d2859
Alerting: Add methods for silences to the forked Alertmanager (#77805)
* Alerting: Add an empty Forked Alertmanager

* Alerting: Add methods for silences to the forked Alertmanager

* check for errors in tests

* make linter happy

* make linter happy

* Alerting: Add methods for silences to the forked Alertmanager
2023-11-08 12:03:40 +01:00
Yuri Tseretyan
a2629f3dd3
Alerting: Remove unused Accesscontrol dependency from DbStore (#77479) 2023-11-02 15:54:30 -04:00
William Wernert
e562250f72
Alerting: Handle edge cases without panicking during template migration (#76890)
* Handle empty variable, remove panics

* Use fmt.Errorf only where appropriate
2023-11-02 13:24:54 -04:00
Santiago
01af8f61f1
Alerting: Separate the forked Alertmanager into two implementations (#77582) 2023-11-02 17:53:18 +01:00
Santiago
8fc9873443
Alerting: Add an empty Forked Alertmanager struct (#77550)
Alerting: Add an empty Forked Alertmanager
2023-11-02 16:49:03 +01:00
Yuri Tseretyan
85425b2194
Alerting: Fix flaky test TestExportRules (#77519)
* fix test to correclty mock data store

* Update pkg/services/ngalert/api/api_ruler_export_test.go

Co-authored-by: Jean-Philippe Quéméner <JohnnyQQQQ@users.noreply.github.com>

* Update pkg/services/ngalert/api/api_ruler_export_test.go

---------

Co-authored-by: Jean-Philippe Quéméner <JohnnyQQQQ@users.noreply.github.com>
2023-11-01 21:35:04 +02:00
Ryan McKinley
5d5f8dfc52
Chore: Upgrade Go to 1.21.3 (#77304) 2023-11-01 09:17:38 -07:00
Santiago
a6b9b27673
Alerting: Remove OrgID() from the Alertmanager interface (#77398) 2023-10-31 10:58:47 +01:00
Kyle Brandt
e4d1fdc3d0
Errors: Make errors the same in dev as prod (#77366)
When running in dev mode, error messages would contain an additional "error" property alongside "message". Since this causes confusion, that has been removed and now error messages are the same both modes (using "message").
2023-10-30 14:06:26 -04:00
Yuri Tseretyan
48b55f39bf
Alerting: Add support for responders to Opsgenie integration (#77159)
* add support for responders in opsgenie UI config
* update export model

Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>
2023-10-27 13:06:46 -04:00
Santiago
f9fc2e4568
Alerting: Remove ConfigHash() from the Alertmanager interface (#77134) 2023-10-25 17:11:53 +02:00