-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathcommand.go
More file actions
233 lines (196 loc) · 6.83 KB
/
command.go
File metadata and controls
233 lines (196 loc) · 6.83 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2023 NetApp, Inc. All Rights Reserved.
package exec
//go:generate mockgen -destination=../../mocks/mock_utils/mock_exec/mock_command.go github.com/netapp/trident/utils/exec Command
import (
"context"
"fmt"
"os/exec"
"regexp"
"strings"
"time"
. "github.com/netapp/trident/logging"
"github.com/netapp/trident/utils/errors"
)
var (
xtermControlRegex = regexp.MustCompile(`\x1B\[[0-9;]*[a-zA-Z]`)
// Ensure these structures always implement these interfaces at compilation.
_ Command = NewCommand()
_ ExitError = &exec.ExitError{}
)
// ExitError defines the methods that exec.ExitError implements.
// This enables unit testing and mocking of exit codes.
type ExitError interface {
error
ExitCode() int
}
// Command defines a set of behaviors for executing commands on a host.
type Command interface {
Execute(ctx context.Context, name string, args ...string) ([]byte, error)
ExecuteRedacted(
ctx context.Context, name string, args []string,
secretsToRedact map[string]string,
) ([]byte, error)
ExecuteWithTimeout(
ctx context.Context, name string, timeout time.Duration, logOutput bool, args ...string,
) ([]byte, error)
ExecuteWithTimeoutAndInput(
ctx context.Context, name string, timeout time.Duration, logOutput bool, stdin string, args ...string,
) ([]byte, error)
ExecuteWithoutLog(ctx context.Context, name string, args ...string) ([]byte, error)
}
// command is a receiver for the Command interface.
type command struct {
executor func(ctx context.Context, name string, args ...string) *exec.Cmd
}
// NewCommand returns a concrete client for executing OS-level commands.
func NewCommand() Command {
return &command{
executor: exec.CommandContext,
}
}
// Execute invokes an external process.
func (c *command) Execute(ctx context.Context, name string, args ...string) ([]byte, error) {
Logc(ctx).WithFields(LogFields{
"command": name,
"args": args,
}).Debug(">>>> command.Execute.")
// create context with a cancellation
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
out, err := c.executor(cancelCtx, name, args...).CombinedOutput()
Logc(ctx).WithFields(LogFields{
"command": name,
"output": sanitizeExecOutput(string(out)),
"error": err,
}).Debug("<<<< Execute.")
return out, err
}
// ExecuteRedacted invokes an external process, and redacts sensitive arguments.
func (c *command) ExecuteRedacted(
ctx context.Context, name string, args []string,
secretsToRedact map[string]string,
) ([]byte, error) {
var sanitizedArgs []string
for _, arg := range args {
val, ok := secretsToRedact[arg]
var sanitizedArg string
if ok {
sanitizedArg = val
} else {
sanitizedArg = arg
}
sanitizedArgs = append(sanitizedArgs, sanitizedArg)
}
Logc(ctx).WithFields(LogFields{
"command": name,
"args": sanitizedArgs,
}).Debug(">>>> command.ExecuteRedacted.")
// create context with a cancellation
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
out, err := c.executor(cancelCtx, name, args...).CombinedOutput()
Logc(ctx).WithFields(LogFields{
"command": name,
"output": sanitizeExecOutput(string(out)),
"error": err,
}).Debug("<<<< command.ExecuteRedacted.")
return out, err
}
// ExecuteWithTimeout invokes an external shell command and lets it time out if it exceeds the
// specified interval.
func (c *command) ExecuteWithTimeout(
ctx context.Context, name string, timeout time.Duration, logOutput bool, args ...string,
) ([]byte, error) {
Logc(ctx).WithFields(LogFields{
"command": name,
"timeout": timeout,
"args": args,
}).Debug(">>>> command.ExecuteWithTimeout.")
defer Logc(ctx).Debug("<<<< command.ExecuteWithTimeout.")
return c.executeWithTimeoutAndInput(ctx, name, timeout, logOutput, "", args...)
}
// ExecuteWithTimeoutAndInput invokes an external shell command and lets it time out if it exceeds the
// specified interval.
func (c *command) ExecuteWithTimeoutAndInput(
ctx context.Context, name string, timeout time.Duration, logOutput bool, stdin string, args ...string,
) ([]byte, error) {
Logc(ctx).WithFields(LogFields{
"command": name,
"timeoutSeconds": timeout,
"args": args,
}).Debug(">>>> command.ExecuteWithTimeoutAndInput.")
defer Logc(ctx).Debug("<<<< command.ExecuteWithTimeoutAndInput.")
return c.executeWithTimeoutAndInput(ctx, name, timeout, logOutput, stdin, args...)
}
// executeWithTimeoutAndInput is a common handler for invoking external shell commands with timeouts.
// It lets commands time out if they exceed the specified interval.
func (c *command) executeWithTimeoutAndInput(
ctx context.Context, name string, timeout time.Duration, logOutput bool, stdin string, args ...string,
) ([]byte, error) {
// Create context with a cancellation.
cancelCtx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// execCommandResult is used to return shell command results via channels between goroutines.
type execCommandResult struct {
Output []byte
Error error
}
cmd := c.executor(cancelCtx, name, args...)
cmd.Stdin = strings.NewReader(stdin)
done := make(chan execCommandResult, 1)
var result execCommandResult
go func() {
out, err := cmd.CombinedOutput()
done <- execCommandResult{Output: out, Error: err}
}()
select {
case <-cancelCtx.Done():
if err := cancelCtx.Err(); err == context.DeadlineExceeded {
Logc(ctx).WithFields(LogFields{
"process": name,
}).Error("process killed after timeout")
result = execCommandResult{Output: nil, Error: errors.TimeoutError("process killed after timeout")}
} else {
Logc(ctx).WithFields(LogFields{
"process": name,
"error": err,
}).Error("context ended unexpectedly")
result = execCommandResult{Output: nil, Error: fmt.Errorf("context ended unexpectedly: %v", err)}
}
case result = <-done:
break
}
logFields := Logc(ctx).WithFields(LogFields{
"command": name,
"error": result.Error,
})
if logOutput {
logFields.WithFields(LogFields{
"output": sanitizeExecOutput(string(result.Output)),
})
}
return result.Output, result.Error
}
func sanitizeExecOutput(s string) string {
// Strip xterm color & movement characters
s = xtermControlRegex.ReplaceAllString(s, "")
// Strip trailing newline
s = strings.TrimSuffix(s, "\n")
return s
}
// ExecuteWithoutLog invokes an external process, and does not log output returned by the command.
func (c *command) ExecuteWithoutLog(ctx context.Context, name string, args ...string) ([]byte, error) {
Logc(ctx).WithFields(LogFields{
"command": name,
"args": args,
}).Debug(">>>> command.ExecuteWithoutLog")
// create context with a cancellation
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
out, err := c.executor(cancelCtx, name, args...).CombinedOutput()
Logc(ctx).WithFields(LogFields{
"command": name,
"error": err,
}).Debug("<<<< command.ExecuteWithoutLog")
return out, err
}