-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
255 lines (251 loc) · 5.86 KB
/
server.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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"bytes"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"text/tabwriter"
"time"
"gnd.la/log"
)
func (g *Governator) serveConn(conn net.Conn) error {
defer conn.Close()
args, err := decodeArgs(conn)
if err != nil {
return fmt.Errorf("error decoding arguments: %s", err)
}
if len(args) > 0 {
var err error
var st *Service
var name string
cmd := strings.ToLower(args[0])
if cmd == "start" || cmd == "stop" || cmd == "restart" || cmd == "log" {
if len(args) != 2 {
err = encodeResponse(conn, respErr, fmt.Sprintf("command %s requires exactly one argument\n", cmd))
cmd = ""
}
if cmd != "" && (cmd == "log" || args[1] != "all") {
st, err = g.serviceByName(args[1])
if err != nil {
err = encodeResponse(conn, respErr, fmt.Sprintf("%s\n", err))
cmd = ""
}
name = args[1]
}
}
switch cmd {
case "":
// cmd already handled
case "start":
if st == nil {
// all
g.startServices(conn)
break
}
if st.State == StateStarted {
err = encodeResponse(conn, respOk, fmt.Sprintf("%s is already running\n", name))
} else {
err = g.startService(conn, st)
}
case "stop":
if st == nil {
// all
g.stopServices(conn)
break
}
if !st.State.canStop() {
err = encodeResponse(conn, respOk, fmt.Sprintf("%s is not running\n", name))
} else {
_, err = g.stopService(conn, st)
}
case "restart":
if st == nil {
// all
g.stopServices(conn)
g.startServices(conn)
break
}
stopped := true
if st.State.isRunState() {
stopped, err = g.stopService(conn, st)
}
if stopped {
err = g.startService(conn, st)
}
case "list":
var buf bytes.Buffer
w := tabwriter.NewWriter(&buf, 4, 4, 4, ' ', 0)
fmt.Fprint(w, "SERVICE\tSTATUS\t\n")
g.mu.Lock()
for _, v := range g.services {
fmt.Fprintf(w, "%s\t", v.Name())
switch v.State {
case StateStopped:
fmt.Fprint(w, "STOPPED")
case StateStopping:
fmt.Fprint(w, "STOPPING")
case StateStarting:
fmt.Fprint(w, "STARTING")
case StateStarted:
if v.Restarts > 0 {
fmt.Fprintf(w, "RUNNING since %s - %d restarts", formatTime(v.Started), v.Restarts)
} else {
fmt.Fprintf(w, "RUNNING since %s", formatTime(v.Started))
}
case StateBackoff:
fmt.Fprintf(w, "BACKOFF - %s - next retry in %s", v.Err, v.untilNextRestart())
case StateFailed:
fmt.Fprintf(w, "FAILED - %s", v.Err)
default:
panic("invalid state")
}
fmt.Fprint(w, "\t\n")
}
g.mu.Unlock()
w.Flush()
buf.WriteString("\n")
err = encodeResponse(conn, respOk, buf.String())
case "log":
if st.State != StateStarted {
err = encodeResponse(conn, respErr, fmt.Sprintf("%s is not running\n", name))
break
}
if st.Config.Log.Monitor != nil {
err = encodeResponse(conn, respErr, fmt.Sprintf("%s is already being monitored\n", name))
break
}
ch := make(chan bool, 1)
st.Config.Log.Monitor = func(prefix string, b []byte) {
var buf bytes.Buffer
buf.WriteByte('[')
buf.WriteString(prefix)
buf.WriteString("] ")
buf.Write(b)
if b[len(b)-1] != '\n' {
buf.Write(newLine)
}
encodeResponse(conn, respOk, buf.String())
}
go func() {
// log stops when the client sends something over the connection
// or the connection is closed
b := make([]byte, 1)
conn.Read(b)
conn.Close()
ch <- true
}()
<-ch
st.Config.Log.Monitor = nil
return nil
case "conf":
if len(args) != 2 {
err = encodeResponse(conn, respErr, fmt.Sprintf("conf requires one argument, %d given", len(args)-1))
break
}
var value string
switch strings.ToLower(args[1]) {
case "config-dir":
value = g.configDir
case "services-dir":
value = g.servicesDir()
}
if !filepath.IsAbs(value) {
p, err := filepath.Abs(value)
if err != nil {
return err
}
value = p
}
r := respOk
if value == "" {
r = respErr
value = fmt.Sprintf("unknown configuration parameter %q", args[1])
} else {
value += "\n"
}
err = encodeResponse(conn, r, value)
case "wait-for":
// wait until a service is registered
if len(args) != 2 {
err = encodeResponse(conn, respErr, fmt.Sprintf("wait-for requires one argument, %d given", len(args)-1))
break
}
start := time.Now()
// wait 10 seconds at max
found := false
for ii := 0; ii < 10; ii++ {
if _, s := g.serviceByFilename(args[1]); s != nil {
found = true
break
}
time.Sleep(time.Second)
}
if found {
err = encodeResponse(conn, respOk, "")
} else {
err = encodeResponse(conn, respErr, fmt.Sprintf("service %s not found after waiting %s", args[1], time.Since(start)))
}
default:
err = encodeResponse(conn, respErr, fmt.Sprintf("unknown command %s - %s\n", cmd, help))
if err != nil {
return err
}
}
}
return encodeResponse(conn, respEnd, "")
}
func (g *Governator) startServer() error {
q := newQuit()
scheme, addr, err := parseServerAddr(g.ServerAddr)
if err != nil {
return err
}
if scheme == "unix" {
os.Remove(addr)
}
server, err := net.Listen(scheme, addr)
if err != nil {
return err
}
if scheme == "unix" {
if gid := getGroupId(AppName); gid >= 0 {
os.Chown(addr, 0, gid)
os.Chmod(addr, 0775)
}
}
conns := make(chan net.Conn, 10)
go func() {
for {
conn, err := server.Accept()
if err != nil {
log.Errorf("error accepting connection: %s", err)
}
log.Debugf("new connection %s", conn.RemoteAddr())
conns <- conn
}
}()
go func() {
for {
select {
case <-q.stop:
if scheme == "unix" {
os.Remove(addr)
}
q.sendStopped()
return
case conn := <-conns:
go func() {
if err := g.serveConn(conn); err != nil {
log.Errorf("error serving connection: %s", err)
}
}()
}
}
}()
g.mu.Lock()
defer g.mu.Unlock()
g.quits = append(g.quits, q)
return nil
}