-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
493 lines (436 loc) · 16.4 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.DATANODE file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package api
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strconv"
"time"
"github.com/elysiumstation/fury/datanode/gateway"
"github.com/elysiumstation/fury/datanode/networkhistory/segment"
"github.com/elysiumstation/fury/libs/subscribers"
"github.com/elysiumstation/fury/datanode/ratelimit"
"github.com/elysiumstation/fury/core/events"
"github.com/elysiumstation/fury/datanode/candlesv2"
"github.com/elysiumstation/fury/datanode/contextutil"
"github.com/elysiumstation/fury/datanode/entities"
"github.com/elysiumstation/fury/datanode/service"
"github.com/elysiumstation/fury/logging"
protoapi "github.com/elysiumstation/fury/protos/data-node/api/v2"
furyprotoapi "github.com/elysiumstation/fury/protos/fury/api/v1"
eventspb "github.com/elysiumstation/fury/protos/fury/events/v1"
"github.com/fullstorydev/grpcui/standalone"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/reflection"
)
// EventService ...
//
//go:generate go run github.com/golang/mock/mockgen -destination mocks/event_service_mock.go -package mocks github.com/elysiumstation/fury/datanode/api EventService
type EventService interface {
ObserveEvents(ctx context.Context, retries int, eTypes []events.Type, batchSize int, filters ...subscribers.EventFilter) (<-chan []*eventspb.BusEvent, chan<- int)
}
// BlockService ...
//
//go:generate go run github.com/golang/mock/mockgen -destination mocks/block_service_mock.go -package mocks github.com/elysiumstation/fury/datanode/api BlockService
type BlockService interface {
GetLastBlock(ctx context.Context) (entities.Block, error)
}
// NetworkHistoryService ...
//
// it would be nice to use go:generate go run github.com/golang/mock/mockgen -destination mocks/networkhistory_service_mock.go -package mocks github.com/elysiumstation/fury/datanode/api NetworkHistoryService
// however it currently can't handle generic arguments and the generated code is not compilable without a bit of manual tweaking.
type NetworkHistoryService interface {
GetHighestBlockHeightHistorySegment() (segment.Full, error)
ListAllHistorySegments() (segment.Segments[segment.Full], error)
FetchHistorySegment(ctx context.Context, historySegmentID string) (segment.Full, error)
GetActivePeerIPAddresses() []string
CopyHistorySegmentToFile(ctx context.Context, historySegmentID string, outFile string) error
GetHistorySegmentReader(ctx context.Context, historySegmentID string) (io.ReadSeekCloser, int64, error)
GetSwarmKeySeed() string
GetConnectedPeerAddresses() ([]string, error)
GetIpfsAddress() (string, error)
GetSwarmKey() string
GetBootstrapPeers() []string
}
// GRPCServer represent the grpc api provided by the fury node.
type GRPCServer struct {
Config
log *logging.Logger
srv *grpc.Server
furyCoreServiceClient CoreServiceClient
eventService *subscribers.Service
coreProxySvc *coreProxyService
orderService *service.Order
candleService *candlesv2.Svc
networkLimitsService *service.NetworkLimits
marketDataService *service.MarketData
tradeService *service.Trade
assetService *service.Asset
accountService *service.Account
rewardService *service.Reward
marketsService *service.Markets
delegationService *service.Delegation
epochService *service.Epoch
depositService *service.Deposit
withdrawalService *service.Withdrawal
governanceService *service.Governance
riskFactorService *service.RiskFactor
riskService *service.Risk
networkParameterService *service.NetworkParameter
blockService BlockService
partyService *service.Party
checkpointService *service.Checkpoint
oracleSpecService *service.OracleSpec
oracleDataService *service.OracleData
liquidityProvisionService *service.LiquidityProvision
positionService *service.Position
transferService *service.Transfer
stakeLinkingService *service.StakeLinking
notaryService *service.Notary
multiSigService *service.MultiSig
keyRotationService *service.KeyRotations
ethereumKeyRotationService *service.EthereumKeyRotation
nodeService *service.Node
marketDepthService *service.MarketDepth
ledgerService *service.Ledger
protocolUpgradeService *service.ProtocolUpgrade
networkHistoryService NetworkHistoryService
coreSnapshotService *service.SnapshotData
eventObserver *eventObserver
// used in order to gracefully close streams
ctx context.Context
cfunc context.CancelFunc
}
// NewGRPCServer create a new instance of the GPRC api for the fury node.
func NewGRPCServer(
log *logging.Logger,
config Config,
coreServiceClient CoreServiceClient,
eventService *subscribers.Service,
orderService *service.Order,
networkLimitsService *service.NetworkLimits,
marketDataService *service.MarketData,
tradeService *service.Trade,
assetService *service.Asset,
accountService *service.Account,
rewardService *service.Reward,
marketsService *service.Markets,
delegationService *service.Delegation,
epochService *service.Epoch,
depositService *service.Deposit,
withdrawalService *service.Withdrawal,
governanceService *service.Governance,
riskFactorService *service.RiskFactor,
riskService *service.Risk,
networkParameterService *service.NetworkParameter,
blockService BlockService,
checkpointService *service.Checkpoint,
partyService *service.Party,
candleService *candlesv2.Svc,
oracleSpecService *service.OracleSpec,
oracleDataService *service.OracleData,
liquidityProvisionService *service.LiquidityProvision,
positionService *service.Position,
transferService *service.Transfer,
stakeLinkingService *service.StakeLinking,
notaryService *service.Notary,
multiSigService *service.MultiSig,
keyRotationService *service.KeyRotations,
ethereumKeyRotationService *service.EthereumKeyRotation,
nodeService *service.Node,
marketDepthService *service.MarketDepth,
ledgerService *service.Ledger,
protocolUpgradeService *service.ProtocolUpgrade,
networkHistoryService NetworkHistoryService,
coreSnapshotService *service.SnapshotData,
) *GRPCServer {
// setup logger
log = log.Named(namedLogger)
log.SetLevel(config.Level.Get())
ctx, cfunc := context.WithCancel(context.Background())
return &GRPCServer{
log: log,
Config: config,
furyCoreServiceClient: coreServiceClient,
eventService: eventService,
orderService: orderService,
networkLimitsService: networkLimitsService,
tradeService: tradeService,
assetService: assetService,
accountService: accountService,
rewardService: rewardService,
marketsService: marketsService,
delegationService: delegationService,
epochService: epochService,
depositService: depositService,
withdrawalService: withdrawalService,
multiSigService: multiSigService,
governanceService: governanceService,
riskFactorService: riskFactorService,
networkParameterService: networkParameterService,
blockService: blockService,
checkpointService: checkpointService,
partyService: partyService,
candleService: candleService,
oracleSpecService: oracleSpecService,
oracleDataService: oracleDataService,
liquidityProvisionService: liquidityProvisionService,
positionService: positionService,
transferService: transferService,
stakeLinkingService: stakeLinkingService,
notaryService: notaryService,
keyRotationService: keyRotationService,
ethereumKeyRotationService: ethereumKeyRotationService,
nodeService: nodeService,
marketDepthService: marketDepthService,
riskService: riskService,
marketDataService: marketDataService,
ledgerService: ledgerService,
protocolUpgradeService: protocolUpgradeService,
networkHistoryService: networkHistoryService,
coreSnapshotService: coreSnapshotService,
eventObserver: &eventObserver{
log: log,
eventService: eventService,
Config: config,
},
ctx: ctx,
cfunc: cfunc,
}
}
// ReloadConf update the internal configuration of the GRPC server.
func (g *GRPCServer) ReloadConf(cfg Config) {
g.log.Info("reloading configuration")
if g.log.GetLevel() != cfg.Level.Get() {
g.log.Info("updating log level",
logging.String("old", g.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
g.log.SetLevel(cfg.Level.Get())
}
// TODO(): not updating the actual server for now, may need to look at this later
// e.g restart the http server on another port or whatever
g.Config = cfg
}
func ipFromContext(ctx context.Context, method string, log *logging.Logger) string {
// first check if the request is forwarded from our restproxy
// get the metadata
md, ok := metadata.FromIncomingContext(ctx)
if ok {
forwardedFor, ok := md["x-forwarded-for"]
if ok && len(forwardedFor) > 0 {
log.Debug("grpc request x-forwarded-for",
logging.String("method", method),
logging.String("remote-ip-addr", forwardedFor[0]),
)
return forwardedFor[0]
}
}
// if the request is not forwarded let's get it from the peer infos
p, ok := peer.FromContext(ctx)
if ok && p != nil {
log.Debug("grpc peer client request",
logging.String("method", method),
logging.String("remote-ip-addr", p.Addr.String()))
return p.Addr.String()
}
return ""
}
func remoteAddrInterceptor(log *logging.Logger) grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
ip := ipFromContext(ctx, info.FullMethod, log)
ctx = contextutil.WithRemoteIPAddr(ctx, ip)
// Calls the handler
h, err := handler(ctx, req)
log.Debug("Invoked RPC call",
logging.String("method", info.FullMethod),
logging.Error(err),
)
return h, err
}
}
func headersInterceptor(
getLastBlock func(context.Context) (entities.Block, error),
log *logging.Logger,
) grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
var (
height int64
timestamp int64
)
block, bErr := getLastBlock(ctx)
if bErr != nil {
log.Debug("failed to get last block", logging.Error(bErr))
} else {
height = block.Height
timestamp = block.FuryTime.UnixNano()
}
for _, h := range []metadata.MD{
// Deprecated: use 'X-Block-Height' and 'X-Block-Timestamp' instead to determine if data is fresh.
metadata.Pairs("X-Block-Height", strconv.FormatInt(height, 10)),
metadata.Pairs("X-Block-Timestamp", strconv.FormatInt(timestamp, 10)),
} {
if errH := grpc.SetHeader(ctx, h); errH != nil {
log.Error("failed to set header", logging.Error(errH))
}
}
return handler(ctx, req)
}
}
func (g *GRPCServer) getTCPListener() (net.Listener, error) {
ip := g.IP
port := strconv.Itoa(g.Port)
g.log.Info("Starting gRPC based API", logging.String("addr", ip), logging.String("port", port))
tpcLis, err := net.Listen("tcp", net.JoinHostPort(ip, port))
if err != nil {
return nil, err
}
return tpcLis, nil
}
// Start starts the grpc server.
// Uses default TCP listener if no provided.
func (g *GRPCServer) Start(ctx context.Context, lis net.Listener) error {
if lis == nil {
tpcLis, err := g.getTCPListener()
if err != nil {
return err
}
lis = tpcLis
}
subscriptionRateLimiter := gateway.NewSubscriptionRateLimiter(g.log, g.Config.MaxSubscriptionPerClient)
rateLimit := ratelimit.NewFromConfig(&g.RateLimit, g.log)
intercept := grpc.ChainUnaryInterceptor(
remoteAddrInterceptor(g.log),
headersInterceptor(g.blockService.GetLastBlock, g.log),
rateLimit.GRPCInterceptor,
)
streamIntercept := grpc.StreamInterceptor(subscriptionRateLimiter.WithGrpcInterceptor(ipFromContext))
g.srv = grpc.NewServer(intercept, streamIntercept)
coreProxySvc := &coreProxyService{
conf: g.Config,
coreServiceClient: g.furyCoreServiceClient,
eventObserver: g.eventObserver,
}
g.coreProxySvc = coreProxySvc
furyprotoapi.RegisterCoreServiceServer(g.srv, coreProxySvc)
tradingDataSvcV2 := &TradingDataServiceV2{
config: g.Config,
log: g.log,
orderService: g.orderService,
networkLimitsService: g.networkLimitsService,
marketDataService: g.marketDataService,
tradeService: g.tradeService,
multiSigService: g.multiSigService,
notaryService: g.notaryService,
assetService: g.assetService,
candleService: g.candleService,
marketsService: g.marketsService,
partyService: g.partyService,
riskService: g.riskService,
positionService: g.positionService,
accountService: g.accountService,
rewardService: g.rewardService,
depositService: g.depositService,
withdrawalService: g.withdrawalService,
oracleSpecService: g.oracleSpecService,
oracleDataService: g.oracleDataService,
liquidityProvisionService: g.liquidityProvisionService,
governanceService: g.governanceService,
transfersService: g.transferService,
delegationService: g.delegationService,
marketService: g.marketsService,
marketDepthService: g.marketDepthService,
nodeService: g.nodeService,
epochService: g.epochService,
riskFactorService: g.riskFactorService,
networkParameterService: g.networkParameterService,
checkpointService: g.checkpointService,
stakeLinkingService: g.stakeLinkingService,
eventService: g.eventService,
ledgerService: g.ledgerService,
keyRotationService: g.keyRotationService,
ethereumKeyRotationService: g.ethereumKeyRotationService,
blockService: g.blockService,
protocolUpgradeService: g.protocolUpgradeService,
NetworkHistoryService: g.networkHistoryService,
coreSnapshotService: g.coreSnapshotService,
}
protoapi.RegisterTradingDataServiceServer(g.srv, tradingDataSvcV2)
eg, ctx := errgroup.WithContext(ctx)
if g.Reflection || g.WebUIEnabled {
reflection.Register(g.srv)
}
eg.Go(func() error {
<-ctx.Done()
g.stop()
return ctx.Err()
})
eg.Go(func() error {
return g.srv.Serve(lis)
})
if g.WebUIEnabled {
g.startWebUI(ctx)
}
return eg.Wait()
}
func (g *GRPCServer) stop() {
if g.srv == nil {
return
}
done := make(chan struct{})
go func() {
g.log.Info("Gracefully stopping gRPC based API")
g.srv.GracefulStop()
done <- struct{}{}
}()
select {
case <-done:
case <-time.After(10 * time.Second):
g.log.Info("Force stopping gRPC based API")
g.srv.Stop()
}
}
func (g *GRPCServer) startWebUI(ctx context.Context) {
cc, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", g.Port), grpc.WithInsecure())
if err != nil {
g.log.Error("failed to create client to local grpc server", logging.Error(err))
return
}
uiHandler, err := standalone.HandlerViaReflection(ctx, cc, "fury data node")
if err != nil {
g.log.Error("failed to create grpc-ui server", logging.Error(err))
return
}
uiListener, err := net.Listen("tcp", net.JoinHostPort(g.IP, strconv.Itoa(g.WebUIPort)))
if err != nil {
g.log.Error("failed to open listen socket on port", logging.Int("port", g.WebUIPort), logging.Error(err))
return
}
g.log.Info("Starting gRPC Web UI", logging.String("addr", g.IP), logging.Int("port", g.WebUIPort))
go http.Serve(uiListener, uiHandler)
}