forked from driskell/log-courier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
335 lines (277 loc) · 7.27 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* Copyright 2014-2015 Jason Woods.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package admin
import (
"encoding/json"
"fmt"
"net/http"
"runtime"
"strings"
"time"
"github.com/driskell/log-courier/lc-lib/config"
"github.com/driskell/log-courier/lc-lib/core"
"gopkg.in/tylerb/graceful.v1"
)
// Server provides a REST interface for administration
type Server struct {
core.PipelineSegment
core.PipelineConfigReceiver
config *Config
listener netListener
server *graceful.Server
}
// NewServer creates a new admin listener on the pipeline
func NewServer(pipeline *core.Pipeline, config *config.Config, reloadFunc func() error) (*Server, error) {
ret := &Server{
config: config.Get("admin").(*Config),
}
ret.config.apiRoot = newAPIRoot(reloadFunc)
listener, err := ret.listen(ret.config)
if err != nil {
return nil, err
}
ret.initServer(listener)
pipeline.Register(ret)
return ret, nil
}
func (l *Server) listen(config *Config) (netListener, error) {
bind := splitAdminConnectString(config.Bind)
if listener, ok := registeredListeners[bind[0]]; ok {
log.Info("[admin] REST admin now listening on %s:%s", bind[0], bind[1])
return listener(bind[0], bind[1])
}
return nil, fmt.Errorf("Unknown transport specified for admin bind: '%s'", bind[0])
}
func (l *Server) initServer(listener netListener) {
l.listener = listener
l.server = &graceful.Server{
// We handle shutdown ourselves
NoSignalHandling: true,
// The HTTP server
Server: &http.Server{
// TODO: Make all these configurable?
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l.handle(w, r)
}),
},
}
}
func (l *Server) startServer() {
// TODO: error checking
go l.server.Serve(l.listener)
}
// Run is the main routine for the admin listener
func (l *Server) Run() {
defer func() {
l.Done()
}()
l.startServer()
var closingOldServer <-chan struct{}
var reloadingConfig *Config
var shuttingDown, shutdownStarted bool
ListenerLoop:
for {
select {
case <-l.OnShutdown():
shuttingDown = true
if closingOldServer == nil {
// Start the shutdown
closingOldServer = l.shutdownServer()
shutdownStarted = true
}
case config := <-l.OnConfig():
// We can't yet disable admin during a reload
aconfig := config.Get("admin").(*Config)
if aconfig.Enabled {
if aconfig.Bind != l.config.Bind {
// Delay reload if still waiting for old server to close
if closingOldServer != nil {
reloadingConfig = aconfig
continue
}
closingOldServer = l.reloadServer(aconfig)
}
}
case <-closingOldServer:
log.Info("[admin] REST administration stopped")
if shuttingDown {
// Is shutdown in progress? Leave if so
if shutdownStarted {
break ListenerLoop
}
// Need to start the shutdown
closingOldServer = l.shutdownServer()
shutdownStarted = true
continue
}
if reloadingConfig != nil {
// Another reload queued - process it
closingOldServer = l.reloadServer(reloadingConfig)
continue
}
}
}
log.Info("[admin] REST administration exited")
}
func (l *Server) shutdownServer() <-chan struct{} {
// TODO: Make configurable? This is the shutdown timeout
l.server.Stop(10 * time.Second)
log.Info("[admin] REST administration exiting")
return l.server.StopChan()
}
func (l *Server) reloadServer(config *Config) <-chan struct{} {
newListener, err := l.listen(config)
if err != nil {
log.Errorf("The new admin configuration failed to apply: %s", err)
return nil
}
stopChan := l.shutdownServer()
l.initServer(newListener)
l.startServer()
return stopChan
}
func (l *Server) handle(w http.ResponseWriter, r *http.Request) {
defer func() {
l.handlePanic(w, r, recover())
}()
if r.Method != "GET" && r.Method != "POST" && r.Method != "PUT" {
l.accessLog(r, http.StatusMethodNotAllowed)
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
// Check for leading forward slash
if len(r.URL.Path) == 0 || r.URL.Path[0] != '/' {
panic(ErrNotFound)
}
parts := strings.Split(r.URL.Path[1:], "/")
root := l.config.apiRoot
if len(parts) == 1 && parts[0] == "" {
parts = parts[:0]
}
for _, part := range parts {
newRoot, err := root.Get(part)
if err != nil {
panic(err)
}
if newRoot == nil {
panic(ErrNotFound)
}
root = newRoot
}
// Call?
if r.Method != "GET" {
l.handleCall(w, r, root)
return
}
// Ensure up to date values
if err := root.Update(); err != nil {
panic(err)
}
l.handleRequest(w, r, root)
}
func (l *Server) handleRequest(w http.ResponseWriter, r *http.Request, root APINavigatable) {
var err error
var contentType string
var response []byte
if r.URL.Query().Get("w") == "pretty" {
contentType = "text/plain"
response, err = root.HumanReadable("")
} else {
contentType = "application/json"
response, err = json.Marshal(root)
}
if err != nil {
panic(err)
}
l.accessLog(r, http.StatusOK)
w.Header().Add("Content-Type", contentType)
w.Write(response)
}
func (l *Server) handleCall(w http.ResponseWriter, r *http.Request, root APINavigatable) {
var err error
err = r.ParseForm()
if err != nil {
panic(err)
}
result, err := root.Call(r.Form)
if err != nil {
panic(err)
}
var contentType string
var response []byte
if r.URL.Query().Get("w") == "pretty" {
contentType = "text/plain"
response = []byte(result)
} else {
contentType = "application/json"
response, err = json.Marshal(struct {
Result string `json:"result"`
}{
Result: result,
})
if err != nil {
panic(err)
}
}
l.accessLog(r, http.StatusOK)
w.Header().Add("Content-Type", contentType)
w.Write(response)
}
func (l *Server) handlePanic(w http.ResponseWriter, r *http.Request, panicArg interface{}) {
if panicArg == nil {
return
}
// Only keep normal errors
err, ok := panicArg.(error)
if !ok {
panic(panicArg)
}
var code int
switch err {
case ErrNotFound:
code = http.StatusNotFound
case ErrNotImplemented:
code = http.StatusNotImplemented
default:
code = http.StatusInternalServerError
}
l.errorResponse(w, r, err, code)
log.Info("[admin] Request error: %s", err.Error())
// Don't keep runtime errors or we'll miss stack trace
if _, ok := err.(runtime.Error); ok {
panic(err)
}
}
func (l *Server) errorResponse(w http.ResponseWriter, r *http.Request, err error, c int) {
structErr := struct {
Error string `json:"error"`
}{
Error: err.Error(),
}
jsonError, encodeErr := json.Marshal(structErr)
if encodeErr != nil {
l.accessLog(r, http.StatusServiceUnavailable)
http.Error(w, encodeErr.Error(), http.StatusServiceUnavailable)
return
}
l.accessLog(r, c)
http.Error(w, string(jsonError), c)
}
func (l *Server) accessLog(r *http.Request, c int) {
log.Debug("[admin] %s %s %d", r.Method, r.URL.Path, c)
}