/
server.go
300 lines (275 loc) · 9.35 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
// Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you 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 grpc implements the gRPC services defined by APIs.
package grpc
import (
"context"
"net"
"runtime/debug"
"strconv"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery"
grpc_validator "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/validator"
"github.com/pkg/errors"
grpclib "google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
measurev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/measure/v1"
propertyv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/property/v1"
streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
"github.com/apache/skywalking-banyandb/banyand/metadata"
"github.com/apache/skywalking-banyandb/banyand/metadata/schema"
"github.com/apache/skywalking-banyandb/banyand/observability"
"github.com/apache/skywalking-banyandb/banyand/queue"
"github.com/apache/skywalking-banyandb/pkg/logger"
"github.com/apache/skywalking-banyandb/pkg/run"
)
const defaultRecvSize = 10 << 20
var (
errServerCert = errors.New("invalid server cert file")
errServerKey = errors.New("invalid server key file")
errNoAddr = errors.New("no address")
errQueryMsg = errors.New("invalid query message")
errAccessLogRootPath = errors.New("access log root path is required")
)
// Server defines the gRPC server.
type Server interface {
run.Unit
GetPort() *uint32
}
type server struct {
creds credentials.TransportCredentials
*streamRegistryServer
log *logger.Logger
*indexRuleBindingRegistryServer
ser *grpclib.Server
*propertyServer
*topNAggregationRegistryServer
*groupRegistryServer
stopCh chan struct{}
*indexRuleRegistryServer
*measureRegistryServer
streamSVC *streamService
measureSVC *measureService
host string
keyFile string
certFile string
accessLogRootPath string
addr string
accessLogRecorders []accessLogRecorder
maxRecvMsgSize run.Bytes
port uint32
enableIngestionAccessLog bool
tls bool
}
// NewServer returns a new gRPC server.
func NewServer(_ context.Context, pipeline, broadcaster queue.Client, schemaRegistry metadata.Repo, nodeRegistry NodeRegistry) Server {
streamSVC := &streamService{
discoveryService: newDiscoveryService(schema.KindStream, schemaRegistry, nodeRegistry),
pipeline: pipeline,
broadcaster: broadcaster,
}
measureSVC := &measureService{
discoveryService: newDiscoveryService(schema.KindMeasure, schemaRegistry, nodeRegistry),
pipeline: pipeline,
broadcaster: broadcaster,
}
s := &server{
streamSVC: streamSVC,
measureSVC: measureSVC,
streamRegistryServer: &streamRegistryServer{
schemaRegistry: schemaRegistry,
},
indexRuleBindingRegistryServer: &indexRuleBindingRegistryServer{
schemaRegistry: schemaRegistry,
},
indexRuleRegistryServer: &indexRuleRegistryServer{
schemaRegistry: schemaRegistry,
},
measureRegistryServer: &measureRegistryServer{
schemaRegistry: schemaRegistry,
},
groupRegistryServer: &groupRegistryServer{
schemaRegistry: schemaRegistry,
},
topNAggregationRegistryServer: &topNAggregationRegistryServer{
schemaRegistry: schemaRegistry,
},
propertyServer: &propertyServer{
schemaRegistry: schemaRegistry,
},
}
s.accessLogRecorders = []accessLogRecorder{streamSVC, measureSVC}
return s
}
func (s *server) PreRun(_ context.Context) error {
s.log = logger.GetLogger("liaison-grpc")
s.streamSVC.setLogger(s.log)
s.measureSVC.setLogger(s.log)
components := []*discoveryService{
s.streamSVC.discoveryService,
s.measureSVC.discoveryService,
}
for _, c := range components {
c.SetLogger(s.log)
if err := c.initialize(); err != nil {
return err
}
}
if s.enableIngestionAccessLog {
for _, alr := range s.accessLogRecorders {
if err := alr.activeIngestionAccessLog(s.accessLogRootPath); err != nil {
return err
}
}
}
return nil
}
func (s *server) Name() string {
return "grpc"
}
func (s *server) Role() databasev1.Role {
return databasev1.Role_ROLE_LIAISON
}
func (s *server) GetPort() *uint32 {
return &s.port
}
func (s *server) FlagSet() *run.FlagSet {
fs := run.NewFlagSet("grpc")
s.maxRecvMsgSize = defaultRecvSize
fs.VarP(&s.maxRecvMsgSize, "max-recv-msg-size", "", "the size of max receiving message")
fs.BoolVar(&s.tls, "tls", false, "connection uses TLS if true, else plain TCP")
fs.StringVar(&s.certFile, "cert-file", "", "the TLS cert file")
fs.StringVar(&s.keyFile, "key-file", "", "the TLS key file")
fs.StringVar(&s.host, "grpc-host", "", "the host of banyand listens")
fs.Uint32Var(&s.port, "grpc-port", 17912, "the port of banyand listens")
fs.BoolVar(&s.enableIngestionAccessLog, "enable-ingestion-access-log", false, "enable ingestion access log")
fs.StringVar(&s.accessLogRootPath, "access-log-root-path", "", "access log root path")
return fs
}
func (s *server) Validate() error {
s.addr = net.JoinHostPort(s.host, strconv.FormatUint(uint64(s.port), 10))
if s.addr == ":" {
return errNoAddr
}
if s.enableIngestionAccessLog && s.accessLogRootPath == "" {
return errAccessLogRootPath
}
observability.UpdateAddress("grpc", s.addr)
if !s.tls {
return nil
}
if s.certFile == "" {
return errServerCert
}
if s.keyFile == "" {
return errServerKey
}
creds, errTLS := credentials.NewServerTLSFromFile(s.certFile, s.keyFile)
if errTLS != nil {
return errors.Wrap(errTLS, "failed to load cert and key")
}
s.creds = creds
return nil
}
func (s *server) Serve() run.StopNotify {
var opts []grpclib.ServerOption
if s.tls {
opts = []grpclib.ServerOption{grpclib.Creds(s.creds)}
}
grpcPanicRecoveryHandler := func(p any) (err error) {
s.log.Error().Interface("panic", p).Str("stack", string(debug.Stack())).Msg("recovered from panic")
return status.Errorf(codes.Internal, "%s", p)
}
unaryMetrics, streamMetrics := observability.MetricsServerInterceptor()
streamChain := []grpclib.StreamServerInterceptor{
grpc_validator.StreamServerInterceptor(),
recovery.StreamServerInterceptor(recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)),
}
if streamMetrics != nil {
streamChain = append(streamChain, streamMetrics)
}
unaryChain := []grpclib.UnaryServerInterceptor{
grpc_validator.UnaryServerInterceptor(),
recovery.UnaryServerInterceptor(recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)),
}
if unaryMetrics != nil {
unaryChain = append(unaryChain, unaryMetrics)
}
opts = append(opts, grpclib.MaxRecvMsgSize(int(s.maxRecvMsgSize)),
grpclib.ChainUnaryInterceptor(unaryChain...),
grpclib.ChainStreamInterceptor(streamChain...),
)
s.ser = grpclib.NewServer(opts...)
streamv1.RegisterStreamServiceServer(s.ser, s.streamSVC)
measurev1.RegisterMeasureServiceServer(s.ser, s.measureSVC)
// register *Registry
databasev1.RegisterGroupRegistryServiceServer(s.ser, s.groupRegistryServer)
databasev1.RegisterIndexRuleBindingRegistryServiceServer(s.ser, s.indexRuleBindingRegistryServer)
databasev1.RegisterIndexRuleRegistryServiceServer(s.ser, s.indexRuleRegistryServer)
databasev1.RegisterStreamRegistryServiceServer(s.ser, s.streamRegistryServer)
databasev1.RegisterMeasureRegistryServiceServer(s.ser, s.measureRegistryServer)
propertyv1.RegisterPropertyServiceServer(s.ser, s.propertyServer)
databasev1.RegisterTopNAggregationRegistryServiceServer(s.ser, s.topNAggregationRegistryServer)
grpc_health_v1.RegisterHealthServer(s.ser, health.NewServer())
s.stopCh = make(chan struct{})
go func() {
lis, err := net.Listen("tcp", s.addr)
if err != nil {
s.log.Error().Err(err).Msg("Failed to listen")
close(s.stopCh)
return
}
s.log.Info().Str("addr", s.addr).Msg("Listening to")
err = s.ser.Serve(lis)
if err != nil {
s.log.Error().Err(err).Msg("server is interrupted")
}
close(s.stopCh)
}()
return s.stopCh
}
func (s *server) GracefulStop() {
s.log.Info().Msg("stopping")
stopped := make(chan struct{})
go func() {
s.ser.GracefulStop()
if s.enableIngestionAccessLog {
for _, alr := range s.accessLogRecorders {
_ = alr.Close()
}
}
close(stopped)
}()
t := time.NewTimer(10 * time.Second)
select {
case <-t.C:
s.ser.Stop()
s.log.Info().Msg("force stopped")
case <-stopped:
t.Stop()
s.log.Info().Msg("stopped gracefully")
}
}
type accessLogRecorder interface {
activeIngestionAccessLog(root string) error
Close() error
}