This repository was archived by the owner on Apr 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathexternal.go
More file actions
63 lines (52 loc) · 1.71 KB
/
external.go
File metadata and controls
63 lines (52 loc) · 1.71 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
package sweet
// sweet.go: network device backups and change alerts for the 21st century - inspired by RANCID.
import (
"bytes"
"fmt"
"github.com/kballard/go-shellquote"
"os"
"os/exec"
"strings"
"time"
)
type External struct {
}
func newExternalCollector() Collector {
return External{}
}
func (collector External) Collect(device DeviceConfig) (map[string]string, error) {
var cmd *exec.Cmd
result := make(map[string]string)
commandParts, err := shellquote.Split(device.Config["scriptPath"])
if err != nil {
return result, fmt.Errorf("External collection script (%s) missing: %s", device.Config["scriptPath"], err.Error())
}
if len(commandParts) > 1 {
cmd = exec.Command(commandParts[0], commandParts[1:]...)
} else {
cmd = exec.Command(commandParts[0])
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return result, fmt.Errorf("Error running external collection script (%s): %s", device.Config["scriptPath"], err.Error())
}
cmdDone := make(chan error)
go func() {
cmdDone <- cmd.Wait()
}()
select {
case err := <-cmdDone:
if err != nil {
return result, fmt.Errorf("External collection script (%s) returned an error: %s - %s", device.Config["scriptPath"], err.Error(), strings.TrimRight(stderr.String(), "\n"))
}
case <-time.After(device.Timeout):
if err := cmd.Process.Signal(os.Interrupt); err != nil {
return result, fmt.Errorf("Error stopping external collection script (%s) after timeout: %s", device.Config["scriptPath"], err.Error())
}
return result, fmt.Errorf("Timeout collecting from %s after %d seconds", device.Hostname, int(device.Timeout.Seconds()))
}
result["config"] = stdout.String()
return result, nil
}