Commit Graph

1608 Commits

Author SHA1 Message Date
Santiago
b79b38f02c
Alertmanager: Support limits for silences (#90826)
* Alertmanager: support limits for silences

* update grafana/alerting to latest main
2024-07-24 14:22:29 +02:00
William Wernert
45f298120e
Alerting: Return error when writing recorded metrics instead of default writing NaN (#90743)
* Return error instead of default writing NaN
2024-07-22 15:47:02 -04:00
AvivGuiser
96c3e9c550
Alerting: Use stable identifier of a group when export to HCL (#90196)
* change the rule-group to be hashed when exporting to HCL

Signed-off-by: Aviv Guiser <avivguiser@gmail.com>

---------

Signed-off-by: Aviv Guiser <avivguiser@gmail.com>
2024-07-19 18:13:26 +03:00
Alexander Weaver
418b077c59
Alerting: Integration testing for recording rules including writes (#90390)
* Add success case and tests for writer using metrics

* Use testable version of clock

* Assert a specific series was written

* Fix linter

* Fix manually constructed writer
2024-07-18 17:14:49 -05:00
Alexander Weaver
0e269db8a9
Alerting: Expose recordingWriter on ngalert (#90573)
Expose recordingWriter on ngalert
2024-07-18 13:24:06 -05:00
Yuri Tseretyan
09e10ae9e0
Alerting: Update State history API Open API documentation (#89795) 2024-07-18 10:37:05 -04:00
Alexander Weaver
88ed77e7e8
Alerting: More graceful handling of NoData in recording rules (#90312)
* Handle NoData as its own case

* Debug

* Scalars parseable by CollectionReader

* fix linter

* Orgit add pkg/*git add pkg/* not and
2024-07-17 15:24:03 -05:00
Yuri Tseretyan
c3b9c9b239
Alerting: Send information about alert rule to data source in headers (#90344)
* add support of metadata to condition and adding it to request headers
* support for additional metadata when condition is built
* add additionall context to conditions: source and folder title
* add version
* use percent-encoding for header values
2024-07-17 22:55:12 +03:00
Yuri Tseretyan
970cafa20f
Alerting: Time interval Delete API to check for usages in alert rules (#90500)
* Check if a time interval is used in alert rules before deleting it
* Add time interval to parameters of ListAlertRulesQuery and ListNotificationSettings of DbStore

== Refacorings == 
* refactor isMuteTimeInUse to accept a single route
* update getMuteTiming to not return err
* update delete to get the mute timing from config first
2024-07-17 10:53:54 -04:00
Matthew Jacobson
b7f422b68d
Alerting: Receiver API Get+List+Delete (#90384) 2024-07-16 10:02:16 -04:00
Yuri Tseretyan
9c05b30489
Chore: Add more logs and tracing to hysteresis flows (#90369) 2024-07-15 13:38:20 -04:00
Santiago
e097ffc771
Alerting: Update grafana/alerting dependency (#90365)
* update grafana/alerting to latest main
* update alertmanager to  66ec17e3aa45
2024-07-12 14:05:17 -04:00
Matthew Jacobson
ba800692c6
Alerting: Persist AlertInstance ResolvedAt & LastSentAt (#89135)
* Alerting: Persist AlertInstance ResolvedAt & LastSentAt

* Fix test

* Modify existing tests

* Fix merge conflicts from nullable LastSentAt & ResolvedAt
2024-07-12 12:26:58 -04:00
Matthew Jacobson
b7767c79e7
Alerting: Fix contact point export 500 error and notifications/receivers missing settings (#90342)
* Regression test

* Fix 500 error when exporting redacted receivers

* Fix tests to check permissions
2024-07-12 11:42:22 -04:00
Kristin Laemmert
8a6107cd35
DashboardStore: Use ReplDB and get dashboard quotas from the ReadReplica (#90235)
* Use ReplDB in dashboard store and update all fixtures - no other changes

* just moving dashboard counts for now

* find the missing test fixture
2024-07-12 10:47:49 -04:00
Alexander Weaver
111ebd4fb2
Alerting: Create integration testing infra for recording rules (#90306)
* Create some integration testing infra for RRs

* whoops

* Require no error in responding

* fix linter

* Panic, no need to pass testing around

* Extend status test
2024-07-11 14:59:52 -05:00
Alexander Weaver
ab32183e18
Alerting: Track recording rule health and last eval info ephemerally (#90247)
* Track health and last eval info

* Read method for status

* Minor tests
2024-07-11 14:05:09 -05:00
Santiago
3bb861b9f0
Alerting: Remove empty/namespace labels when sending alerts to the remote Alertmanager (#90284)
* Alerting: Remove empty/namespace labels when sending alerts to the remote Alertmanager

* update tests

* fix typo in comment
2024-07-11 15:20:12 +02:00
Yuri Tseretyan
5ae5fa3a7a
Alerting: Support field selectors in time interval API (#90022)
* fix kind of TimeInterval
* register custom fields for selectors
* support field selectors in legacy storage
* support selectors in storage

===== Misc
* refactor conversions to build in one place
* hide implementation of provenance status behind accessors to use the key in selectors
* fix provenance error
2024-07-08 22:45:30 +03:00
Alexander Weaver
3b6a8775bb
Alerting: Fix stale values associated with states that have gone to NoData, unify values calculation (#89807)
* Unify values

* Fix with latest changes on main

* Fix up NaN test

* Keep refIDs with -1 as value

* Test that refIDs are preserved on Normal to Error transition

* Alerting to err test too

* Add a blurb to docs about this behavior
2024-07-08 12:30:23 -05:00
Steve Simpson
e9fd191065
Alerting: Fix some status codes returned from provisioning API. (#90117)
The contact point deletion API was returning 500 when it should have been
returning a 4xx error, when the contact point is in use:

- When in use by a notificiation policy, we were missing
  the `.Errorf("")` to convert `errutil.Base` into `errutil.Error`.
- When in use by an alert rule, an regular error was returned.
2024-07-05 19:06:37 +02:00
Alexander Zobnin
87d86e81ce
Zanzana: Evaluate permissions alongside with RBAC engine (#90064)
* Zanzana: Evaluate permissions if feature flag enabled

* Fix tests

* adjust logs

* fix spelling

* remove unused

* only evaluate implemented resources

* refactor
2024-07-05 11:31:23 +02:00
Yuri Tseretyan
411bab6d44
Alerting: Lower severity of logs about duplicates to debug (#89971)
lower severity of logs about duplicates to debug
2024-07-03 16:46:28 -04:00
Yuri Tseretyan
c3b5cabb14
Alerting: Refactor scheduler's rule evaluator to store rule key (#89925) 2024-07-01 16:43:23 -04:00
Yuri Tseretyan
655e477c20
Alerting: Fix flaky test in scheduler's tests (#89923) 2024-07-01 13:31:03 -04:00
Santiago
fce03cd724
Alerting: Send static headers to the remote Alertmanager (#89846) 2024-07-01 17:48:40 +02:00
Yuri Tseretyan
559738ce6a
Alerting: Fix flaky test in historian (#89913) 2024-07-01 16:59:06 +03:00
Gabriel MABILLE
71d31397e5
Fix flaky tests (#89910) 2024-07-01 14:39:51 +02:00
Alexander Akhmetov
68691c9386
Alerting: Add setting for maximum allowed rule evaluation results (#89468)
* Alerting: Add setting for maximum allowed rule evaluation results

Added a new configuration setting `quota.alerting_rule_evaluation_results` to set the maximum number of alert rule evaluation results per rule. If the limit is exceeded, the evaluation will result in an error.
2024-06-27 09:45:15 +02:00
Yuri Tseretyan
06d5850396
Alerting: Update alerting state history API to authorize access using RBAC (#89579)
* add method CanReadAllRules to rule authorization service

* add alias type Namespace for Folder in ngalert's models package. It implements the Namespacer interface that is used by authz logic

* update state history's backends to authorize access to rules.
* update Loki to add folders UIDs to query. 
    * Update BuildLogQuery to drop filter by folders if it's too long and fall back to in-memory filtering.
2024-06-26 10:25:37 -04:00
Santiago
fe1309dd96
Alerting: Send external URL to the remote Alertmanager (#89701)
* Alerting: Send external URL to the remote Alertmanager

* test that the URL is sent to the remote Alertmanager

* AppURL -> ExternalURL
2024-06-26 14:02:02 +02:00
Nihal
b1ce7e8a83
Alerting: Reduce cyclomatic complexity of PrepareRuleGroupStatuses (#89649)
* reduce cyclomatic complexity of PrepareRuleGroupStatuses. see https://github.com/grafana/grafana/issues/88670

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

* reduce cyclomatic complexity for PrepareRuleGroupStatuses in pkg/services/ngalert/api/api_prometheus.go

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

* reduce cyclomatic complexity for PrepareRuleGroupStatuses in pkg/services/ngalert/api/api_prometheus.go

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

---------

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>
2024-06-26 10:21:37 +02:00
Matthew Jacobson
83d05ea777
Alerting: Fix broken state tests (#89712) 2024-06-25 14:19:46 -04:00
Matthew Jacobson
47c9259d75
Alerting: Ensure we update State.LastSentAt before persisting (#89427) 2024-06-25 13:01:26 -04:00
William Wernert
fcfa89f864
Alerting: Implement Prometheus remote write for recording rules (#89189)
* Fix timestamp recorded by rule

* Implement prometheus remote write

* Create http client instead of transport

* Address PR comments

* Remove status code label
2024-06-25 17:23:42 +03:00
Yuri Tseretyan
4a5aab54a5
Alerting: Add max limit for Loki query size in state history API (#89646)
* add setting for query limit

* update BuildLogQuery to return error if limit is exceeded

* move tests for BuildLogQuery to separate suite
2024-06-25 09:20:38 -04:00
Alexander Akhmetov
2035814059
Alerting: fix updating error in the alert rule state during error to error transitions and restarts (#89557)
Alerting: fix preserving errors in the alert rule state during error to error transitions

Alert state transition from one error to another did not update state.Error correctly.
The error in state.Error remained as the initial error encountered.
This led to another issue, where after a Grafana restart, the error was lost because
the state of the alert rule did not change, but the Error is not preserved in the database
between restarts.

This could happen if the expression service returned an error or the alert routine panicked
during querying.
2024-06-25 09:42:00 +02:00
Yuri Tseretyan
b075926202
Alerting: Time Intervals API (#88201)
* expose ngalert API to public
* add delete action to time-intervals
* introduce time-interval model generated by app-platform-sdk from CUE model the fields of the model are chosen to be compatible with the current model
* implement api server
* add feature flag alertingApiServer
---- Test Infra
* update helper to support creating custom users with enterprise permissions
* add generator for Interval model
2024-06-20 16:52:03 -04:00
Matthew Jacobson
3228b64fe6
Alerting: Resend resolved notifications for ResolvedRetention duration (#88938)
* Simple replace of State.Resolved with State.ResolvedAt

* Retain ResolvedAt time between Normal->Normal transition

* Introduce ResolvedRetention to keep sending recently resolved alerts

* Make ResolvedRetention configurable with resolved_alert_retention

* Tick-based LastSentAt for testing of ResendDelay and ResolvedRetention

* Do not reset ResolvedAt during Normal->Pending transition

Initially this was done to be inline with Prom ruler. However, Prom ruler
doesn't keep track of Inactive->Pending/Alerting using the same alert instance,
so it's more understandable that they choose not to retain ResolvedAt. In our
case, since we use the same cached instance to represent the transition, it
makes more sense to retain it.

This should help alleviate some odd situations where temporarily entering
Pending will stop future resolved notifications that would have happened
because of ResolvedRetention.

* Pointers for ResolvedAt & LastSentAt

To avoid awkward time.Time{}.Unix() defaults on persist
2024-06-20 16:33:03 -04:00
Yuri Tseretyan
92f10b73a8
Alerting: Move interface Namespaced from accesscontrol to models package (#89439)
move Namespaced interface from accesscontrol to models
2024-06-19 16:18:33 -04:00
Steve Simpson
8eabef1f91
Alerting: Update remote alertmanager to use extended receivers API. (#89253)
* Alerting: Update remote alertmanager to use extended receivers API.

* Update integration test and Mimir image

* Update Mimir image in more places
2024-06-19 12:40:22 +03:00
Steve Simpson
43a246f431
Alerting: Improve performance of /api/prometheus for large numbers of alerts. (#89268)
* Alerting: Optimize sorting alert instances.

* Also change other Labels fields for consistency
2024-06-17 12:25:47 +02:00
Alexander Weaver
8491e02caf
Alerting: Instrument outbound requests for Loki Historian and Remote Alertmanager with tracing (#89185)
* Add TracedClient

* Handle errors and status codes

* Wire up tracing to normal ASH and loki annotation mapping

* Add tracing to remote alertmanager

* one more spot

* and not or

* More consistency with other grafana traces, lower cardinality name
2024-06-14 13:24:12 -05:00
Dave Henderson
6262c56132
chore(perf): Pre-allocate where possible (enable prealloc linter) (#88952)
* chore(perf): Pre-allocate where possible (enable prealloc linter)

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>

* fix TestAlertManagers_buildRedactedAMs

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>

* prealloc a slice that appeared after rebase

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>

---------

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>
2024-06-14 14:16:36 -04:00
Steve Simpson
dd3c3b5857
Alerting: Update grafana/alerting. (#88914) 2024-06-14 09:19:04 +02:00
Ryan McKinley
99d8025829
Chore: Move identity and errutil to apimachinery module (#89116) 2024-06-13 07:11:35 +03:00
William Wernert
c62cc25513
Alerting: Configure recording rule writer from config.ini (#89056) 2024-06-12 16:04:46 -04:00
Santiago
b7120c5a30
Alerting: Fix missing argument in call to createRemoteAlertmanager() (#89101) 2024-06-12 11:57:22 +03:00
Santiago
12d5251c12
Alerting: Alertmanager configuration sync loop (#88822)
* make the config sync happen on each call to ApplyConfig(), fix tests

* send autogen config

* add fake autogen function for tests

* update stale comments, tidy things up, make linter happy

* add auto-gen routes only if the feature toggle is enabled

* remove unnecessary fake autogen function

* throttle configuration syncs

* restore pkg/services/store/entity/sqlstash/sql_storage_server.go

* test sync loop in ApplyConfig, skip invalid autogen routes

* restore conf/defaults.ini

* restore conf/defaults.ini

* avoid skipping invalid auto-gen routes in SaveAndApplyConfig

* test that autogenFn is called and its errors are returned

* add debug message about the sync interval not having elapsed

* collapse two log lines into one
2024-06-12 10:13:34 +02:00
Jacob Valdemar
eb76ea47a0
Alerting: Add ha_reconnect_timeout configuration option (#88823)
* Docs: Update "Configure high availability" guide with ha_reconnect_timeout configuration

---------

Co-authored-by: Christopher Moyer <35463610+chri2547@users.noreply.github.com>
2024-06-11 13:25:48 -04:00
Alexander Akhmetov
667fea6623
Alerting: use hash of labels instead of labels string as the alert state cache key (#88956)
* Alerting: use hash instead of labels as the cache key
* Use data.Labels.Fingerprint to calculate the cache key
2024-06-11 18:34:58 +02:00
Alexander Weaver
d004f8a98d
Alerting: Recording rules understands errors embedded in dataframes (#88946)
* Make MakeDependencyError public for tests in another package

* Create tests for errors in eval results

* Extract logic to pull frame errors out into exported function

* Maybe we can drop cyclomatic complexity lint suppression now?

* extract frame errors and fail recording rules if frames contain error

* Fix up retry logic to actually work

* Do not retry non retryable errors
2024-06-11 10:37:10 -05:00
Steve Simpson
d440d86bbb
Alerting: Fix erroneous use of grafana-cli/logger. (#89037)
Can't see how this was intentional, likely just a typo.
2024-06-11 14:29:56 +02:00
Santiago
cdbc9d801f
Alerting: Use the internal Alertmanager to test templates and receivers (remote primary) (#88988) 2024-06-11 11:06:07 +02:00
Yuri Tseretyan
d4b0ac5973
Alerting: Fix rule storage to filter by group names using case-sensitive comparison (#88992)
* add test for the bug
* remove unused struct
* update db store to post process filters by group using go-lang's case-sensitive string comparison

--------

Co-authored-by: Alexander Weaver <weaver.alex.d@gmail.com>
2024-06-10 19:05:47 -04:00
Santiago
5f4d07bb75
Alerting: Enable remote primary mode using feature toggles (#88976) 2024-06-10 17:07:13 +02:00
Santiago
e15e40fbd3
Alerting: Skip setting up clustering in remote primary/only modes (#88968)
* Alerting: Skip setting up clustering in remote primary mode

* Update pkg/services/ngalert/notifier/multiorg_alertmanager.go

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>

---------

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>
2024-06-10 13:51:11 +02:00
William Wernert
63e9969c1b
Alerting: Recording rule mapping logic for data frames to Prometheus metrics (#88550)
* Add stub Prometheus writer with mapping logic

* Add tests
2024-06-07 20:00:22 +03:00
Alexander Weaver
58fdb24b0b
Alerting: Recording rules appear as type=recording in Prometheus API + better abstraction for type (#88805)
* Wire status through to prom API

* Regenerate swagger
2024-06-07 11:24:06 -05:00
Yuri Tseretyan
32ea1801aa
Alerting: Support AWS SNS integration in Grafana (#88867) 2024-06-07 11:49:49 -04:00
Alexander Weaver
f1dc63565e
Alerting: Fix go-swagger extraction and several embedded types from Alertmanager in Swagger docs (#88879)
Drop redundant swagger model comments
2024-06-07 10:47:47 -05:00
Yuri Tseretyan
003e3efce9
Alerting: Update mute timings provisioning API to support optimistic locking (#88731)
* add version to time-interval models
* set time interval fingerprint as version
* update to check provided version
* delete to check if version is provided in query parameter 'version'
* update integration tests
* update specs
2024-06-06 18:06:37 -04:00
Alexander Weaver
a2e21d61f8
Alerting: Remove dead evalRunning guard in rule routine (#88312)
Remove dead guard
2024-06-06 16:15:01 -05:00
William Wernert
d359591dac
Alerting: Support recording rule struct in provisioning API (#87849)
* Support record struct in provisioning API

* Update api spec

* Use record field

* Restrict API endpoints following toggle

* Fix swagger spec

* Add recording rule validation to store validator
2024-06-06 21:05:02 +03:00
Alexander Weaver
820ee6e9db
Alerting: Make all in api generator tooling now actually makes all (#88793)
* Make all now actually makes all

* Clean depends on clean-go
2024-06-05 11:52:31 -05:00
Fayzal Ghantiwala
80f54778f3
Alerting: Add option to use Redis in cluster mode for Alerting HA (#88696)
* Add config option to use Redis in cluster mode

* Use UniversalOptions
2024-06-05 17:02:25 +01:00
Dave Henderson
df784917e4
Alerting: Improve performance of tupleLablesToLabels function (#88736)
* Alerting: Improve performance of tupleLablesToLabels function

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>

* use %s for string rather than %v

Co-authored-by: Sofia Papagiannaki <1632407+papagian@users.noreply.github.com>

---------

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>
Co-authored-by: Sofia Papagiannaki <1632407+papagian@users.noreply.github.com>
2024-06-05 16:19:09 +03:00
Santiago
9f9928d41a
Alerting: Update grafana/alerting (#88363)
* Alerting: Update grafana/alerting

* make tests pass by implementing yaml unmarshallers and deleting fields with omitempty in their yaml tags

* go mod tidy

* fix tests by implementing not calling GettableApiAlertingConfig.UnmarshalYAML from GettableApiAlertingConfig.UnmarshalJSON

* cleanup, reduce diff

* fix more tests

* update grafana/alerting to latest commit, delete global section from configs in tests

* bring back YAML unmarshaller for GettableApiAlertingConfig

* update alerting package dependency to point to main

* skip test for sns notifier
2024-06-04 20:29:37 +02:00
Yuri Tseretyan
a63ef42816
Alerting: Mute Timing service to prevent changing provenance status to none (#88462)
* use relaxed validation to not introduce breaking changes for now but to be able to use the service
in non-provisioning APIs.
2024-06-04 08:54:33 -04:00
Fayzal Ghantiwala
b66cd7ef79
Alerting: Add filters for RouteGetRuleStatuses (#88295)
* Placeholder commit with rule_uid change

* Add new filters to grafana rule state API

* Revert type change

* Split rule_group and rule_name params

* remove debug line

* Change how query params are parsed

* Comment
2024-06-04 10:57:55 +01:00
Matthew Jacobson
31d5dd0a12
Alerting: Prevent updating rule uid matcher for silences (#88519)
Prevents updating the `__alert_rule_uid__` equality matcher (used for rule-specific silences) on existing silences
2024-06-03 17:39:06 -04:00
Fayzal Ghantiwala
67b9e3b269
Alerting: Update HA Redis TLS docs (#88538)
* Update HA Redis TLS doc

* Add test for regular TLS

* Update docs

* Update prom registry
2024-05-31 13:23:45 +01:00
Sofia Papagiannaki
17ca61d7f8
Alerting: Export and provisioning rules into subfolders (#77450)
* Folders: Optionally include fullpath in service responses
* Alerting: Export folder fullpath instead of title
* Escape separator in folder title
* Add support for provisiong alret rules into subfolders
* Use FolderService for creating folders during provisioning
* Export WithFullpath() folder service function

---------

Co-authored-by: Tania B <yalyna.ts@gmail.com>
Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
2024-05-31 11:09:20 +03:00
Matthew Jacobson
09cb3a6048
Alerting: Add optional metadata via query param to silence GET requests (#88000)
* Alerting: Add optional metadata to GET silence responses

- ruleMetadata: to request rule metadata.
- accesscontrol: to request access control metadata.
2024-05-30 12:04:47 -04:00
William Wernert
5de7d4d06d
Alerting: Create writer interface for recording rules (#88459)
* Create writer interface for recording rules

Also create fake impl + use it for stub in scheduler
2024-05-29 22:38:33 +03:00
Fayzal Ghantiwala
543f0ae37e
Alerting: Update ListAlertRulesQuery to take a slice of RuleGroups (#88385)
* Change ListAlertRulesQuery to take RuleGroup slice instead

* Change func name

* Change func name

* Fix fakes

* Fix function arg
2024-05-29 11:50:33 +01:00
Alexander Weaver
b926b6336d
Alerting: Scheduled recording rules execute their queries (#88309)
* Basic eval flow

* Wiring-up

* fix

* Extend todo

* Start with tests

* Include some relevant tests, skip ones that seem to have timing-based race conditions

* Some tests, touch up linter and todo

* Solve TODO

* Add tracing

* Tests to make sure an eval went through

* Wire up feature toggles

* Update pkg/services/ngalert/schedule/recording_rule.go

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>

* Update pkg/services/ngalert/schedule/recording_rule_test.go

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>

* Update pkg/services/ngalert/schedule/recording_rule_test.go

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>

* Update pkg/services/ngalert/schedule/recording_rule_test.go

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>

---------

Co-authored-by: Steve Simpson <steve.simpson@grafana.com>
2024-05-28 10:59:21 -05:00
Matthew Jacobson
8418aca823
Alerting: Add single rule checks to alert rule access control (#88307)
* Alerting: Add single rule checks to alert rule access control

Modifies ruler api single rule read to no longer fetch entire groups and instead
 use the new single rule ac check.
Simplifies provisioning api getAlertRuleAuthorized logic to always load a single
 rule instead of conditionally loading the entire group when provisioning
 permissions are not present.

* Swap out Has/AuthorizeAccessToRule for Has/AuthorizeAccessInFolder
2024-05-28 10:49:24 -04:00
Kyle Brandt
a738cb42d8
Prometheus: Update dependency to v0.52.0 (#87809)
* Prometheus: Update dependency to v0.52.0

* go work sync

* fix panics in tests

* go work sync

* prometheus v0.52.0

* handle errors

* Update pkg/services/ngalert/sender/sender_test.go

Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>

* Update pkg/services/ngalert/sender/sender_test.go

Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>

---------

Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>
Co-authored-by: ismail simsek <ismailsimsek09@gmail.com>
2024-05-28 15:22:20 +02:00
Steve Simpson
08b18113d2
Alerting: Wire up alertmanagerRemoteOnly feature toggle. (#88329)
* Alerting: Wire up alertmanagerRemoteOnly feature toggle.

Though the mode isn't feature complete yet, it will be useful to have the
feature toggle wired up in order to start testing.

* Apply suggestions from code review

Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>

* Formatting

---------

Co-authored-by: Santiago <santiagohernandez.1997@gmail.com>
2024-05-27 16:18:46 +02:00
Steve Simpson
ed42119907
Alerting: Pass metrics Registerer into NewExternalAlertmanagerSender. (#88313)
* Alerting: Pass metrics Registerer into NewExternalAlertmanagerSender.

I will work on a separate change to export the metrics from Grafana, this
is a little more complicated.

* Typo
2024-05-24 23:03:34 +02:00
Steve Simpson
8bcf589301
Alerting: Pass logger into NewExternalAlertmanagerSender (#88256) 2024-05-24 20:11:26 +02:00
Alexander Weaver
65793440d3
Alerting: Test infrastructure for recording rules (#88200)
* Add test rule generator support for recording rules

* Remove accidental add

* Recording rules appear in GetRulesForScheduling

* A couple more tests, updates, count

* No need to capture rule defs
2024-05-23 16:27:07 -05:00
William Wernert
006d0021e3
Alerting: Remove requirement for datasource query on rule read (#87349)
* Remove requirement for datasource query for rule read

* Address PR comments
2024-05-23 12:44:30 -04:00
Matthew Jacobson
bc5d077b30
Alerting: separate out silence auth service preconditions checks (#87998)
* Alerting: separate out silence auth service preconditions checks

Will be useful for subsequent PR that adds metadata to silence response

* Add silence read wildcard scope to precondition for read all silences
2024-05-23 12:34:42 -04:00
Steve Simpson
8421919cb5
Alerting: Feature toggle to disallow sending alerts externally (#87982)
* Define feature toggle

* Implement feature toggle
2024-05-23 14:29:19 +02:00
Gaurav Agrawal
fdaa091a4d
Alerting: Support custom API URL for PagerDuty integration (#88007)
* fix assert in LINE
* fix pagerduty asserts

---------

Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
2024-05-22 15:31:55 -04:00
Alexander Weaver
89b54d06e9
Alerting: Schedule a shim implementation for recording rules (#87939)
* Add shim rule implementation for recording rules

* Give ruleFactory access to the original rule definition

* Schedule shim implementation if the rule is a recording rule

* Fix or suppress linter

* Fix nolint
2024-05-21 16:42:58 -05:00
Alexander Weaver
49c8deb1ea
Alerting: Add recording rules to ruler API and validation (#87779)
* Read path, main API

* Define record field for incoming requests

* Refactor several alerting specific validators into two paths

* Refactor validateCondition actually contain all the condition validation logic

* Move condition validation inside rule path

* Validators for recording rules

* Wire feature flag through to validators

* Test for accepting a valid recording rule

* Tests for negative case, no UID

* Test for ignoring alerting fields

* Build conditions based on recording rules as well

* Regenerate swagger docs

* Fix CRUD test to cover the right thing

* Re-generate swagger docs with backdated v0.30.2 version

* Regenerate base spec

* Regenerate ngalert specs

* Regenerate top level specs

* Comment and rename

* Return struct instead of modifying ref
2024-05-21 14:39:28 -05:00
William Wernert
cb0bcb6fe4
Alerting: Fix/update alerting API spec (#88130) 2024-05-21 10:06:44 -04:00
Santiago
60e7a4e746
Alerting/Chore: Remove unused parameters (#88045)
Alerting/Chore: Remove unused parameters from redisPeer.receiveLoop() and ReceiverService.shouldDecrypt()
2024-05-20 16:37:39 +02:00
Yuri Tseretyan
8c2a382788
Alerting: Fix typo in JSON response for rule export. (#88028) 2024-05-20 09:39:39 -04:00
Yuri Tseretyan
05d6813a09
Alerting: Fix scheduler to sort rules before evaluation (#88006)
sort rules scheduled for evaluation to make sure that the order is stable between evaluations.
This is especially important in HA mode.
2024-05-17 11:38:19 -04:00
Santiago
e41434c332
Alerting: Promote configuration in the remote Alertmanager (#87388) 2024-05-16 12:06:03 +02:00
Yuri Tseretyan
f410c7fca1
Alerting: use logger with same context within rule scheduling loop (#87934) 2024-05-15 15:38:00 -04:00
Alexander Weaver
1badcf4b63
Alerting: Allow NoData and ExecErrState to be fully blank on recording rules (#87868)
* Allow empty NoData and ExecErrState on recording rules

* remove TODO about this
2024-05-15 09:35:54 -05:00
Alexander Weaver
b8a284fb81
Alerting: Fix xorm serialization of Record field struct, add tests for storing and reading (#87857)
Fix sub struct ser and deser, add tests
2024-05-14 14:50:06 -05:00
Steve Simpson
67fa96f88d
Alerting: Pass logger into NewAnnotationBackend. (#87812)
* Alerting: Pass logger into NewAnnotationBackend.

Make it possible to pass loggers into more places for code reuse.

* Mistake in passing logger
2024-05-14 15:51:27 +02:00
William Wernert
563fcb8bf4
Alerting: Encode query model map to string in rule export to avoid html escape sequences (#87663)
* Encode query model map to string to avoid html escape sequences

* Remove insignificant whitespace in test request
2024-05-14 09:29:50 -04:00
Fayzal Ghantiwala
7a2fbad0c8
Alerting: Add options to configure TLS for HA using Redis (#87567)
* Add Alerting HA Redis Client TLS configs

* Add test to ping miniredis with mTLS

* Update .ini files and docs

* Add tests for unified alerting ha redis TLS settings

* Fix malformed go.sum

* Add modowner

* Fix lint error

* Update docs and use dstls config
2024-05-14 14:21:42 +01:00
Alexander Weaver
e39658097f
Alerting: Wire recording rules feature toggle into limits struct (#87778)
Wire toggle into limits
2024-05-14 07:44:14 -05:00
Ieva
167151b211
Chore: Remove use of deprecated method in AC code (#87541)
* switch from using cfg to using featuremgmt for checking a feature toggle in AC code

* merge test fixes
2024-05-10 11:56:52 +01:00
Alexander Weaver
a6a9ab4008
Alerting: Do not store series values from past evaluations in state manager for no reason (#87525)
Do not store previous execution results on states
2024-05-09 15:51:55 -05:00
Yuri Tseretyan
356a29592b
Alerting: Add two sets of provisioning actions for rules and notifications (#87149) 2024-05-09 13:19:07 -04:00
Alexander Weaver
36ef611cf4
Alerting: Add database migration for recording rule fields (#87012)
* Create recording rule fields in model

* Add migration

* Write to database, support in version table

* extend fingerprint

* Force fields to be empty on validate

* Another storage spot, tests for fingerprint

* Explicitly set defaults in provisioning API

* Tests for main API validation

* Add diff tests even though fields are unpopulated for now

* Use struct tag approach instead of FromDB/ToDB hooks as it better handles nulls when deserializing

* test for deser

* Backout RecordTo for now since it's not decided in the doc

* back out of migration too

* Drop datasourceref for now

* address linter complaints

* Try a single outer struct with all fields embedded
2024-05-09 12:12:44 -05:00
Alexander Weaver
6c47968f6c
Alerting: Do not retry rule evaluations with "input data must be a wide series but got type long" style errors (#87343)
add typed error for series must be wide, do not retry
2024-05-07 11:31:07 -05:00
Matthew Jacobson
babfa2beac
Alerting: Hook up GMA silence APIs to new authentication handler (#86625)
This PR connects the new RBAC authentication service to existing alertmanager API silence endpoints.
2024-05-03 15:32:30 -04:00
Santiago
b76a9e4d31
Alerting: Implement GetStatus in the remote Alertmanager struct (#84887)
* Alerting: Implement GetStatus in the remote Alertmanager struct

* update tests

* fix tests, extract AlertmanagerConfig from PostableConfig

* get the remote AM config instead of the Grafana one from the remote AM

* pass grafana AM config in test

* return error in GetStatus instead of logging it (internal AM)
2024-05-03 13:59:02 +02:00
Fayzal Ghantiwala
df25e9197e
Alerting: Get grafana-managed alert rule by UID (#86845)
* Add auth checks and test

* Check user is authorized to view rule and add tests

* Change naming

* Update Swagger params

* Update auth test and swagger gen

* Update swagger gen

* Change response to GettableExtendedRuleNode

* openapi3-gen

* Update tests with refactors models pkg
2024-05-02 15:24:59 +01:00
Serge Zaitsev
ad5613d7d4
Chore: Remove cfg from folder service (#87212)
remove cfg from folder service
2024-05-02 13:18:54 +02:00
William Wernert
93519f70ca
Alerting: Also fix HCL field name for MuteTimeIntervals (#87079)
* Correct HCL field name for MuteTimeIntervals

* Update test
2024-04-30 16:14:01 +01:00
Yuri Tseretyan
052082a927
Alerting: Refactor Alert Rule Generators (#86813) 2024-04-29 21:52:15 -04:00
William Wernert
70ff229bed
Alerting: Use expected field name for receiver in HCL export (#87065)
* Use expected field name for receiver in hcl

Terraform provider expects `contact_point` instead of `receiver` in
notification settings on a rule.
2024-04-29 18:13:29 +01:00
Santiago
36a0499128
Alerting: Implement CreateSilence in the forked Alertmanager (remote primary mode) (#85716) 2024-04-29 18:47:25 +02:00
Santiago
1af2e69625
Alerting: Implement DeleteSilence in the forked AM (remote primary) (#85721) 2024-04-29 17:23:41 +02:00
Steve Simpson
fbaa847a3c
Alerting: Pass logger into NewRemoteLokiBackend. (#87029)
Tiny refactor to allow a logger to be passed into NewRemoteLokiBackend.
2024-04-29 12:10:23 +02:00
Yuri Tseretyan
dff7cb9afb
Alerting: Move alertmanager api silence code to separate files (#86947)
* Move alertmanager api silence code to separate files unchanged

* Replace with silence model instead interface

---------

Co-authored-by: Matt Jacobson <matthew.jacobson@grafana.com>
2024-04-25 15:20:37 -04:00
Matthew Jacobson
3397e8bf09
Alerting: Improve error when receiver or time interval used by rule is deleted (#86865)
* Alerting: Improve error when receiver used by rule is deleted

* Remove RuleUID from public error and data

* Improve fallback error in am config post

* Refactor to expand to time intervals

* Fix message on unchecked errors to be same as before
2024-04-25 13:36:00 -04:00
Santiago
a6be12c037
Alerting: Implement SaveAndApplyConfig in the forked Alertmanager (remote primary) (#84659)
* Alerting: Implement SaveAndApplyConfiguration in the forked Alertmanager struct

* call SaveAndApplyConfig on the remote first, log errors for the internal

* add comments explaining why we ignore errors in the internal AM

* restore go.work.sum
2024-04-23 15:45:35 +02:00
Steve Simpson
a6ad2380bf
Alerting: Refactor api_prometheus.go request handlers. (#86639)
This splits the request handlers into two functions, one which is the actual
handler and one which is independent from the Grafana `ReqContext` object. This
is to make it easier to reuse the implementation in other code.

Part of the refactoring changes the functions which get query parameters from
the request to operate on a `url.Values` instead of the request object.

The change also makes the code consistently use `req.Form` instead of a
combination of `req.URL.Query()` and `req.Form`, though I have left
`api_ruler` as-is to avoid this PR growing too large.
2024-04-23 14:50:26 +02:00
Santiago
c77ab53819
Alerting: implement SaveAndApplyConfig in the remote Alertmanager struct (#84642)
* implement SaveAndApplyConfig in the remote Alertmanager struct

* remove ID from CreateGrafanaAlertmanagerConfig call

* decrypt, test that we decrypt, refactor

* fix duplicated declaration in test

* rephrase comment, remove unnecessary conversion to slice of bytes

* fix test
2024-04-23 14:37:10 +02:00
Santiago
8b7c2a459b
Alerting: Implement SaveAndApplyDefaultConfig in the forked Alertmanager (remote primary mode) (#85668)
* Alerting: Implement SaveAndApplyDefaultConfig in the forked Alertmanager (remote primary)

* log the error for the internal AM instead of returning it
2024-04-23 14:36:40 +02:00
Yuri Tseretyan
9735a8a080
Alerting: Distinguish conflict violation errors (#86634)
* update generator to set ID = 0 and do not set 0 if unique is needed
* return proper message when the constraint violation
2024-04-22 12:28:46 -04:00
Julian Siebert
14f018e3fc
Docs: Use correct description for "og_priority" (#80889) 2024-04-22 13:53:18 +00:00
Steve Simpson
54290f2ac4
Alerting: Fix TestRouteGetRuleStatuses as much as possible. (#86666)
This test has been skipped for a long time, so it doesn't work anymore. I've
fixed the test so it works again, but left some tests disabled which were
apparently flaky. If we see the other test cases flaking, we'll have to
disable it again.

Fixes:
- Use fake access control for most test cases, and real one for FGAC test cases.
- Check that "file" in API responses the full folder path, not folder title.
2024-04-22 12:36:50 +02:00
Steve Simpson
f07f48616a
Alerting: Fix panic when limit_alerts=0. (#86640)
Oversight in the TopK function meant if k=0, then we'd panic when checking
element zero in the heap, because no items are ever allowed into the heap.
2024-04-22 10:14:19 +02:00
Steve Simpson
6ea97e41fb
Alerting: Consistently return Prometheus-style responses from rules APIs. (#86600)
* Alerting: Consistently return Prometheus-style responses from rules APIs.

This commit is part refactor and part fix. The /rules API occasionally returns
error responses which are inconsistent with other error responses. This fixes
that, and adds a function to map from Prometheus error type and HTTP code.

* Fix integration tests

* Linter happiness

* Make linter more happy

* Fix up one more place returning non-Prometheus responses
2024-04-19 21:03:20 +02:00
Santiago
529f55cfe8
Alerting: Remove isDefault field from receivers (Alertmanager configuration) (#86605)
Alerting: Remove isDefault field from receivers in the Alertmanager configuration
2024-04-19 15:44:20 +02:00
Santiago
309a7e7684
Alerting: Implement SaveAndApplyDefaultConfig in the remote Alertmanager struct (#85005)
* Alerting: Implement SaveAndApplyDefaultConfig in the remote Alertmanager struct

* send the hash of the encrypted configuration

* tests, default config hash in AM struct

* add missing default config to test

* restore build directory

* go work file...

* fix broken test

* remove unnecessary conversion to []byte

* go work again...

* make things work again with latest main branch changes

* update error messages in tests for decrypting config
2024-04-19 15:11:07 +02:00
Santiago
a2ce8fefed
Alerting: Use a struct when sending a Grafana AM configuration to the remote Alertmanager (#86451)
* Alerting: Use a struct when sending a Grafana AM configuration to the remote Alertmanager

* remove '-distroless' from mimir image name
2024-04-19 13:04:18 +02:00
Steve Simpson
5f7612834e
Alerting: Refactoring in api_prometheus.go to allow code reuse. (#86575)
Preparing these functions to be used by some other part of the codebase,
which does not have a `contextmodel.ReqContext`, only the normal request
structure (`url.Values`, etc). This is slightly messy because of how
Grafana allows url parameters to be in the URL or in the request body,
so we need to make sure to invoke the form parsing logic in `ReqContext`.
2024-04-19 12:52:01 +02:00
Steve Simpson
73873f5a8a
Alerting: Optimize rule status gathering APIs when a limit is applied. (#86568)
* Alerting: Optimize rule status gathering APIs when a limit is applied.

The frontend very commonly calls the `/rules` API with `limit_alerts=16`. When
there are a very large number of alert instances present, this API is quite
slow to respond, and profiling suggests that a big part of the problem is
sorting the alerts by importance, in order to select the first 16.

This changes the application of the limit to use a more efficient heap-based
top-k algorithm. This maintains a slice of only the highest ranked items whilst
iterating the full set of alert instances, which substantially reduces the
number of comparisons needed. This is particularly effective, as the
`AlertsByImportance` comparison is quite complex.

I've included a benchmark to compare the new TopK function to the existing
Sort/limit strategy. It shows that for small limits, the new approach is
much faster, especially at high numbers of alerts, e.g.

100K alerts / limit 16: 1.91s vs 0.02s (-99%)

For situations where there is no effective limit, sorting is marginally faster,
therefore in the API implementation, if there is either a) no limit or b) no
effective limit, then we just sort the alerts as before. There is also a space
overhead using a heap which would matter for large limits.

* Remove commented test cases

* Make linter happy
2024-04-19 11:51:22 +02:00
Matthew Jacobson
a20197229e
Alerting: Prevent simplified routing zero duration GroupInterval and RepeatInterval (#86561)
Prevent zero duration GroupInterval and RepeatInterval
2024-04-18 21:08:38 -04:00
Matthew Jacobson
71445002b7
Alerting: Fix simplified routing group by override (#86552)
* Alerting: Fix simplified routing custom group by override

Custom group by overrides for simplified routing were missing required fields
GroupBy and GroupByAll normally set during upstream Route validation.

This fix ensures those missing fields are applied to the generated routes.

* Inline GroupBy and GroupByAll initialization instead of normalize after
2024-04-18 21:08:14 -04:00
Matthew Jacobson
533bed6d94
Alerting: Fix simplified routes '...' groupBy creating invalid routes (#86006)
* Alerting: Fix simplified routes '...' groupBy creating invalid routes

There were a few ways to go about this fix:
1. Modifying our copy of upstream validation to allow this
2. Modify our notification settings validation to prevent this
3. Normalize group by on save
4. Normalized group by on generate

Option 4. was chosen as the others have a mix of the following cons:
- Generated routes risk being incompatible with upstream/remote AM
- Awkward FE UX when using '...'
- Rule definition changing after save and potential pitfalls with TF

With option 4. generated routes stay compatible with external/remote AMs, FE
doesn't need to change as we allow mixed '...' and custom label groupBys, and
settings we save to db are the same ones requested.

In addition, it has the slight benefit of allowing us to hide the internal
implementation details of `alertname, grafana_folder` from the user in the
future, since we don't need to send them with every FE or TF request.

* Safer use of DefaultNotificationSettingsGroupBy

* Fix missed API tests
2024-04-16 12:14:39 -04:00
Alexander Weaver
5b1498f98f
Alerting: Return a 400 and errutil error when trying to delete a contact point that is referenced by a policy (#85481)
Return a 400 and errutil error when trying to delete a contact point that is referenced by a policy
2024-04-15 09:25:28 -05:00
Yuri Tseretyan
12605bfed2
Alerting: Update fixed roles to include silences permissions (#85826)
* update fixed roles to include silences
* add silence actions to managed permissions
* update documentation
2024-04-12 12:37:34 -04:00
Steve Simpson
ad7f804255
Alerting: Fix evaluation metrics to not count retries (#85873)
* Change evaluation metrics to only count once per eval, and add new metrics.

* Cosmetic: Move eval total Inc() to orginal place.
2024-04-12 16:20:46 +02:00
Matthew Jacobson
f79dd7c7f9
Alerting: Persist silence state immediately on Create/Delete (#84705)
* Alerting: Persist silence state immediately on Create/Delete

Persists the silence state to the kvstore immediately instead of waiting for the
 next maintenance run. This is used after Create/Delete to prevent silences from
 being lost when a new Alertmanager is started before the state has persisted.
 This can happen, for example, in a rolling deployment scenario.

* Fix test that requires real data

* Don't error if silence state persist fails, maintenance will correct
2024-04-09 13:39:34 -04:00
Santiago
2e7cc68394
Alerting: Remove CleanUp method from the Alertmanager (#85650)
Alerting: Remove Cleanup method from the Alertmanager
2024-04-09 12:13:27 +02:00
Yuri Tseretyan
509691b416
Alerting: Introduce authorization logic for operations on silences (#85418)
* extract genericService from RuleService just to reuse it later
* implement silence service

---------

Co-authored-by: William Wernert <william.wernert@grafana.com>
Co-authored-by: Matthew Jacobson <matthew.jacobson@grafana.com>
2024-04-08 18:02:28 -04:00
Santiago
6a75a8f354
Alerting: Update grafana/alerting and use Upsert for creating silences (#85676)
* Alerting: Update grafana/alerting and use Upsert for creating silences

* go.work.sum

* change error message in tests for silences (save -> upsert)
2024-04-08 11:46:14 +02:00
Alexander Weaver
03114e7602
Alerting: Return better error for invalid time range on alert queries (#85611)
* Return better error for invalid time range

* drop comment
2024-04-05 09:20:21 -05:00
Alexander Weaver
734d0111cb
Alerting: Export pure function to convert query results to alert results (#85393)
Exported pure function to convert query results to alert results
2024-04-05 08:57:31 -05:00
Santiago
c7573bb0f7
Alerting: Make retention period configurable for the notification log (#85605)
* Alerting: Make retention period configurable for the notification log

* update sample.ini

* fix outdated comment (on disk -> kvstore)

* skip checking cyclomatic complexity for ReadUnifiedAlertingSettings
2024-04-05 12:25:43 +02:00
Alexander Weaver
623ee3a2be
Alerting: Only append /alertmanager when sending alerts to mimir targets if not already present (#85543)
Don't append alertmanager if not present
2024-04-04 11:58:41 -05:00
Dave Henderson
5687243d0b
Feature Flags: use FeatureToggles interface where possible (#85131)
* Feature Flags: use FeatureToggles interface where possible

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>

* Replace TestFeatureToggles with existing WithFeatures

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>

---------

Signed-off-by: Dave Henderson <dave.henderson@grafana.com>
2024-04-04 12:22:31 -04:00
Serge Zaitsev
faa1244518
Chore: Replace sqlstore with db interface (#85366)
* replace sqlstore with db interface in a few packages

* remove from stats

* remove sqlstore in admin test

* remove sqlstore from api plugin tests

* fix another createUser

* remove sqlstore in publicdashboards

* remove sqlstore from orgs

* clean up orguser test

* more clean up in sso

* clean up service accounts

* further cleanup

* more cleanup in accesscontrol

* last cleanup in accesscontrol

* clean up teams

* more removals

* split cfg from db in testenv

* few remaining fixes

* fix test with bus

* pass cfg for testing inside db as an option

* set query retries when no opts provided

* revert golden test data

* rebase and rollback
2024-04-04 15:04:47 +02:00
Jean-Philippe Quéméner
7cfd470c91
fix(alerting): only expose metrics if executing alerts (#85512) 2024-04-03 17:18:02 +02:00
Benoit Tigeot
6f38ac6615
Alerting: Reduce set of fields that could trigger alert state change (#83496)
We want to avoid too much change of alert state based on change on
alert's fields. For that we ignore some fields from the diff.
2024-03-26 12:35:30 -04:00