This repository has been archived by the owner on Sep 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
util.go
90 lines (85 loc) · 2.46 KB
/
util.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
/*
Onix Config Manager - Pilot
Copyright (c) 2018-2020 by www.gatblau.org
Licensed under the Apache License, Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0
Contributors to this project, hereby assign copyright in this code to the project,
to be licensed under the same terms as the rest of the code.
*/
package core
import (
"bytes"
"encoding/base64"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// executes a command
func execute(cmd string) (string, error) {
strArr := strings.Split(cmd, " ")
var c *exec.Cmd
if len(strArr) == 1 {
//nolint:gosec
c = exec.Command(strArr[0])
} else {
//nolint:gosec
c = exec.Command(strArr[0], strArr[1:]...)
}
var stdout, stderr bytes.Buffer
c.Stdout = &stdout
c.Stderr = &stderr
// execute the command asynchronously
if err := c.Start(); err != nil {
return stderr.String(), fmt.Errorf("executing %s failed: %s", cmd, err)
}
done := make(chan error)
// launch a go routine to wait for the command to execute
go func() {
// send a message to the done channel if completed or error
done <- c.Wait()
}()
// wait for the done channel
select {
case <-done:
// command completed
case <-time.After(6 * time.Second):
// command timed out after 6 secs
return stderr.String(), fmt.Errorf("executing '%s' timed out", cmd)
}
return stdout.String(), nil
}
// creates a new Basic Authentication Token
func basicToken(user string, pwd string) string {
return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pwd))))
}
// cmdToRun := "/path/to/someCommand"
// args := []string{"someCommand", "arg1"}
// starts a process
func startProc(cmd string, args []string) (*os.Process, error) {
procAttr := new(os.ProcAttr)
procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
return os.StartProcess(cmd, args, procAttr)
}
// launch a command with a specified timeout period
func startCmd(cmd *exec.Cmd, timeoutSecs time.Duration) error {
// execute the command asynchronously
if err := cmd.Start(); err != nil {
return fmt.Errorf("executing %s failed: %s", cmd, err)
}
done := make(chan error)
// launch a go routine to wait for the command to execute
go func() {
// send a message to the done channel if completed or error
done <- cmd.Wait()
}()
// wait for the done channel
select {
case <-done:
// command completed
case <-time.After(timeoutSecs * time.Second):
// command timed out after 6 secs
return fmt.Errorf("executing '%s' timed out", cmd)
}
return nil
}