Commit Graph

1423 Commits

Author SHA1 Message Date
Ryan McKinley
5f6bf93dd5
Expressions: Use enumerations rather than strings (#83741) 2024-03-01 19:38:32 +02:00
Santiago
8ad367e4ad
Chore: Remove redundant error check (#83769) 2024-03-01 13:28:08 -03:00
Alexander Weaver
a862a4264d
Alerting: Export rule validation logic and make it portable (#83555)
* ValidateInterval doesn't need the entire config

* Validation no longer depends on entire folder now that we've dropped foldertitle from api

* Don't depend on entire config struct

* Export validate group
2024-02-28 14:40:13 -06:00
Joe Blubaugh
b905777ba9
Alerting: Support deleting rule groups in the provisioning API (#83514)
* Alerting: feat: support deleting rule groups in the provisioning API

Adds support for DELETE to the provisioning API's alert rule groups route, which allows deleting the rule group with a
single API call. Previously, groups were deleted by deleting rules one-by-one.

Fixes #81860

This change doesn't add any new paths to the API, only new methods.

---------

Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
2024-02-28 10:19:02 -05:00
김은빈
96dfb385ca
Grafana: Replace magic number with a constant variable in response status (#80132)
* Chore: Replace response status with const var

* Apply suggestions from code review

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

* Add net/http import

---------

Co-authored-by: Sofia Papagiannaki <1632407+papagian@users.noreply.github.com>
2024-02-27 18:39:51 +02:00
Takashi Idobe
f209a5a8b8
fix typos (#83414) 2024-02-26 10:52:44 -07:00
Serge Zaitsev
d0679f0993
Chore: Add support bundle for folders (#83360)
* add support bundle for folders

* fix ProvideService in tests

* add a test for collector
2024-02-26 11:27:22 +01:00
George Robinson
a0353b237a
Alerting: Update swagger specs (#83260) 2024-02-23 11:25:43 +00:00
George Robinson
a564c8c439
Alerting: Keep order of time and mute time intervals consistent (#83257) 2024-02-22 16:57:20 +00:00
George Robinson
1ed1242358
Alerting: Basic support for time_intervals (#83216)
This commit adds basic support for time_intervals, as mute_time_intervals
is deprecated in Alertmanager and scheduled to be removed before 1.0.
It does not add support for time_intervals in API or file provisioning,
nor does it support exporting time intervals. This will be added in
later commits to keep the changes as simple as possible.
2024-02-22 15:58:56 +00:00
Matthew Jacobson
87ab98ea95
Alerting: Fix panic in provisioning filter contacts by unknown name (#83070) 2024-02-19 17:30:13 +02:00
Matthew Jacobson
46a77c0074
Alerting: Validate upgraded receivers early to display in preview (#82956)
Previously receivers were only validated before saving the alertmanager
configuration. This is a suboptimal experience for those upgrading with preview
as the failed channel upgrade will return an API error instead of being
summarized in the table.
2024-02-16 15:17:07 -05:00
William Wernert
fabaff9a24
Alerting: Create metric for rules using simple notifications (#82904)
---------

Co-authored-by: Matthew Jacobson <matthew.jacobson@grafana.com>
2024-02-16 19:01:49 +02:00
Matthew Jacobson
dfaf6d1e2e
Alerting: Dry-run legacy upgrade on startup (#82835)
Adds a feature flag (alertingUpgradeDryrunOnStart) that will dry-run the legacy 
alert upgrade on startup. It is enabled by default.

When on legacy alerting, this feature flag will log the results of the legacy 
alerting upgrade on startup and draw attention to anything in the current legacy 
alerting configuration that will cause issues when the upgrade is eventually 
performed. It acts as a log warning for those where action is required before 
upgrading to Grafana v11 where legacy alerting will be removed.
2024-02-16 11:29:54 -05:00
Matthew Jacobson
e7c6e9c5c9
Alerting: Fix migration edge-case race condition for silences (#81206)
If the db already has an entry in the kvstore for the silences of an
alertmanager before the migration has taken place, then it's possible that the
active alertmanager will overwrite the silence file created by the migration
before it has a chance to load it into memory.

This should not happen normally but is possible in edge-cases.

This change opts to bypass the unnecessary step of writing the silences to disk
during the migration and instead write them directly to the kvstore. This avoids
 the race condition entirely and is more correct as we treat the database as the
  source of truth for AM state.
2024-02-16 10:47:34 -05:00
Gabriel MABILLE
846eadff63
RBAC Search: Replace userLogin filter by namespacedID filter (#81810)
* Add namespace ID

* Refactor and add tests

* Rename maxOneOption -> atMostOneOption

* Add ToDo

* Remove UserLogin & UserID for NamespaceID

Co-authored-by: jguer <joao.guerreiro@grafana.com>

* Remove unecessary import of the userSvc

* Update pkg/services/accesscontrol/acimpl/service.go

* fix 1 -> userID

* Update pkg/services/accesscontrol/accesscontrol.go

---------

Co-authored-by: jguer <joao.guerreiro@grafana.com>
2024-02-16 11:42:36 +01:00
Sven Kirschbaum
86c618a6d6
Alerting: Escape namespace and group path parameters (#80504)
Co-authored-by: Jean-Philippe Quéméner <JohnnyQQQQ@users.noreply.github.com>
2024-02-16 09:43:47 +01:00
Matthew Jacobson
118e4a50b7
Alerting: Remove start page of legacy upgrade preview (#82010)
Alerting: Remove start page of upgrade preview

Alerting upgrade page will now always show the summary table even before
upgrading any alerts or notification channels. There a few reasons for this:

- The information on the start page is redundant as it's now contained in the
documentation.
- Previously, if some unexpected issue prevented performing a full upgrade, a
user would have limited to no means to using the preview tool to help fix the
problem. This is because you could not see the summary table until the full
upgrade was performed at least once. Now, you can upgrade individual alerts and
notification channels from the beginning.
2024-02-15 17:34:00 -05:00
Julien Duchesne
ba63e62311
Alerting: Return provenance of notification templates (#82274) 2024-02-15 14:35:54 -05:00
William Wernert
b7bbc5058f
Alerting: Don't validate rules on group update if they've only been reordered (#81841)
---------

Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
2024-02-15 12:03:28 -05:00
Yuri Tseretyan
1eebd2a4de
Alerting: Support for simplified notification settings in rule API (#81011)
* Add notification settings to storage\domain and API models. Settings are a slice to workaround XORM mapping
* Support validation of notification settings when rules are updated

* Implement route generator for Alertmanager configuration. That fetches all notification settings.
* Update multi-tenant Alertmanager to run the generator before applying the configuration.

* Add notification settings labels to state calculation
* update the Multi-tenant Alertmanager to provide validation for notification settings

* update GET API so only admins can see auto-gen
2024-02-15 09:45:10 -05:00
Alexander Weaver
d4ae10ecc6
Alerting: Small refactor, move unrelated functions out of fetcher (#82459)
Move unrelated functions out of fetcher
2024-02-14 20:01:32 +02:00
Diego Augusto Molina
ff08c0a790
Chore: improve test readability in ngalert/schedule (#82453)
Chore: improve test readability
2024-02-14 14:53:32 -03:00
Diego Augusto Molina
9c29e1a783
Alerting: Fix data races and improve testing (#81994)
* Alerting: fix race condition in (*ngalert/sender.ExternalAlertmanager).Run

* Chore: Fix data races when accessing members of *ngalert/state.FakeInstanceStore

* Chore: Fix data races in tests in ngalert/schedule and enable some parallel tests

* Chore: fix linters

* Chore: add TODO comment to remove loopvar once we move to Go 1.22
2024-02-14 12:45:39 -03:00
Alexander Weaver
ccb4533a86
Alerting: Remove unused AlertRuleVersionWithPauseStatus (#82383)
Remove unused AlertRuleVersionWithPauseStatus
2024-02-13 10:56:24 -06:00
Alexander Weaver
99fa064576
Alerting: Emit warning when creating or updating unusually large groups (#82279)
* Add config for limit of rules per rule group

* Warn when editing big groups through normal API

* Warn on prov api writes for groups

* Wire up comp root, tests

* Also add warning to state manager warm

* Drop unnecessary conversion
2024-02-13 08:29:03 -06:00
Ryan McKinley
0c6e409350
Chore: Update arrow and prometheus dependencies (#82215)
* update arrow and prometheus

* keep codeowner

* use compare

* use grafana-plugin-sdk-go v0.210.0

---------

Co-authored-by: ismail simsek <ismailsimsek09@gmail.com>
2024-02-13 01:50:25 +01:00
Karl Persson
1315c67c8b
Team/User: UID migrations (#82298)
* Add user uid migration to run on every startup to protect against empty values in a upgrade downgrade scenario

* Add team uid migration to run on every startup to protect against empty values in a upgrade downgrade scenario

* Run team uid migration
2024-02-12 14:48:29 +01:00
Alexander Weaver
5bbe9c6e61
Alerting: Enable group-level rule evaluation jittering by default, remove feature toggle (#82212)
* remove jitter feature flag

* Add an out so users can manually disable jitter

* Pass in cfg

* Add TODO to remove knob in future
2024-02-09 15:53:58 -06:00
Dan Cech
790e1feb93
Chore: Update test database initialization (#81673)
* streamline initialization of test databases, support on-disk sqlite test db

* clean up test databases

* introduce testsuite helper

* use testsuite everywhere we use a test db

* update documentation

* improve error handling

* disable entity integration test until we can figure out locking error
2024-02-09 09:35:39 -05:00
Jean-Philippe Quéméner
4dc1ebbb66
fix(alerting): add a proper compare func for location in mute timings (#82153) 2024-02-08 13:36:09 +01:00
George Robinson
90a26e18db
Alerting: Update Alertmanager to e82436c (#82145)
This commit updates Alertmanager to commit e82436c, which is based
on commit f69a508 from Prometheus Alertmanager.
2024-02-08 11:25:27 +00:00
Matthew Jacobson
dd0ca1263b
Alerting: Include rule uid, title, namespace in unique constraint errors (#82011)
* Alerting: Include rule_uid, title, namespace_uid in unique constraint errors
2024-02-07 12:55:48 -05:00
Alexander Weaver
843c477899
Alerting: Add exported API to scheduler to access currently loaded rules (#82031)
* Add exported API to fetch rule definitions from scheduler

* Add comment
2024-02-07 09:31:22 -06:00
Yuri Tseretyan
47546a4c72
Alerting: Update API to use folders' full paths (#81214)
* update GetUserVisibleNamespaces to use FolderSeriver
* update GetNamespaceByUID to use FolderService.GetFolders
* update GetAlertRulesForScheduling to use FolderService.GetFolders 

* Update API and GetAlertRulesForScheduling to use the folder's full path
* get full path of folder in RouteTestGrafanaRuleConfig

* fix escaping of titles for MySQL
2024-02-06 17:12:13 -05:00
Gokhan
cf601fab09
Alerting: Enable sending notifications to a specific topic on Telegram (#79546)
Co-authored-by: Yuri Tseretyan <yuriy.tseretyan@grafana.com>
2024-02-06 17:19:22 +02:00
William Wernert
2ea82af6e7
Alerting: Pass in receiver service to API struct (#81978) 2024-02-06 16:49:47 +02:00
George Robinson
c8ccc4649c
Alerting: Support UTF-8 (#81512)
This pull request updates our fork of Alertmanager to commit 65bdab0, which is based on commit 5658f8c in Prometheus Alertmanager.

It applies the changes from grafana/alerting#155 which removes the overrides for validation of alerts, labels and silences that we had put in place to allow alerts and silences to work for non-Prometheus datasources. However, as this is now supported in Alertmanager with the UTF-8 work, we can use the new upstream functions and remove these overrides.

The compat package is a package in Alertmanager that takes care of backwards compatibility when parsing matchers, validating alerts, labels and silences. It has three modes: classic mode, UTF-8 strict mode, fallback mode. These modes are controlled via compat.InitFromFlags. Grafana initializes the compat package without any feature flags, which is the equivalent of fallback mode. Classic and UTF-8 strict mode are used in Mimir.

While Grafana Managed Alerts have no need for fallback mode, Grafana can still be used as an interface to manage the configurations of Mimir Alertmanagers and view configurations of Prometheus Alertmanager, and those installations might not have migrated or being running on older versions. Such installations behave as if in classic mode, and Grafana must be able to parse their configurations to interact with them for some period of time. As such, Grafana uses fallback mode until we are ready to drop support for outdated installations of Mimir and the Prometheus Alertmanager.
2024-02-06 08:33:47 +00:00
William Wernert
2ab7d3c725
Alerting: Receivers API (read only endpoints) (#81751)
* Add single receiver method

* Add receiver permissions

* Add single/multi GET endpoints for receivers

* Remove stable tag from time intervals

See end of PR description here: https://github.com/grafana/grafana/pull/81672
2024-02-05 20:12:15 +02:00
Ryan McKinley
9c9e5e68c8
User: Add uid colum to user table (#81615) 2024-02-01 18:14:10 -08:00
Yuri Tseretyan
d1073deefd
Alerting: Time intervals API (read only endpoints) (#81672)
* declare new API and models GettableTimeIntervals, PostableTimeIntervals
* add new actions alert.notifications.time-intervals:read and alert.notifications.time-intervals:write.
* update existing alerting roles with the read action. Add to all alerting roles.
* add integration tests
2024-02-01 15:17:13 -05:00
William Wernert
7e939401dc
Alerting: Introduce initial common receiver service (#81211)
* Create locking config store that mimics existing provisioning store

* Rename existing receivers(_test).go

* Introduce shared receiver group service

* Fix test

* Move query model to models package

* ReceiverGroup -> Receiver

* Remove locking config store

* Move convert methods to compat.go

* Cleanup
2024-02-01 14:42:59 -05:00
George Robinson
0726c7c3fa
Alerting: Prevent inhibition rules in Grafana Alertmanager (#81712)
This commit prevents saving configurations containing inhibition
rules in Grafana Alertmanager. It does not reject inhibition
rules when using external Alertmanagers, such as Mimir. This meant
the validation had to be put in the MultiOrgAlertmanager instead of
in the validation of PostableUserConfig. We can remove this when
inhibition rules are supported in Grafana Managed Alerts.
2024-02-01 14:53:15 +00:00
Matthew Jacobson
0ce1ccd6f9
Alerting: Fix inconsistent AM raw config when applied via sync vs API (#81655)
AM config applied via API would use the PostableUserConfig as the AM raw
config and also the hash used to decide when the AM config has changed.
However, when applied via the periodic sync the PostableApiAlertingConfig would
be used instead.

This leads to two issues:
- Inconsistent hash comparisons when modifying the AM causing redundant applies.
- GetStatus assumed the raw config was PostableUserConfig causing the endpoint
to return correctly after a new config is applied via API and then nothing once
 the periodic sync runs.

Note: Technically, the upstream GrafanaAlertamanger GetStatus shouldn't be
returning PostableUserConfig or PostableApiAlertingConfig, but instead
GettableStatus. However, this issue required changes elsewhere and is out of
scope.
2024-01-31 21:05:30 +02:00
Ashley Harrison
39057552dc
QueryField: Handle autocomplete better (#81484)
* extract out function + add unit tests

* add feature toggle and default it to on
2024-01-31 10:01:20 +00:00
Yuri Tseretyan
131c72d655
Alerting: Fix scheduler to group folders by the unique key (orgID and UID) (#81303) 2024-01-30 17:14:11 -05:00
Sofia Papagiannaki
89d3b55bec
Folders: Reduce DB queries when counting and deleting resources under folders (#81153)
* Add folder store method for fetching all folder descendants

* Modify GetDescendantCounts() to fetch folder descendants at once

* Reduce DB calls when counting library panels under dashboard

* Reduce DB calls when counting dashboards under folder

* Reduce DB calls during folder delete

* Modify folder registry to count/delete entities under multiple folders

* Reduce DB calls when counting

* Reduce DB calls when deleting
2024-01-30 18:26:34 +02:00
William Wernert
de662810cf
Alerting: Create instance of alert rule generator in historian annotation tests (#81394)
* Create generator variable to ensure closures have correct context
2024-01-29 11:22:43 -05:00
idafurjes
f44592a97a
Remove folderID from service tests (#80615)
* Remove folderID from service tests

* Remove folderID from ngalert migration tests

* Remove tests related to folderIDs

* Roll back change

Before removing FolderID from this test, we need to adjust the code

* Remove FolderID from publicdashboard pkg

* Add back annotations test
2024-01-26 17:36:35 +02:00
Gabriel MABILLE
722b78f3e0
RBAC: Add userLogin filter to the permission search endpoint (#81137)
* RBAC: Search add user login filter

* Switch to a userService resolving instead

* Remove unused error

* Fallback to use the cache

* account for userID filter

* Account for the error

* snake case

* Add test cases

* Add api tests

* Fix return on error

* Re-order imports
2024-01-26 09:43:16 +01:00
Sofia Papagiannaki
b1eec36df3
Alerting: Fix authorisation to use namespace UIDs for scope (#81231) 2024-01-25 15:19:51 -05:00
idafurjes
7e5544ab21
Add MFolderIDsServiceCount to count folderIDs in services pkg (#81237) 2024-01-25 11:10:35 +01:00
Sofia Papagiannaki
478d7d58fa
Nested folders: Allow creating folders with duplicate names in different locations (#77076)
* Add API test

* Add move tests

* Fix create folder

* Fix move

* Fix test

* Drop and re-create index so that allows a folder to contain a dashboard and a subfolder with same name

* Get folder by title defaults to root folder and optionally fetches folder by provided parent folder

* Apply suggestions from code review
2024-01-25 11:29:56 +02:00
William Wernert
2203bc2a3d
Alerting: Refactor provisioning tests/fakes (#81205)
* Fix up test Alertmanager config JSON

* Move fake AM config and provisioning stores to fakes package
2024-01-24 17:15:55 -05:00
Matthew Jacobson
71e70c424f
Alerting: During legacy migration reduce the number of created silences (#78505)
* Alerting: During legacy migration reduce the number of created silences

During legacy migration every migrated rule was given a label rule_uid=<uid>.
This was used to silence DatasourceError/DatasourceNoData alerts for
migrated rules that had either ExecutionErrorState/NoDataState set to
keep_state, respectively.

This could potentially create a large amount of silences and a high cardinality
label. Both of these scenarios have poor outcomes for CPU load and latency in
unified alerting.

Instead, this change creates one label per ExecutionErrorState/NoDataState when
they are set to keep_state as well as two silence rules, if rules with said
labels were created during migration. These silence rules are:

- __legacy_silence_error_keep_state__ = true
- __legacy_silence_nodata_keep_state__ = true

This will drastically reduce the number of created silence rules in most cases
as well as not create the potentially high cardinality label `rule_uid`.
2024-01-24 15:56:19 -05:00
Santiago
fbbda6c05e
Alerting: Retry readiness check to the remote Alertmanager on 5xx status code responses (#81174) 2024-01-24 21:39:06 +01:00
George Robinson
05d858635c
Alerting: Add metric for inhibition rules (#81119)
This commit adds a metric for the number of inhibition rules.
It matches the metric added upstream in #3681.
2024-01-23 19:43:17 +00:00
Jean-Philippe Quéméner
aa25776f81
Alerting: Add a feature flag to periodically save states (#80987) 2024-01-23 17:03:30 +01:00
George Robinson
85b9edcd28
Alerting: Fix incorrect initialization of logger (#81099) 2024-01-23 17:29:38 +02:00
Marcus Efraimsson
6768c6c059
Chore: Remove public vars in setting package (#81018)
Removes the public variable setting.SecretKey plus some other ones. 
Introduces some new functions for creating setting.Cfg.
2024-01-23 12:36:22 +01:00
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