-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
589 lines (498 loc) · 15.2 KB
/
command.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// Copyright 2021 The Tiyo authors
//
// 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 pipeline
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
// TIMEOUT : The maximum number of minutes a command can execute for if not forever
const TIMEOUT = 15
// Command : Define the structure of a command taken from JointJS and executed by Syphon
type Command struct {
// ID is the jointJS element ID
ID string `json:"id"`
// Parent is the jointJS ID of a parent container
Parent string `json:"parent"`
// The command container name
Name string `json:"name"`
// The executable binary name to trigger when events are recieved
Command string `json:"command"`
// Should the command automatically be started
AutoStart bool `json:"autostart"`
// Arguments to give to the command
Args string `json:"args"`
// The version of the container
Version string `json:"version"`
// The programming language the container is executing
Language string `json:"element"`
// Does this container have a script to execute
Script bool `json:"script"`
// The content of the script - will be base64 encoded for transmission safety
ScriptContent string `json:"scriptcontent"`
// Is this a custom container or is it a pre-fabricated container from an upstream source
Custom bool `json:"custom"`
// The user defined timeout in minutes - if >15 will be rounded down to 15
Timeout int `json:"timeout"`
// (Re)Use an existing container
UseExisting bool `json:"existing"`
// Expose this port as a service port
ExposePort int `json:"exposeport"`
// Is the service port a UDP port
IsUDP bool `json:"isudp"`
// The required CPU of the container (default 500m cpu)
CPU string `json:"cpu"`
// The required memory of the container (default 256Mi)
Memory string `json:"memory"`
// The time this command was started in unix nano
StartTime int64 `json:"starttime"`
// The time this command ended in unix nano
EndTime int64 `json:"endtime"`
// Environment variables to set directly on the command
Environment []string `json:"environment"`
// Details about any Git repository configured for the command
GitRepo *GitRepo `json:"gitrepo"`
// The image string to build the docker container from and load into kubernetes
Image string
// The computed tag to upload the container docker image as
Tag string
// Standard output buffer
Stdout bytes.Buffer
// Standard error buffer
Stderr bytes.Buffer
// The commands process ID whilst executing
ProcessID int
// A computed set of process arguments including any files
ProcessArgs []string
// A computed file separator
FileSeperator string
}
var regex *regexp.Regexp
// Sanitize a given string, removing any non-alphanumeric characters and replacing them with sep.
func Sanitize(str string, sep string) string {
regex, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatal("Failed to compile regex - ", err)
}
return strings.Trim(strings.ToLower(regex.ReplaceAllString(str, sep)), sep)
}
// NewCommand : Create a new command instance
func NewCommand(cell map[string]interface{}) *Command {
command := Command{
ID: "",
Name: "",
Command: "",
AutoStart: false,
Args: "",
Version: "",
Language: "",
Script: false,
ScriptContent: "",
Custom: false,
Timeout: TIMEOUT,
UseExisting: false,
ExposePort: -1,
IsUDP: false,
StartTime: 0,
EndTime: 0,
CPU: "500m",
Memory: "256Mi",
}
command.Environment = make([]string, 0)
if cell["id"] != nil {
command.ID = cell["id"].(string)
}
if cell["parent"] != nil {
command.Parent = cell["parent"].(string)
}
if cell["name"] != nil {
command.Name = Sanitize(cell["name"].(string), "-")
}
if cell["command"] != nil {
command.Command = cell["command"].(string)
}
if cell["autostart"] != nil {
command.AutoStart = cell["autostart"].(bool)
}
if cell["arguments"] != nil {
command.Args = cell["arguments"].(string)
}
if cell["version"] != nil {
command.Version = cell["version"].(string)
}
if cell["element"] != nil {
command.Language = cell["element"].(string)
}
if cell["script"] != nil {
command.Script = cell["script"].(bool)
}
if cell["scriptcontent"] != nil {
command.ScriptContent = cell["scriptcontent"].(string)
}
if cell["custom"] != nil {
command.Custom = cell["custom"].(bool)
}
if cell["timeout"] != nil {
command.Timeout = int(cell["timeout"].(float64))
if command.Timeout == 0 {
command.Timeout = TIMEOUT
}
if command.Timeout != -1 {
command.Timeout = command.Timeout * 60
}
} else {
command.Timeout = TIMEOUT * 60
}
if cell["existing"] != nil {
command.UseExisting = cell["existing"].(bool)
}
if cell["exposeport"] != nil {
command.ExposePort = int(cell["exposeport"].(float64))
}
if cell["isudp"] != nil {
command.IsUDP = cell["isudp"].(bool)
}
if cell["cpu"] != nil {
command.CPU = cell["cpu"].(string)
}
if cell["memory"] != nil {
command.Memory = cell["memory"].(string)
}
if cell["environment"] != nil {
envvars := cell["environment"].([]interface{})
for _, value := range envvars {
command.Environment = append(command.Environment, value.(string))
}
}
if cell["gitrepo"] != nil {
gitRepo := NewGitRepo()
gitRepo.Configure(cell["gitrepo"].(map[string]interface{}))
command.GitRepo = gitRepo
}
return &command
}
// AddEnvVar : Add a value to the environment variables
// key, value will be converted to KEY=value
func (command *Command) AddEnvVar(key, value string) {
command.Environment = append(command.Environment, strings.ToUpper(key)+"='"+value+"'")
}
// GetContainer : Gets a container build string.
//
// if asTag is True, returns a modified form of the container string
// for uploading to the primary source
func (command *Command) GetContainer(asTag bool) string {
container := command.Language
switch command.Language {
case "r":
container = "r-base"
case "javascript":
container = "node"
case "jupyter":
container = "jupyter/datascience-notebook"
if asTag {
container = "datascience-notebook"
}
case "dockerfile":
container = command.Name
}
var name string = container + ":" + command.Version
if asTag {
name = container + "-tiyo:" + command.Version
}
if !command.Custom {
name = command.Name + ":" + command.Version
if asTag {
name = command.Name + "-tiyo:" + command.Version
}
}
return name
}
// GenerateRandomString : Generates a random string of 12 characters for use in temporary filenames
func (command *Command) GenerateRandomString() string {
const charset = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, 12)
var seededRand *rand.Rand = rand.New(
rand.NewSource(time.Now().UnixNano()))
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}
// WriteScript : Convert script content provided in the JointJS element to file on disk for processing
func (command *Command) writeScript() (string, error) {
if command.Language == "dockerfile" {
return "", nil
}
var (
name string = command.GenerateRandomString()
dirname string = "/tiyo/workspace"
extension string = ""
content string
script []byte
err error
)
if fi, err := os.Stat(dirname); err != nil || !fi.IsDir() {
if !os.IsNotExist(err) && !fi.IsDir() {
return "", err
}
}
if err := os.Mkdir(dirname, 0775); err != nil && !os.IsExist(err) {
return "", err
}
// golang caused this
// (but surely there's a better way)
switch command.Language {
case "r":
extension = "R"
case "javascript":
extension = "js"
case "python":
extension = "py"
case "groovy":
extension = "groovy"
case "perl":
extension = "pl"
case "sh":
fallthrough
case "bash":
extension = "sh"
case "golang":
extension = "go"
case "ruby":
extension = "rb"
case "php":
extension = "php"
}
// not everything has an extension
name = fmt.Sprintf("%s/%s-%s", dirname, command.Name, name)
if extension != "" {
name = fmt.Sprintf("%s.%s", name, extension)
}
if script, err = base64.StdEncoding.DecodeString(command.ScriptContent); err != nil {
return "", err
}
content = string(script)
file, err := os.Create(name)
if err != nil {
return "", fmt.Errorf("Failed to create script file for %s. %s", name, err)
}
defer file.Close()
if _, err := file.WriteString(content); err != nil {
return "", fmt.Errorf("Failed to write script contents for %s. Error was: %s", name, err)
}
file.Sync()
return name, nil
}
// Execute : Execute the current command inside the container
//
// This is the main workhorse function for the application, taking all
// User configured and temporary variables, mapping them into the environment
// and process arguments then executing the command, terminating as necesssary
// after the configured timeout, and capturing the output for later storage and
// retrieval
func (command *Command) Execute(directory string, subdir string, filename string, event string, libraryDir string) int {
log.Info("Using environment:")
var environment []string = append(os.Environ(), command.Environment...)
for _, value := range environment {
log.Info(" - ", value)
}
var (
name string
err error
)
command.ProcessArgs = make([]string, 0)
// For certain commands, there needs to be an element of control over
// how files are separated
for _, item := range strings.Split(command.Args, " ") {
log.Info("Appending argument ", item)
var flag, _ = regexp.Compile(`--tiyo-flag(-[a-zA-Z]+)`)
var library, _ = regexp.Compile(`--tiyo-library="(.*)"`)
// switch out library paths and custom file flags
switch {
case flag.MatchString(item):
command.FileSeperator = flag.FindStringSubmatch(item)[1]
continue
case library.MatchString(item):
command.ProcessArgs = append(
command.ProcessArgs,
filepath.Join(libraryDir, library.FindStringSubmatch(item)[1]),
)
continue
}
// Never remove these - they are critical in RNA processing
// and in some instances, applications will literally fail
// to parse files in a meaningful manner
// Switch all other tiyo file separator flags
switch item {
// comma separated index
case "--tiyo-csi":
command.FileSeperator = ","
// comma space separated index
case "--tiyo-cssi":
command.FileSeperator = ", "
// space comma space separated index
case "--tiyo-scssi":
command.FileSeperator = " , "
default:
command.ProcessArgs = append(command.ProcessArgs, item)
}
}
if command.ScriptContent != "" {
name, err = command.writeScript()
if err != nil {
log.Error(err)
return 1
}
}
if name != "" {
log.Info("Setting working directory to", filepath.Dir(name))
os.Chdir(filepath.Dir(name))
name = filepath.Base(name)
command.ProcessArgs = append(command.ProcessArgs, name)
}
info, _ := os.Stat(directory)
if info != nil {
var filedir string = command.collectFiles(directory, filename)
directory = filepath.Join(directory, subdir, filedir)
if _, err := os.Stat(directory); err != nil {
_ = os.Mkdir(directory, 0755)
}
// this may be problematic for go apps as go run does
// not work with absolute paths.
log.Info("Setting working directory to ", directory)
os.Chdir(directory)
}
log.Info("Triggering command ", command.Command, " ", command.ProcessArgs)
cmd := exec.Command(command.Command, command.ProcessArgs...)
cmd.Env = environment
// dont collect logs on forever run
if command.Timeout != -1 {
cmd.Stdout = io.MultiWriter(os.Stdout, &command.Stdout)
cmd.Stderr = io.MultiWriter(os.Stderr, &command.Stderr)
} else {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
command.StartTime = time.Now().UnixNano()
done := make(chan error)
if err := cmd.Start(); err != nil {
command.EndTime = time.Now().UnixNano()
log.Error("Failed to start command `", command.Command, " ", command.Args, "`")
log.Error("error was: ", err)
return 1
}
if command.Timeout == -1 {
return command.ExecuteForever(cmd, done)
}
return command.ExecuteWithTimeout(cmd, done)
}
// Globs the input directory and appends each file as an argument to the command
//
// Uses command.FileSeperator to append the filenames
// If more than 1 file is found, returns the filename as an additional directory
// otherwise returns an empty string
func (command *Command) collectFiles(directory string, filename string) string {
if command.Timeout == -1 {
log.Info("Not collecting files for forever run")
return ""
}
var glob string = filepath.Join(directory, "*"+filename+"*")
files, err := filepath.Glob(glob)
if err != nil {
log.Error(err)
return ""
}
log.Info("Found ", len(files), " for fileglob ", glob)
var dirReturn = ""
if len(files) > 1 {
dirReturn = filename
}
var csifiles string = ""
for index, file := range files {
if command.FileSeperator == "," {
csifiles = strings.TrimLeft(strings.Join([]string{csifiles, file}, ","), ",")
continue
} else if command.FileSeperator == ", " {
if index < len(files)-1 {
file = file + ","
}
} else if command.FileSeperator == " , " {
if index < len(files)-1 {
file = file + " ,"
}
} else if command.FileSeperator == "-f" {
command.ProcessArgs = append(command.ProcessArgs, "-f")
}
command.ProcessArgs = append(command.ProcessArgs, file)
}
if csifiles != "" {
log.Info("Got Comma separated index of files ", csifiles)
command.ProcessArgs = append(command.ProcessArgs, strings.Trim(csifiles, ","))
}
return dirReturn
}
// ExecuteForever : Executes the given command in a "forever" loop
//
// Note:
// This command does not copy any logs - presuming they will grow exponentially
// large over time. Check STDERR/STDOUT on the pod for the logs garnered by it.
func (command *Command) ExecuteForever(cmd *exec.Cmd, done chan error) int {
go func() {
done <- cmd.Wait()
}()
select {
case err := <-done:
if exitError, ok := err.(*exec.ExitError); ok {
command.EndTime = time.Now().UnixNano()
return exitError.ExitCode()
}
}
return 0
}
// ExecuteWithTimeout : Runs the given command with a timeout
//
// By default, this timeout is set to 15 minutes and this value is used if 0 is provided.
// Longer timeouts can be set or set to -1 to run forever.
func (command *Command) ExecuteWithTimeout(cmd *exec.Cmd, done chan error) int {
go func() {
done <- cmd.Wait()
}()
var exitCode int = 1
select {
case err := <-done:
if exitError, ok := err.(*exec.ExitError); ok {
command.EndTime = time.Now().UnixNano()
exitCode = exitError.ExitCode()
}
break
case <-time.After(time.Duration(command.Timeout) * time.Second):
if err := cmd.Process.Kill(); err != nil {
log.Errorf("Failed to kill command %s - you might have zombies. %s", command.Name, err.Error())
}
log.Error("Command ", command.Name, " exited due to timeout - ", command.Timeout, " seconds exceeded")
break
}
command.recreateWorkspace()
return exitCode
}
// recreateWorkspace : Deletes and recreates the workspace directory inside the container
func (command *Command) recreateWorkspace() {
os.Chdir("/tiyo")
err := os.RemoveAll("workspace")
if err == nil {
os.Mkdir("workspace", 0775)
}
}