Skip to content
Open
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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ See the [documentation on pkg.go.dev](https://pkg.go.dev/github.com/NETWAYS/go-c
package main

import (
"fmt"
"github.com/NETWAYS/go-check"
)

Expand All @@ -33,7 +34,7 @@ func main() {
config.ParseArguments()

// Some checking should be done here, when --help is not passed
check.Exitf(check.OK, "Everything is fine - answer=%d", 42)
check.Exit(check.OK, fmt.Sprintf("Everything is fine - answer=%d", 42))
// Output:
// OK - Everything is fine - answer=42
}
Expand All @@ -42,9 +43,9 @@ func main() {
## Exit Codes

```
check.Exitf(OK, "Everything is fine - value=%d", 42) // OK, 0
check.Exit(OK, fmt.Sprintf("Everything is fine - value=%d", 42)) // OK, 0

check.ExitRaw(check.Critical, "CRITICAL", "|", "percent_packet_loss=100") // CRITICAL, 2
check.Exit(check.Critical, "CRITICAL", "|", "percent_packet_loss=100") // CRITICAL, 2

err := fmt.Errorf("connection to %s has been timed out", "localhost:12345")

Expand Down
3 changes: 2 additions & 1 deletion config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package check

import (
"fmt"
"os"
"testing"
)
Expand All @@ -17,7 +18,7 @@ func ExampleConfig() {

// Some checking should be done here

Exitf(OK, "Everything is fine - answer=%d", 42)
Exit(OK, fmt.Sprintf("Everything is fine - answer=%d", 42))

// Output: [OK] - Everything is fine - answer=42
// would exit with code 0
Expand Down
10 changes: 6 additions & 4 deletions examples/check_example/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package main

import (
"github.com/NETWAYS/go-check"
"fmt"
"log"

"github.com/NETWAYS/go-check"
)

func main() {
Expand All @@ -25,10 +27,10 @@ func main() {
// time.Sleep(20 * time.Second)

if *value > *critical {
check.Exitf(check.Critical, "value is %d", *value)
check.Exit(check.Critical, fmt.Sprintf("value is %d", *value))
} else if *value > *warning {
check.Exitf(check.Warning, "value is %d", *value)
check.Exit(check.Warning, fmt.Sprintf("value is %d", *value))
} else {
check.Exitf(check.OK, "value is %d", *value)
check.Exit(check.OK, fmt.Sprintf("value is %d", *value))
}
}
2 changes: 1 addition & 1 deletion examples/check_example/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func TestMyMain(t *testing.T) {
actual := testhelper.RunMainTest(main, "--help")
expected := `would exit with code 3`
expected := `pflag: help requested`

if !strings.Contains(actual, expected) {
t.Fatalf("expected %v, got %v", expected, actual)
Expand Down
2 changes: 1 addition & 1 deletion examples/check_example2/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ func main() {
overall.AddSubcheck(check1)
overall.AddSubcheck(check2)

check.ExitRaw(overall.GetStatus(), overall.GetOutput())
check.Exit(overall.GetStatus(), overall.GetOutput())
}
28 changes: 9 additions & 19 deletions exit.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,25 @@ import (
"fmt"
"os"
"runtime/debug"
"strconv"
"strings"
)

// AllowExit lets you disable the call to os.Exit() in ExitXxx() functions of this package.
//
// This should be used carefully and most likely only for testing.
var AllowExit = true

// PrintStack prints the error stack when recovering from a panic with CatchPanic()
var PrintStack = true

// Exitf prints the plugin output using formatting and exits the program.
//
// Output is the formatting string, and the rest of the arguments help adding values.
//
// Also see fmt package: https://golang.org/pkg/fmt
func Exitf(rc int, output string, args ...interface{}) {
ExitRaw(rc, fmt.Sprintf(output, args...))
}

// ExitRaw prints the plugin output with the state prefixed and exits the program.
// Exit prints the plugin output with the state prefixed and exits the program.
//
// Example:
//
// OK - everything is fine
func ExitRaw(rc int, output ...string) {
func Exit(rc Status, output ...string) {
var text strings.Builder

text.WriteString("[" + StatusText(rc) + "] -")
text.WriteString("[" + rc.String() + "] -")

for _, s := range output {
text.WriteString(" " + s)
Expand All @@ -49,17 +38,18 @@ func ExitRaw(rc int, output ...string) {
// BaseExit exits the process with a given return code.
//
// Can be controlled with the global AllowExit
func BaseExit(rc int) {
func BaseExit(rc Status) {
if AllowExit {
os.Exit(rc)
os.Exit(int(rc))
}

_, _ = os.Stdout.WriteString("would exit with code " + strconv.Itoa(rc) + "\n")
o := fmt.Sprintf("would exit with code %d\n", rc)
_, _ = os.Stdout.WriteString(o)
}

// ExitError exists with an Unknown state while reporting the error
func ExitError(err error) {
Exitf(Unknown, "%s (%T)", err.Error(), err)
Exit(Unknown, fmt.Sprintf("%s (%T)", err.Error(), err))
}

// CatchPanic is a general function for defer, to capture any panic that occurred during runtime of a check
Expand All @@ -81,6 +71,6 @@ func CatchPanic() {
output += "\n\n" + string(debug.Stack())
}

ExitRaw(Unknown, output)
Exit(Unknown, output)
}
}
14 changes: 1 addition & 13 deletions exit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,11 @@ import (
)

func ExampleExit() {
Exitf(OK, "Everything is fine - value=%d", 42)
Exit(OK, fmt.Sprintf("Everything is fine - value=%d", 42))
// Output: [OK] - Everything is fine - value=42
// would exit with code 0
}

func ExampleExitf() {
Exitf(OK, "Everything is fine - value=%d", 42)
// Output: [OK] - Everything is fine - value=42
// would exit with code 0
}

func ExampleExitRaw() {
ExitRaw(OK, "Everything is fine")
// Output: [OK] - Everything is fine
// would exit with code 0
}

func ExampleExitError() {
err := fmt.Errorf("connection to %s has been timed out", "localhost:12345")
ExitError(err)
Expand Down
30 changes: 14 additions & 16 deletions result/overall.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// result tries to
package result

import (
"errors"
"fmt"
"strconv"
"strings"

"github.com/NETWAYS/go-check"
Expand Down Expand Up @@ -39,10 +37,10 @@ type PartialResult struct {
Perfdata perfdata.PerfdataList
PartialResults []PartialResult
Output string
state int // Result state, either set explicitly or derived from partialResults
defaultState int // Default result state, if no partial results are available and no state is set explicitly
stateSetExplicitly bool // nolint: unused
defaultStateSet bool // nolint: unused
state check.Status // Result state, either set explicitly or derived from partialResults
defaultState check.Status // Default result state, if no partial results are available and no state is set explicitly
stateSetExplicitly bool // nolint: unused
defaultStateSet bool // nolint: unused
}

// Initializer for a PartialResult with "sane" defaults
Expand All @@ -56,13 +54,13 @@ func NewPartialResult() PartialResult {

// String returns the status and output of the PartialResult
func (s *PartialResult) String() string {
return fmt.Sprintf("[%s] %s", check.StatusText(s.GetStatus()), s.Output)
return fmt.Sprintf("[%s] %s", s.GetStatus(), s.Output)
}

// Add adds a return state explicitly
//
// Hint: This will set stateSetExplicitly to true
func (o *Overall) Add(state int, output string) {
func (o *Overall) Add(state check.Status, output string) {
switch state {
case check.OK:
o.oks++
Expand All @@ -77,7 +75,7 @@ func (o *Overall) Add(state int, output string) {
// TODO: Might be a bit obscure that the Add method also sets stateSetExplicitly
o.stateSetExplicitly = true

o.Outputs = append(o.Outputs, fmt.Sprintf("[%s] %s", check.StatusText(state), output))
o.Outputs = append(o.Outputs, fmt.Sprintf("[%s] %s", state, output))
}

// AddSubcheck adds a PartialResult to the Overall
Expand All @@ -91,7 +89,7 @@ func (s *PartialResult) AddSubcheck(subcheck PartialResult) {
}

// GetStatus returns the current state (ok, warning, critical, unknown) of the Overall
func (o *Overall) GetStatus() int {
func (o *Overall) GetStatus() check.Status {
if o.stateSetExplicitly {
// nolint: gocritic
if o.criticals > 0 {
Expand Down Expand Up @@ -263,9 +261,9 @@ func (o *Overall) GetOutput() string {
}

// SetDefaultState sets a new default state for a PartialResult
func (s *PartialResult) SetDefaultState(state int) error {
func (s *PartialResult) SetDefaultState(state check.Status) error {
if state < check.OK || state > check.Unknown {
return errors.New("Default State is not a valid result state. Got " + strconv.Itoa(state) + " which is not valid")
return errors.New("Default State is not a valid result state. Got " + state.String() + " which is not valid")
}

s.defaultState = state
Expand All @@ -275,9 +273,9 @@ func (s *PartialResult) SetDefaultState(state int) error {
}

// SetState sets a state for a PartialResult
func (s *PartialResult) SetState(state int) error {
func (s *PartialResult) SetState(state check.Status) error {
if state < check.OK || state > check.Unknown {
return errors.New("Default State is not a valid result state. Got " + strconv.Itoa(state) + " which is not valid")
return errors.New("Default State is not a valid result state. Got " + state.String() + " which is not valid")
}

s.state = state
Expand All @@ -288,7 +286,7 @@ func (s *PartialResult) SetState(state int) error {

// GetStatus returns the current state (ok, warning, critical, unknown) of the PartialResult
// nolint: unused
func (s *PartialResult) GetStatus() int {
func (s *PartialResult) GetStatus() check.Status {
if s.stateSetExplicitly {
return s.state
}
Expand All @@ -301,7 +299,7 @@ func (s *PartialResult) GetStatus() int {
return check.Unknown
}

states := make([]int, len(s.PartialResults))
states := make([]check.Status, len(s.PartialResults))

for i := range s.PartialResults {
states[i] = s.PartialResults[i].GetStatus()
Expand Down
46 changes: 24 additions & 22 deletions result/overall_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,51 +66,53 @@ func TestOverall_AddUnknown(t *testing.T) {
}

func TestOverall_GetStatus_GetSummary(t *testing.T) {
testcases := []struct {
testcases := map[string]struct {
actual Overall
expectedSummary string
expectedStatus int
expectedStatus check.Status
}{
{
"No status information": {
actual: Overall{},
expectedSummary: "No status information",
expectedStatus: 3,
expectedStatus: check.Unknown,
},
{
"states: ok=1": {
actual: Overall{oks: 1, stateSetExplicitly: true},
expectedSummary: "states: ok=1",
expectedStatus: 0,
expectedStatus: check.OK,
},
{
"states: critical=2 unknown=1 warning=2 ok=1": {
actual: Overall{criticals: 2, oks: 1, warnings: 2, unknowns: 1, stateSetExplicitly: true},
expectedSummary: "states: critical=2 unknown=1 warning=2 ok=1",
expectedStatus: 2,
expectedStatus: check.Critical,
},
{
"states: unknown=2 warning=2 ok=1": {
actual: Overall{unknowns: 2, oks: 1, warnings: 2, stateSetExplicitly: true},
expectedSummary: "states: unknown=2 warning=2 ok=1",
expectedStatus: 3,
expectedStatus: check.Unknown,
},
{
"states: warning=2 ok=1": {
actual: Overall{oks: 1, warnings: 2, stateSetExplicitly: true},
expectedSummary: "states: warning=2 ok=1",
expectedStatus: 1,
expectedStatus: check.Warning,
},
{
"foobar": {
actual: Overall{Summary: "foobar"},
expectedSummary: "foobar",
expectedStatus: 3,
expectedStatus: check.Unknown,
},
}

for _, test := range testcases {
if test.expectedStatus != test.actual.GetStatus() {
t.Fatalf("expected %d, got %d", test.expectedStatus, test.actual.GetStatus())
}
for name, test := range testcases {
t.Run(name, func(t *testing.T) {
if test.expectedSummary != test.actual.GetSummary() {
t.Fatalf("expected summary %s, got %s", test.expectedSummary, test.actual.GetSummary())
}

if test.expectedSummary != test.actual.GetSummary() {
t.Fatalf("expected %s, got %s", test.expectedSummary, test.actual.GetSummary())
}
if test.expectedStatus != test.actual.GetStatus() {
t.Fatalf("expected status %d, got %d", test.expectedStatus, test.actual.GetStatus())
}
})
}
}

Expand Down Expand Up @@ -176,7 +178,7 @@ func ExampleOverall_GetStatus() {
overall.Add(check.Critical, "The other is critical")

fmt.Println(overall.GetStatus())
// Output: 2
// Output: CRITICAL
}

func ExampleOverall_withSubchecks() {
Expand Down
4 changes: 2 additions & 2 deletions result/worst.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import "github.com/NETWAYS/go-check"
// few numbers for various checks.
//
// Order of preference: Critical, Unknown, Warning, Ok
func WorstState(states ...int) int {
overall := -1
func WorstState(states ...check.Status) check.Status {
overall := check.Invalid
// nolint: gocritic
for _, state := range states {
if state == check.Critical {
Expand Down
Loading
Loading