alertshadow 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alertshadow-0.1.0/CHANGELOG.md +14 -0
- alertshadow-0.1.0/CONTRIBUTING.md +8 -0
- alertshadow-0.1.0/LICENSE +202 -0
- alertshadow-0.1.0/MANIFEST.in +5 -0
- alertshadow-0.1.0/PKG-INFO +42 -0
- alertshadow-0.1.0/README.md +29 -0
- alertshadow-0.1.0/SECURITY.md +5 -0
- alertshadow-0.1.0/alertshadow/__init__.py +3 -0
- alertshadow-0.1.0/alertshadow/__main__.py +3 -0
- alertshadow-0.1.0/alertshadow/cli.py +59 -0
- alertshadow-0.1.0/alertshadow/core.py +173 -0
- alertshadow-0.1.0/alertshadow.egg-info/PKG-INFO +42 -0
- alertshadow-0.1.0/alertshadow.egg-info/SOURCES.txt +32 -0
- alertshadow-0.1.0/alertshadow.egg-info/dependency_links.txt +1 -0
- alertshadow-0.1.0/alertshadow.egg-info/entry_points.txt +2 -0
- alertshadow-0.1.0/alertshadow.egg-info/requires.txt +4 -0
- alertshadow-0.1.0/alertshadow.egg-info/top_level.txt +1 -0
- alertshadow-0.1.0/docs/architecture.md +21 -0
- alertshadow-0.1.0/docs/releases.md +22 -0
- alertshadow-0.1.0/docs/usage.md +43 -0
- alertshadow-0.1.0/examples/alertshadow.toml +9 -0
- alertshadow-0.1.0/examples/fixtures/value.yaml +26 -0
- alertshadow-0.1.0/examples/rules/value.yaml +27 -0
- alertshadow-0.1.0/pyproject.toml +22 -0
- alertshadow-0.1.0/setup.cfg +4 -0
- alertshadow-0.1.0/tests/fixtures/classic.yaml +24 -0
- alertshadow-0.1.0/tests/fixtures/labels.yaml +25 -0
- alertshadow-0.1.0/tests/fixtures/math.yaml +15 -0
- alertshadow-0.1.0/tests/fixtures/pending.yaml +24 -0
- alertshadow-0.1.0/tests/fixtures/presence.yaml +24 -0
- alertshadow-0.1.0/tests/fixtures/skip-datasource.yaml +24 -0
- alertshadow-0.1.0/tests/fixtures/skip-graph.yaml +15 -0
- alertshadow-0.1.0/tests/fixtures/threshold.yaml +31 -0
- alertshadow-0.1.0/tests/test_projection.py +209 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-22)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* add the alertshadow package, tests and documentation ([cb8ee45](https://github.com/citrustudio/alertshadow/commit/cb8ee45b43b5d5020aaa6e20fadd6def1f7befd0))
|
|
9
|
+
|
|
10
|
+
## 0.1.0 — unreleased
|
|
11
|
+
|
|
12
|
+
- Safe offline projection of classic, reduce-last threshold and simple math rules.
|
|
13
|
+
- Native PrometheusRule alert passthrough, strict diagnostics and owned output.
|
|
14
|
+
- Explicit datasource/environment config and an installed-promtool test runner.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Local development
|
|
2
|
+
|
|
3
|
+
See the [organization contribution policy](https://github.com/citrustudio/.github/blob/main/CONTRIBUTING.md)
|
|
4
|
+
for pull requests, review, DCO and AI disclosure.
|
|
5
|
+
|
|
6
|
+
Run `python -m pytest -q`, `ruff check alertshadow tests` and `mypy --strict alertshadow`.
|
|
7
|
+
Install hash-locked build/test tools with `python -m pip install --require-hashes -r requirements-ci.txt`.
|
|
8
|
+
Build with `python -m build --no-isolation`.
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: alertshadow
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline Prometheus test shadows for Grafana-managed rules
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: PyYAML<7,>=6.0.3
|
|
10
|
+
Provides-Extra: test
|
|
11
|
+
Requires-Dist: pytest<10,>=8; extra == "test"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# alertshadow
|
|
15
|
+
|
|
16
|
+
Test PromQL-backed Grafana-managed provisioning rules offline with Prometheus
|
|
17
|
+
`promtool`. The package projects a disposable **test shadow**, then runs your
|
|
18
|
+
synthetic-series fixtures. Prefer authoring Prometheus-format rules and importing
|
|
19
|
+
them on Grafana 12.1+ where possible; this bridge serves existing native graphs.
|
|
20
|
+
|
|
21
|
+
Python 3.11–3.13. Runtime dependency: PyYAML only. No network, live queries, parser
|
|
22
|
+
subprocess or automatic executable download. Install `promtool` separately to test.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install --require-hashes -r requirements-ci.txt
|
|
26
|
+
python -m pytest -q
|
|
27
|
+
ruff check alertshadow tests
|
|
28
|
+
mypy --strict alertshadow
|
|
29
|
+
python -m alertshadow project --root examples
|
|
30
|
+
python -m alertshadow test --root examples
|
|
31
|
+
python -m build --no-isolation
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The test command requires `promtool` on PATH; end-to-end pytest cases skip cleanly
|
|
35
|
+
when it is absent. CI installs version 2.53.2 and verifies its release checksum.
|
|
36
|
+
After a release, install with `pip install alertshadow`; the console script accepts
|
|
37
|
+
the same arguments as `python -m alertshadow`.
|
|
38
|
+
|
|
39
|
+
See [usage](docs/usage.md), [architecture](docs/architecture.md),
|
|
40
|
+
[contributing](CONTRIBUTING.md), [security](SECURITY.md), [releases](docs/releases.md)
|
|
41
|
+
and [changelog](CHANGELOG.md). Licensed under [Apache-2.0](LICENSE).
|
|
42
|
+
No supported public release yet.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# alertshadow
|
|
2
|
+
|
|
3
|
+
Test PromQL-backed Grafana-managed provisioning rules offline with Prometheus
|
|
4
|
+
`promtool`. The package projects a disposable **test shadow**, then runs your
|
|
5
|
+
synthetic-series fixtures. Prefer authoring Prometheus-format rules and importing
|
|
6
|
+
them on Grafana 12.1+ where possible; this bridge serves existing native graphs.
|
|
7
|
+
|
|
8
|
+
Python 3.11–3.13. Runtime dependency: PyYAML only. No network, live queries, parser
|
|
9
|
+
subprocess or automatic executable download. Install `promtool` separately to test.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
python -m pip install --require-hashes -r requirements-ci.txt
|
|
13
|
+
python -m pytest -q
|
|
14
|
+
ruff check alertshadow tests
|
|
15
|
+
mypy --strict alertshadow
|
|
16
|
+
python -m alertshadow project --root examples
|
|
17
|
+
python -m alertshadow test --root examples
|
|
18
|
+
python -m build --no-isolation
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The test command requires `promtool` on PATH; end-to-end pytest cases skip cleanly
|
|
22
|
+
when it is absent. CI installs version 2.53.2 and verifies its release checksum.
|
|
23
|
+
After a release, install with `pip install alertshadow`; the console script accepts
|
|
24
|
+
the same arguments as `python -m alertshadow`.
|
|
25
|
+
|
|
26
|
+
See [usage](docs/usage.md), [architecture](docs/architecture.md),
|
|
27
|
+
[contributing](CONTRIBUTING.md), [security](SECURITY.md), [releases](docs/releases.md)
|
|
28
|
+
and [changelog](CHANGELOG.md). Licensed under [Apache-2.0](LICENSE).
|
|
29
|
+
No supported public release yet.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Command-line interface; no network or promtool installation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tomllib
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
from .core import Invalid, project_files
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_tests(root: Path, config: dict[str, Any], files: list[Path]) -> None:
|
|
18
|
+
executable = shutil.which("promtool")
|
|
19
|
+
if executable is None:
|
|
20
|
+
raise Invalid("promtool is required on PATH; install it explicitly")
|
|
21
|
+
fixtures = sorted({path for pattern in config.get("fixtures", []) for path in root.glob(pattern)})
|
|
22
|
+
if not fixtures:
|
|
23
|
+
raise Invalid("no test fixtures matched")
|
|
24
|
+
for args in (["check", "rules", *map(str, files)], ["test", "rules", *map(str, fixtures)]):
|
|
25
|
+
subprocess.run([executable, *args], cwd=root, check=True, timeout=120)
|
|
26
|
+
projected = {r["alert"] for p in files for g in yaml.safe_load(p.read_text())["groups"] for r in g["rules"]}
|
|
27
|
+
tested = {a["alertname"] for p in fixtures for t in yaml.safe_load(p.read_text()).get("tests", []) for a in t.get("alert_rule_test", [])}
|
|
28
|
+
print(f"coverage: {len(projected & tested)}/{len(projected)} projected alert names have assertions")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main(argv: list[str] | None = None) -> int:
|
|
32
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
33
|
+
parser.add_argument("command", choices=["project", "test"])
|
|
34
|
+
parser.add_argument("--root", type=Path, default=Path.cwd())
|
|
35
|
+
parser.add_argument("--config", type=Path, default=Path("alertshadow.toml"))
|
|
36
|
+
parser.add_argument("--no-project", action="store_true", help="test existing marker-owned shadows")
|
|
37
|
+
args = parser.parse_args(argv)
|
|
38
|
+
try:
|
|
39
|
+
root = args.root.resolve()
|
|
40
|
+
with (root / args.config).open("rb") as stream:
|
|
41
|
+
config = tomllib.load(stream)
|
|
42
|
+
if args.no_project:
|
|
43
|
+
if args.command != "test":
|
|
44
|
+
raise Invalid("--no-project requires test")
|
|
45
|
+
out = (root / config.get("out", "generated")).resolve()
|
|
46
|
+
if root not in out.parents:
|
|
47
|
+
raise Invalid("output must be strictly inside root")
|
|
48
|
+
from .core import HEADER
|
|
49
|
+
files = [p for p in out.rglob("*") if p.is_file() and not p.is_symlink() and p.read_bytes().startswith(HEADER.encode())]
|
|
50
|
+
if not files:
|
|
51
|
+
raise Invalid("no marker-owned shadows")
|
|
52
|
+
else:
|
|
53
|
+
files = project_files(root, config)
|
|
54
|
+
if args.command == "test":
|
|
55
|
+
run_tests(root, config, files)
|
|
56
|
+
return 0
|
|
57
|
+
except (Invalid, OSError, ValueError, TypeError, AttributeError, subprocess.SubprocessError) as exc:
|
|
58
|
+
print(f"alertshadow: {exc}", file=sys.stderr)
|
|
59
|
+
return 1
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Conservative graph projection and owned output management."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
HEADER = "# Generated by alertshadow; test shadow only.\n"
|
|
13
|
+
OPS = {"gt": ">", "lt": "<", "gte": ">=", "lte": "<="}
|
|
14
|
+
NUMBER = r"-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Invalid(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def project_rule(rule: dict[str, Any], datasources: dict[str, str]) -> dict[str, Any]:
|
|
22
|
+
data = rule.get("data", [])
|
|
23
|
+
if not isinstance(data, list) or not all(isinstance(d, dict) for d in data):
|
|
24
|
+
raise Invalid("data must be a list of nodes")
|
|
25
|
+
refs = {d.get("refId"): d for d in data}
|
|
26
|
+
if None in refs or len(refs) != len(data):
|
|
27
|
+
raise Invalid("node references must be present and unique")
|
|
28
|
+
queries = [d for d in data if d.get("datasourceUid") not in (None, "__expr__")]
|
|
29
|
+
if len(queries) != 1:
|
|
30
|
+
raise Invalid("exactly one datasource query is required")
|
|
31
|
+
query = queries[0]
|
|
32
|
+
mode = datasources.get(query["datasourceUid"])
|
|
33
|
+
if mode != "prometheus":
|
|
34
|
+
raise Invalid("datasource is skipped" if mode == "skip" else "unknown datasource")
|
|
35
|
+
expr = query.get("model", {}).get("expr")
|
|
36
|
+
if not isinstance(expr, str) or not expr.strip():
|
|
37
|
+
raise Invalid("empty query expression")
|
|
38
|
+
cond = refs.get(rule.get("condition"))
|
|
39
|
+
if cond is None:
|
|
40
|
+
raise Invalid("missing condition node")
|
|
41
|
+
if cond is query:
|
|
42
|
+
if not re.search(rf"(?:<=|>=|<|>)\s*{NUMBER}\s*$", expr):
|
|
43
|
+
raise Invalid("direct query needs a filtering comparison")
|
|
44
|
+
else:
|
|
45
|
+
if cond.get("datasourceUid") != "__expr__":
|
|
46
|
+
raise Invalid("condition is not an expression node")
|
|
47
|
+
model = cond.get("model", {})
|
|
48
|
+
kind = model.get("type")
|
|
49
|
+
if kind == "math":
|
|
50
|
+
match = re.fullmatch(rf"\${re.escape(str(query['refId']))}\s*(<=|>=|<|>)\s*({NUMBER})", str(model.get("expression", "")).strip())
|
|
51
|
+
if not match:
|
|
52
|
+
raise Invalid("unsupported math graph")
|
|
53
|
+
expr = f"({expr}) {match[1]} {match[2]}"
|
|
54
|
+
else:
|
|
55
|
+
conditions = model.get("conditions", [])
|
|
56
|
+
if not isinstance(conditions, list) or len(conditions) != 1:
|
|
57
|
+
raise Invalid("exactly one evaluator is required")
|
|
58
|
+
condition = conditions[0]
|
|
59
|
+
if kind == "classic_conditions":
|
|
60
|
+
if condition.get("query", {}).get("params") != [query["refId"]]:
|
|
61
|
+
raise Invalid("classic condition must consume the query")
|
|
62
|
+
if condition.get("reducer", {}).get("type") != "last":
|
|
63
|
+
raise Invalid("only last reduction is supported")
|
|
64
|
+
elif kind == "threshold":
|
|
65
|
+
reduce = refs.get(model.get("expression"), {}).get("model", {})
|
|
66
|
+
if (reduce.get("type"), reduce.get("reducer"), reduce.get("expression")) != ("reduce", "last", query["refId"]):
|
|
67
|
+
raise Invalid("threshold needs direct reduce-last of query")
|
|
68
|
+
else:
|
|
69
|
+
raise Invalid("unsupported condition type")
|
|
70
|
+
evaluator = condition.get("evaluator", {})
|
|
71
|
+
params = evaluator.get("params", [])
|
|
72
|
+
op = OPS.get(evaluator.get("type"))
|
|
73
|
+
if op is None or len(params) != 1 or isinstance(params[0], bool):
|
|
74
|
+
raise Invalid("unsupported evaluator")
|
|
75
|
+
value = float(params[0])
|
|
76
|
+
if not math.isfinite(value):
|
|
77
|
+
raise Invalid("threshold must be finite")
|
|
78
|
+
# Grafana compares sample values; Prometheus fires on sample presence.
|
|
79
|
+
threshold = str(int(value)) if value.is_integer() else repr(value)
|
|
80
|
+
expr = f"({expr}) {op} {threshold}"
|
|
81
|
+
uid = rule.get("uid")
|
|
82
|
+
if not isinstance(uid, str) or not uid:
|
|
83
|
+
raise Invalid("rule uid is required")
|
|
84
|
+
result = {"alert": uid, "expr": expr}
|
|
85
|
+
for key in ("for", "labels"):
|
|
86
|
+
if key in rule:
|
|
87
|
+
result[key] = rule[key]
|
|
88
|
+
return result
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def read_document(path: Path, env_names: list[str]) -> dict[str, Any]:
|
|
92
|
+
if path.stat().st_size > 8 * 1024 * 1024:
|
|
93
|
+
raise Invalid("rule file exceeds 8 MiB")
|
|
94
|
+
text = path.read_text(encoding="utf-8")
|
|
95
|
+
# Expand only allow-listed placeholders, before parsing with the safe loader.
|
|
96
|
+
for name in env_names:
|
|
97
|
+
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name) or name not in os.environ:
|
|
98
|
+
raise Invalid("invalid or unset allow-listed environment variable")
|
|
99
|
+
text = re.sub(r"\$\{" + re.escape(name) + r"\}|\$" + re.escape(name) + r"\b", lambda _: os.environ[name], text)
|
|
100
|
+
try:
|
|
101
|
+
doc = yaml.safe_load(text)
|
|
102
|
+
except yaml.YAMLError as exc:
|
|
103
|
+
raise Invalid(f"invalid YAML in {path}") from exc
|
|
104
|
+
if not isinstance(doc, dict):
|
|
105
|
+
raise Invalid("rule document must be a mapping")
|
|
106
|
+
return doc
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def project_files(root: Path, config: dict[str, Any]) -> list[Path]:
|
|
110
|
+
root = root.resolve()
|
|
111
|
+
out = root / config.get("out", "generated")
|
|
112
|
+
if out.is_symlink() or root not in out.resolve().parents:
|
|
113
|
+
raise Invalid("output must be a non-symlink directory strictly inside root")
|
|
114
|
+
if any(p.is_symlink() for p in [out, *out.parents] if p != root and root in p.parents):
|
|
115
|
+
raise Invalid("symlink output ancestry is forbidden")
|
|
116
|
+
out = out.resolve()
|
|
117
|
+
patterns = config.get("rules", [])
|
|
118
|
+
if not isinstance(patterns, list) or not patterns:
|
|
119
|
+
raise Invalid("rules must be a nonempty list of relative globs")
|
|
120
|
+
inputs: set[Path] = set()
|
|
121
|
+
for pattern in patterns:
|
|
122
|
+
if Path(pattern).is_absolute() or ".." in Path(pattern).parts:
|
|
123
|
+
raise Invalid("rule globs must stay inside root")
|
|
124
|
+
inputs.update(root.glob(pattern))
|
|
125
|
+
if not inputs:
|
|
126
|
+
raise Invalid("no rule inputs matched")
|
|
127
|
+
outputs: dict[Path, str] = {}
|
|
128
|
+
for source in sorted(inputs):
|
|
129
|
+
if any(p.is_symlink() for p in [source, *source.parents] if p != root and root in p.parents) or root not in source.resolve().parents or out == source.resolve() or out in source.resolve().parents:
|
|
130
|
+
raise Invalid("input must be outside output and inside root")
|
|
131
|
+
doc = read_document(source, config.get("env", []))
|
|
132
|
+
native = doc.get("kind") == "PrometheusRule"
|
|
133
|
+
groups = doc.get("spec", {}).get("groups") if native else doc.get("groups")
|
|
134
|
+
if not isinstance(groups, list):
|
|
135
|
+
raise Invalid("groups must be a list")
|
|
136
|
+
projected = []
|
|
137
|
+
for group in groups:
|
|
138
|
+
rules = []
|
|
139
|
+
for rule in group.get("rules", []):
|
|
140
|
+
try:
|
|
141
|
+
if native:
|
|
142
|
+
if not rule.get("alert") or not rule.get("expr"):
|
|
143
|
+
raise Invalid("native recording rules are unsupported")
|
|
144
|
+
result = {k: rule[k] for k in ("alert", "expr", "for", "labels") if k in rule}
|
|
145
|
+
else:
|
|
146
|
+
result = project_rule(rule, config.get("datasources", {}))
|
|
147
|
+
rules.append(result)
|
|
148
|
+
except (Invalid, TypeError, ValueError, AttributeError) as exc:
|
|
149
|
+
if config.get("strict", True):
|
|
150
|
+
raise Invalid(f"{source}: {exc}") from exc
|
|
151
|
+
print(f"skipped {rule.get('uid', rule.get('alert', '?'))}: {exc}")
|
|
152
|
+
if rules:
|
|
153
|
+
projected.append({"name": group.get("name", "unnamed"), "rules": rules})
|
|
154
|
+
if projected:
|
|
155
|
+
target = out / source.relative_to(root)
|
|
156
|
+
outputs[target] = HEADER + yaml.safe_dump({"groups": projected}, sort_keys=False)
|
|
157
|
+
if not outputs:
|
|
158
|
+
raise Invalid("no projectable rules")
|
|
159
|
+
# Preflight everything before deleting or writing anything.
|
|
160
|
+
if out.exists():
|
|
161
|
+
for target in out.rglob("*"):
|
|
162
|
+
if target.is_symlink():
|
|
163
|
+
raise Invalid("symlink in output")
|
|
164
|
+
if target in outputs and not target.read_text().startswith(HEADER):
|
|
165
|
+
raise Invalid("refusing to overwrite unowned file")
|
|
166
|
+
for target in list(out.rglob("*")) if out.exists() else []:
|
|
167
|
+
if target.is_file() and target not in outputs and target.read_bytes().startswith(HEADER.encode()):
|
|
168
|
+
target.unlink()
|
|
169
|
+
for target, text in outputs.items():
|
|
170
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
171
|
+
target.write_text(text, encoding="utf-8")
|
|
172
|
+
print(f"projected {len(outputs)} file(s)")
|
|
173
|
+
return sorted(outputs)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: alertshadow
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline Prometheus test shadows for Grafana-managed rules
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: PyYAML<7,>=6.0.3
|
|
10
|
+
Provides-Extra: test
|
|
11
|
+
Requires-Dist: pytest<10,>=8; extra == "test"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# alertshadow
|
|
15
|
+
|
|
16
|
+
Test PromQL-backed Grafana-managed provisioning rules offline with Prometheus
|
|
17
|
+
`promtool`. The package projects a disposable **test shadow**, then runs your
|
|
18
|
+
synthetic-series fixtures. Prefer authoring Prometheus-format rules and importing
|
|
19
|
+
them on Grafana 12.1+ where possible; this bridge serves existing native graphs.
|
|
20
|
+
|
|
21
|
+
Python 3.11–3.13. Runtime dependency: PyYAML only. No network, live queries, parser
|
|
22
|
+
subprocess or automatic executable download. Install `promtool` separately to test.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install --require-hashes -r requirements-ci.txt
|
|
26
|
+
python -m pytest -q
|
|
27
|
+
ruff check alertshadow tests
|
|
28
|
+
mypy --strict alertshadow
|
|
29
|
+
python -m alertshadow project --root examples
|
|
30
|
+
python -m alertshadow test --root examples
|
|
31
|
+
python -m build --no-isolation
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The test command requires `promtool` on PATH; end-to-end pytest cases skip cleanly
|
|
35
|
+
when it is absent. CI installs version 2.53.2 and verifies its release checksum.
|
|
36
|
+
After a release, install with `pip install alertshadow`; the console script accepts
|
|
37
|
+
the same arguments as `python -m alertshadow`.
|
|
38
|
+
|
|
39
|
+
See [usage](docs/usage.md), [architecture](docs/architecture.md),
|
|
40
|
+
[contributing](CONTRIBUTING.md), [security](SECURITY.md), [releases](docs/releases.md)
|
|
41
|
+
and [changelog](CHANGELOG.md). Licensed under [Apache-2.0](LICENSE).
|
|
42
|
+
No supported public release yet.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
CHANGELOG.md
|
|
2
|
+
CONTRIBUTING.md
|
|
3
|
+
LICENSE
|
|
4
|
+
MANIFEST.in
|
|
5
|
+
README.md
|
|
6
|
+
SECURITY.md
|
|
7
|
+
pyproject.toml
|
|
8
|
+
alertshadow/__init__.py
|
|
9
|
+
alertshadow/__main__.py
|
|
10
|
+
alertshadow/cli.py
|
|
11
|
+
alertshadow/core.py
|
|
12
|
+
alertshadow.egg-info/PKG-INFO
|
|
13
|
+
alertshadow.egg-info/SOURCES.txt
|
|
14
|
+
alertshadow.egg-info/dependency_links.txt
|
|
15
|
+
alertshadow.egg-info/entry_points.txt
|
|
16
|
+
alertshadow.egg-info/requires.txt
|
|
17
|
+
alertshadow.egg-info/top_level.txt
|
|
18
|
+
docs/architecture.md
|
|
19
|
+
docs/releases.md
|
|
20
|
+
docs/usage.md
|
|
21
|
+
examples/alertshadow.toml
|
|
22
|
+
examples/fixtures/value.yaml
|
|
23
|
+
examples/rules/value.yaml
|
|
24
|
+
tests/test_projection.py
|
|
25
|
+
tests/fixtures/classic.yaml
|
|
26
|
+
tests/fixtures/labels.yaml
|
|
27
|
+
tests/fixtures/math.yaml
|
|
28
|
+
tests/fixtures/pending.yaml
|
|
29
|
+
tests/fixtures/presence.yaml
|
|
30
|
+
tests/fixtures/skip-datasource.yaml
|
|
31
|
+
tests/fixtures/skip-graph.yaml
|
|
32
|
+
tests/fixtures/threshold.yaml
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
alertshadow
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
The CLI reads TOML, the core parses provisioning YAML with `yaml.safe_load`, then
|
|
4
|
+
projects a conservative subset of expression graphs. It emits YAML through
|
|
5
|
+
PyYAML, preserving source-relative paths and an ownership header. All inputs are
|
|
6
|
+
projected before output preflight and mutation. Cleanup unlinks only marked stale
|
|
7
|
+
files and never removes a directory tree. Source or output symlink traversal is
|
|
8
|
+
refused. The root is an explicit caller-selected workspace trust boundary.
|
|
9
|
+
|
|
10
|
+
Grafana tests sample **values**, while Prometheus alert rules fire on series
|
|
11
|
+
**presence**. Every evaluator is folded into the query, even when it already has a
|
|
12
|
+
comparison: `(service_ready == bool 0) > 0` excludes healthy zero-valued samples.
|
|
13
|
+
Reduce-last/threshold and simple math have equivalent explicit projections.
|
|
14
|
+
The runner only invokes the installed promtool, with argument arrays and a deadline.
|
|
15
|
+
|
|
16
|
+
This is deliberately lossy: annotations, group intervals, NoData/execErrState,
|
|
17
|
+
Grafana templating and live datasource behavior are not reproduced. Multi-query,
|
|
18
|
+
compound expressions and non-last reductions are rejected rather than guessed.
|
|
19
|
+
It is not a Grafana evaluator or a rule linter. Passing fixtures prove only the
|
|
20
|
+
projected PromQL at the tested series, thresholds, labels and pending duration.
|
|
21
|
+
The private canary-analysis converters are not part of this package.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Releases
|
|
2
|
+
|
|
3
|
+
Before enabling releases, check the package version and name availability again,
|
|
4
|
+
configure the dedicated release App ID as `RELEASE_APP_ID` and its organisation
|
|
5
|
+
Actions key secret as `RELEASE_APP_PRIVATE_KEY`. Grant the App only Contents write,
|
|
6
|
+
Pull requests write and Metadata read, with no ruleset bypass. Release-please opens
|
|
7
|
+
a release PR; required checks and owner approval apply before merge.
|
|
8
|
+
|
|
9
|
+
Configure a protected `release` environment with owner approval.
|
|
10
|
+
Register the PyPI trusted publisher for this repository, `release.yml`, and
|
|
11
|
+
that environment. The workflow builds wheel/sdist, attests both, and uses OIDC
|
|
12
|
+
trusted publishing, with no long-lived PyPI token.
|
|
13
|
+
|
|
14
|
+
Do not enable App auto-merge or add it as a bypass actor. The templates cannot
|
|
15
|
+
enforce remote rulesets: verify required checks and code-owner approval using the
|
|
16
|
+
organisation baseline before the first public push or real release.
|
|
17
|
+
|
|
18
|
+
Before the first public push, bind public-text.yml to a reviewed public workflow
|
|
19
|
+
commit and review the exact file list and fresh tree/history secret scans. An
|
|
20
|
+
offline extraction with a private workflow SHA proves no public enforcement.
|
|
21
|
+
Configure the pending PyPI publisher for alertshadow, release.yml and the protected
|
|
22
|
+
release environment. Internal consumers and script deletion wait for a release.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Usage
|
|
2
|
+
|
|
3
|
+
`alertshadow [-h] {project,test} [--root DIR] [--config FILE] [--no-project]`.
|
|
4
|
+
`-h` / `--help` shows help. `--root` defaults to the current directory; relative
|
|
5
|
+
`--config` defaults to `alertshadow.toml` inside root. Exit 0 means success; exit 1
|
|
6
|
+
means invalid input, missing executable, timeout or failed promtool validation.
|
|
7
|
+
Argparse uses exit 2 for invalid command syntax.
|
|
8
|
+
|
|
9
|
+
Configuration is TOML, with the complete example in `examples/alertshadow.toml`:
|
|
10
|
+
|
|
11
|
+
- `rules`: nonempty relative rule globs; no absolute paths or parent traversal.
|
|
12
|
+
- `out`: shadow directory, default `generated`, strictly beneath root. Input files
|
|
13
|
+
must be outside it. Do not use it for your own files or provision its contents.
|
|
14
|
+
- `fixtures`: relative promtool fixture globs, required by `test`.
|
|
15
|
+
- `strict`: default true. Unsupported rules fail; false prints skip reasons.
|
|
16
|
+
Parse errors always fail, and projecting zero files always fails.
|
|
17
|
+
- `env`: names of environment variables to expand as `$NAME` or `${NAME}` in YAML.
|
|
18
|
+
Names must be valid and set. Other placeholders stay literal. Values must form
|
|
19
|
+
valid YAML; treat config and environment as trusted inputs.
|
|
20
|
+
- `[datasources]`: datasource UID keys mapped to `prometheus` or `skip`. Unknown
|
|
21
|
+
UIDs fail in strict mode, never guessed from a name.
|
|
22
|
+
|
|
23
|
+
`project` supports one-query classic conditions using last reduction and one
|
|
24
|
+
comparison, direct reduce-last → threshold, one-query math comparisons against a
|
|
25
|
+
number, and directly filtering query conditions. Operators are gt/lt/gte/lte;
|
|
26
|
+
math uses >, <, >=, <=. Multiple queries, unsupported reducers, compound math,
|
|
27
|
+
missing/duplicate references, unknown datasources, multiple conditions, empty
|
|
28
|
+
queries and non-finite thresholds are rejected or explicitly skipped.
|
|
29
|
+
Native Kubernetes `PrometheusRule` alert groups pass through; recording rules are
|
|
30
|
+
reported unsupported. Alert names, expressions, `for` and labels survive.
|
|
31
|
+
|
|
32
|
+
Each output keeps the source-relative path: `rules/value.yaml` becomes
|
|
33
|
+
`generated/rules/value.yaml`. A fixture in `fixtures/` references it as
|
|
34
|
+
`../generated/rules/value.yaml`. `test` projects, checks every shadow with
|
|
35
|
+
`promtool check rules`, runs `promtool test rules` and reports distinct alert-name
|
|
36
|
+
assertion coverage. An empty fixture match fails. Each subprocess has a 120-second
|
|
37
|
+
deadline. `test --no-project` uses existing marker-owned shadows, enabling an
|
|
38
|
+
external projection step; it fails if none exist.
|
|
39
|
+
|
|
40
|
+
Only files bearing the exact generator header may be overwritten or removed as
|
|
41
|
+
stale. Other files are preserved; collisions and symlinks fail before writes.
|
|
42
|
+
Rules are limited to 8 MiB each. A failed parse or projection leaves existing
|
|
43
|
+
outputs intact. Keep fixture evaluation intervals consistent with Grafana groups.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
rule_files:
|
|
2
|
+
- ../generated/rules/value.yaml
|
|
3
|
+
evaluation_interval: 1m
|
|
4
|
+
tests:
|
|
5
|
+
- interval: 1m
|
|
6
|
+
input_series:
|
|
7
|
+
- series: service_ready
|
|
8
|
+
values: 1 1 1 1 1
|
|
9
|
+
alert_rule_test:
|
|
10
|
+
- eval_time: 4m
|
|
11
|
+
alertname: ValueAlert
|
|
12
|
+
exp_alerts: []
|
|
13
|
+
- interval: 1m
|
|
14
|
+
input_series:
|
|
15
|
+
- series: service_ready
|
|
16
|
+
values: 0 0 0 0 0
|
|
17
|
+
alert_rule_test:
|
|
18
|
+
- eval_time: 1m
|
|
19
|
+
alertname: ValueAlert
|
|
20
|
+
exp_alerts: []
|
|
21
|
+
- eval_time: 3m
|
|
22
|
+
alertname: ValueAlert
|
|
23
|
+
exp_alerts:
|
|
24
|
+
- exp_labels:
|
|
25
|
+
severity: warning
|
|
26
|
+
exp_annotations: {}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
groups:
|
|
2
|
+
- name: example
|
|
3
|
+
rules:
|
|
4
|
+
- uid: ValueAlert
|
|
5
|
+
condition: B
|
|
6
|
+
for: 2m
|
|
7
|
+
labels:
|
|
8
|
+
severity: warning
|
|
9
|
+
data:
|
|
10
|
+
- refId: A
|
|
11
|
+
datasourceUid: metrics
|
|
12
|
+
model:
|
|
13
|
+
expr: service_ready == bool 0
|
|
14
|
+
- refId: B
|
|
15
|
+
datasourceUid: __expr__
|
|
16
|
+
model:
|
|
17
|
+
type: classic_conditions
|
|
18
|
+
conditions:
|
|
19
|
+
- query:
|
|
20
|
+
params:
|
|
21
|
+
- A
|
|
22
|
+
reducer:
|
|
23
|
+
type: last
|
|
24
|
+
evaluator:
|
|
25
|
+
type: gt
|
|
26
|
+
params:
|
|
27
|
+
- 0
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools==80.9.0", "wheel==0.45.1"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "alertshadow"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Offline Prometheus test shadows for Grafana-managed rules"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = ["PyYAML>=6.0.3,<7"]
|
|
11
|
+
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
test = ["pytest>=8,<10"]
|
|
17
|
+
|
|
18
|
+
[project.scripts]
|
|
19
|
+
alertshadow = "alertshadow.cli:main"
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
include = ["alertshadow*"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
uid: classic
|
|
2
|
+
condition: B
|
|
3
|
+
for: 2m
|
|
4
|
+
labels:
|
|
5
|
+
severity: warning
|
|
6
|
+
data:
|
|
7
|
+
- refId: A
|
|
8
|
+
datasourceUid: metrics
|
|
9
|
+
model:
|
|
10
|
+
expr: service_ready == bool 0
|
|
11
|
+
- refId: B
|
|
12
|
+
datasourceUid: __expr__
|
|
13
|
+
model:
|
|
14
|
+
type: classic_conditions
|
|
15
|
+
conditions:
|
|
16
|
+
- query:
|
|
17
|
+
params:
|
|
18
|
+
- A
|
|
19
|
+
reducer:
|
|
20
|
+
type: last
|
|
21
|
+
evaluator:
|
|
22
|
+
type: gt
|
|
23
|
+
params:
|
|
24
|
+
- 0
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
uid: labels
|
|
2
|
+
condition: B
|
|
3
|
+
for: 2m
|
|
4
|
+
labels:
|
|
5
|
+
team: example
|
|
6
|
+
severity: critical
|
|
7
|
+
data:
|
|
8
|
+
- refId: A
|
|
9
|
+
datasourceUid: metrics
|
|
10
|
+
model:
|
|
11
|
+
expr: service_ready == bool 0
|
|
12
|
+
- refId: B
|
|
13
|
+
datasourceUid: __expr__
|
|
14
|
+
model:
|
|
15
|
+
type: classic_conditions
|
|
16
|
+
conditions:
|
|
17
|
+
- query:
|
|
18
|
+
params:
|
|
19
|
+
- A
|
|
20
|
+
reducer:
|
|
21
|
+
type: last
|
|
22
|
+
evaluator:
|
|
23
|
+
type: gt
|
|
24
|
+
params:
|
|
25
|
+
- 0
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
uid: pending
|
|
2
|
+
condition: B
|
|
3
|
+
for: 5m
|
|
4
|
+
labels:
|
|
5
|
+
severity: warning
|
|
6
|
+
data:
|
|
7
|
+
- refId: A
|
|
8
|
+
datasourceUid: metrics
|
|
9
|
+
model:
|
|
10
|
+
expr: service_ready == bool 0
|
|
11
|
+
- refId: B
|
|
12
|
+
datasourceUid: __expr__
|
|
13
|
+
model:
|
|
14
|
+
type: classic_conditions
|
|
15
|
+
conditions:
|
|
16
|
+
- query:
|
|
17
|
+
params:
|
|
18
|
+
- A
|
|
19
|
+
reducer:
|
|
20
|
+
type: last
|
|
21
|
+
evaluator:
|
|
22
|
+
type: gt
|
|
23
|
+
params:
|
|
24
|
+
- 0
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
uid: presence
|
|
2
|
+
condition: B
|
|
3
|
+
for: 2m
|
|
4
|
+
labels:
|
|
5
|
+
severity: warning
|
|
6
|
+
data:
|
|
7
|
+
- refId: A
|
|
8
|
+
datasourceUid: metrics
|
|
9
|
+
model:
|
|
10
|
+
expr: queue_size == bool 0
|
|
11
|
+
- refId: B
|
|
12
|
+
datasourceUid: __expr__
|
|
13
|
+
model:
|
|
14
|
+
type: classic_conditions
|
|
15
|
+
conditions:
|
|
16
|
+
- query:
|
|
17
|
+
params:
|
|
18
|
+
- A
|
|
19
|
+
reducer:
|
|
20
|
+
type: last
|
|
21
|
+
evaluator:
|
|
22
|
+
type: gt
|
|
23
|
+
params:
|
|
24
|
+
- 0
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
uid: skip-datasource
|
|
2
|
+
condition: B
|
|
3
|
+
for: 2m
|
|
4
|
+
labels:
|
|
5
|
+
severity: warning
|
|
6
|
+
data:
|
|
7
|
+
- refId: A
|
|
8
|
+
datasourceUid: logs
|
|
9
|
+
model:
|
|
10
|
+
expr: service_ready == bool 0
|
|
11
|
+
- refId: B
|
|
12
|
+
datasourceUid: __expr__
|
|
13
|
+
model:
|
|
14
|
+
type: classic_conditions
|
|
15
|
+
conditions:
|
|
16
|
+
- query:
|
|
17
|
+
params:
|
|
18
|
+
- A
|
|
19
|
+
reducer:
|
|
20
|
+
type: last
|
|
21
|
+
evaluator:
|
|
22
|
+
type: gt
|
|
23
|
+
params:
|
|
24
|
+
- 0
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
uid: skip-graph
|
|
2
|
+
condition: B
|
|
3
|
+
for: 2m
|
|
4
|
+
labels:
|
|
5
|
+
severity: warning
|
|
6
|
+
data:
|
|
7
|
+
- refId: A
|
|
8
|
+
datasourceUid: metrics
|
|
9
|
+
model:
|
|
10
|
+
expr: service_ready == bool 0
|
|
11
|
+
- refId: B
|
|
12
|
+
datasourceUid: __expr__
|
|
13
|
+
model:
|
|
14
|
+
type: math
|
|
15
|
+
expression: $A > 0 && $C > 1
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
uid: threshold
|
|
2
|
+
condition: B
|
|
3
|
+
for: 2m
|
|
4
|
+
labels:
|
|
5
|
+
severity: warning
|
|
6
|
+
data:
|
|
7
|
+
- refId: A
|
|
8
|
+
datasourceUid: metrics
|
|
9
|
+
model:
|
|
10
|
+
expr: service_ready == bool 0
|
|
11
|
+
- refId: R
|
|
12
|
+
datasourceUid: __expr__
|
|
13
|
+
model:
|
|
14
|
+
type: reduce
|
|
15
|
+
reducer: last
|
|
16
|
+
expression: A
|
|
17
|
+
- refId: B
|
|
18
|
+
datasourceUid: __expr__
|
|
19
|
+
model:
|
|
20
|
+
type: threshold
|
|
21
|
+
conditions:
|
|
22
|
+
- query:
|
|
23
|
+
params:
|
|
24
|
+
- A
|
|
25
|
+
reducer:
|
|
26
|
+
type: last
|
|
27
|
+
evaluator:
|
|
28
|
+
type: gt
|
|
29
|
+
params:
|
|
30
|
+
- 0
|
|
31
|
+
expression: R
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
from copy import deepcopy
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
import yaml
|
|
8
|
+
|
|
9
|
+
from alertshadow.core import HEADER, Invalid, project_files, project_rule
|
|
10
|
+
from alertshadow.cli import main, run_tests
|
|
11
|
+
|
|
12
|
+
EXAMPLES = Path(__file__).resolve().parents[1] / "examples"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture
|
|
16
|
+
def rule():
|
|
17
|
+
return yaml.safe_load((EXAMPLES / "rules/value.yaml").read_text())["groups"][0]["rules"][0]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_classic_value_not_presence(rule):
|
|
21
|
+
result = project_rule(rule, {"metrics": "prometheus"})
|
|
22
|
+
assert result == {"alert": "ValueAlert", "expr": "(service_ready == bool 0) > 0", "for": "2m", "labels": {"severity": "warning"}}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_threshold(rule):
|
|
26
|
+
rule["data"].insert(1, {"refId": "R", "datasourceUid": "__expr__", "model": {"type": "reduce", "reducer": "last", "expression": "A"}})
|
|
27
|
+
rule["data"][-1]["model"].update(type="threshold", expression="R")
|
|
28
|
+
assert project_rule(rule, {"metrics": "prometheus"})["expr"].endswith("> 0")
|
|
29
|
+
rule["data"][1]["model"]["reducer"] = "mean"
|
|
30
|
+
with pytest.raises(Invalid, match="reduce-last"):
|
|
31
|
+
project_rule(rule, {"metrics": "prometheus"})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_math(rule):
|
|
35
|
+
rule["data"][-1]["model"] = {"type": "math", "expression": "$A >= 2e-3"}
|
|
36
|
+
assert project_rule(rule, {"metrics": "prometheus"})["expr"].endswith(">= 2e-3")
|
|
37
|
+
rule["data"][-1]["model"]["expression"] = "$A > 1 && $C > 1"
|
|
38
|
+
with pytest.raises(Invalid, match="math"):
|
|
39
|
+
project_rule(rule, {"metrics": "prometheus"})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@pytest.mark.parametrize("mode", [None, "skip"])
|
|
43
|
+
def test_datasource_skip(rule, mode):
|
|
44
|
+
with pytest.raises(Invalid, match="datasource"):
|
|
45
|
+
project_rule(rule, {} if mode is None else {"metrics": mode})
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_unsupported(rule):
|
|
49
|
+
for mutation in ("multi", "count", "reference", "duplicate"):
|
|
50
|
+
other = deepcopy(rule)
|
|
51
|
+
if mutation == "multi":
|
|
52
|
+
other["data"].append({"refId": "C", "datasourceUid": "metrics", "model": {"expr": "up"}})
|
|
53
|
+
elif mutation == "count":
|
|
54
|
+
other["data"][-1]["model"]["conditions"] *= 2
|
|
55
|
+
elif mutation == "reference":
|
|
56
|
+
other["data"][-1]["model"]["conditions"][0]["query"]["params"] = ["X"]
|
|
57
|
+
else:
|
|
58
|
+
other["data"].append(other["data"][0])
|
|
59
|
+
with pytest.raises(Invalid):
|
|
60
|
+
project_rule(other, {"metrics": "prometheus"})
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def setup_tree(tmp_path):
|
|
64
|
+
shutil.copytree(EXAMPLES, tmp_path, dirs_exist_ok=True, ignore=shutil.ignore_patterns("generated"))
|
|
65
|
+
return {"rules": ["rules/*.yaml"], "out": "generated", "datasources": {"metrics": "prometheus"}, "fixtures": ["fixtures/*.yaml"]}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_native_and_same_basename(tmp_path):
|
|
69
|
+
native = {"kind": "PrometheusRule", "spec": {"groups": [{"name": "native", "rules": [{"alert": "Native", "expr": "up < 1"}]}]}}
|
|
70
|
+
for folder in ("one", "two"):
|
|
71
|
+
(tmp_path / folder).mkdir()
|
|
72
|
+
(tmp_path / folder / "rules.yaml").write_text(yaml.safe_dump(native))
|
|
73
|
+
result = project_files(tmp_path, {"rules": ["*/rules.yaml"]})
|
|
74
|
+
assert {p.relative_to(tmp_path).as_posix() for p in result} == {"generated/one/rules.yaml", "generated/two/rules.yaml"}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_parse_failure_never_silent(tmp_path):
|
|
78
|
+
config = setup_tree(tmp_path)
|
|
79
|
+
source = tmp_path / "rules/value.yaml"
|
|
80
|
+
for content in ("groups: [", "!!python/object/apply:os.system ['echo forbidden']", "null"):
|
|
81
|
+
source.write_text(content)
|
|
82
|
+
with pytest.raises(Invalid):
|
|
83
|
+
project_files(tmp_path, {**config, "strict": False})
|
|
84
|
+
assert not (tmp_path / "generated").exists()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_owned_cleanup_and_preflight(tmp_path):
|
|
88
|
+
config = setup_tree(tmp_path)
|
|
89
|
+
outputs = project_files(tmp_path, config)
|
|
90
|
+
keep = tmp_path / "generated/keep.txt"
|
|
91
|
+
keep.write_text("user text")
|
|
92
|
+
stale = tmp_path / "generated/stale.yaml"
|
|
93
|
+
stale.write_text(HEADER + "groups: []")
|
|
94
|
+
project_files(tmp_path, config)
|
|
95
|
+
assert keep.read_text() == "user text" and not stale.exists()
|
|
96
|
+
outputs[0].write_text("unowned")
|
|
97
|
+
with pytest.raises(Invalid, match="unowned"):
|
|
98
|
+
project_files(tmp_path, config)
|
|
99
|
+
assert outputs[0].read_text() == "unowned"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.mark.parametrize("out", [".", "../outside"])
|
|
103
|
+
def test_unsafe_out(tmp_path, out):
|
|
104
|
+
config = setup_tree(tmp_path)
|
|
105
|
+
with pytest.raises(Invalid):
|
|
106
|
+
project_files(tmp_path, {**config, "out": out})
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_symlink(tmp_path):
|
|
110
|
+
config = setup_tree(tmp_path)
|
|
111
|
+
(tmp_path / "generated").symlink_to(tmp_path / "rules", target_is_directory=True)
|
|
112
|
+
with pytest.raises(Invalid):
|
|
113
|
+
project_files(tmp_path, config)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_environment(tmp_path, monkeypatch):
|
|
117
|
+
config = setup_tree(tmp_path)
|
|
118
|
+
source = tmp_path / "rules/value.yaml"
|
|
119
|
+
source.write_text(source.read_text().replace("service_ready", "${METRIC}"))
|
|
120
|
+
monkeypatch.setenv("METRIC", "example_ready")
|
|
121
|
+
outputs = project_files(tmp_path, {**config, "env": ["METRIC"]})
|
|
122
|
+
assert "example_ready" in outputs[0].read_text()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_nonstrict_report(tmp_path, capsys):
|
|
126
|
+
config = setup_tree(tmp_path)
|
|
127
|
+
doc = yaml.safe_load((tmp_path / "rules/value.yaml").read_text())
|
|
128
|
+
other = deepcopy(doc["groups"][0]["rules"][0])
|
|
129
|
+
other["data"][0]["datasourceUid"] = "logs"
|
|
130
|
+
doc["groups"][0]["rules"].append(other)
|
|
131
|
+
(tmp_path / "rules/value.yaml").write_text(yaml.safe_dump(doc))
|
|
132
|
+
project_files(tmp_path, {**config, "strict": False})
|
|
133
|
+
assert "skipped" in capsys.readouterr().out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_runner_errors(tmp_path, monkeypatch):
|
|
137
|
+
config = setup_tree(tmp_path)
|
|
138
|
+
files = project_files(tmp_path, config)
|
|
139
|
+
monkeypatch.setattr(shutil, "which", lambda _: None)
|
|
140
|
+
with pytest.raises(Invalid, match="required"):
|
|
141
|
+
run_tests(tmp_path, config, files)
|
|
142
|
+
monkeypatch.setattr(shutil, "which", lambda _: "promtool")
|
|
143
|
+
with pytest.raises(Invalid, match="no test"):
|
|
144
|
+
run_tests(tmp_path, {**config, "fixtures": []}, files)
|
|
145
|
+
def fail(*args, **kwargs):
|
|
146
|
+
raise subprocess.CalledProcessError(1, args[0])
|
|
147
|
+
monkeypatch.setattr(subprocess, "run", fail)
|
|
148
|
+
with pytest.raises(subprocess.CalledProcessError):
|
|
149
|
+
run_tests(tmp_path, config, files)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_cli(tmp_path):
|
|
153
|
+
setup_tree(tmp_path)
|
|
154
|
+
assert main(["project", "--root", str(tmp_path)]) == 0
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@pytest.mark.skipif(shutil.which("promtool") is None, reason="promtool is not installed")
|
|
158
|
+
def test_promtool_end_to_end(tmp_path):
|
|
159
|
+
config = setup_tree(tmp_path)
|
|
160
|
+
run_tests(tmp_path, config, project_files(tmp_path, config))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@pytest.mark.parametrize("fixture", sorted((Path(__file__).parent / "fixtures").glob("*.yaml")))
|
|
164
|
+
def test_neutral_fixture_contract(fixture):
|
|
165
|
+
rule = yaml.safe_load(fixture.read_text())
|
|
166
|
+
if fixture.stem.startswith("skip-"):
|
|
167
|
+
with pytest.raises(Invalid):
|
|
168
|
+
project_rule(rule, {"metrics": "prometheus", "logs": "skip"})
|
|
169
|
+
else:
|
|
170
|
+
result = project_rule(rule, {"metrics": "prometheus"})
|
|
171
|
+
assert result["alert"] == fixture.stem
|
|
172
|
+
assert result["for"] == rule["for"]
|
|
173
|
+
assert result["labels"] == rule["labels"]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def test_output_symlink_ancestor(tmp_path):
|
|
177
|
+
config = setup_tree(tmp_path)
|
|
178
|
+
(tmp_path / "actual").mkdir()
|
|
179
|
+
(tmp_path / "link").symlink_to(tmp_path / "actual", target_is_directory=True)
|
|
180
|
+
with pytest.raises(Invalid):
|
|
181
|
+
project_files(tmp_path, {**config, "out": "link/generated"})
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@pytest.mark.skipif(shutil.which("promtool") is None, reason="promtool is not installed")
|
|
185
|
+
def test_missing_value_fold_is_red(tmp_path):
|
|
186
|
+
config = setup_tree(tmp_path)
|
|
187
|
+
files = project_files(tmp_path, config)
|
|
188
|
+
files[0].write_text(files[0].read_text().replace('(service_ready == bool 0) > 0', 'service_ready == bool 0'))
|
|
189
|
+
with pytest.raises(subprocess.CalledProcessError):
|
|
190
|
+
run_tests(tmp_path, config, files)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@pytest.mark.skipif(shutil.which("promtool") is None, reason="promtool is not installed")
|
|
194
|
+
def test_existing_shadows_cli(tmp_path):
|
|
195
|
+
setup_tree(tmp_path)
|
|
196
|
+
assert main(["project", "--root", str(tmp_path)]) == 0
|
|
197
|
+
assert main(["test", "--no-project", "--root", str(tmp_path)]) == 0
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@pytest.mark.parametrize("kind", ["classic_conditions", "threshold"])
|
|
201
|
+
def test_threshold_precision(rule, kind):
|
|
202
|
+
if kind == "threshold":
|
|
203
|
+
rule["data"].insert(1, {"refId": "R", "datasourceUid": "__expr__", "model": {"type": "reduce", "reducer": "last", "expression": "A"}})
|
|
204
|
+
rule["data"][-1]["model"].update(type="threshold", expression="R")
|
|
205
|
+
rule["data"][-1]["model"]["conditions"][0]["evaluator"]["params"] = [0.123456789]
|
|
206
|
+
expr = project_rule(rule, {"metrics": "prometheus"})["expr"]
|
|
207
|
+
threshold = float(expr.rsplit(" ", 1)[1])
|
|
208
|
+
assert threshold == 0.123456789
|
|
209
|
+
assert 0.1234568 > threshold
|