-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.go
More file actions
62 lines (51 loc) · 1.66 KB
/
executor.go
File metadata and controls
62 lines (51 loc) · 1.66 KB
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
package machineid
import (
"context"
"log/slog"
"os/exec"
"strings"
"time"
)
// defaultCommandExecutor implements CommandExecutor using actual system command execution.
type defaultCommandExecutor struct {
Timeout time.Duration
}
// Execute runs a system command with a timeout and returns the output.
// It uses context.WithTimeout to prevent commands from hanging indefinitely.
func (e *defaultCommandExecutor) Execute(ctx context.Context, name string, args ...string) (string, error) {
timeout := e.Timeout
if timeout <= 0 {
timeout = defaultTimeout
}
timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(timeoutCtx, name, args...)
output, err := cmd.Output()
if err != nil {
return "", &CommandError{Command: name, Err: err}
}
return strings.TrimSpace(string(output)), nil
}
// executeCommand is a convenience wrapper that calls Execute with the given context.
// This function is used by platform-specific collectors that need the Provider's executor.
func executeCommand(ctx context.Context, executor CommandExecutor, logger *slog.Logger, name string, args ...string) (string, error) {
if executor == nil {
executor = &defaultCommandExecutor{
Timeout: defaultTimeout,
}
}
if logger != nil {
logger.Debug("executing command", "command", name, "args", args)
}
start := time.Now()
result, err := executor.Execute(ctx, name, args...)
duration := time.Since(start)
if logger != nil {
if err != nil {
logger.Debug("command failed", "command", name, "duration", duration, "error", err)
} else {
logger.Debug("command completed", "command", name, "duration", duration)
}
}
return result, err
}