summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/smartctl/exec.go
blob: a90e1b529bde88b158f5d1e9d6f006bed8efff49 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// SPDX-License-Identifier: GPL-3.0-or-later

package smartctl

import (
	"context"
	"errors"
	"fmt"
	"os/exec"
	"time"

	"github.com/netdata/netdata/go/go.d.plugin/logger"

	"github.com/tidwall/gjson"
)

func newSmartctlCliExec(ndsudoPath string, timeout time.Duration, log *logger.Logger) *smartctlCliExec {
	return &smartctlCliExec{
		Logger:     log,
		ndsudoPath: ndsudoPath,
		timeout:    timeout,
	}
}

type smartctlCliExec struct {
	*logger.Logger

	ndsudoPath string
	timeout    time.Duration
}

func (e *smartctlCliExec) scan() (*gjson.Result, error) {
	return e.execute("smartctl-json-scan")
}

func (e *smartctlCliExec) deviceInfo(deviceName, deviceType, powerMode string) (*gjson.Result, error) {
	return e.execute("smartctl-json-device-info",
		"--deviceName", deviceName,
		"--deviceType", deviceType,
		"--powerMode", powerMode,
	)
}

func (e *smartctlCliExec) execute(args ...string) (*gjson.Result, error) {
	ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
	defer cancel()

	cmd := exec.CommandContext(ctx, e.ndsudoPath, args...)
	e.Debugf("executing '%s'", cmd)

	bs, err := cmd.Output()
	if err != nil {
		if errors.Is(err, context.DeadlineExceeded) || isExecExitCode(err, 1) || len(bs) == 0 {
			return nil, fmt.Errorf("'%s' execution failed: %v", cmd, err)
		}
	}
	if len(bs) == 0 {
		return nil, fmt.Errorf("'%s' returned no output", cmd)
	}

	if !gjson.ValidBytes(bs) {
		return nil, fmt.Errorf("'%s' returned invalid JSON output", cmd)
	}

	res := gjson.ParseBytes(bs)
	if !res.Get("smartctl.exit_status").Exists() {
		return nil, fmt.Errorf("'%s' returned unexpected data", cmd)
	}

	for _, msg := range res.Get("smartctl.messages").Array() {
		if msg.Get("severity").String() == "error" {
			return &res, fmt.Errorf("'%s' reported an error: %s", cmd, msg.Get("string"))
		}
	}

	return &res, nil
}

func isExecExitCode(err error, exitCode int) bool {
	var v *exec.ExitError
	return errors.As(err, &v) && v.ExitCode() == exitCode
}