Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 30 additions & 27 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
run:
timeout: 5m
skip-files:
- '(.+)_test\.go'

tests: false
linters:
disable-all: false
enable:
- funlen
- dogsled
- dupl
# - lll
- whitespace
- wsl
- exportloopref
disable:
- scopelint
- bodyclose
- contextcheck
- nilerr
- noctx
- rowserrcheck
- sqlclosecheck
- structcheck
- unparam
presets:
- bugs
- unused
# - style
fast: false
enable-all: true
disable:
- cyclop
- depguard
- exhaustivestruct
- exhaustruct
- forbidigo
- forcetypeassert
- gci
- gochecknoglobals
- gochecknoinits
- godox
- goerr113
- gofumpt
- gomnd
- lll
- musttag
- nakedret
- nlreturn
- nolintlint
- nonamedreturns
- tagliatelle
- varnamelen
- wrapcheck
linters-settings:
estif:
min-complexity: 4
maligned:
suggest-new: true
7 changes: 4 additions & 3 deletions cmd/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package cmd

import (
"fmt"
"strings"

"github.com/NETWAYS/check_prometheus/internal/alert"
"github.com/NETWAYS/go-check"
"github.com/NETWAYS/go-check/perfdata"
"github.com/NETWAYS/go-check/result"
"github.com/spf13/cobra"
"strings"
)

