-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathshellfunc.go
More file actions
190 lines (165 loc) · 4.61 KB
/
shellfunc.go
File metadata and controls
190 lines (165 loc) · 4.61 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
// Ultimate Provisioner: UP cmd
// Copyright (c) 2019 Stephen Cheng and contributors
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
package impl
import (
"bytes"
"context"
"github.com/fatih/color"
ms "github.com/mitchellh/mapstructure"
"github.com/upcmd/up/model/core"
u "github.com/upcmd/up/utils"
"io"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
)
func runCmd(f *ShellFuncAction, cmd string, idx1 int) {
var result u.ExecResult
result.Cmd = cmd
if TaskerRuntime().Tasker.Dryrun {
u.Pdryrun("in dryrun mode and skipping the actual commands")
result.Code = 0
result.Output = strings.TrimSpace("dryrun result")
} else {
switch u.MainConfig.ShellType {
case "GOSH":
envvarObjMap := f.Vars.GetPrefixMatched("envVar_")
envVars := map[string]string{}
for k, v := range *envvarObjMap {
envVars[k] = v.(string)
}
result = u.RunCmd(cmd,
"",
&envVars,
)
u.Pfv("%s\n", color.HiGreenString("%s", result.Output))
default:
defaultTimeout, _ := strconv.Atoi(ConfigRuntime().Timeout)
timeout := func() time.Duration {
var t int
if f.Timeout == 0 {
t = defaultTimeout
} else {
t = f.Timeout
u.LogWarn("explicit timeout:", u.Spf("%d milli seconds", t))
}
return time.Duration(t)
}()
ctx, cancel := context.WithTimeout(context.Background(), timeout*time.Millisecond)
defer cancel()
cmdExec := exec.CommandContext(ctx, u.MainConfig.ShellType, "-c", cmd)
func() {
//inject the envvars
cmdExec.Env = os.Environ()
envvarObjMap := f.Vars.GetPrefixMatched("envVar_")
for k, v := range *envvarObjMap {
cmdExec.Env = append(cmdExec.Env, u.Spf("%s=%s", k, v.(string)))
}
}()
cmdExec.Stdin = os.Stdin
stdout, err := cmdExec.StdoutPipe()
if err != nil {
u.LogError("stdout pipe", err)
}
stderr, stderrErr := cmdExec.StderrPipe()
if err != nil {
u.LogError("stderr pipe", err)
}
if err = cmdExec.Start(); err != nil {
u.LogError("exec started", err)
}
u.PlnInfo("-")
outputResult := asyncStdReader("stdout", stdout, err, color.HiGreenString, idx1)
stdErrorResult := asyncStdReader("stderr", stderr, stderrErr, color.HiRedString, idx1)
u.PlnInfo("\n-")
err = cmdExec.Wait()
if ctx.Err() == context.DeadlineExceeded {
u.LogWarn("timeout", "shell execution timed out")
}
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
result.Code = exitError.ExitCode()
if len(stdErrorResult) > 0 {
result.ErrMsg = stdErrorResult
} else {
result.ErrMsg = err.Error()
}
}
} else {
result.Code = 0
}
result.Output = outputResult
}
}
f.Result = u.ExecResult{
ErrMsg: strings.TrimSpace(result.ErrMsg),
Output: strings.TrimSpace(result.Output),
Cmd: result.Cmd,
Code: result.Code,
}
}
func asyncStdReader(readtype string, ch io.ReadCloser, err error, colorfunc func(format string, a ...interface{}) string, idx1 int) string {
var result *bytes.Buffer = bytes.NewBufferString("")
buff := make([]byte, 5120)
var n int
for err == nil {
n, err = ch.Read(buff)
if n > 0 {
if !(u.Contains(*StepRuntime().Flags, FLAG_SILENT) && readtype == "stdout") {
if u.Contains(*StepRuntime().Flags, u.Spf("%s-%d", FLAG_SILENT, idx1)) && readtype == "stdout" {
} else {
u.Pfv("%s", colorfunc("%s", string(buff[:n])))
}
}
result.Write(buff[:n])
}
}
return result.String()
}
type ShellFuncAction struct {
Do interface{}
Vars *core.Cache
Cmds []string
Result u.ExecResult
Timeout int
}
//adapt the abstract step.Do to concrete ShellFuncAction Cmds
func (f *ShellFuncAction) Adapt() {
var cmd string
var cmds []string
f.Timeout = StepRuntime().Timeout
switch f.Do.(type) {
case string:
cmd = f.Do.(string)
cmds = append(cmds, cmd)
case []interface{}:
err := ms.Decode(f.Do, &cmds)
u.LogError("shell adapter", err)
default:
u.LogWarn("shell", "Not implemented or void for no action!")
}
f.Cmds = cmds
}
func (f *ShellFuncAction) Exec() {
for idx, tcmd := range f.Cmds {
u.Pfv("cmd(%2d):\n", idx+1)
u.Pvv(tcmd)
cleansed := func() string {
re := regexp.MustCompile(`{{.*\.secure_.*}}`)
return re.ReplaceAllString(tcmd, `SECURE_SENSITIVE_INFO_MASKED`)
}()
cmd := Render(tcmd, f.Vars)
cleansedCmd := Render(cleansed, f.Vars)
u.Pfvvvv("cmd=>:\n%s\n", color.HiBlueString("%s", cleansedCmd))
runCmd(f, cmd, idx+1)
u.SubStepStatus("..", f.Result.Code)
u.Dvvvvv(f.Result)
}
StepRuntime().Result = &f.Result
}