Skip to content

Commit 2675181

Browse files
committed
Update to go-check v1.0.0
1 parent e1004c0 commit 2675181

7 files changed

Lines changed: 51 additions & 73 deletions

File tree

cmd/alert.go

Lines changed: 21 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
package cmd
22

33
import (
4-
"errors"
54
"fmt"
65
"regexp"
76
"slices"
87
"strings"
98

109
"github.com/NETWAYS/check_prometheus/internal/alert"
1110
"github.com/NETWAYS/go-check"
12-
"github.com/NETWAYS/go-check/perfdata"
13-
"github.com/NETWAYS/go-check/result"
11+
goresult "github.com/NETWAYS/go-check/result"
1412
"github.com/prometheus/common/model"
1513
"github.com/spf13/cobra"
1614
)
@@ -49,7 +47,7 @@ inactive = 0`,
4947
| total=2 firing=1 pending=0 inactive=1`,
5048
Run: func(_ *cobra.Command, _ []string) {
5149
// Convert --no-alerts-state to integer and validate input
52-
noAlertsState, err := convertStateToInt(cliAlertConfig.NoAlertsState)
50+
noAlertsState, err := check.NewStatusFromString(cliAlertConfig.NoAlertsState)
5351
if err != nil {
5452
check.ExitError(fmt.Errorf("invalid value for --no-alerts-state: %s", cliAlertConfig.NoAlertsState))
5553
}
@@ -88,7 +86,7 @@ inactive = 0`,
8886
// If there are no rules we can exit early
8987
if len(rules) == 0 {
9088
// Just an empty PerfdataList to have consistent perfdata output
91-
pdlist := perfdata.PerfdataList{
89+
pdlist := check.PerfdataList{
9290
{Label: "total", Value: 0},
9391
{Label: "firing", Value: 0},
9492
{Label: "pending", Value: 0},
@@ -98,10 +96,10 @@ inactive = 0`,
9896
// Since the user is expecting the state of a certain alert and
9997
// it that is not present it might be noteworthy.
10098
if cliAlertConfig.AlertName != nil {
101-
check.ExitRaw(check.Unknown, "No such alert defined", "|", pdlist.String())
99+
check.ExitWithPerfdata(check.Unknown, pdlist, "No such alert defined")
102100
}
103101

104-
check.ExitRaw(noAlertsState, "No alerts defined", "|", pdlist.String())
102+
check.ExitWithPerfdata(noAlertsState, pdlist, "No alerts defined")
105103
}
106104

107105
// Set initial capacity to reduce memory allocations
@@ -110,7 +108,7 @@ inactive = 0`,
110108
l *= len(rl.AlertingRule.Alerts)
111109
}
112110

113-
var overall result.Overall
111+
var overall goresult.Overall
114112

115113
for _, rl := range rules {
116114
// If it's not the Alert we're looking for, Skip!
@@ -128,7 +126,7 @@ inactive = 0`,
128126
alertMatchedExclude, regexErr := matches(rl.AlertingRule.Name, cliAlertConfig.ExcludeAlerts)
129127