func generateOutput(rl alert.Rule, cfg AlertConfig) (output string) {
Expand Down Expand Up @@ -78,7 +79,7 @@ inactive = 0`,
// We use the Rules endpoint since it contains
// the state of inactive Alert Rules, unlike the Alert endpoint
// Search requested Alert in all Groups and all Rules
alerts, err := c.Api.Rules(ctx)
alerts, err := c.API.Rules(ctx)
if err != nil {
check.ExitError(err)
}
Expand All @@ -89,7 +90,7 @@ inactive = 0`,
// Set initial capacity to reduce memory allocations
var l int
for _, rl := range rules {
l = l * len(rl.AlertingRule.Alerts)
l *= len(rl.AlertingRule.Alerts)
}
rStates := make([]int, 0, l)

Expand Down
10 changes: 5 additions & 5 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ type Config struct {
CertFile string
KeyFile string
Hostname string
Port int
Info bool
Insecure bool
PReady bool
Port int
Secure bool
}

Expand Down Expand Up @@ -95,20 +95,20 @@ func (c *Config) NewClient() *client.Client {

// Using a Bearer Token for authentication
if c.Bearer != "" {
var t config.Secret = config.Secret(c.Bearer)
var t = config.Secret(c.Bearer)
rt = config.NewAuthorizationCredentialsRoundTripper("Bearer", t, rt)
}

// Using a BasicAuth for authentication
if c.BasicAuth != "" {
s := strings.Split(c.BasicAuth, ":")
if len(s) != 2 {
check.ExitError(fmt.Errorf("Specify the user name and password for server authentication <user:password>"))
check.ExitError(fmt.Errorf("specify the user name and password for server authentication <user:password>"))
}

var u string = s[0]
var u = s[0]

var p config.Secret = config.Secret(s[1])
var p = config.Secret(s[1])

rt = config.NewBasicAuthRoundTripper(u, p, "", rt)
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
func TestConfig(t *testing.T) {
c := cliConfig.NewClient()
expected := "http://localhost:9090"
if c.Url != "http://localhost:9090" {
t.Error("\nActual: ", c.Url, "\nExpected: ", expected)
if c.URL != "http://localhost:9090" {
t.Error("\nActual: ", c.URL, "\nExpected: ", expected)
}
}
3 changes: 2 additions & 1 deletion cmd/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"fmt"

"github.com/NETWAYS/go-check"
"github.com/NETWAYS/go-check/perfdata"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -53,7 +54,7 @@ Ready: Checks the readiness of an endpoint, which returns OK if the Prometheus s

if cliConfig.Info {
// Displays various build information properties about the Prometheus server
info, err := c.Api.Buildinfo(ctx)
info, err := c.API.Buildinfo(ctx)
if err != nil {
check.ExitError(err)
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestHealth_ConnectionRefused(t *testing.T) {
out, _ := cmd.CombinedOutput()

actual := string(out)
expected := "[UNKNOWN] - Could not get status: Get \"http://localhost:9999/-/healthy\": dial"
expected := "[UNKNOWN] - could not get status: Get \"http://localhost:9999/-/healthy\": dial"

if !strings.Contains(actual, expected) {
t.Error("\nActual: ", actual, "\nExpected: ", expected)
Expand Down Expand Up @@ -133,7 +133,7 @@ func TestHealthCmd(t *testing.T) {
w.Write([]byte(`Access Denied!`))
})),
args: []string{"run", "../main.go", "--user", "passwordmissing", "health"},
expected: "[UNKNOWN] - Specify the user name and password for server authentication <user:password> (*errors.errorString)\nexit status 3\n",
expected: "[UNKNOWN] - specify the user name and password for server authentication <user:password> (*errors.errorString)\nexit status 3\n",
},
}

Expand Down
23 changes: 11 additions & 12 deletions cmd/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package cmd

import (
"fmt"
"strings"
"time"

"github.com/NETWAYS/go-check"
"github.com/NETWAYS/go-check/perfdata"
goresult "github.com/NETWAYS/go-check/result"
"github.com/prometheus/common/model"
"github.com/spf13/cobra"
"strings"
"time"
)

type QueryConfig struct {
Expand Down Expand Up @@ -54,7 +55,7 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
| value_go_gc_duration_seconds_count_localhost:9090_prometheus=1599 value_go_gc_duration_seconds_count_node-exporter:9100_node-exporter=79610`,
PreRun: func(cmd *cobra.Command, args []string) {
if cliQueryConfig.Warning == "" || cliQueryConfig.Critical == "" {
check.ExitError(fmt.Errorf("Please specify warning and critical thresholds"))
check.ExitError(fmt.Errorf("please specify warning and critical thresholds"))
}
},
Run: func(cmd *cobra.Command, args []string) {
Expand Down Expand Up @@ -89,26 +90,26 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
ctx, cancel := cliConfig.timeoutContext()
defer cancel()

result, warnings, err := c.Api.Query(ctx, cliQueryConfig.RawQuery, time.Now())
result, warnings, err := c.API.Query(ctx, cliQueryConfig.RawQuery, time.Now())

if err != nil {
if strings.Contains(err.Error(), "unmarshalerDecoder: unexpected value type \"string\"") {
err = fmt.Errorf("String value results are not supported")
err = fmt.Errorf("string value results are not supported")
}
check.ExitError(err)
}

switch result.Type() {
default:
check.ExitError(fmt.Errorf("None value results are not supported"))
check.ExitError(fmt.Errorf("none value results are not supported"))
// Scalar - a simple numeric floating point value
case model.ValScalar:
check.ExitError(fmt.Errorf("Scalar value results are not supported"))
check.ExitError(fmt.Errorf("scalar value results are not supported"))
case model.ValNone:
check.ExitError(fmt.Errorf("None value results are not supported"))
check.ExitError(fmt.Errorf("none value results are not supported"))
case model.ValString:
// String - a simple string value; currently unused
check.ExitError(fmt.Errorf("String value results are not supported"))
check.ExitError(fmt.Errorf("string value results are not supported"))
case model.ValVector:
// Instant vector - a set of time series containing a single sample for each time series, all sharing the same timestamp
vectorVal := result.(model.Vector)
Expand Down Expand Up @@ -175,9 +176,7 @@ Note: Time range values e.G. 'go_memstats_alloc_bytes_total[0s]' only the latest
states = mStates
}

// The worst state of all metrics determines the final return state. Example:
// OK, OK, OK > OK
// Critical, OK, OK > Critical
// The worst state of all metrics determines the final return state.
worstState := goresult.WorstState(states...)
if worstState == check.OK {
summary.WriteString(fmt.Sprintf("%d Metrics OK", metricsCounter))
Expand Down
4 changes: 2 additions & 2 deletions cmd/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func TestQueryCmd(t *testing.T) {
w.Write([]byte(`{"status":"success","data":{"resultType":"scalar","result":[1670339013.992,"1"]}}`))
})),
args: []string{"run", "../main.go", "query", "--query", "1"},
expected: "[UNKNOWN] - Scalar value results are not supported (*errors.errorString)\nexit status 3\n",
expected: "[UNKNOWN] - scalar value results are not supported (*errors.errorString)\nexit status 3\n",
},
{
name: "query-string",
Expand All @@ -88,7 +88,7 @@ func TestQueryCmd(t *testing.T) {
w.Write([]byte(`{"status":"success","data":{"resultType":"string","result":[1670339013.992,"up"]}}`))
})),
args: []string{"run", "../main.go", "query", "--query", "up"},
expected: "[UNKNOWN] - String value results are not supported (*errors.errorString)\nexit status 3\n",
expected: "[UNKNOWN] - string value results are not supported (*errors.errorString)\nexit status 3\n",
},
{
name: "query-matrix-exists",
Expand Down
5 changes: 3 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package cmd

import (
"os"

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

var Timeout = 30
Expand Down Expand Up @@ -66,7 +67,7 @@ func init() {
rootCmd.SetHelpTemplate(help + Copyright)
}

func Usage(cmd *cobra.Command, strings []string) {
func Usage(cmd *cobra.Command, _ []string) {
_ = cmd.Usage()

os.Exit(3)
Expand Down
19 changes: 10 additions & 9 deletions internal/alert/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,28 @@ package alert

import (
"fmt"
"strconv"
"strings"

"github.com/NETWAYS/go-check"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"strconv"
"strings"
)

// Internal representation of Prometheus Rules
// Alert attribute will be used when iterating over multiple AlertingRules
// Internal representation of Prometheus Rules.
// Alert attribute will be used when iterating over multiple AlertingRules.
type Rule struct {
AlertingRule v1.AlertingRule
Alert *v1.Alert
}

func FlattenRules(groups []v1.RuleGroup) []Rule {
// Flattens a list of RuleGroup containing a list of Rules into
// a list of internal Alertingrules
// a list of internal Alertingrules.
var l int
// Set initial capacity to reduce memory allocations
// Set initial capacity to reduce memory allocations.
for _, grp := range groups {
l = l + len(grp.Rules)
l += len(grp.Rules)
}

rules := make([]Rule, 0, l)
Expand All @@ -31,8 +32,8 @@ func FlattenRules(groups []v1.RuleGroup) []Rule {

for _, grp := range groups {
for _, rl := range grp.Rules {
// For now we only care about AlertingRules
// since RecodingRules can simply be queried
// For now we only care about AlertingRules,
// since RecodingRules can simply be queried.
if _, ok := rl.(v1.AlertingRule); ok {
r.AlertingRule = rl.(v1.AlertingRule)
rules = append(rules, r)
Expand Down
5 changes: 3 additions & 2 deletions internal/alert/alert_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package alert

import (
"testing"
"time"

"github.com/NETWAYS/go-check"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"testing"
"time"
)

func TestGetStatus(t *testing.T) {
Expand Down
Loading