-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
server.go
341 lines (291 loc) · 10.3 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
336
337
338
339
340
341
// Copyright (c) 2019,2020 The Jaeger Authors.
//
// 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 app
import (
"context"
"errors"
"net"
"net/http"
"strings"
"time"
"github.com/gorilla/handlers"
"github.com/opentracing/opentracing-go"
"github.com/soheilhy/cmux"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
"github.com/jaegertracing/jaeger/cmd/query/app/apiv3"
"github.com/jaegertracing/jaeger/cmd/query/app/querysvc"
"github.com/jaegertracing/jaeger/pkg/bearertoken"
"github.com/jaegertracing/jaeger/pkg/healthcheck"
"github.com/jaegertracing/jaeger/pkg/netutils"
"github.com/jaegertracing/jaeger/pkg/recoveryhandler"
"github.com/jaegertracing/jaeger/pkg/tenancy"
"github.com/jaegertracing/jaeger/proto-gen/api_v2"
"github.com/jaegertracing/jaeger/proto-gen/api_v2/metrics"
"github.com/jaegertracing/jaeger/proto-gen/api_v3"
)
// Server runs HTTP, Mux and a grpc server
type Server struct {
logger *zap.Logger
querySvc *querysvc.QueryService
queryOptions *QueryOptions
tracer opentracing.Tracer // TODO make part of flags.Service
conn net.Listener
grpcConn net.Listener
httpConn net.Listener
cmuxServer cmux.CMux
grpcServer *grpc.Server
httpServer *http.Server
separatePorts bool
unavailableChannel chan healthcheck.Status
grpcGatewayCancel context.CancelFunc
}
// NewServer creates and initializes Server
func NewServer(logger *zap.Logger, querySvc *querysvc.QueryService, metricsQuerySvc querysvc.MetricsQueryService, options *QueryOptions, tm *tenancy.Manager, tracer opentracing.Tracer) (*Server, error) {
_, httpPort, err := net.SplitHostPort(options.HTTPHostPort)
if err != nil {
return nil, err
}
_, grpcPort, err := net.SplitHostPort(options.GRPCHostPort)
if err != nil {
return nil, err
}
if (options.TLSHTTP.Enabled || options.TLSGRPC.Enabled) && (grpcPort == httpPort) {
return nil, errors.New("server with TLS enabled can not use same host ports for gRPC and HTTP. Use dedicated HTTP and gRPC host ports instead")
}
grpcServer, err := createGRPCServer(querySvc, metricsQuerySvc, options, tm, logger, tracer)
if err != nil {
return nil, err
}
httpServer, closeGRPCGateway, err := createHTTPServer(querySvc, metricsQuerySvc, options, tm, tracer, logger)
if err != nil {
return nil, err
}
return &Server{
logger: logger,
querySvc: querySvc,
queryOptions: options,
tracer: tracer,
grpcServer: grpcServer,
httpServer: httpServer,
separatePorts: grpcPort != httpPort,
unavailableChannel: make(chan healthcheck.Status),
grpcGatewayCancel: closeGRPCGateway,
}, nil
}
// HealthCheckStatus returns health check status channel a client can subscribe to
func (s Server) HealthCheckStatus() chan healthcheck.Status {
return s.unavailableChannel
}
func createGRPCServer(querySvc *querysvc.QueryService, metricsQuerySvc querysvc.MetricsQueryService, options *QueryOptions, tm *tenancy.Manager, logger *zap.Logger, tracer opentracing.Tracer) (*grpc.Server, error) {
var grpcOpts []grpc.ServerOption
if options.TLSGRPC.Enabled {
tlsCfg, err := options.TLSGRPC.Config(logger)
if err != nil {
return nil, err
}
creds := credentials.NewTLS(tlsCfg)
grpcOpts = append(grpcOpts, grpc.Creds(creds))
}
if tm.Enabled {
grpcOpts = append(grpcOpts,
grpc.StreamInterceptor(tenancy.NewGuardingStreamInterceptor(tm)),
grpc.UnaryInterceptor(tenancy.NewGuardingUnaryInterceptor(tm)),
)
}
server := grpc.NewServer(grpcOpts...)
reflection.Register(server)
handler := &GRPCHandler{
queryService: querySvc,
metricsQueryService: metricsQuerySvc,
logger: logger,
tracer: tracer,
nowFn: time.Now,
}
healthServer := health.NewServer()
api_v2.RegisterQueryServiceServer(server, handler)
metrics.RegisterMetricsQueryServiceServer(server, handler)
api_v3.RegisterQueryServiceServer(server, &apiv3.Handler{QueryService: querySvc})
healthServer.SetServingStatus("jaeger.api_v2.QueryService", grpc_health_v1.HealthCheckResponse_SERVING)
healthServer.SetServingStatus("jaeger.api_v2.metrics.MetricsQueryService", grpc_health_v1.HealthCheckResponse_SERVING)
healthServer.SetServingStatus("jaeger.api_v3.QueryService", grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(server, healthServer)
return server, nil
}
func createHTTPServer(querySvc *querysvc.QueryService, metricsQuerySvc querysvc.MetricsQueryService, queryOpts *QueryOptions, tm *tenancy.Manager, tracer opentracing.Tracer, logger *zap.Logger) (*http.Server, context.CancelFunc, error) {
apiHandlerOptions := []HandlerOption{
HandlerOptions.Logger(logger),
HandlerOptions.Tracer(tracer),
HandlerOptions.MetricsQueryService(metricsQuerySvc),
}
apiHandler := NewAPIHandler(
querySvc,
tm,
apiHandlerOptions...)
r := NewRouter()
if queryOpts.BasePath != "/" {
r = r.PathPrefix(queryOpts.BasePath).Subrouter()
}
ctx, closeGRPCGateway := context.WithCancel(context.Background())
if err := apiv3.RegisterGRPCGateway(ctx, logger, r, queryOpts.BasePath, queryOpts.GRPCHostPort, queryOpts.TLSGRPC, tm); err != nil {
closeGRPCGateway()
return nil, nil, err
}
apiHandler.RegisterRoutes(r)
RegisterStaticHandler(r, logger, queryOpts)
var handler http.Handler = r
handler = additionalHeadersHandler(handler, queryOpts.AdditionalHeaders)
if queryOpts.BearerTokenPropagation {
handler = bearertoken.PropagationHandler(logger, handler)
}
handler = handlers.CompressHandler(handler)
recoveryHandler := recoveryhandler.NewRecoveryHandler(logger, true)
errorLog, _ := zap.NewStdLogAt(logger, zapcore.ErrorLevel)
server := &http.Server{
Handler: recoveryHandler(handler),
ErrorLog: errorLog,
ReadHeaderTimeout: 2 * time.Second,
}
if queryOpts.TLSHTTP.Enabled {
tlsCfg, err := queryOpts.TLSHTTP.Config(logger) // This checks if the certificates are correctly provided
if err != nil {
closeGRPCGateway()
return nil, nil, err
}
server.TLSConfig = tlsCfg
}
return server, closeGRPCGateway, nil
}
// initListener initialises listeners of the server
func (s *Server) initListener() (cmux.CMux, error) {
if s.separatePorts { // use separate ports and listeners each for gRPC and HTTP requests
var err error
s.grpcConn, err = net.Listen("tcp", s.queryOptions.GRPCHostPort)
if err != nil {
return nil, err
}
s.httpConn, err = net.Listen("tcp", s.queryOptions.HTTPHostPort)
if err != nil {
return nil, err
}
s.logger.Info(
"Query server started",
zap.String("http_addr", s.httpConn.Addr().String()),
zap.String("grpc_addr", s.grpcConn.Addr().String()),
)
return nil, nil
}
// old behavior using cmux
conn, err := net.Listen("tcp", s.queryOptions.HTTPHostPort)
if err != nil {
return nil, err
}
s.conn = conn
var tcpPort int
if port, err := netutils.GetPort(s.conn.Addr()); err == nil {
tcpPort = port
}
s.logger.Info(
"Query server started",
zap.Int("port", tcpPort),
zap.String("addr", s.queryOptions.HTTPHostPort))
// cmux server acts as a reverse-proxy between HTTP and GRPC backends.
cmuxServer := cmux.New(s.conn)
s.grpcConn = cmuxServer.MatchWithWriters(
cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"),
cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc+proto"),
)
s.httpConn = cmuxServer.Match(cmux.Any())
return cmuxServer, nil
}
// Start http, GRPC and cmux servers concurrently
func (s *Server) Start() error {
cmuxServer, err := s.initListener()
if err != nil {
return err
}
s.cmuxServer = cmuxServer
var tcpPort int
if !s.separatePorts {
if port, err := netutils.GetPort(s.conn.Addr()); err == nil {
tcpPort = port
}
}
var httpPort int
if port, err := netutils.GetPort(s.httpConn.Addr()); err == nil {
httpPort = port
}
var grpcPort int
if port, err := netutils.GetPort(s.grpcConn.Addr()); err == nil {
grpcPort = port
}
go func() {
s.logger.Info("Starting HTTP server", zap.Int("port", httpPort), zap.String("addr", s.queryOptions.HTTPHostPort))
var err error
if s.queryOptions.TLSHTTP.Enabled {
err = s.httpServer.ServeTLS(s.httpConn, "", "")
} else {
err = s.httpServer.Serve(s.httpConn)
}
switch err {
case nil, http.ErrServerClosed, cmux.ErrListenerClosed, cmux.ErrServerClosed:
// normal exit, nothing to do
default:
s.logger.Error("Could not start HTTP server", zap.Error(err))
}
s.unavailableChannel <- healthcheck.Unavailable
}()
// Start GRPC server concurrently
go func() {
s.logger.Info("Starting GRPC server", zap.Int("port", grpcPort), zap.String("addr", s.queryOptions.GRPCHostPort))
if err := s.grpcServer.Serve(s.grpcConn); err != nil {
s.logger.Error("Could not start GRPC server", zap.Error(err))
}
s.unavailableChannel <- healthcheck.Unavailable
}()
// Start cmux server concurrently.
if !s.separatePorts {
go func() {
s.logger.Info("Starting CMUX server", zap.Int("port", tcpPort), zap.String("addr", s.queryOptions.HTTPHostPort))
err := cmuxServer.Serve()
// TODO: find a way to avoid string comparison. Even though cmux has ErrServerClosed, it's not returned here.
if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
s.logger.Error("Could not start multiplexed server", zap.Error(err))
}
s.unavailableChannel <- healthcheck.Unavailable
}()
}
return nil
}
// Close stops http, GRPC servers and closes the port listener.
func (s *Server) Close() error {
s.grpcGatewayCancel()
s.queryOptions.TLSGRPC.Close()
s.queryOptions.TLSHTTP.Close()
s.grpcServer.Stop()
s.httpServer.Close()
if s.separatePorts {
s.httpConn.Close()
s.grpcConn.Close()
} else {
s.cmuxServer.Close()
s.conn.Close()
}
return nil
}