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
|
package shell
import "fmt"
import "strings"
import "time"
import "os"
import "os/exec"
import "bufio"
import "bytes"
import "io"
// import "io/ioutil"
import "github.com/davecgh/go-spew/spew"
import "github.com/svent/go-nbreader"
import log "github.com/sirupsen/logrus"
// import "github.com/wercker/journalhook"
var callback func(interface{}, int)
var shellStdout *os.File
var shellStderr *os.File
var spewOn bool = false
var msecDelay int = 20 // number of milliseconds to delay between reads with no data
var bytesBuffer bytes.Buffer
var bytesSplice []byte
func handleShell(c interface{}, ret int) {
log.Println("shell.Run() Returned", ret)
}
func init() {
callback = handleShell
}
func InitCallback(f func(interface{}, int)) {
callback = f
}
func Script(cmds string) int {
// split on new lines (while we are at it, handle stupid windows text files
lines := strings.Split(strings.Replace(cmds, "\r\n", "\n", -1), "\n")
for _, line := range lines {
line = Chomp(line) // this is like 'chomp' in perl
log.Println("LINE:", line)
time.Sleep(1)
Run(line)
}
return 0
}
/*
func UseJournalctl() {
journalhook.Enable()
}
*/
func SpewOn() {
spewOn = true
}
func SetDelayInMsec(msecs int) {
msecDelay = msecs
}
func SetStdout(newout *os.File) {
shellStdout = newout
}
func SetStderr(newerr *os.File) {
shellStderr = newerr
}
// NOTE: this might cause problems:
// always remove the newlines at the end ?
func Run(cmdline string) string {
log.Println("shell.Run() START " + cmdline)
cmd := Chomp(cmdline) // this is like 'chomp' in perl
cmdArgs := strings.Fields(cmd)
if (len(cmdArgs) == 0) {
callback(fmt.Errorf("cmdline == ''"), 0)
log.Debug("END ", cmd)
return "" // nothing to do
}
if (cmdArgs[0] == "cd") {
if (len(cmdArgs) > 1) {
log.Println("os.Chdir()", cmd)
os.Chdir(cmdArgs[1])
}
log.Debug("END ", cmd)
return "" // nothing to do
}
process := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
pstdout, _ := process.StdoutPipe()
pstderr, _ := process.StderrPipe()
if (spewOn) {
spew.Dump(pstdout)
}
process.Start()
if (shellStdout == nil) {
shellStdout = os.Stdout
}
f := bufio.NewWriter(shellStdout)
newreader := bufio.NewReader(pstdout)
nbr := nbreader.NewNBReader(newreader, 1024)
tmp := bufio.NewReader(pstderr)
go NonBlockingReader(tmp, shellStderr)
totalCount := 0
var dead bool = false
for (dead == false) {
time.Sleep(time.Duration(msecDelay) * time.Millisecond) // only check the buffer 500 times a second
// log.Println("sleep done")
var empty bool = false
// tight loop that reads 1K at a time until buffer is empty
for (empty == false) {
oneByte := make([]byte, 1024)
count, err := nbr.Read(oneByte)
totalCount += count
if (err != nil) {
log.Debug("Read() count = ", count, "err = ", err)
oneByte = make([]byte, 1024)
count, err = nbr.Read(oneByte)
log.Debug("STDOUT: count = ", count)
f.Write(oneByte[0:count])
f.Flush()
empty = true
dead = true
}
// f.Write([]byte(string(oneByte)))
if (count == 0) {
empty = true
} else {
log.Debug("STDOUT: count = ", count)
io.WriteString(&bytesBuffer, string(oneByte))
f.Write(oneByte[0:count])
f.Flush()
}
}
if (totalCount != 0) {
log.Debug("STDOUT: totalCount = ", totalCount)
totalCount = 0
}
}
err := process.Wait()
if err != nil {
if (spewOn) {
// this panics: spew.Dump(err.(*exec.ExitError))
spew.Dump(process.ProcessState)
}
// stuff := err.(*exec.ExitError)
log.Debug("ERROR ", err.Error())
log.Debug("END ", cmdline)
// return -1, "", fmt.Errorf(err.Error())
callback(fmt.Errorf(err.Error()), -1)
return ""
}
// log.Println("shell.Run() END buf =", bytesBuffer)
// convert this to a byte array and then trip NULLs
// WTF this copies nulls with b.String() is fucking insanly stupid
byteSlice := bytesBuffer.Bytes()
b := bytes.Trim(byteSlice, "\x00")
log.Debug("shell.Run() END b =", b)
// reset the bytesBuffer
bytesBuffer.Reset()
// NOTE: this might cause problems:
// this removes the newlines at the end
tmp2 := string(b)
tmp2 = strings.TrimSuffix(tmp2, "\n")
log.Println("shell.Run() END ", cmdline)
log.Println("shell.Run() calling callback() :")
callback(fmt.Errorf("no error"), 0)
return Chomp(b)
}
func Daemon(cmdline string, timeout time.Duration) int {
for {
Run(cmdline)
time.Sleep(timeout)
}
}
// pass in two file handles (1 read, 1 write)
func NonBlockingReader(buffReader *bufio.Reader, writeFileHandle *os.File) {
// newreader := bufio.NewReader(readFileHandle)
// create a nonblocking GO reader
nbr := nbreader.NewNBReader(buffReader, 1024)
for {
// defer buffReader.Close()
// defer writeFileHandle.Flush()
defer writeFileHandle.Close()
totalCount := 0
for {
oneByte := make([]byte, 1024)
count, err := nbr.Read(oneByte)
if (err != nil) {
log.Debug("count, err =", count, err)
return
}
totalCount += count
if (count == 0) {
time.Sleep(time.Duration(msecDelay) * time.Millisecond) // without this delay this will peg the CPU
if (totalCount != 0) {
log.Debug("STDERR: totalCount = ", totalCount)
totalCount = 0
}
} else {
log.Debug("STDERR: count = ", count)
writeFileHandle.Write(oneByte[0:count])
}
}
}
}
|