summaryrefslogtreecommitdiff
path: root/internal/check.go
blob: a9efd299da5350e4c5c65b7b674f02f46c3e0298 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package internal

import (
	"bytes"
	"context"
	"os/exec"
	"strings"
)

type check struct {
	Plugin    string
	Args      []string
	DependsOn []string `json:"DependsOn,omitempty"`
}

type namedCheck struct {
	check
	name string
}

type checkResult struct {
	name   string
	output string
	status nagiosCode
}

func (c check) run(ctx context.Context, name string) checkResult {
	cmd := exec.CommandContext(ctx, c.Plugin, c.Args...)

	var bytes bytes.Buffer
	cmd.Stdout = &bytes
	cmd.Stderr = &bytes

	if err := cmd.Run(); err != nil {
		if ctx.Err() == context.DeadlineExceeded {
			return checkResult{name, "Check command timed out", critical}
		}
	}

	// Remove Nagios perf data from output and trim whitespaces
	parts := strings.Split(bytes.String(), "|")
	output := strings.TrimSpace(parts[0])

	return checkResult{name, output, nagiosCode(cmd.ProcessState.ExitCode())}
}

func (c check) skip(name, output string) checkResult {
	return checkResult{name, output, unknown}
}

func (c namedCheck) run(ctx context.Context) checkResult {
	return c.check.run(ctx, c.name)
}

func (c namedCheck) skip(output string) checkResult {
	return c.check.skip(c.name, output)
}