-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.go
189 lines (160 loc) · 5 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
/*
* Copyright 2017 Kopano and its licensors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package server
import (
"context"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
"github.com/longsleep/go-metrics/loggedwriter"
"github.com/longsleep/go-metrics/timing"
"github.com/sirupsen/logrus"
)
// Server is our HTTP server implementation.
type Server struct {
Config *Config
listenAddr string
logger logrus.FieldLogger
requestLog bool
}
// NewServer constructs a server from the provided parameters.
func NewServer(c *Config) (*Server, error) {
s := &Server{
Config: c,
listenAddr: c.Config.ListenAddr,
logger: c.Config.Logger,
requestLog: os.Getenv("KOPANO_DEBUG_SERVER_REQUEST_LOG") == "1",
}
return s, nil
}
// AddContext adds the accociated server context with cancel to the the provided
// httprouter.Handle. When the handler is done, the per Request context is
// cancelled.
func (s *Server) AddContext(parent context.Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// Create per request context.
ctx, cancel := context.WithCancel(parent)
if s.requestLog {
loggedWriter := metrics.NewLoggedResponseWriter(rw)
// Create per request context.
ctx = timing.NewContext(ctx, func(duration time.Duration) {
// This is the stop callback, called when complete with duration.
durationMs := float64(duration) / float64(time.Millisecond)
// Log request.
s.logger.WithFields(logrus.Fields{
"status": loggedWriter.Status(),
"method": req.Method,
"path": req.URL.Path,
"remote": req.RemoteAddr,
"duration": durationMs,
"referer": req.Referer(),
"user-agent": req.UserAgent(),
"origin": req.Header.Get("Origin"),
}).Debug("HTTP request complete")
})
rw = loggedWriter
}
// Run the request.
next.ServeHTTP(rw, req.WithContext(ctx))
// Cancel per request context when done.
cancel()
})
}
// AddRoutes add the accociated Servers URL routes to the provided router with
// the provided context.Context.
func (s *Server) AddRoutes(ctx context.Context, router *mux.Router) {
// TODO(longsleep): Add subpath support to all handlers and paths.
router.HandleFunc("/health-check", s.HealthCheckHandler)
for _, route := range s.Config.Routes {
route.AddRoutes(ctx, router)
}
if s.Config.Handler != nil {
// Delegate rest to provider which is also a handler.
router.NotFoundHandler = s.Config.Handler
}
}
// Serve starts all the accociated servers resources and listeners and blocks
// forever until signals or error occurs. Returns error and gracefully stops
// all HTTP listeners before return.
func (s *Server) Serve(ctx context.Context) error {
serveCtx, serveCtxCancel := context.WithCancel(ctx)
defer serveCtxCancel()
logger := s.logger
errCh := make(chan error, 2)
exitCh := make(chan bool, 1)
signalCh := make(chan os.Signal)
router := mux.NewRouter()
s.AddRoutes(serveCtx, router)
// HTTP listener.
srv := &http.Server{
Handler: s.AddContext(serveCtx, router),
}
logger.WithField("listenAddr", s.listenAddr).Infoln("starting http listener")
listener, err := net.Listen("tcp", s.listenAddr)
if err != nil {
return err
}
logger.Infoln("ready to handle requests")
go func() {
serveErr := srv.Serve(listener)
if serveErr != nil {
errCh <- serveErr
}
logger.Debugln("http listener stopped")
close(exitCh)
}()
// Wait for exit or error.
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
select {
case err = <-errCh:
// breaks
case reason := <-signalCh:
logger.WithField("signal", reason).Warnln("received signal")
// breaks
}
// Shutdown, server will stop to accept new connections, requires Go 1.8+.
logger.Infoln("clean server shutdown start")
shutDownCtx, shutDownCtxCancel := context.WithTimeout(ctx, 10*time.Second)
if shutdownErr := srv.Shutdown(shutDownCtx); shutdownErr != nil {
logger.WithError(shutdownErr).Warn("clean server shutdown failed")
}
// Cancel our own context, wait on managers.
serveCtxCancel()
func() {
for {
select {
case <-exitCh:
return
default:
// HTTP listener has not quit yet.
logger.Info("waiting for http listener to exit")
}
select {
case reason := <-signalCh:
logger.WithField("signal", reason).Warn("received signal")
return
case <-time.After(100 * time.Millisecond):
}
}
}()
shutDownCtxCancel() // prevent leak.
return err
}