-
Notifications
You must be signed in to change notification settings - Fork 113
/
rgrpc.go
348 lines (297 loc) · 9.98 KB
/
rgrpc.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
// Copyright 2018-2021 CERN
//
// 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.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package rgrpc
import (
"fmt"
"io"
"net"
"sort"
"github.com/cs3org/reva/internal/grpc/interceptors/appctx"
"github.com/cs3org/reva/internal/grpc/interceptors/auth"
"github.com/cs3org/reva/internal/grpc/interceptors/log"
"github.com/cs3org/reva/internal/grpc/interceptors/recovery"
"github.com/cs3org/reva/internal/grpc/interceptors/token"
"github.com/cs3org/reva/internal/grpc/interceptors/useragent"
"github.com/cs3org/reva/pkg/sharedconf"
rtrace "github.com/cs3org/reva/pkg/trace"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
// UnaryInterceptors is a map of registered unary grpc interceptors.
var UnaryInterceptors = map[string]NewUnaryInterceptor{}
// StreamInterceptors is a map of registered streaming grpc interceptor
var StreamInterceptors = map[string]NewStreamInterceptor{}
// NewUnaryInterceptor is the type that unary interceptors need to register.
type NewUnaryInterceptor func(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error)
// NewStreamInterceptor is the type that stream interceptors need to register.
type NewStreamInterceptor func(m map[string]interface{}) (grpc.StreamServerInterceptor, int, error)
// RegisterUnaryInterceptor registers a new unary interceptor.
func RegisterUnaryInterceptor(name string, newFunc NewUnaryInterceptor) {
UnaryInterceptors[name] = newFunc
}
// RegisterStreamInterceptor registers a new stream interceptor.
func RegisterStreamInterceptor(name string, newFunc NewStreamInterceptor) {
StreamInterceptors[name] = newFunc
}
// Services is a map of service name and its new function.
var Services = map[string]NewService{}
// Register registers a new gRPC service with name and new function.
func Register(name string, newFunc NewService) {
Services[name] = newFunc
}
// NewService is the function that gRPC services need to register at init time.
// It returns an io.Closer to close the service and a list of service endpoints that need to be unprotected.
type NewService func(conf map[string]interface{}, ss *grpc.Server) (Service, error)
// Service represents a grpc service.
type Service interface {
Register(ss *grpc.Server)
io.Closer
UnprotectedEndpoints() []string
}
type unaryInterceptorTriple struct {
Name string
Priority int
Interceptor grpc.UnaryServerInterceptor
}
type streamInterceptorTriple struct {
Name string
Priority int
Interceptor grpc.StreamServerInterceptor
}
type config struct {
Network string `mapstructure:"network"`
Address string `mapstructure:"address"`
ShutdownDeadline int `mapstructure:"shutdown_deadline"`
Services map[string]map[string]interface{} `mapstructure:"services"`
Interceptors map[string]map[string]interface{} `mapstructure:"interceptors"`
EnableReflection bool `mapstructure:"enable_reflection"`
}
func (c *config) init() {
if c.Network == "" {
c.Network = "tcp"
}
if c.Address == "" {
c.Address = sharedconf.GetGatewaySVC("0.0.0.0:19000")
}
}
// Server is a gRPC server.
type Server struct {
s *grpc.Server
conf *config
listener net.Listener
log zerolog.Logger
services map[string]Service
}
// NewServer returns a new Server.
func NewServer(m interface{}, log zerolog.Logger) (*Server, error) {
conf := &config{}
if err := mapstructure.Decode(m, conf); err != nil {
return nil, err
}
conf.init()
server := &Server{conf: conf, log: log, services: map[string]Service{}}
return server, nil
}
// Start starts the server.
func (s *Server) Start(ln net.Listener) error {
if err := s.registerServices(); err != nil {
err = errors.Wrap(err, "unable to register services")
return err
}
s.listener = ln
s.log.Info().Msgf("grpc server listening at %s:%s", s.Network(), s.Address())
err := s.s.Serve(s.listener)
if err != nil {
err = errors.Wrap(err, "serve failed")
return err
}
return nil
}
func (s *Server) isInterceptorEnabled(name string) bool {
for k := range s.conf.Interceptors {
if k == name {
return true
}
}
return false
}
func (s *Server) isServiceEnabled(svcName string) bool {
for key := range Services {
if key == svcName {
return true
}
}
return false
}
func (s *Server) registerServices() error {
for svcName := range s.conf.Services {
if s.isServiceEnabled(svcName) {
newFunc := Services[svcName]
svc, err := newFunc(s.conf.Services[svcName], s.s)
if err != nil {
return errors.Wrapf(err, "rgrpc: grpc service %s could not be started,", svcName)
}
s.services[svcName] = svc
s.log.Info().Msgf("rgrpc: grpc service enabled: %s", svcName)
} else {
message := fmt.Sprintf("rgrpc: grpc service %s does not exist", svcName)
return errors.New(message)
}
}
// obtain list of unprotected endpoints
unprotected := []string{}
for _, svc := range s.services {
unprotected = append(unprotected, svc.UnprotectedEndpoints()...)
}
opts, err := s.getInterceptors(unprotected)
if err != nil {
return err
}
grpcServer := grpc.NewServer(opts...)
for _, svc := range s.services {
svc.Register(grpcServer)
}
if s.conf.EnableReflection {
s.log.Info().Msg("rgrpc: grpc server reflection enabled")
reflection.Register(grpcServer)
}
s.s = grpcServer
return nil
}
// TODO(labkode): make closing with deadline.
func (s *Server) cleanupServices() {
for name, svc := range s.services {
if err := svc.Close(); err != nil {
s.log.Error().Err(err).Msgf("error closing service %q", name)
} else {
s.log.Info().Msgf("service %q correctly closed", name)
}
}
}
// Stop stops the server.
func (s *Server) Stop() error {
s.cleanupServices()
s.s.Stop()
return nil
}
// GracefulStop gracefully stops the server.
func (s *Server) GracefulStop() error {
s.cleanupServices()
s.s.GracefulStop()
return nil
}
// Network returns the network type.
func (s *Server) Network() string {
return s.conf.Network
}
// Address returns the network address.
func (s *Server) Address() string {
return s.conf.Address
}
func (s *Server) getInterceptors(unprotected []string) ([]grpc.ServerOption, error) {
unaryTriples := []*unaryInterceptorTriple{}
for name, newFunc := range UnaryInterceptors {
if s.isInterceptorEnabled(name) {
inter, prio, err := newFunc(s.conf.Interceptors[name])
if err != nil {
err = errors.Wrapf(err, "rgrpc: error creating unary interceptor: %s,", name)
return nil, err
}
triple := &unaryInterceptorTriple{
Name: name,
Priority: prio,
Interceptor: inter,
}
unaryTriples = append(unaryTriples, triple)
}
}
// sort unary triples
sort.SliceStable(unaryTriples, func(i, j int) bool {
return unaryTriples[i].Priority < unaryTriples[j].Priority
})
authUnary, err := auth.NewUnary(s.conf.Interceptors["auth"], unprotected)
if err != nil {
return nil, errors.Wrap(err, "rgrpc: error creating unary auth interceptor")
}
unaryInterceptors := []grpc.UnaryServerInterceptor{authUnary}
for _, t := range unaryTriples {
unaryInterceptors = append(unaryInterceptors, t.Interceptor)
s.log.Info().Msgf("rgrpc: chaining grpc unary interceptor %s with priority %d", t.Name, t.Priority)
}
unaryInterceptors = append(unaryInterceptors,
otelgrpc.UnaryServerInterceptor(
otelgrpc.WithTracerProvider(rtrace.Provider),
otelgrpc.WithPropagators(rtrace.Propagator)),
)
unaryInterceptors = append([]grpc.UnaryServerInterceptor{
appctx.NewUnary(s.log),
token.NewUnary(),
useragent.NewUnary(),
log.NewUnary(),
recovery.NewUnary(),
}, unaryInterceptors...)
unaryChain := grpc_middleware.ChainUnaryServer(unaryInterceptors...)
streamTriples := []*streamInterceptorTriple{}
for name, newFunc := range StreamInterceptors {
if s.isInterceptorEnabled(name) {
inter, prio, err := newFunc(s.conf.Interceptors[name])
if err != nil {
err = errors.Wrapf(err, "rgrpc: error creating streaming interceptor: %s,", name)
return nil, err
}
triple := &streamInterceptorTriple{
Name: name,
Priority: prio,
Interceptor: inter,
}
streamTriples = append(streamTriples, triple)
}
}
// sort stream triples
sort.SliceStable(streamTriples, func(i, j int) bool {
return streamTriples[i].Priority < streamTriples[j].Priority
})
authStream, err := auth.NewStream(s.conf.Interceptors["auth"], unprotected)
if err != nil {
return nil, errors.Wrap(err, "rgrpc: error creating stream auth interceptor")
}
streamInterceptors := []grpc.StreamServerInterceptor{authStream}
for _, t := range streamTriples {
streamInterceptors = append(streamInterceptors, t.Interceptor)
s.log.Info().Msgf("rgrpc: chaining grpc streaming interceptor %s with priority %d", t.Name, t.Priority)
}
streamInterceptors = append([]grpc.StreamServerInterceptor{
authStream,
appctx.NewStream(s.log),
token.NewStream(),
useragent.NewStream(),
log.NewStream(),
recovery.NewStream(),
}, streamInterceptors...)
streamChain := grpc_middleware.ChainStreamServer(streamInterceptors...)
opts := []grpc.ServerOption{
grpc.UnaryInterceptor(unaryChain),
grpc.StreamInterceptor(streamChain),
}
return opts, nil
}