Skip to content

Commit 9e3ee18

Browse files
FUSAKLAGiedrius Statkevičius
authored and
Giedrius Statkevičius
committed
feat: added thanos check rules command (#1097)
* feat: added thanos check rules command Signed-off-by: Martin Chodur <[email protected]> * feat: switched to strict unmarshal in rule check * refactor: changed logging of highest error using logger * chore: updated changelog * fix check: fixed tsdb MultiError package import * fix docs: update check cmd flags docs
1 parent 9cc17f4 commit 9e3ee18

File tree

10 files changed

+320
-24
lines changed

10 files changed

+320
-24
lines changed

CHANGELOG.md

+26-22
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ We use *breaking* word for marking changes that are not backward compatible (rel
1111

1212
## Unreleased.
1313

14+
### Added
15+
16+
- [#1097](https://github.com/improbable-eng/thanos/pull/1097) Added `thanos check rules` linter for Thanos rule rules files.
17+
1418
## [v0.5.0](https://github.com/improbable-eng/thanos/releases/tag/v0.5.0) - 2019.06.05
1519

1620
TL;DR: Store LRU cache is no longer leaking, Upgraded Thanos UI to Prometheus 2.9, Fixed auto-downsampling, Moved to Go 1.12.5 and more.
@@ -105,28 +109,28 @@ Using cadvisor `container_memory_usage_bytes` metric could be misleading e.g: ht
105109
New options:
106110

107111
New Store flags:
108-
112+
109113
* `--store.grpc.series-sample-limit` limits the amount of samples that might be retrieved on a single Series() call. By default it is 0. Consider enabling it by setting it to more than 0 if you are running on limited resources.
110114
* `--store.grpc.series-max-concurrency` limits the number of concurrent Series() calls in Thanos Store. By default it is 20. Considering making it lower or bigger depending on the scale of your deployment.
111115

112116
New Store metrics:
113-
117+
114118
* `thanos_bucket_store_queries_dropped_total` shows how many queries were dropped due to the samples limit;
115119
* `thanos_bucket_store_queries_concurrent_max` is a constant metric which shows how many Series() calls can concurrently be executed by Thanos Store;
116120
* `thanos_bucket_store_queries_in_flight` shows how many queries are currently "in flight" i.e. they are being executed;
117121
* `thanos_bucket_store_gate_duration_seconds` shows how many seconds it took for queries to pass through the gate in both cases - when that fails and when it does not.
118-
122+
119123
New Store tracing span:
120124
* `store_query_gate_ismyturn` shows how long it took for a query to pass (or not) through the gate.
121-
122-
- [#1016](https://github.com/improbable-eng/thanos/pull/1016) Added option for another DNS resolver (miekg/dns client).
125+
126+
- [#1016](https://github.com/improbable-eng/thanos/pull/1016) Added option for another DNS resolver (miekg/dns client).
123127
Note that this is required to have SRV resolution working on [Golang 1.11+ with KubeDNS below v1.14](https://github.com/golang/go/issues/27546)
124128

125129
New Querier and Ruler flag: `-- store.sd-dns-resolver` which allows to specify resolver to use. Either `golang` or `miekgdns`
126-
130+
127131
- [#986](https://github.com/improbable-eng/thanos/pull/986) Allow to save some startup & sync time in store gateway as it is no longer needed to compute index-cache from block index on its own for larger blocks.
128-
The store Gateway still can do it, but it first checks bucket if there is index-cached uploaded already.
129-
In the same time, compactor precomputes the index cache file on every compaction.
132+
The store Gateway still can do it, but it first checks bucket if there is index-cached uploaded already.
133+
In the same time, compactor precomputes the index cache file on every compaction.
130134

131135
New Compactor flag: `--index.generate-missing-cache-file` was added to allow quicker addition of index cache files. If enabled it precomputes missing files on compactor startup. Note that it will take time and it's only one-off step per bucket.
132136

@@ -143,31 +147,31 @@ Note that this is required to have SRV resolution working on [Golang 1.11+ with
143147
- [#1021](https://github.com/improbable-eng/thanos/pull/1021) Query API `series` now supports POST method.
144148
- [#939](https://github.com/improbable-eng/thanos/pull/939) Query API `query_range` now supports POST method.
145149

146-
### Changed
150+
### Changed
147151

148152
- [#970](https://github.com/improbable-eng/thanos/pull/970) Deprecated `partial_response_disabled` proto field. Added `partial_response_strategy` instead. Both in gRPC and Query API.
149153
No `PartialResponseStrategy` field for `RuleGroups` by default means `abort` strategy (old PartialResponse disabled) as this is recommended option for Rules and alerts.
150154

151155
Metrics:
152-
156+
153157
* Added `thanos_rule_evaluation_with_warnings_total` to Ruler.
154158
* DNS `thanos_ruler_query_apis*` are now `thanos_ruler_query_apis_*` for consistency.
155159
* DNS `thanos_querier_store_apis*` are now `thanos_querier_store_apis__*` for consistency.
156160
* Query Gate `thanos_bucket_store_series*` are now `thanos_bucket_store_series_*` for consistency.
157161
* Most of thanos ruler metris related to rule manager has `strategy` label.
158-
162+
159163
Ruler tracing spans:
160-
164+
161165
* `/rule_instant_query HTTP[client]` is now `/rule_instant_query_part_resp_abort HTTP[client]"` if request is for abort strategy.
162-
166+
163167
- [#1009](https://github.com/improbable-eng/thanos/pull/1009): Upgraded Prometheus (~v2.7.0-rc.0 to v2.8.1) and TSDB (`v0.4.0` to `v0.6.1`) deps.
164-
168+
165169
Changes that affects Thanos:
166-
* query:
167-
* [ENHANCEMENT] In histogram_quantile merge buckets with equivalent le values. #5158.
168-
* [ENHANCEMENT] Show list of offending labels in the error message in many-to-many scenarios. #5189
170+
* query:
171+
* [ENHANCEMENT] In histogram_quantile merge buckets with equivalent le values. #5158.
172+
* [ENHANCEMENT] Show list of offending labels in the error message in many-to-many scenarios. #5189
169173
* [BUGFIX] Fix panic when aggregator param is not a literal. #5290
170-
* ruler:
174+
* ruler:
171175
* [ENHANCEMENT] Reduce time that Alertmanagers are in flux when reloaded. #5126
172176
* [BUGFIX] prometheus_rule_group_last_evaluation_timestamp_seconds is now a unix timestamp. #5186
173177
* [BUGFIX] prometheus_rule_group_last_duration_seconds now reports seconds instead of nanoseconds. Fixes our [issue #1027](https://github.com/improbable-eng/thanos/issues/1027)
@@ -179,26 +183,26 @@ Note that this is required to have SRV resolution working on [Golang 1.11+ with
179183
* [CHANGE] *breaking* Renamed flag `--sync-delay` to `--consistency-delay` [#1053](https://github.com/improbable-eng/thanos/pull/1053)
180184

181185
For ruler essentially whole TSDB CHANGELOG applies beween v0.4.0-v0.6.1: https://github.com/prometheus/tsdb/blob/master/CHANGELOG.md
182-
186+
183187
Note that this was added on TSDB and Prometheus: [FEATURE] Time-ovelapping blocks are now allowed. #370
184188
Whoever due to nature of Thanos compaction (distributed systems), for safety reason this is disabled for Thanos compactor for now.
185189

186190
- [#868](https://github.com/improbable-eng/thanos/pull/868) Go has been updated to 1.12.
187-
- [#1055](https://github.com/improbable-eng/thanos/pull/1055) Gossip flags are now disabled by default and deprecated.
191+
- [#1055](https://github.com/improbable-eng/thanos/pull/1055) Gossip flags are now disabled by default and deprecated.
188192
- [#964](https://github.com/improbable-eng/thanos/pull/964) repair: Repair process now sorts the series and labels within block.
189193
- [#1073](https://github.com/improbable-eng/thanos/pull/1073) Store: index cache for requests. It now calculates the size properly (includes slice header), has anti-deadlock safeguard and reports more metrics.
190194

191195
### Fixed
192196

193197
- [#921](https://github.com/improbable-eng/thanos/pull/921) `thanos_objstore_bucket_last_successful_upload_time` now does not appear when no blocks have been uploaded so far.
194-
- [#966](https://github.com/improbable-eng/thanos/pull/966) Bucket: verify no longer warns about overlapping blocks, that overlap `0s`
198+
- [#966](https://github.com/improbable-eng/thanos/pull/966) Bucket: verify no longer warns about overlapping blocks, that overlap `0s`
195199
- [#848](https://github.com/improbable-eng/thanos/pull/848) Compact: now correctly works with time series with duplicate labels.
196200
- [#894](https://github.com/improbable-eng/thanos/pull/894) Thanos Rule: UI now correctly shows evaluation time.
197201
- [#865](https://github.com/improbable-eng/thanos/pull/865) Query: now properly parses DNS SRV Service Discovery.
198202
- [#889](https://github.com/improbable-eng/thanos/pull/889) Store: added safeguard against merging posting groups segfault
199203
- [#941](https://github.com/improbable-eng/thanos/pull/941) Sidecar: added better handling of intermediate restarts.
200204
- [#933](https://github.com/improbable-eng/thanos/pull/933) Query: Fixed 30 seconds lag of adding new store to query.
201-
- [#962](https://github.com/improbable-eng/thanos/pull/962) Sidecar: Make config reloader file writes atomic.
205+
- [#962](https://github.com/improbable-eng/thanos/pull/962) Sidecar: Make config reloader file writes atomic.
202206
- [#982](https://github.com/improbable-eng/thanos/pull/982) Query: now advertises Min & Max Time accordingly to the nodes.
203207
- [#1041](https://github.com/improbable-eng/thanos/issues/1038) Ruler is now able to return long time range queries.
204208
- [#904](https://github.com/improbable-eng/thanos/pull/904) Compact: Skip compaction for blocks with no samples.

cmd/thanos/check.go

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
package main
2+
3+
import (
4+
"io/ioutil"
5+
6+
"github.com/go-kit/kit/log"
7+
"github.com/go-kit/kit/log/level"
8+
"github.com/oklog/run"
9+
"github.com/opentracing/opentracing-go"
10+
"github.com/prometheus/client_golang/prometheus"
11+
"github.com/prometheus/prometheus/pkg/rulefmt"
12+
"github.com/prometheus/tsdb/errors"
13+
"gopkg.in/alecthomas/kingpin.v2"
14+
"gopkg.in/yaml.v2"
15+
)
16+
17+
func registerChecks(m map[string]setupFunc, app *kingpin.Application, name string) {
18+
cmd := app.Command(name, "Linting tools for Thanos")
19+
registerCheckRules(m, cmd, name)
20+
}
21+
22+
func registerCheckRules(m map[string]setupFunc, root *kingpin.CmdClause, name string) {
23+
checkRulesCmd := root.Command("rules", "Check if the rule files are valid or not.")
24+
ruleFiles := checkRulesCmd.Arg(
25+
"rule-files",
26+
"The rule files to check.",
27+
).Required().ExistingFiles()
28+
29+
m[name+" rules"] = func(g *run.Group, logger log.Logger, reg *prometheus.Registry, _ opentracing.Tracer, _ bool) error {
30+
// Dummy actor to immediately kill the group after the run function returns.
31+
g.Add(func() error { return nil }, func(error) {})
32+
return checkRulesFiles(logger, ruleFiles)
33+
}
34+
}
35+
36+
func checkRulesFiles(logger log.Logger, files *[]string) error {
37+
failed := errors.MultiError{}
38+
39+
for _, f := range *files {
40+
n, errs := checkRules(logger, f)
41+
if errs.Err() != nil {
42+
level.Error(logger).Log("result", "FAILED")
43+
for _, e := range errs {
44+
level.Error(logger).Log("error", e.Error())
45+
failed.Add(e)
46+
}
47+
level.Info(logger).Log()
48+
continue
49+
}
50+
level.Info(logger).Log("result", "SUCCESS", "rules found", n)
51+
}
52+
if failed.Err() != nil {
53+
return failed
54+
}
55+
return nil
56+
}
57+
58+
type ThanosRuleGroup struct {
59+
PartialResponseStrategy string `yaml:"partial_response_strategy"`
60+
rulefmt.RuleGroup `yaml:",inline"`
61+
}
62+
63+
type ThanosRuleGroups struct {
64+
Groups []ThanosRuleGroup `yaml:"groups"`
65+
}
66+
67+
func checkRules(logger log.Logger, filename string) (int, errors.MultiError) {
68+
level.Info(logger).Log("msg", "checking", "filename", filename)
69+
checkErrors := errors.MultiError{}
70+
71+
b, err := ioutil.ReadFile(filename)
72+
if err != nil {
73+
checkErrors.Add(err)
74+
return 0, checkErrors
75+
}
76+
77+
var rgs ThanosRuleGroups
78+
if err := yaml.UnmarshalStrict(b, &rgs); err != nil {
79+
checkErrors.Add(err)
80+
return 0, checkErrors
81+
}
82+
83+
// We need to convert Thanos rules to Prometheus rules so we can use their validation.
84+
promRgs := thanosRuleGroupsToPromRuleGroups(rgs)
85+
if errs := promRgs.Validate(); errs != nil {
86+
for _, e := range errs {
87+
checkErrors.Add(e)
88+
}
89+
return 0, checkErrors
90+
}
91+
92+
numRules := 0
93+
for _, rg := range rgs.Groups {
94+
numRules += len(rg.Rules)
95+
}
96+
97+
return numRules, checkErrors
98+
}
99+
100+
func thanosRuleGroupsToPromRuleGroups(ruleGroups ThanosRuleGroups) rulefmt.RuleGroups {
101+
promRuleGroups := rulefmt.RuleGroups{Groups: []rulefmt.RuleGroup{}}
102+
for _, g := range ruleGroups.Groups {
103+
group := rulefmt.RuleGroup{
104+
Name: g.Name,
105+
Interval: g.Interval,
106+
Rules: []rulefmt.Rule{},
107+
}
108+
for _, r := range g.Rules {
109+
group.Rules = append(
110+
group.Rules,
111+
rulefmt.Rule{
112+
Record: r.Record,
113+
Alert: r.Alert,
114+
Expr: r.Expr,
115+
For: r.For,
116+
Labels: r.Labels,
117+
Annotations: r.Annotations,
118+
},
119+
)
120+
}
121+
promRuleGroups.Groups = append(
122+
promRuleGroups.Groups,
123+
group,
124+
)
125+
}
126+
return promRuleGroups
127+
}

cmd/thanos/check_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package main
2+
3+
import (
4+
"testing"
5+
6+
"github.com/go-kit/kit/log"
7+
"github.com/improbable-eng/thanos/pkg/testutil"
8+
)
9+
10+
func Test_checkRules(t *testing.T) {
11+
12+
validFiles := []string{
13+
"./testdata/rules-files/valid.yaml",
14+
}
15+
16+
invalidFiles := [][]string{
17+
[]string{"./testdata/rules-files/non-existing-file.yaml"},
18+
[]string{"./testdata/rules-files/invalid-yaml-format.yaml"},
19+
[]string{"./testdata/rules-files/invalid-rules-data.yaml"},
20+
[]string{"./testdata/rules-files/invalid-unknown-field.yaml"},
21+
}
22+
23+
logger := log.NewNopLogger()
24+
25+
testutil.Ok(t, checkRulesFiles(logger, &validFiles))
26+
27+
for _, fn := range invalidFiles {
28+
testutil.NotOk(t, checkRulesFiles(logger, &fn))
29+
}
30+
}

cmd/thanos/main.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ func main() {
7777
registerBucket(cmds, app, "bucket")
7878
registerDownsample(cmds, app, "downsample")
7979
registerReceive(cmds, app, "receive")
80+
registerChecks(cmds, app, "check")
8081

8182
cmd, err := app.Parse(os.Args[1:])
8283
if err != nil {
@@ -176,7 +177,7 @@ func main() {
176177
}
177178

178179
if err := cmds[cmd](&g, logger, metrics, tracer, *logLevel == "debug"); err != nil {
179-
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "%s command failed", cmd))
180+
level.Error(logger).Log("err", errors.Wrapf(err, "%s command failed", cmd))
180181
os.Exit(1)
181182
}
182183

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
groups:
2+
- name: null
3+
partial_response_strategy: "warn"
4+
interval: 2m
5+
rules:
6+
- alert: TestAlert
7+
partial_response_strategy: "warn"
8+
expr: 1
9+
labels:
10+
key: value
11+
annotations:
12+
key: value
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
groups:
2+
- name: test-alert-group
3+
partial_response_strategy: "warn"
4+
interrrrrrrrval: 2m
5+
rules:
6+
- alert: TestAlert
7+
expr: 1
8+
labels:
9+
key: value
10+
annotations:
11+
key: value
12+
13+
- name: test-rule-group
14+
partial_response_strategy: "warn"
15+
interval: 2m
16+
rules:
17+
- record: test_metric
18+
expr: 1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
groups:
2+
- name: test
3+
invalid_yaml_reason
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
groups:
2+
- name: test-alert-group
3+
partial_response_strategy: "warn"
4+
interval: 2m
5+
rules:
6+
- alert: TestAlert
7+
expr: 1
8+
labels:
9+
key: value
10+
annotations:
11+
key: value
12+
13+
- name: test-rule-group
14+
partial_response_strategy: "warn"
15+
interval: 2m
16+
rules:
17+
- record: test_metric
18+
expr: 1

0 commit comments

Comments
 (0)