-
Notifications
You must be signed in to change notification settings - Fork 938
/
main.go
112 lines (90 loc) · 1.92 KB
/
main.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
105
106
107
108
109
110
111
112
package main
import (
"bufio"
"container/ring"
"fmt"
"io"
"os"
"os/exec"
"time"
)
var idgen = make(chan int64)
func idFiller() {
var i int64
for {
idgen <- i
i++
}
}
func main() {
if len(os.Args) < 2 {
os.Exit(1)
}
err := os.Mkdir("shutdown_logs", 0755)
if err != nil && !os.IsExist(err) {
fmt.Println("Failed creating panic log folder: ", err)
os.Exit(1)
}
go idFiller()
cmdName := os.Args[1]
args := os.Args[2:]
cmd := exec.Command(cmdName, args...)
cmd.Env = os.Environ()
stdErr, err := cmd.StderrPipe()
stdOut, err2 := cmd.StdoutPipe()
if err != nil {
fmt.Println("failed creating stderr pipe: ", err)
os.Exit(1)
}
if err2 != nil {
fmt.Println("failed creating stdout pipe: ", err2)
os.Exit(1)
}
go reader(stdErr, "stderr")
go reader(stdOut, "stdout")
err = cmd.Run()
if err != nil {
fmt.Println("returned error: ", err)
time.Sleep(time.Second * 10) // make sure all output is processed before exiting
os.Exit(1)
}
fmt.Println("Exited")
time.Sleep(time.Second * 10) // make sure all output is processed before exiting
}
func reader(reader io.ReadCloser, logPrefix string) {
r := ring.New(50000)
bufReader := bufio.NewReader(reader)
running := true
for running {
line, err := bufReader.ReadBytes('\n')
if err != nil {
running = false
fmt.Println("Read Err: ", err, len(line))
}
if len(line) < 1 {
continue
}
r.Value = line
r = r.Prev()
}
writeLogs(logPrefix, r)
}
func writeLogs(prefix string, r *ring.Ring) {
compiled := make([]byte, 0, 10000000)
r.Do(func(p interface{}) {
if p != nil {
v := p.([]byte)
compiled = append(compiled, v...)
}
})
id := <-idgen
now := time.Now().Format("2006-01-02T15-04-05")
fName := fmt.Sprintf("%s_shutdown_%s_%d.log", prefix, now, id)
f, err := os.Create("shutdown_logs/" + fName)
if err != nil {
fmt.Println("Failed writing panic logs: ", err)
} else {
defer f.Close()
f.Write(compiled)
}
}