Debian Codegraph @

server/server.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package server provides a preconfigured HTTP server with diagnostic hooks.
16 package server // import "gocloud.dev/server"
17
18 import (
19 "context"
20 "fmt"
21 "net/http"
22 "sync"
23 "time"
24
25 "github.com/google/wire"
26 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
27 "go.opentelemetry.io/otel"
28 "go.opentelemetry.io/otel/metric"
29 "go.opentelemetry.io/otel/propagation"
30 "go.opentelemetry.io/otel/trace"
31
32 "gocloud.dev/server/driver"
33 "gocloud.dev/server/health"
34 "gocloud.dev/server/requestlog"
35 )
36
37 // Set is a Wire provider set that produces a *Server given the fields of
38 // Options.
39 var Set = wire.NewSet(
40 New,
41 wire.Struct(new(Options), "RequestLogger", "HealthChecks",
42 "TraceTextMapPropagator", "TraceProvider", "MetricsProvider", "Driver"),
43 wire.Value(&DefaultDriver{}),
44 wire.Bind(new(driver.Server), new(*DefaultDriver)),
45 )
46
47 // Server is a preconfigured HTTP server with diagnostic hooks.
48 // The zero value is a server with the default options.
49 type Server struct {
50 reqlog requestlog.Logger
51 handler http.Handler
52 wrappedHandler http.Handler
53 healthHandler health.Handler
54 textMapPropagator propagation.TextMapPropagator
55 traceProvider trace.TracerProvider
56 meterProvider metric.MeterProvider
57 once sync.Once
58 driver driver.Server
59 }
60
61 // Options is the set of optional parameters.
62 type Options struct {
63 // RequestLogger specifies the logger that will be used to log requests.
64 RequestLogger requestlog.Logger
65
66 // HealthChecks specifies the health checks to be run when the
67 // /healthz/readiness endpoint is requested.
68 HealthChecks []health.Checker
69
70 // TraceTextMapPropagator decides the format of trace text propagated.
71 TraceTextMapPropagator propagation.TextMapPropagator
72
73 // TraceProvider handles sampled trace spans.
74 TraceProvider trace.TracerProvider
75
76 // MetricsProvider handles application metrics.
77 MetricsProvider metric.MeterProvider
78
79 // Driver serves HTTP requests.
80 Driver driver.Server
81 }
82
83 // New creates a new server. New(nil, nil) is the same as new(Server).
84 func New(h http.Handler, opts *Options) *Server {
85 srv := &Server{handler: h}
86 if opts != nil {
87 srv.reqlog = opts.RequestLogger
88 srv.textMapPropagator = opts.TraceTextMapPropagator
89 srv.traceProvider = opts.TraceProvider
90 srv.meterProvider = opts.MetricsProvider
91 for _, c := range opts.HealthChecks {
92 srv.healthHandler.Add(c)
93 }
94 srv.driver = opts.Driver
95 }
96 return srv
97 }
98
99 func (srv *Server) init() {
100 srv.once.Do(func() {
101
102 if srv.textMapPropagator != nil {
103 otel.SetTextMapPropagator(srv.textMapPropagator)
104 }
105
106 if srv.traceProvider != nil {
107 otel.SetTracerProvider(srv.traceProvider)
108 }
109
110 if srv.meterProvider != nil {
111 otel.SetMeterProvider(srv.meterProvider)
112 }
113
114 if srv.driver == nil {
115 srv.driver = NewDefaultDriver()
116 }
117 if srv.handler == nil {
118 srv.handler = http.DefaultServeMux
119 }
120 // Setup health checks, /healthz route is taken by health checks by default.
121 // Note: App Engine Flex uses /_ah/health by default, which can be changed
122 // in app.yaml. We may want to do an auto-detection for flex in future.
123 const healthPrefix = "/healthz/"
124
125 mux := http.NewServeMux()
126 mux.HandleFunc(healthPrefix+"liveness", health.HandleLive)
127 mux.Handle(healthPrefix+"readiness", &srv.healthHandler)
128 h := srv.handler
129 if srv.reqlog != nil {
130 h = requestlog.NewHandler(srv.reqlog, h)
131 }
132 // Wrap with OpenTelemetry HTTP handler.
133 h = otelhttp.NewHandler(h, "", otelhttp.WithPublicEndpoint())
134 mux.Handle("/", h)
135 srv.wrappedHandler = mux
136 })
137 }
138
139 // ListenAndServe is a wrapper to use wherever http.ListenAndServe is used.
140 // It wraps the http.Handler provided to New with a handler that handles tracing and
141 // request logging. If the handler is nil, then http.DefaultServeMux will be used.
142 // A configured Requestlogger will log all requests except HealthChecks.
143 func (srv *Server) ListenAndServe(addr string) error {
144 srv.init()
145 return srv.driver.ListenAndServe(addr, srv.wrappedHandler)
146 }
147
148 // ListenAndServeTLS is a wrapper to use wherever http.ListenAndServeTLS is used.
149 // It wraps the http.Handler provided to New with a handler that handles tracing and
150 // request logging. If the handler is nil, then http.DefaultServeMux will be used.
151 // A configured Requestlogger will log all requests except HealthChecks.
152 func (srv *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
153 // Check if the driver implements the optional interface.
154 tlsDriver, ok := srv.driver.(driver.TLSServer)
155 if !ok {
156 return fmt.Errorf("driver %T does not support ListenAndServeTLS", srv.driver)
157 }
158 srv.init()
159 return tlsDriver.ListenAndServeTLS(addr, certFile, keyFile, srv.wrappedHandler)
160 }
161
162 // Shutdown gracefully shuts down the server without interrupting any active connections.
163 func (srv *Server) Shutdown(ctx context.Context) error {
164 if srv.driver == nil {
165 return nil
166 }
167 return srv.driver.Shutdown(ctx)
168 }
169
170 // DefaultDriver implements the driver.Server interface. The zero value is a valid http.Server.
171 type DefaultDriver struct {
172 Server http.Server
173 }
174
175 // NewDefaultDriver creates a driver with an http.Server with default timeouts.
176 func NewDefaultDriver() *DefaultDriver {
177 return &DefaultDriver{
178 Server: http.Server{
179 ReadTimeout: 30 * time.Second,
180 WriteTimeout: 30 * time.Second,
181 IdleTimeout: 120 * time.Second,
182 },
183 }
184 }
185
186 // ListenAndServe sets the address and handler on DefaultDriver's http.Server,
187 // then calls ListenAndServe on it.
188 func (dd *DefaultDriver) ListenAndServe(addr string, h http.Handler) error {
189 dd.Server.Addr = addr
190 dd.Server.Handler = h
191 return dd.Server.ListenAndServe()
192 }
193
194 // ListenAndServeTLS sets the address and handler on DefaultDriver's http.Server,
195 // then calls ListenAndServeTLS on it.
196 //
197 // DefaultDriver.Server.TLSConfig may be set to configure additional TLS settings.
198 func (dd *DefaultDriver) ListenAndServeTLS(addr, certFile, keyFile string, h http.Handler) error {
199 dd.Server.Addr = addr
200 dd.Server.Handler = h
201 return dd.Server.ListenAndServeTLS(certFile, keyFile)
202 }
203
204 // Shutdown gracefully shuts down the server without interrupting any active connections,
205 // by calling Shutdown on DefaultDriver's http.Server
206 func (dd *DefaultDriver) Shutdown(ctx context.Context) error {
207 return dd.Server.Shutdown(ctx)
208 }