-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathemissary.go
322 lines (286 loc) · 9.52 KB
/
emissary.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package commands
import (
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/argoproj/argo-workflows/v3/util/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/client-go/util/retry"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/util/archive"
"github.com/argoproj/argo-workflows/v3/workflow/common"
osspecific "github.com/argoproj/argo-workflows/v3/workflow/executor/os-specific"
)
var (
varRunArgo = common.VarRunArgoPath
containerName = os.Getenv(common.EnvVarContainerName)
includeScriptOutput = os.Getenv(common.EnvVarIncludeScriptOutput) == "true" // capture stdout/combined
template = &wfv1.Template{}
logger = log.WithField("argo", true)
)
func NewEmissaryCommand() *cobra.Command {
return &cobra.Command{
Use: "emissary",
SilenceUsage: true, // this prevents confusing usage message being printed when we SIGTERM
RunE: func(cmd *cobra.Command, args []string) error {
exitCode := 64
defer func() {
err := ioutil.WriteFile(varRunArgo+"/ctr/"+containerName+"/exitcode", []byte(strconv.Itoa(exitCode)), 0o644)
if err != nil {
logger.Error(fmt.Errorf("failed to write exit code: %w", err))
}
}()
osspecific.AllowGrantingAccessToEveryone()
// Dir permission set to rwxrwxrwx, so that non-root wait container can also write kill signal to the folder.
// Note it's important varRunArgo+"/ctr/" folder is writable by all, because multiple containers may want to
// write to it with different users.
// This also indicates we've started.
if err := os.MkdirAll(varRunArgo+"/ctr/"+containerName, 0o777); err != nil {
return fmt.Errorf("failed to create ctr directory: %w", err)
}
name, args := args[0], args[1:]
data, err := ioutil.ReadFile(varRunArgo + "/template")
if err != nil {
return fmt.Errorf("failed to read template: %w", err)
}
if err := json.Unmarshal(data, template); err != nil {
return fmt.Errorf("failed to unmarshal template: %w", err)
}
for _, x := range template.ContainerSet.GetGraph() {
if x.Name == containerName {
for _, y := range x.Dependencies {
logger.Infof("waiting for dependency %q", y)
for {
data, err := ioutil.ReadFile(filepath.Clean(varRunArgo + "/ctr/" + y + "/exitcode"))
if os.IsNotExist(err) {
time.Sleep(time.Second)
continue
}
exitCode, err := strconv.Atoi(string(data))
if err != nil {
return fmt.Errorf("failed to read exit-code of dependency %q: %w", y, err)
}
if exitCode != 0 {
return fmt.Errorf("dependency %q exited with non-zero code: %d", y, exitCode)
}
break
}
}
}
}
name, err = exec.LookPath(name)
if err != nil {
return fmt.Errorf("failed to find name in PATH: %w", err)
}
if os.Getenv("ARGO_DEBUG_PAUSE_BEFORE") == "true" {
for {
// User can create the file: /ctr/NAME_OF_THE_CONTAINER/before
// in order to break out of the sleep and release the container from
// the debugging state.
if _, err := os.Stat(varRunArgo + "/ctr/" + containerName + "/before"); os.IsNotExist(err) {
time.Sleep(time.Second)
continue
}
break
}
}
backoff, err := template.GetRetryStrategy()
if err != nil {
return fmt.Errorf("failed to get retry strategy: %w", err)
}
cmdErr := retry.OnError(backoff, func(error) bool { return true }, func() error {
// setup signal handlers
signals := make(chan os.Signal, 1)
defer close(signals)
signal.Notify(signals)
defer signal.Reset()
command, closer, err := startCommand(name, args, template)
if err != nil {
return fmt.Errorf("failed to start command: %w", err)
}
defer closer()
go func() {
for s := range signals {
if osspecific.CanIgnoreSignal(s) {
logger.Debugf("ignore signal %s", s)
continue
}
logger.Debugf("forwarding signal %s", s)
_ = osspecific.Kill(command.Process.Pid, s.(syscall.Signal))
}
}()
pid := command.Process.Pid
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for {
select {
case <-ctx.Done():
return
default:
data, _ := ioutil.ReadFile(filepath.Clean(varRunArgo + "/ctr/" + containerName + "/signal"))
_ = os.Remove(varRunArgo + "/ctr/" + containerName + "/signal")
s, _ := strconv.Atoi(string(data))
if s > 0 {
_ = osspecific.Kill(pid, syscall.Signal(s))
}
time.Sleep(2 * time.Second)
}
}
}()
return osspecific.Wait(command.Process)
})
logger.WithError(err).Info("sub-process exited")
if os.Getenv("ARGO_DEBUG_PAUSE_AFTER") == "true" {
for {
// User can create the file: /ctr/NAME_OF_THE_CONTAINER/after
// in order to break out of the sleep and release the container from
// the debugging state.
if _, err := os.Stat(varRunArgo + "/ctr/" + containerName + "/after"); os.IsNotExist(err) {
time.Sleep(time.Second)
continue
}
break
}
}
if cmdErr == nil {
exitCode = 0
} else if exitError, ok := cmdErr.(errors.Exited); ok {
if exitError.ExitCode() >= 0 {
exitCode = exitError.ExitCode()
} else {
exitCode = 137 // SIGTERM
}
}
if containerName == common.MainContainerName {
for _, x := range template.Outputs.Parameters {
if x.ValueFrom != nil && x.ValueFrom.Path != "" {
if err := saveParameter(x.ValueFrom.Path); err != nil {
return err
}
}
}
for _, x := range template.Outputs.Artifacts {
if x.Path != "" {
if err := saveArtifact(x.Path); err != nil {
return err
}
}
}
} else {
logger.Info("not saving outputs - not main container")
}
return cmdErr // this is the error returned from cmd.Wait(), which maybe an exitError
},
}
}
func startCommand(name string, args []string, template *wfv1.Template) (*exec.Cmd, func(), error) {
command := exec.Command(name, args...)
command.Env = os.Environ()
var closer func() = func() {}
var stdout io.Writer = os.Stdout
var stderr io.Writer = os.Stderr
// this may not be that important an optimisation, except for very long logs we don't want to capture
if includeScriptOutput || template.SaveLogsAsArtifact() {
logger.Info("capturing logs")
stdoutf, err := os.OpenFile(varRunArgo+"/ctr/"+containerName+"/stdout", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, nil, fmt.Errorf("failed to open stdout: %w", err)
}
combinedf, err := os.OpenFile(varRunArgo+"/ctr/"+containerName+"/combined", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, nil, fmt.Errorf("failed to open combined: %w", err)
}
stdout = io.MultiWriter(stdout, stdoutf, combinedf)
stderr = io.MultiWriter(stderr, combinedf)
closer = func() {
_ = stdoutf.Close()
_ = combinedf.Close()
}
}
command.Stdout = stdout
command.Stderr = stderr
cmdCloser, err := osspecific.StartCommand(command)
if err != nil {
return nil, nil, err
}
origCloser := closer
closer = func() {
cmdCloser()
origCloser()
}
return command, closer, nil
}
func saveArtifact(srcPath string) error {
if common.FindOverlappingVolume(template, srcPath) != nil {
logger.Infof("no need to save artifact - on overlapping volume: %s", srcPath)
return nil
}
if _, err := os.Stat(srcPath); os.IsNotExist(err) { // might be optional, so we ignore
logger.WithError(err).Warnf("cannot save artifact %s", srcPath)
return nil
}
dstPath := filepath.Join(varRunArgo, "/outputs/artifacts/", strings.TrimSuffix(srcPath, "/")+".tgz")
logger.Infof("%s -> %s", srcPath, dstPath)
z := filepath.Dir(dstPath)
if err := os.MkdirAll(z, 0o755); err != nil { // chmod rwxr-xr-x
return fmt.Errorf("failed to create directory %s: %w", z, err)
}
dst, err := os.Create(dstPath)
if err != nil {
return fmt.Errorf("failed to create destination %s: %w", dstPath, err)
}
defer func() { _ = dst.Close() }()
if err = archive.TarGzToWriter(srcPath, gzip.DefaultCompression, dst); err != nil {
return fmt.Errorf("failed to tarball the output %s to %s: %w", srcPath, dstPath, err)
}
if err = dst.Close(); err != nil {
return fmt.Errorf("failed to close %s: %w", dstPath, err)
}
return nil
}
func saveParameter(srcPath string) error {
if common.FindOverlappingVolume(template, srcPath) != nil {
logger.Infof("no need to save parameter - on overlapping volume: %s", srcPath)
return nil
}
src, err := os.Open(filepath.Clean(srcPath))
if os.IsNotExist(err) { // might be optional, so we ignore
logger.WithError(err).Errorf("cannot save parameter %s", srcPath)
return nil
}
if err != nil {
return fmt.Errorf("failed to open %s: %w", srcPath, err)
}
defer func() { _ = src.Close() }()
dstPath := varRunArgo + "/outputs/parameters/" + srcPath
logger.Infof("%s -> %s", srcPath, dstPath)
z := filepath.Dir(dstPath)
if err := os.MkdirAll(z, 0o755); err != nil { // chmod rwxr-xr-x
return fmt.Errorf("failed to create directory %s: %w", z, err)
}
dst, err := os.Create(dstPath)
if err != nil {
return fmt.Errorf("failed to create %s: %w", srcPath, err)
}
defer func() { _ = dst.Close() }()
if _, err = io.Copy(dst, src); err != nil {
return fmt.Errorf("failed to copy %s to %s: %w", srcPath, dstPath, err)
}
if err = dst.Close(); err != nil {
return fmt.Errorf("failed to close %s: %w", dstPath, err)
}
return nil
}