forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_server.go
363 lines (304 loc) · 9.1 KB
/
simple_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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package server
import (
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"runtime/debug"
"strings"
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/metrics/provider"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
netContext "golang.org/x/net/context"
"google.golang.org/appengine"
metricscfg "github.com/NYTimes/gizmo/config/metrics"
"github.com/NYTimes/gizmo/web"
)
// SimpleServer is a basic http Server implementation for
// serving SimpleService, JSONService or MixedService implementations.
type SimpleServer struct {
// tracks if the Register function is already called or not
registered bool
cfg *Config
// exit chan for graceful shutdown
exit chan chan error
// mux for routing
mux Router
svc Service
// tracks active requests
monitor *ActivityMonitor
// for collecting metrics
mets provider.Provider
panicCounter metrics.Counter
}
// NewSimpleServer will init the mux, exit channel and
// build the address from the given port. It will register the HealthCheckHandler
// at the given path and set up the shutDownHandler to be called on Stop().
func NewSimpleServer(cfg *Config) *SimpleServer {
if cfg == nil {
cfg = &Config{}
}
mx := NewRouter(cfg)
if cfg.NotFoundHandler != nil {
mx.SetNotFoundHandler(cfg.NotFoundHandler)
}
mets := newMetricsProvider(cfg)
return &SimpleServer{
mux: mx,
cfg: cfg,
exit: make(chan chan error),
monitor: NewActivityMonitor(),
mets: mets,
panicCounter: mets.NewCounter("panic"),
}
}
// ServeHTTP is SimpleServer's hook for metrics and safely executing each request.
func (s *SimpleServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
AddIPToContext(r)
// only count non-LB requests
if r.URL.Path != s.cfg.HealthCheckPath {
s.monitor.CountRequest()
defer s.monitor.UncountRequest()
}
s.safelyExecuteRequest(w, r)
}
// UnexpectedServerError is returned with a 500 status code when SimpleServer recovers
// from a panic in a request.
var UnexpectedServerError = []byte("unexpected server error")
// executeRequestSafely will prevent a panic in a request from bringing the server down.
func (s *SimpleServer) safelyExecuteRequest(w http.ResponseWriter, r *http.Request) {
defer func() {
if x := recover(); x != nil {
// register a panic'd request with our metrics
s.panicCounter.Add(1)
// log the panic for all the details later
LogWithFields(r).Errorf("simple server recovered from a panic\n%v: %v", x, string(debug.Stack()))
// give the users our deepest regrets
w.WriteHeader(http.StatusInternalServerError)
if _, err := w.Write(UnexpectedServerError); err != nil {
LogWithFields(r).Warn("unable to write response: ", err)
}
}
}()
// lookup metric name if we can
registeredPath := r.URL.Path
if muxr, ok := s.mux.(*GorillaRouter); ok {
registeredPath = "__404__"
var match mux.RouteMatch
if muxr.mux.Match(r, &match) && match.MatchErr == nil {
if tmpl, err := match.Route.GetPathTemplate(); err == nil {
registeredPath = tmpl
}
}
}
TimedAndCounted(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
defer func() {
if err := r.Body.Close(); err != nil {
Log.Warn("unable to close request body: ", err)
}
}()
}
s.svc.Middleware(s.mux).ServeHTTP(w, r)
}), registeredPath, r.Method, s.mets).ServeHTTP(w, r)
}
// Start will start the SimpleServer at it's configured address.
// If they are configured, this will start health checks and access logging.
func (s *SimpleServer) Start() error {
healthHandler := RegisterHealthHandler(s.cfg, s.monitor, s.mux)
s.cfg.HealthCheckPath = healthHandler.Path()
// if expvar, register on our router
switch s.cfg.Metrics.Type {
case metricscfg.Expvar:
if s.cfg.Metrics.Path == "" {
s.cfg.Metrics.Path = "/debug/vars"
}
s.mux.HandleFunc("GET", s.cfg.Metrics.Path, expvarHandler)
case metricscfg.Prometheus:
if s.cfg.Metrics.Path == "" {
s.cfg.Metrics.Path = "/metrics"
}
s.mux.HandleFunc("GET", s.cfg.Metrics.Path,
prometheus.InstrumentHandler("prometheus", prometheus.UninstrumentedHandler()))
}
// if this is an App Engine setup, just run it here
if s.cfg.appEngine {
http.Handle("/", s)
appengine.Main()
return nil
}
wrappedHandler, err := NewAccessLogMiddleware(s.cfg.HTTPAccessLog, s)
if err != nil {
Log.Fatalf("unable to create http access log: %s", err)
}
srv := httpServer(wrappedHandler)
l, err := net.Listen("tcp", fmt.Sprintf(":%d", s.cfg.HTTPPort))
if err != nil {
return err
}
l = net.Listener(TCPKeepAliveListener{l.(*net.TCPListener)})
// add TLS if in the configs
if s.cfg.TLSCertFile != nil && s.cfg.TLSKeyFile != nil {
cert, err := tls.LoadX509KeyPair(*s.cfg.TLSCertFile, *s.cfg.TLSKeyFile)
if err != nil {
return err
}
srv.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
NextProtos: []string{"http/1.1"},
}
l = tls.NewListener(l, srv.TLSConfig)
}
go func() {
if err := srv.Serve(l); err != nil {
Log.Error("encountered an error while serving listener: ", err)
}
}()
Log.Infof("Listening on %s", l.Addr().String())
// join the LB
go func() {
exit := <-s.exit
// let the health check clean up if it needs to
if err := healthHandler.Stop(); err != nil {
Log.Warn("health check Stop returned with error: ", err)
}
// flush any remaining metrics and close connections
s.mets.Stop()
// stop the listener
exit <- l.Close()
}()
return nil
}
// Stop initiates the shutdown process and returns when
// the server completes.
func (s *SimpleServer) Stop() error {
ch := make(chan error)
s.exit <- ch
return <-ch
}
// Register will accept and register SimpleServer, JSONService or MixedService implementations.
func (s *SimpleServer) Register(svcI Service) error {
// check multiple register call error
if s.registered {
return ErrMultiRegister
}
// set registered to true because we called it
s.registered = true
s.svc = svcI
prefix := svcI.Prefix()
// quick fix for backwards compatibility
prefix = strings.TrimRight(prefix, "/")
var (
js JSONService
ss SimpleService
cs ContextService
mcs MixedContextService
)
switch svc := svcI.(type) {
case MixedService:
js = svc
ss = svc
case SimpleService:
ss = svc
case JSONService:
js = svc
case MixedContextService:
mcs = svc
cs = svc
case ContextService:
cs = svc
default:
return errors.New("services for SimpleServers must implement the SimpleService, JSONService or MixedService interfaces")
}
if ss != nil {
// register all simple endpoints with our wrapper
for path, epMethods := range ss.Endpoints() {
for method, ep := range epMethods {
s.mux.Handle(method, prefix+path, ep)
}
}
}
if js != nil {
// register all JSON endpoints with our wrapper
for path, epMethods := range js.JSONEndpoints() {
for method, ep := range epMethods {
s.mux.Handle(method, prefix+path, JSONToHTTP(js.JSONMiddleware(ep)))
}
}
}
if cs != nil {
// register all context endpoints with our wrapper
for path, epMethods := range cs.ContextEndpoints() {
for method, ep := range epMethods {
s.mux.Handle(method, prefix+path, ContextToHTTP(cs.ContextMiddleware(ep)))
}
}
}
if mcs != nil {
// register all context endpoints with our wrapper
for path, epMethods := range mcs.JSONEndpoints() {
for method, ep := range epMethods {
// set the function handle and register it to metrics
s.mux.Handle(method, prefix+path, ContextToHTTP(mcs.ContextMiddleware(
JSONContextToHTTP(mcs.JSONContextMiddleware(ep)),
)))
}
}
}
RegisterProfiler(s.cfg, s.mux)
return nil
}
// GetForwardedIP returns the "X-Forwarded-For" header value.
func GetForwardedIP(r *http.Request) string {
return r.Header.Get("X-Forwarded-For")
}
// GetIP returns the IP address for the given request.
func GetIP(r *http.Request) (string, error) {
ip, ok := web.Vars(r)["ip"]
if ok {
return ip, nil
}
// check real ip header first
ip = r.Header.Get("X-Real-IP")
if len(ip) > 0 {
return ip, nil
}
// no nginx reverse proxy?
// get IP old fashioned way
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", fmt.Errorf("%q is not IP:port", r.RemoteAddr)
}
userIP := net.ParseIP(ip)
if userIP == nil {
return "", fmt.Errorf("%q is not IP:port", r.RemoteAddr)
}
return userIP.String(), nil
}
// ContextKey used to create context keys.
type ContextKey int
const (
// UserIPKey is key to set/retrieve value from context.
UserIPKey ContextKey = 0
// UserForwardForIPKey is key to set/retrieve value from context.
UserForwardForIPKey ContextKey = 1
)
// ContextWithUserIP returns new context with user ip address.
func ContextWithUserIP(ctx netContext.Context, r *http.Request) netContext.Context {
ip, err := GetIP(r)
if err != nil {
LogWithFields(r).Warningf("unable to get IP: %s", err)
return ctx
}
return netContext.WithValue(ctx, UserIPKey, ip)
}
// ContextWithForwardForIP returns new context with forward for ip.
func ContextWithForwardForIP(ctx netContext.Context, r *http.Request) netContext.Context {
ip := GetForwardedIP(r)
if len(ip) > 0 {
ctx = netContext.WithValue(ctx, UserForwardForIPKey, ip)
}
return ctx
}