-
Notifications
You must be signed in to change notification settings - Fork 14
/
cli.go
77 lines (67 loc) · 2.01 KB
/
cli.go
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
// Copyright 2022 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package worker
import (
"bytes"
"context"
"os/exec"
"time"
"github.com/mendersoftware/workflows/app/processor"
"github.com/mendersoftware/workflows/model"
)
const (
// MaxExecutionTime is the maximum number of seconds a task can run
MaxExecutionTime int = 3600 * 4
)
func processCLITask(
cliTask *model.CLITask,
ps *processor.JobStringProcessor,
jp *processor.JobProcessor,
) (*model.TaskResult, error) {
commands := make([]string, 0, 10)
for _, command := range cliTask.Command {
command := ps.ProcessJobString(command)
commands = append(commands, command)
}
ctx := context.Background()
timeout := cliTask.ExecutionTimeOut
if timeout <= 0 {
timeout = MaxExecutionTime
}
ctxWithOptionalTimeOut, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
defer cancel()
var result *model.TaskResult = &model.TaskResult{
CLI: &model.TaskResultCLI{
Command: commands,
},
}
cmd := exec.CommandContext(ctxWithOptionalTimeOut, commands[0], commands[1:]...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
result.Success = false
if exiterr, ok := err.(*exec.ExitError); ok {
result.CLI.ExitCode = exiterr.ExitCode()
} else {
result.CLI.ExitCode = -1
}
} else {
result.Success = true
result.CLI.ExitCode = 0
}
result.CLI.Output = stdout.String()
result.CLI.Error = stderr.String()
return result, nil
}