Skip to content

Commit

Permalink
Merge pull request #48 from NETWAYS/refactor_for_more_gocheck
Browse files Browse the repository at this point in the history
Refactor for more gocheck
  • Loading branch information
RincewindsHat authored Jul 10, 2024
2 parents 11e2138 + 5bff529 commit 2fdf5d8
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 157 deletions.
55 changes: 19 additions & 36 deletions cmd/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"fmt"
"strings"

"github.com/NETWAYS/check_prometheus/internal/alert"
"github.com/NETWAYS/go-check"
Expand All @@ -11,23 +10,6 @@ import (
"github.com/spf13/cobra"
)

func generateOutput(rl alert.Rule, cfg AlertConfig) (output string) {
// Generates the console output for the AlertingRules
var out strings.Builder

if len(cfg.AlertName) > 1 || cfg.Group == nil {
out.WriteString(" \\_")
}

out.WriteString(fmt.Sprintf("[%s] %s", check.StatusText(rl.GetStatus()), rl.GetOutput()))

if len(cfg.AlertName) > 1 || cfg.Group == nil {
out.WriteString("\n")
}

return out.String()
}

func contains(s string, list []string) bool {
// Tiny helper to see if a string is in a list of strings
for _, elem := range list {
Expand Down Expand Up @@ -59,12 +41,9 @@ inactive = 0`,
| total=2 firing=1 pending=0 inactive=1`,
Run: func(cmd *cobra.Command, args []string) {
var (
output strings.Builder
summary string
counterFiring int
counterPending int
counterInactive int
perfList perfdata.PerfdataList
)

c := cliConfig.NewClient()
Expand All @@ -91,7 +70,8 @@ inactive = 0`,
for _, rl := range rules {
l *= len(rl.AlertingRule.Alerts)
}
states := make([]int, 0, l)

var overall result.Overall

for _, rl := range rules {

Expand Down Expand Up @@ -119,9 +99,11 @@ inactive = 0`,
counterFiring++
}

// Gather the state to evaluate the worst at the end
states = append(states, rl.GetStatus())
output.WriteString(generateOutput(rl, cliAlertConfig))
sc := result.NewPartialResult()

_ = sc.SetState(rl.GetStatus())
sc.Output = rl.GetOutput()
overall.AddSubcheck(sc)
}

// Handle active alerts
Expand All @@ -138,44 +120,45 @@ inactive = 0`,
counterFiring++
}

sc := result.NewPartialResult()

_ = sc.SetState(rl.GetStatus())
// Set the alert in the internal Type to generate the output
rl.Alert = alert
// Gather the state to evaluate the worst at the end
states = append(states, rl.GetStatus())
output.WriteString(generateOutput(rl, cliAlertConfig))
sc.Output = rl.GetOutput()
overall.AddSubcheck(sc)
}
}
}

counterAlert := counterFiring + counterPending + counterInactive
if len(cliAlertConfig.AlertName) > 1 || counterAlert > 1 {
perfList = perfdata.PerfdataList{
perfList := perfdata.PerfdataList{
{Label: "total", Value: counterAlert},
{Label: "firing", Value: counterFiring},
{Label: "pending", Value: counterPending},
{Label: "inactive", Value: counterInactive},
}

overall.PartialResults[0].Perfdata = append(overall.PartialResults[0].Perfdata, perfList...)
}

if len(cliAlertConfig.AlertName) == 1 && counterAlert == 1 {
perfList = perfdata.PerfdataList{
perfList := perfdata.PerfdataList{
{Label: "firing", Value: counterFiring},
{Label: "pending", Value: counterPending},
{Label: "inactive", Value: counterInactive},
}
overall.PartialResults[0].Perfdata = append(overall.PartialResults[0].Perfdata, perfList...)
}

summary = fmt.Sprintf("%d Alerts: %d Firing - %d Pending - %d Inactive",
overall.Summary = fmt.Sprintf("%d Alerts: %d Firing - %d Pending - %d Inactive",
counterAlert,
counterFiring,
counterPending,
counterInactive)

if result.WorstState(states...) == 0 {
check.ExitRaw(result.WorstState(states...), "Alerts inactive", "|", perfList.String())
} else {
check.ExitRaw(result.WorstState(states...), summary+"\n"+output.String(), "|", perfList.String())
}
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
},
}

Expand Down
36 changes: 20 additions & 16 deletions cmd/alert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ func TestAlertCmd(t *testing.T) {
})),
args: []string{"run", "../main.go", "alert"},
expected: `[CRITICAL] - 3 Alerts: 1 Firing - 1 Pending - 1 Inactive
\_[OK] [HostOutOfMemory] is inactive
\_[WARNING] [SqlAccessDeniedRate] - Job: [mysql] on Instance: [localhost] is pending - value: 0.40
\_[CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
| total=3 firing=1 pending=1 inactive=1
\_ [OK] [HostOutOfMemory] is inactive
\_ [WARNING] [SqlAccessDeniedRate] - Job: [mysql] on Instance: [localhost] is pending - value: 0.40
\_ [CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
|total=3 firing=1 pending=1 inactive=1
exit status 2
`,
},
Expand All @@ -54,9 +55,10 @@ exit status 2
})),
args: []string{"run", "../main.go", "alert", "--problems"},
expected: `[CRITICAL] - 2 Alerts: 1 Firing - 1 Pending - 0 Inactive
\_[WARNING] [SqlAccessDeniedRate] - Job: [mysql] on Instance: [localhost] is pending - value: 0.40
\_[CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
| total=2 firing=1 pending=1 inactive=0
\_ [WARNING] [SqlAccessDeniedRate] - Job: [mysql] on Instance: [localhost] is pending - value: 0.40
\_ [CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
|total=2 firing=1 pending=1 inactive=0
exit status 2
`,
},
Expand All @@ -67,7 +69,7 @@ exit status 2
w.Write([]byte(`{"status":"success","data":{"groups":[{"name":"Foo","file":"alerts.yaml","rules":[{"state":"inactive","name":"InactiveAlert","query":"foo","duration":120,"labels":{"severity":"critical"},"annotations":{"description":"Inactive","summary":"Inactive"},"alerts":[],"health":"ok","evaluationTime":0.000462382,"lastEvaluation":"2022-11-18T14:01:07.597034323Z","type":"alerting"}],"interval":10,"limit":0,"evaluationTime":0.000478395,"lastEvaluation":"2022-11-18T14:01:07.597021953Z"}]}}`))
})),
args: []string{"run", "../main.go", "alert", "--name", "NoSuchAlert"},
expected: "[UNKNOWN] - 0 Alerts: 0 Firing - 0 Pending - 0 Inactive\n | \nexit status 3\n",
expected: "[UNKNOWN] - 0 Alerts: 0 Firing - 0 Pending - 0 Inactive\n\nexit status 3\n",
},
{
name: "alert-inactive-with-problems",
Expand All @@ -76,7 +78,7 @@ exit status 2
w.Write([]byte(`{"status":"success","data":{"groups":[{"name":"Foo","file":"alerts.yaml","rules":[{"state":"inactive","name":"InactiveAlert","query":"foo","duration":120,"labels":{"severity":"critical"},"annotations":{"description":"Inactive","summary":"Inactive"},"alerts":[],"health":"ok","evaluationTime":0.000462382,"lastEvaluation":"2022-11-18T14:01:07.597034323Z","type":"alerting"}],"interval":10,"limit":0,"evaluationTime":0.000478395,"lastEvaluation":"2022-11-18T14:01:07.597021953Z"}]}}`))
})),
args: []string{"run", "../main.go", "alert", "--name", "InactiveAlert", "--problems"},
expected: "[UNKNOWN] - 0 Alerts: 0 Firing - 0 Pending - 0 Inactive\n | \nexit status 3\n",
expected: "[UNKNOWN] - 0 Alerts: 0 Firing - 0 Pending - 0 Inactive\n\nexit status 3\n",
},
{
name: "alert-multiple-alerts",
Expand All @@ -86,9 +88,10 @@ exit status 2
})),
args: []string{"run", "../main.go", "alert", "--name", "HostOutOfMemory", "--name", "BlackboxTLS"},
expected: `[CRITICAL] - 2 Alerts: 1 Firing - 0 Pending - 1 Inactive
\_[OK] [HostOutOfMemory] is inactive
\_[CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
| total=2 firing=1 pending=0 inactive=1
\_ [OK] [HostOutOfMemory] is inactive
\_ [CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
|total=2 firing=1 pending=0 inactive=1
exit status 2
`,
},
Expand All @@ -100,8 +103,9 @@ exit status 2
})),
args: []string{"run", "../main.go", "alert", "--name", "HostOutOfMemory", "--name", "BlackboxTLS", "--problems"},
expected: `[CRITICAL] - 1 Alerts: 1 Firing - 0 Pending - 0 Inactive
\_[CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
| total=1 firing=1 pending=0 inactive=0
\_ [CRITICAL] [BlackboxTLS] - Job: [blackbox] on Instance: [https://localhost:443] is firing - value: -6065338.00
|total=1 firing=1 pending=0 inactive=0
exit status 2
`,
},
Expand All @@ -112,7 +116,7 @@ exit status 2
w.Write([]byte(`{"status":"success","data":{"groups":[{"name":"Foo","file":"alerts.yaml","rules":[{"state":"inactive","name":"InactiveAlert","query":"foo","duration":120,"labels":{"severity":"critical"},"annotations":{"description":"Inactive","summary":"Inactive"},"alerts":[],"health":"ok","evaluationTime":0.000462382,"lastEvaluation":"2022-11-18T14:01:07.597034323Z","type":"alerting"}],"interval":10,"limit":0,"evaluationTime":0.000478395,"lastEvaluation":"2022-11-18T14:01:07.597021953Z"}]}}`))
})),
args: []string{"run", "../main.go", "alert", "--name", "InactiveAlert"},
expected: "[OK] - Alerts inactive | firing=0 pending=0 inactive=1\n",
expected: "[OK] - 1 Alerts: 0 Firing - 0 Pending - 1 Inactive\n\\_ [OK] [InactiveAlert] is inactive\n|firing=0 pending=0 inactive=1\n\n",
},
{
name: "alert-recording-rule",
Expand All @@ -121,7 +125,7 @@ exit status 2
w.Write([]byte(`{"status":"success","data":{"groups":[{"name":"example","file":"recoding.yaml","rules":[{"name":"job:foo","query":"sum by(job) (requests_total)","health":"ok","evaluationTime":0.000391321,"lastEvaluation":"2023-01-13T14:26:08.687065894Z","type":"recording"}],"interval":10,"evaluationTime":0.000403777,"lastEvaluation":"2023-01-13T14:26:08.687058029Z"},{"name":"Foo","file":"alerts.yaml","rules":[{"state":"inactive","name":"InactiveAlert","query":"foo","duration":120,"labels":{"severity":"critical"},"annotations":{"description":"Inactive","summary":"Inactive"},"alerts":[],"health":"ok","evaluationTime":0.000462382,"lastEvaluation":"2022-11-18T14:01:07.597034323Z","type":"alerting"}],"interval":10,"limit":0,"evaluationTime":0.000478395,"lastEvaluation":"2022-11-18T14:01:07.597021953Z"}]}}`))
})),
args: []string{"run", "../main.go", "alert", "--name", "InactiveAlert"},
expected: "[OK] - Alerts inactive | firing=0 pending=0 inactive=1\n",
expected: "[OK] - 1 Alerts: 0 Firing - 0 Pending - 1 Inactive\n\\_ [OK] [InactiveAlert] is inactive\n|firing=0 pending=0 inactive=1\n\n",
},
}

Expand Down
43 changes: 24 additions & 19 deletions cmd/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"

"github.com/NETWAYS/go-check"
"github.com/NETWAYS/go-check/perfdata"
"github.com/NETWAYS/go-check/result"
"github.com/spf13/cobra"
)

Expand All @@ -22,11 +22,11 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s
OK - Prometheus Server is Ready. | statuscode=200`,
Run: func(cmd *cobra.Command, args []string) {
var (
output string
rc int
sc int
rc int
)

overall := result.Overall{}

// Creating an client and connecting to the API
c := cliConfig.NewClient()
err := c.Connect()
Expand All @@ -40,16 +40,19 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s

if cliConfig.PReady {
// Getting the ready status
rc, sc, output, err = c.GetStatus(ctx, "ready")
rc, _, output, err := c.GetStatus(ctx, "ready")

if err != nil {
check.ExitError(fmt.Errorf(output))
}
p := perfdata.PerfdataList{
{Label: "statuscode", Value: float64(sc)},
}

check.ExitRaw(rc, output, "|", p.String())
partialResult := result.NewPartialResult()

_ = partialResult.SetState(rc)
partialResult.Output = output
overall.AddSubcheck(partialResult)

check.ExitRaw(overall.GetStatus(), overall.GetOutput())
}

if cliConfig.Info {
Expand All @@ -58,33 +61,35 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s
if err != nil {
check.ExitError(err)
}
partialResult := result.NewPartialResult()

output = "Prometheus Server information\n\n" +
_ = partialResult.SetState(rc)

partialResult.Output = "Prometheus Server information\n\n" +
"Version: " + info.Version + "\n" +
"Branch: " + info.Branch + "\n" +
"BuildDate: " + info.BuildDate + "\n" +
"BuildUser: " + info.BuildUser + "\n" +
"Revision: " + info.Revision

p := perfdata.PerfdataList{
{Label: "statuscode", Value: 200},
}
overall.AddSubcheck(partialResult)

check.ExitRaw(rc, output, "|", p.String())
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
}

// Getting the health status is the default
rc, sc, output, err = c.GetStatus(ctx, "healthy")
rc, _, output, err := c.GetStatus(ctx, "healthy")

if err != nil {
check.ExitError(fmt.Errorf(output))
}

p := perfdata.PerfdataList{
{Label: "statuscode", Value: float64(sc)},
}
partialResult := result.NewPartialResult()
_ = partialResult.SetState(rc)
partialResult.Output = output
overall.AddSubcheck(partialResult)

check.ExitRaw(rc, output, "|", p.String())
check.ExitRaw(overall.GetStatus(), overall.GetOutput())
},
}

Expand Down
18 changes: 9 additions & 9 deletions cmd/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`Prometheus Server is Healthy.`))
})),
args: []string{"run", "../main.go", "health"},
expected: "[OK] - Prometheus Server is Healthy. | statuscode=200\n",
expected: "[OK] - states: ok=1\n\\_ [OK] Prometheus Server is Healthy.\n\n",
},
{
name: "health-ok-older-versions",
Expand All @@ -47,7 +47,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`Prometheus is Healthy.`))
})),
args: []string{"run", "../main.go", "health"},
expected: "[OK] - Prometheus is Healthy. | statuscode=200\n",
expected: "[OK] - states: ok=1\n\\_ [OK] Prometheus is Healthy.\n\n",
},
{
name: "ready-ok",
Expand All @@ -56,7 +56,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`Prometheus Server is Ready.`))
})),
args: []string{"run", "../main.go", "health", "--ready"},
expected: "[OK] - Prometheus Server is Ready. | statuscode=200\n",
expected: "[OK] - states: ok=1\n\\_ [OK] Prometheus Server is Ready.\n\n",
},
{
name: "info-ok",
Expand All @@ -65,7 +65,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`{"status":"success","data":{"version":"2.30.3","revision":"foo","branch":"HEAD","buildUser":"root@foo","buildDate":"20211005-16:10:52","goVersion":"go1.17.1"}}`))
})),
args: []string{"run", "../main.go", "health", "--info"},
expected: "[OK] - Prometheus Server information\n\nVersion: 2.30.3\nBranch: HEAD\nBuildDate: 20211005-16:10:52\nBuildUser: root@foo\nRevision: foo | statuscode=200\n",
expected: "[OK] - states: ok=1\n\\_ [OK] Prometheus Server information\n\nVersion: 2.30.3\nBranch: HEAD\nBuildDate: 20211005-16:10:52\nBuildUser: root@foo\nRevision: foo\n\n",
},
{
name: "health-bearer-ok",
Expand All @@ -81,7 +81,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`The Authorization header wasn't set`))
})),
args: []string{"run", "../main.go", "--bearer", "secret", "health"},
expected: "[OK] - Prometheus Server is Healthy. | statuscode=200\n",
expected: "[OK] - states: ok=1\n\\_ [OK] Prometheus Server is Healthy.\n\n",
},
{
name: "health-bearer-unauthorized",
Expand All @@ -97,7 +97,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`Access Denied!`))
})),
args: []string{"run", "../main.go", "--bearer", "wrong-token", "health"},
expected: "[CRITICAL] - Access Denied! | statuscode=401\nexit status 2\n",
expected: "[CRITICAL] - states: critical=1\n\\_ [CRITICAL] Access Denied!\n\nexit status 2\n",
},
{
name: "health-basic-auth-ok",
Expand All @@ -115,7 +115,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`The Authorization header wasn't set`))
})),
args: []string{"run", "../main.go", "--user", "username:password", "health"},
expected: "[OK] - Prometheus Server is Healthy. | statuscode=200\n",
expected: "[OK] - states: ok=1\n\\_ [OK] Prometheus Server is Healthy.\n\n",
},
{
name: "health-basic-auth-unauthorized",
Expand All @@ -133,7 +133,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`Access Denied!`))
})),
args: []string{"run", "../main.go", "health"},
expected: "[CRITICAL] - Access Denied! | statuscode=401\nexit status 2\n",
expected: "[CRITICAL] - states: critical=1\n\\_ [CRITICAL] Access Denied!\n\nexit status 2\n",
},
{
name: "health-basic-auth-wrong-use",
Expand All @@ -158,7 +158,7 @@ func TestHealthCmd(t *testing.T) {
actual := string(out)

if actual != test.expected {
t.Error("\nActual: ", actual, "\nExpected: ", test.expected)
t.Errorf("\nActual:\n%#v\nExpected:\n%#v\n", actual, test.expected)
}

})
Expand Down
Loading

0 comments on commit 2fdf5d8

Please sign in to comment.