130128
if regexErr != nil {
131-
check.ExitRaw(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
129+
check.Exit(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
132130
}
133131

134132
if alertMatchedExclude {
@@ -140,7 +138,7 @@ inactive = 0`,
140138
labelsMatchedExclude, regexErr := matchesLabel(rl.AlertingRule.Labels, cliAlertConfig.ExcludeLabels)
141139

142140
if regexErr != nil {
143-
check.ExitRaw(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
141+
check.Exit(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
144142
}
145143

146144
if len(cliAlertConfig.ExcludeLabels) > 0 && labelsMatchedExclude {
@@ -161,16 +159,16 @@ inactive = 0`,
161159
counterFiring++
162160
}
163161

164-
sc := result.NewPartialResult()
162+
sc := goresult.NewPartialResult()
165163

166164
rlStatus := rl.GetStatus(cliAlertConfig.StateLabelKey)
167165
// If the negate flag is set we negate this state
168166
if cliAlertConfig.FlipExitState {
169167
rlStatus = negateStatus(rlStatus)
170168
}
171169

172-
_ = sc.SetState(rlStatus)
173-
sc.Output = rl.GetOutput()
170+
sc.SetState(rlStatus)
171+
sc.SetOutput(rl.GetOutput())
174172
overall.AddSubcheck(sc)
175173
}
176174

@@ -192,7 +190,7 @@ inactive = 0`,
192190
labelsMatchedInclude, regexErr := matchesLabel(alert.Labels, cliAlertConfig.IncludeLabels)
193191

194192
if regexErr != nil {
195-
check.ExitRaw(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
193+
check.Exit(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
196194
}
197195

198196
if len(cliAlertConfig.IncludeLabels) > 0 && !labelsMatchedInclude {
@@ -203,34 +201,34 @@ inactive = 0`,
203201
labelsMatchedExclude, regexErr := matchesLabel(alert.Labels, cliAlertConfig.ExcludeLabels)
204202

205203
if regexErr != nil {
206-
check.ExitRaw(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
204+
check.Exit(check.Unknown, "Invalid regular expression provided:", regexErr.Error())
207205
}
208206

209207
if len(cliAlertConfig.ExcludeLabels) > 0 && labelsMatchedExclude {
210208
// If the alert labels matches here we can skip it.
211209
continue
212210
}
213211

214-
sc := result.NewPartialResult()
212+
sc := goresult.NewPartialResult()
215213

216214
rlStatus := rl.GetStatus(cliAlertConfig.StateLabelKey)
217215
// If the negate flag is set we negate this state
218216
if cliAlertConfig.FlipExitState {
219217
rlStatus = negateStatus(rlStatus)
220218
}
221219

222-
_ = sc.SetState(rlStatus)
220+
sc.SetState(rlStatus)
223221
// Set the alert in the internal Type to generate the output
224222
rl.Alert = alert
225-
sc.Output = rl.GetOutput()
223+
sc.SetOutput(rl.GetOutput())
226224
overall.AddSubcheck(sc)
227225
}
228226
}
229227
}
230228

231229
counterAlert := counterFiring + counterPending + counterInactive
232230

233-
perfList := perfdata.PerfdataList{
231+
perfList := check.PerfdataList{
234232
{Label: "total", Value: counterAlert},
235233
{Label: "firing", Value: counterFiring},
236234
{Label: "pending", Value: counterPending},
@@ -239,11 +237,11 @@ inactive = 0`,
239237

240238
// When there are no alerts we add an empty PartialResult just to have consistent output
241239
if len(overall.PartialResults) == 0 {
242-
sc := result.NewPartialResult()
240+
sc := goresult.NewPartialResult()
243241
// We already make sure it's valid
244242
//nolint: errcheck
245243
sc.SetDefaultState(noAlertsState)
246-
sc.Output = "No alerts retrieved"
244+
sc.SetOutput("No alerts retrieved")
247245
overall.AddSubcheck(sc)
248246
}
249247

@@ -255,7 +253,7 @@ inactive = 0`,
255253
counterPending,
256254
counterInactive)
257255

258-
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
256+
check.Exit(overall.GetStatus(), overall.GetOutput())
259257
},
260258
}
261259

@@ -299,23 +297,6 @@ func init() {
299297
"\nIf this flag is set the plugin looks for the strings 'warning/critical/ok' in the provided label key")
300298
}
301299

