forked from TheThingsNetwork/lorawan-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpcserver.go
More file actions
242 lines (222 loc) · 8.48 KB
/
rpcserver.go
File metadata and controls
242 lines (222 loc) · 8.48 KB
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
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// 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 rpcserver initializes The Things Network's base gRPC server
package rpcserver
import (
"context"
"fmt"
"math"
"net/http"
"os"
"runtime/debug"
"time"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"go.opencensus.io/plugin/ocgrpc"
"go.thethings.network/lorawan-stack/v3/pkg/errors"
"go.thethings.network/lorawan-stack/v3/pkg/events"
"go.thethings.network/lorawan-stack/v3/pkg/fillcontext"
"go.thethings.network/lorawan-stack/v3/pkg/jsonpb"
"go.thethings.network/lorawan-stack/v3/pkg/metrics"
"go.thethings.network/lorawan-stack/v3/pkg/rpcmetadata"
"go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware"
rpcfillcontext "go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware/fillcontext"
"go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware/hooks"
"go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware/rpclog"
sentrymiddleware "go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware/sentry"
"go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware/validator"
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
"google.golang.org/grpc"
_ "google.golang.org/grpc/encoding/gzip" // Register gzip compression.
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
)
func init() {
grpc.EnableTracing = false
for rpc, paths := range ttnpb.AllowedFieldMaskPathsForRPC {
validator.RegisterAllowedFieldMaskPaths(rpc, paths...)
}
}
type options struct {
contextFillers []fillcontext.Filler
fieldExtractor grpc_ctxtags.RequestFieldExtractorFunc
streamInterceptors []grpc.StreamServerInterceptor
unaryInterceptors []grpc.UnaryServerInterceptor
serverOptions []grpc.ServerOption
logIgnoreMethods []string
}
// Option for the gRPC server
type Option func(*options)
// WithServerOptions adds gRPC ServerOptions
func WithServerOptions(serverOptions ...grpc.ServerOption) Option {
return func(o *options) {
o.serverOptions = append(o.serverOptions, serverOptions...)
}
}
// WithContextFiller sets a context filler
func WithContextFiller(contextFillers ...fillcontext.Filler) Option {
return func(o *options) {
o.contextFillers = append(o.contextFillers, contextFillers...)
}
}
// WithFieldExtractor sets a field extractor
func WithFieldExtractor(fieldExtractor grpc_ctxtags.RequestFieldExtractorFunc) Option {
return func(o *options) {
o.fieldExtractor = fieldExtractor
}
}
// WithStreamInterceptors adds gRPC stream interceptors
func WithStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option {
return func(o *options) {
o.streamInterceptors = append(o.streamInterceptors, interceptors...)
}
}
// WithUnaryInterceptors adds gRPC unary interceptors
func WithUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option {
return func(o *options) {
o.unaryInterceptors = append(o.unaryInterceptors, interceptors...)
}
}
// WithLogIgnoreMethods sets a list of methods for which no log messages are printed on success.
func WithLogIgnoreMethods(methods []string) Option {
return func(o *options) {
o.logIgnoreMethods = methods
}
}
// ErrRPCRecovered is returned when a panic is caught from an RPC.
var ErrRPCRecovered = errors.DefineInternal("rpc_recovered", "Internal Server Error")
// New returns a new RPC server with a set of middlewares.
// The given context is used in some of the middlewares, the given server options are passed to gRPC
//
// Currently the following middlewares are included: tag extraction, metrics,
// logging, sending errors to Sentry, validation, errors, panic recovery
func New(ctx context.Context, opts ...Option) *Server {
options := new(options)
for _, opt := range opts {
opt(options)
}
server := &Server{ctx: ctx}
ctxtagsOpts := []grpc_ctxtags.Option{
grpc_ctxtags.WithFieldExtractor(options.fieldExtractor),
}
recoveryOpts := []grpc_recovery.Option{
grpc_recovery.WithRecoveryHandler(func(p interface{}) (err error) {
fmt.Fprintln(os.Stderr, p)
os.Stderr.Write(debug.Stack())
if pErr, ok := p.(error); ok {
err = ErrRPCRecovered.WithCause(pErr)
} else {
err = ErrRPCRecovered.WithAttributes("panic", p)
}
return err
}),
}
streamInterceptors := []grpc.StreamServerInterceptor{
rpcfillcontext.StreamServerInterceptor(options.contextFillers...),
grpc_ctxtags.StreamServerInterceptor(ctxtagsOpts...),
rpcmiddleware.RequestIDStreamServerInterceptor(),
grpc_opentracing.StreamServerInterceptor(),
events.StreamServerInterceptor,
rpclog.StreamServerInterceptor(ctx, rpclog.WithIgnoreMethods(options.logIgnoreMethods)),
metrics.StreamServerInterceptor,
sentrymiddleware.StreamServerInterceptor(),
errors.StreamServerInterceptor(),
validator.StreamServerInterceptor(),
hooks.StreamServerInterceptor(),
}
unaryInterceptors := []grpc.UnaryServerInterceptor{
rpcfillcontext.UnaryServerInterceptor(options.contextFillers...),
grpc_ctxtags.UnaryServerInterceptor(ctxtagsOpts...),
rpcmiddleware.RequestIDUnaryServerInterceptor(),
grpc_opentracing.UnaryServerInterceptor(),
events.UnaryServerInterceptor,
rpclog.UnaryServerInterceptor(ctx, rpclog.WithIgnoreMethods(options.logIgnoreMethods)),
metrics.UnaryServerInterceptor,
sentrymiddleware.UnaryServerInterceptor(),
errors.UnaryServerInterceptor(),
validator.UnaryServerInterceptor(),
hooks.UnaryServerInterceptor(),
}
baseOptions := []grpc.ServerOption{
grpc.StatsHandler(rpcmiddleware.StatsHandlers{new(ocgrpc.ServerHandler), metrics.StatsHandler}),
grpc.MaxConcurrentStreams(math.MaxUint16),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 1 * time.Minute,
PermitWithoutStream: true,
}),
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: 6 * time.Hour,
MaxConnectionAge: 24 * time.Hour,
Time: 1 * time.Minute,
Timeout: 20 * time.Second,
}),
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
append(
append(streamInterceptors, options.streamInterceptors...),
grpc_recovery.StreamServerInterceptor(recoveryOpts...),
)...,
)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
append(
append(unaryInterceptors, options.unaryInterceptors...),
grpc_recovery.UnaryServerInterceptor(recoveryOpts...),
)...,
)),
}
server.Server = grpc.NewServer(append(baseOptions, options.serverOptions...)...)
server.ServeMux = runtime.NewServeMux(
runtime.WithMarshalerOption("*", jsonpb.TTN()),
runtime.WithMarshalerOption("text/event-stream", jsonpb.TTNEventStream()),
runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler),
runtime.WithMetadata(func(ctx context.Context, req *http.Request) metadata.MD {
md := rpcmetadata.MD{
Host: req.Host,
URI: req.RequestURI,
}
return md.ToMetadata()
}),
runtime.WithOutgoingHeaderMatcher(func(s string) (string, bool) {
// NOTE: When adding headers, also add them to CORSConfig in ../component/grpc.go.
switch s {
case "x-total-count":
return "X-Total-Count", true
case "warning":
// NOTE: the "Warning" header in HTTP is specified differently than our "warning" gRPC metadata.
return "X-Warning", true
}
return s, false
}),
runtime.WithDisablePathLengthFallback(),
)
return server
}
// Registerer allows components to register their services to the gRPC server and the HTTP gateway
type Registerer interface {
Roles() []ttnpb.ClusterRole
RegisterServices(s *grpc.Server)
RegisterHandlers(s *runtime.ServeMux, conn *grpc.ClientConn)
}
// Server wraps the gRPC server
type Server struct {
ctx context.Context
*grpc.Server
*runtime.ServeMux
}
// ServeHTTP forwards requests to the gRPC gateway
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.ServeMux.ServeHTTP(w, r)
}