-
Notifications
You must be signed in to change notification settings - Fork 115
/
generic_script.go
94 lines (77 loc) · 1.8 KB
/
generic_script.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
package script
import (
"os"
"path/filepath"
boshenv "github.com/cloudfoundry/bosh-agent/agent/script/pathenv"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
const (
fileOpenFlag int = os.O_RDWR | os.O_CREATE | os.O_APPEND
fileOpenPerm os.FileMode = os.FileMode(0640)
)
type GenericScript struct {
fs boshsys.FileSystem
runner boshsys.CmdRunner
tag string
path string
stdoutLogPath string
stderrLogPath string
}
func NewScript(
fs boshsys.FileSystem,
runner boshsys.CmdRunner,
tag string,
path string,
stdoutLogPath string,
stderrLogPath string,
) GenericScript {
return GenericScript{
fs: fs,
runner: runner,
tag: tag,
path: path,
stdoutLogPath: stdoutLogPath,
stderrLogPath: stderrLogPath,
}
}
func (s GenericScript) Tag() string { return s.tag }
func (s GenericScript) Path() string { return s.path }
func (s GenericScript) Exists() bool { return s.fs.FileExists(s.path) }
func (s GenericScript) Run() error {
err := s.ensureContainingDir(s.stdoutLogPath)
if err != nil {
return err
}
err = s.ensureContainingDir(s.stderrLogPath)
if err != nil {
return err
}
stdoutFile, err := s.fs.OpenFile(s.stdoutLogPath, fileOpenFlag, fileOpenPerm)
if err != nil {
return err
}
defer func() {
_ = stdoutFile.Close()
}()
stderrFile, err := s.fs.OpenFile(s.stderrLogPath, fileOpenFlag, fileOpenPerm)
if err != nil {
return err
}
defer func() {
_ = stderrFile.Close()
}()
command := boshsys.Command{
Name: s.path,
Env: map[string]string{
"PATH": boshenv.Path(),
},
Stdout: stdoutFile,
Stderr: stderrFile,
}
_, _, _, err = s.runner.RunComplexCommand(command)
return err
}
func (s GenericScript) ensureContainingDir(fullLogFilename string) error {
dir, _ := filepath.Split(fullLogFilename)
return s.fs.MkdirAll(dir, os.FileMode(0750))
}