302-
// Function to convert state to integer.
303-
func convertStateToInt(state string) (int, error) {
304-
state = strings.ToUpper(state)
305-
switch state {
306-
case "OK", "0":
307-
return check.OK, nil
308-
case "WARNING", "1":
309-
return check.Warning, nil
310-
case "CRITICAL", "2":
311-
return check.Critical, nil
312-
case "UNKNOWN", "3":
313-
return check.Unknown, nil
314-
default:
315-
return check.Unknown, errors.New("invalid state")
316-
}
317-
}
318-
319300
// Matches a list of regular expressions against a string.
320301
func matches(input string, regexToExclude []string) (bool, error) {
321302
for _, regex := range regexToExclude {
@@ -364,7 +345,7 @@ func matchesLabel(labels model.LabelSet, labelsToMatch []string) (bool, error) {
364345
}
365346

366347
// negateStatus turns an OK state into critical and a warning/critical state into OK
367-
func negateStatus(state int) int {
348+
func negateStatus(state check.Status) check.Status {
368349
switch state {
369350
case check.OK:
370351
return check.Critical

cmd/health.go

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,7 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s
2121
$ check_prometheus --bearer secrettoken health --ready
2222
OK - Prometheus Server is Ready. | statuscode=200`,
2323
Run: func(_ *cobra.Command, _ []string) {
24-
var (
25-
rc int
26-
)
24+
var rc check.Status
2725

2826
overall := result.Overall{}
2927

@@ -49,11 +47,11 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s
4947

5048
partialResult := result.NewPartialResult()
5149

52-
_ = partialResult.SetState(rc)
53-
partialResult.Output = output
50+
partialResult.SetState(rc)
51+
partialResult.SetOutput(output)
5452
overall.AddSubcheck(partialResult)
5553

56-
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
54+
check.Exit(overall.GetStatus(), overall.GetOutput())
5755
}
5856

5957
if cliConfig.Info {
@@ -65,18 +63,18 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s
6563

6664
partialResult := result.NewPartialResult()
6765

68-
_ = partialResult.SetState(rc)
66+
partialResult.SetState(rc)
6967

70-
partialResult.Output = "Prometheus Server information\n\n" +
68+
partialResult.SetOutput("Prometheus Server information\n\n" +
7169
"Version: " + info.Version + "\n" +
7270
"Branch: " + info.Branch + "\n" +
7371
"BuildDate: " + info.BuildDate + "\n" +
7472
"BuildUser: " + info.BuildUser + "\n" +
75-
"Revision: " + info.Revision
73+
"Revision: " + info.Revision)
7674

7775
overall.AddSubcheck(partialResult)
7876

79-
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
77+
check.Exit(overall.GetStatus(), overall.GetOutput())
8078
}
8179

8280
// Getting the health status is the default
@@ -87,11 +85,11 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s
8785
}
8886

8987
partialResult := result.NewPartialResult()
90-
_ = partialResult.SetState(rc)
91-
partialResult.Output = output
88+
partialResult.SetState(rc)
89+
partialResult.SetOutput(output)
9290
overall.AddSubcheck(partialResult)
9391

94-
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
92+
check.Exit(overall.GetStatus(), overall.GetOutput())
9593
},
9694
}
9795

cmd/query.go

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"time"
1010

1111
"github.com/NETWAYS/go-check"
12-
"github.com/NETWAYS/go-check/perfdata"
1312
goresult "github.com/NETWAYS/go-check/result"
1413
"github.com/prometheus/common/model"
1514
"github.com/spf13/cobra"
@@ -41,9 +40,9 @@ type Number interface {
4140
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64
4241
}
4342

44-
func generatePerfdata[T Number](metric string, value T, warning, critical *check.Threshold) perfdata.Perfdata {
43+
func generatePerfdata[T Number](metric string, value T, warning, critical *check.Threshold) check.Perfdata {
4544
// We trim the trailing "} from the string, so that the Perfdata won't have a trailing _
46-
return perfdata.Perfdata{
45+
return check.Perfdata{
4746
Label: replacer.Replace(metric),
4847
Value: value,
4948
Warn: warning,
@@ -120,23 +119,23 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
120119
partial := goresult.NewPartialResult()
121120

122121
if crit.DoesViolate(numberValue) {
123-
_ = partial.SetState(check.Critical)
122+
partial.SetState(check.Critical)
124123
} else if warn.DoesViolate(numberValue) {
125-
_ = partial.SetState(check.Warning)
124+
partial.SetState(check.Warning)
126125
} else {
127-
_ = partial.SetState(check.OK)
126+
partial.SetState(check.OK)
128127
}
129128

130129
// Format the metric and RC output for console output
131-
partial.Output = generateMetricOutput(sample.Metric.String(), sample.Value.String())
130+
partial.SetOutput(generateMetricOutput(sample.Metric.String(), sample.Value.String()))
132131

133132
// Generate Perfdata from API return
134133
if math.IsInf(numberValue, 0) || math.IsNaN(numberValue) {
135134
continue
136135
}
137136

138137
perf := generatePerfdata(sample.Metric.String(), numberValue, warn, crit)
139-
partial.Perfdata.Add(&perf)
138+
partial.AddPerfdata(&perf)
140139
overall.AddSubcheck(partial)
141140
}
142141

@@ -155,15 +154,15 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
155154
partial := goresult.NewPartialResult()
156155

157156
if crit.DoesViolate(numberValue) {
158-
_ = partial.SetState(check.Critical)
157+
partial.SetState(check.Critical)
159158
} else if warn.DoesViolate(numberValue) {
160-
_ = partial.SetState(check.Warning)
159+
partial.SetState(check.Warning)
161160
} else {
162-
_ = partial.SetState(check.OK)
161+
partial.SetState(check.OK)
163162
}
164163

165164
// Format the metric and RC output for console output
166-
partial.Output = generateMetricOutput(samplepair.String(), samplepair.Value.String())
165+
partial.SetOutput(generateMetricOutput(samplepair.String(), samplepair.Value.String()))
167166

168167
valueString := samplepair.Value.String()
169168

@@ -173,7 +172,7 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
173172

174173
// Generate Perfdata from API return
175174
if !math.IsInf(numberValue, 0) && !math.IsNaN(numberValue) {
176-
partial.Perfdata.Add(&pd)
175+
partial.AddPerfdata(&pd)
177176
}
178177
}
179178

@@ -186,7 +185,7 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
186185
overall.Summary = overall.GetOutput() + appendum
187186
}
188187

189-
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
188+
check.Exit(overall.GetStatus(), overall.GetOutput())
190189
},
191190
}
192191

go.mod

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
module github.com/NETWAYS/check_prometheus
22

3-
go 1.25.0
3+
go 1.26
44

55
require (
6-
github.com/NETWAYS/go-check v0.6.4
6+
github.com/NETWAYS/go-check v1.0.0
77
github.com/prometheus/client_golang v1.23.2
88
github.com/prometheus/common v0.69.0
99
github.com/spf13/cobra v1.10.2

go.sum

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
github.com/NETWAYS/go-check v0.6.4 h1:4WETSVNZNEP0Yudcp5xlvxq6RGn920cmUKq4fz/P1GQ=
2-
github.com/NETWAYS/go-check v0.6.4/go.mod h1:8/GWnq8SirreAixgRmcp82JG16NnEl38rHq9phICy9s=
1+
github.com/NETWAYS/go-check v1.0.0 h1:YkzTwFfGR+Z+mK3Wsqpnu8wibzsB30im19iPNfCOsMQ=
2+
github.com/NETWAYS/go-check v1.0.0/go.mod h1:8/GWnq8SirreAixgRmcp82JG16NnEl38rHq9phICy9s=
33
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
44
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
55
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=

internal/alert/alert.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func FlattenRules(groups []v1.RuleGroup, wantedGroups []string, alerts []v1.Aler
7070
return rules
7171
}
7272

73-
func (a *Rule) GetStatus(labelKey string) (status int) {
73+
func (a *Rule) GetStatus(labelKey string) (status check.Status) {
7474
state := a.AlertingRule.State
7575

7676
switch state {

internal/client/client.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func (c *Client) Connect() error {
4242
return nil
4343
}
4444

45-
func (c *Client) GetStatus(ctx context.Context, endpoint string) (returncode int, statuscode int, body string, err error) {
45+
func (c *Client) GetStatus(ctx context.Context, endpoint string) (returncode check.Status, statuscode int, body string, err error) {
4646
// Parses the response from the Prometheus /healthy and /ready endpoint
4747
// Return: Exit Status Code, HTTP Status Code, HTTP Body, Error
4848
// Building the final URL with the endpoint parameter

0 commit comments

Comments
 (0)