This repository has been archived by the owner on Jan 12, 2021. It is now read-only.
forked from goss-org/goss
-
Notifications
You must be signed in to change notification settings - Fork 1
/
command.go
104 lines (86 loc) · 1.81 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
package system
import (
"bytes"
"fmt"
"io"
"os/exec"
"time"
"github.com/aelsabbahy/goss/util"
)
type Command interface {
Command() string
Exists() (bool, error)
ExitStatus() (int, error)
Stdout() (io.Reader, error)
Stderr() (io.Reader, error)
}
type DefCommand struct {
command string
exitStatus int
stdout io.Reader
stderr io.Reader
loaded bool
Timeout int
err error
}
func NewDefCommand(command string, system *System, config util.Config) Command {
return &DefCommand{
command: command,
Timeout: config.Timeout,
}
}
func (c *DefCommand) setup() error {
if c.loaded {
return c.err
}
c.loaded = true
cmd := util.NewCommand("sh", "-c", c.command)
err := runCommand(cmd, c.Timeout)
// We don't care about ExitError since it's covered by status
if _, ok := err.(*exec.ExitError); !ok {
c.err = err
}
c.exitStatus = cmd.Status
c.stdout = bytes.NewReader(cmd.Stdout.Bytes())
c.stderr = bytes.NewReader(cmd.Stderr.Bytes())
return c.err
}
func (c *DefCommand) Command() string {
return c.command
}
func (c *DefCommand) ExitStatus() (int, error) {
err := c.setup()
return c.exitStatus, err
}
func (c *DefCommand) Stdout() (io.Reader, error) {
err := c.setup()
return c.stdout, err
}
func (c *DefCommand) Stderr() (io.Reader, error) {
err := c.setup()
return c.stderr, err
}
// Stub out
func (c *DefCommand) Exists() (bool, error) {
return false, nil
}
func runCommand(cmd *util.Command, timeout int) error {
c1 := make(chan bool, 1)
e1 := make(chan error, 1)
timeoutD := time.Duration(timeout) * time.Millisecond
go func() {
err := cmd.Run()
if err != nil {
e1 <- err
}
c1 <- true
}()
select {
case <-c1:
return nil
case err := <-e1:
return err
case <-time.After(timeoutD):
return fmt.Errorf("Command execution timed out (%s)", timeoutD)
}
}