-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdaemon.go
144 lines (129 loc) · 2.55 KB
/
daemon.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
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
package main
import (
"fmt"
"io"
"os"
"os/exec"
"syscall"
)
// Daemon : Implements a Daemon object that can be referenced for each
// daemon listed in config.yaml
type Daemon struct {
Name string `json:"name"`
Command string `json:"command"`
Args []string `json:"args"`
Description string `json:"description"`
Vital bool `default:"true" json:"vital"`
Env []string `json:"env"`
dlog bool
Pid int `default:"nil" json:"pid"`
proc exec.Cmd
stdout io.ReadCloser
stderr io.ReadCloser
q chan interface{}
quit chan *Daemon
ready chan bool
}
// start the daemon
func (d *Daemon) start() {
d.ready = make(chan bool)
subp := exec.Command(d.Command, d.Args...)
d.stdout, _ = subp.StdoutPipe()
d.stderr, _ = subp.StderrPipe()
if d.dlog == true {
go d.readStdout()
go d.readStderr()
}
d.proc.Env = append(os.Environ(), d.Env...)
err := subp.Start()
go d.watch()
if err != nil {
d.log("fatal", "Unable to start daemon")
}
d.Pid = subp.Process.Pid
d.proc = *subp
for range []int{1, 2, 3} {
d.ready <- true
}
d.log("info", "daemon started")
}
func (d *Daemon) watch() {
<-d.ready
d.proc.Wait()
if d.Vital == true {
d.quit <- d
} else {
d.log("info", "Daemon process exited.")
}
}
func (d *Daemon) signal(s syscall.Signal) {
d.proc.Process.Signal(s)
if d.Vital == true {
d.quit <- d
} else {
d.log("info", fmt.Sprintf("Sent signal %v to daemon", s))
}
}
// stop the daemon
func (d *Daemon) kill() {
d.proc.Process.Kill()
if d.Vital == true {
d.quit <- d
} else {
d.log("info", "daemon killed")
}
}
func (d *Daemon) readStdout() {
<-d.ready
var stdout []byte
outbuf := make([]byte, 1, 1)
for {
n, erro := d.stdout.Read(outbuf[:])
if n > 0 {
b := outbuf[:n]
if string(b) == "\n" {
d.log("debug", string(stdout))
stdout = nil
} else {
stdout = append(stdout, b...)
}
}
if erro == io.EOF {
erro = nil
}
}
}
func (d *Daemon) readStderr() {
<-d.ready
var stderr []byte
errbuf := make([]byte, 1, 1)
for {
n, erro := d.stderr.Read(errbuf[:])
if n > 0 {
b := errbuf[:n]
if string(b) == "\n" {
d.log("warn", string(stderr))
stderr = nil
} else {
stderr = append(stderr, b...)
}
}
if erro == io.EOF {
erro = nil
}
}
}
func (d *Daemon) log(l string, m string) {
var logMessage = DaemonLog{
msg: m,
level: l,
msgtype: "daemon",
name: d.Name,
command: d.Command,
args: d.Args,
vital: d.Vital,
env: d.Env,
pid: d.Pid,
}
d.q <- &logMessage
}