-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.go
683 lines (579 loc) · 18.3 KB
/
main.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
package main
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"math/big"
"net"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/Filecoin-Titan/titan/node"
"github.com/Filecoin-Titan/titan/node/asset"
"github.com/Filecoin-Titan/titan/node/httpserver"
"github.com/Filecoin-Titan/titan/node/modules/dtypes"
"github.com/Filecoin-Titan/titan/node/validation"
"github.com/gbrlsnchs/jwt/v3"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3"
"github.com/Filecoin-Titan/titan/api"
"github.com/Filecoin-Titan/titan/api/client"
"github.com/Filecoin-Titan/titan/api/terrors"
"github.com/Filecoin-Titan/titan/api/types"
"github.com/Filecoin-Titan/titan/build"
lcli "github.com/Filecoin-Titan/titan/cli"
"github.com/Filecoin-Titan/titan/lib/titanlog"
"github.com/Filecoin-Titan/titan/metrics"
"github.com/Filecoin-Titan/titan/node/config"
"github.com/Filecoin-Titan/titan/node/repo"
titanrsa "github.com/Filecoin-Titan/titan/node/rsa"
"github.com/filecoin-project/go-jsonrpc"
"github.com/filecoin-project/go-jsonrpc/auth"
"github.com/google/uuid"
logging "github.com/ipfs/go-log/v2"
manet "github.com/multiformats/go-multiaddr/net"
"github.com/urfave/cli/v2"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"golang.org/x/xerrors"
)
var log = logging.Logger("main")
const (
FlagCandidateRepo = "candidate-repo"
// TODO remove after deprecation period
FlagCandidateRepoDeprecation = "candidaterepo"
DefaultStorageDir = "storage"
HeartbeatInterval = 10 * time.Second
)
func main() {
types.RunningNodeType = types.NodeCandidate
titanlog.SetupLogLevels()
local := []*cli.Command{
daemonCmd,
}
local = append(local, lcli.CommonCommands...)
// candidate cmds include edge cmds
candidateCmds := append(local, lcli.CandidateCmds...)
app := &cli.App{
Name: "titan-candidate",
Usage: "Titan candidate node",
Version: build.UserVersion(),
EnableBashCompletion: true,
Flags: []cli.Flag{
&cli.StringFlag{
Name: FlagCandidateRepo,
Aliases: []string{FlagCandidateRepoDeprecation},
EnvVars: []string{"TITAN_CANDIDATE_PATH", "CANDIDATE_PATH"},
Value: "~/.titancandidate", // TODO: Consider XDG_DATA_HOME
Usage: fmt.Sprintf("Specify candidate repo path. flag %s and env TITAN_CANDIDATE_PATH are DEPRECATION, will REMOVE SOON", FlagCandidateRepoDeprecation),
},
&cli.StringFlag{
Name: "panic-reports",
EnvVars: []string{"TITAN_PANIC_REPORT_PATH"},
Hidden: true,
Value: "~/.titancandidate", // should follow --repo default
},
},
After: func(c *cli.Context) error {
if r := recover(); r != nil {
// Generate report in TITAN_PATH and re-raise panic
build.GeneratePanicReport(c.String("panic-reports"), c.String(FlagCandidateRepo), c.App.Name)
panic(r)
}
return nil
},
Commands: candidateCmds,
}
app.Setup()
app.Metadata["repoType"] = repo.Candidate
if err := app.Run(os.Args); err != nil {
log.Errorf("%+v", err)
return
}
}
var daemonCmd = &cli.Command{
Name: "daemon",
Usage: "daemon cmd",
Subcommands: []*cli.Command{
daemonStartCmd,
daemonStopCmd,
},
}
var daemonStopCmd = &cli.Command{
Name: "stop",
Usage: "stop a running daemon",
Flags: []cli.Flag{},
Action: func(cctx *cli.Context) error {
candidateAPI, close, err := lcli.GetCandidateAPI(cctx)
if err != nil {
return err
}
defer close()
return candidateAPI.Shutdown(cctx.Context)
},
}
var daemonStartCmd = &cli.Command{
Name: "start",
Usage: "Start titan candidate node",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "init",
Usage: "--init=true, initialize candidate at first run",
Value: false,
},
&cli.StringFlag{
Name: "url",
Usage: "--url=https://titan-server-domain/rpc/v0",
Value: "",
},
},
Before: func(cctx *cli.Context) error {
return nil
},
Action: func(cctx *cli.Context) error {
log.Info("Starting titan edge node")
// Register all metric views
if err := view.Register(
metrics.DefaultViews...,
); err != nil {
log.Fatalf("Cannot register the view: %v", err)
}
repoPath := cctx.String(FlagCandidateRepo)
r, err := repo.NewFS(repoPath)
if err != nil {
return err
}
ok, err := r.Exists()
if err != nil {
return err
}
if !ok {
if err := r.Init(repo.Candidate); err != nil {
return err
}
}
lr, err := r.Lock(repo.Candidate)
if err != nil {
return err
}
_, nodeIDErr := r.NodeID()
isNeedInit := cctx.Bool("init")
if nodeIDErr == repo.ErrNodeIDNotExist && isNeedInit {
locatorURL := cctx.String("url")
if len(locatorURL) == 0 {
return fmt.Errorf("Must set --url for --init")
}
if err := lcli.RegitsterNode(cctx, lr, locatorURL, types.NodeCandidate); err != nil {
return err
}
}
cfg, err := lr.Config()
if err != nil {
return err
}
candidateCfg := cfg.(*config.CandidateCfg)
err = lr.Close()
if err != nil {
return err
}
privateKey, err := loadPrivateKey(r)
if err != nil {
return fmt.Errorf(`please initialize candidate, example:
titan-candidate daemon start --init --url https://titan-network-url/rpc/v0`)
}
if len(candidateCfg.AreaID) == 0 {
return fmt.Errorf(`please config node id and area id, example:
titan-candidate config set --node-id=your_node_id --area-id=your_area_id`)
}
nodeIDBuf, err := r.NodeID()
if err != nil {
return err
}
nodeID := string(nodeIDBuf)
connectTimeout, err := time.ParseDuration(candidateCfg.Network.Timeout)
if err != nil {
return err
}
packetConn, err := net.ListenPacket("udp", candidateCfg.Network.ListenAddress)
if err != nil {
return err
}
defer packetConn.Close() //nolint:errcheck // ignore error
transport := &quic.Transport{Conn: packetConn}
schedulerURL, _, _ := lcli.GetRawAPI(cctx, repo.Scheduler, "v0")
if len(schedulerURL) == 0 {
schedulerURL, err = getAccessPoint(cctx, candidateCfg.Network.LocatorURL, nodeID, candidateCfg.AreaID)
if err != nil {
return err
}
}
// Connect to scheduler
schedulerAPI, closer, err := newSchedulerAPI(cctx, transport, schedulerURL, nodeID, privateKey)
if err != nil {
return err
}
defer closer()
ctx := lcli.ReqContext(cctx)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
v, err := getSchedulerVersion(schedulerAPI, connectTimeout)
if err != nil {
return err
}
if v.APIVersion != api.SchedulerAPIVersion0 {
return xerrors.Errorf("titan-scheduler API version doesn't match: expected: %s", api.APIVersion{APIVersion: api.SchedulerAPIVersion0})
}
log.Infof("Remote version %s", v)
var shutdownChan = make(chan struct{})
var httpServer *httpserver.HttpServer
var candidateAPI api.Candidate
stop, err := node.New(cctx.Context,
node.Candidate(&candidateAPI),
node.Base(),
node.Repo(r),
node.Override(new(dtypes.NodeID), dtypes.NodeID(nodeID)),
node.Override(new(api.Scheduler), schedulerAPI),
node.Override(new(dtypes.ShutdownChan), shutdownChan),
node.Override(new(dtypes.NodeMetadataPath), func() dtypes.NodeMetadataPath {
metadataPath := candidateCfg.MetadataPath
if len(metadataPath) == 0 {
metadataPath = path.Join(lr.Path(), DefaultStorageDir)
}
log.Infof("metadataPath:%s", metadataPath)
return dtypes.NodeMetadataPath(metadataPath)
}),
node.Override(new(dtypes.AssetsPaths), func() dtypes.AssetsPaths {
assetsPaths := candidateCfg.AssetsPaths
if len(assetsPaths) == 0 {
assetsPaths = []string{path.Join(lr.Path(), DefaultStorageDir)}
}
log.Debugf("assetsPaths:%#v", assetsPaths)
return dtypes.AssetsPaths(assetsPaths)
}),
node.Override(new(dtypes.InternalIP), func() (dtypes.InternalIP, error) {
ainfo, err := lcli.GetAPIInfo(cctx, repo.Scheduler)
if err != nil {
return "", xerrors.Errorf("could not get scheduler API info: %w", err)
}
schedulerAddr := strings.Split(ainfo.Addr, "/")
conn, err := net.DialTimeout("tcp", schedulerAddr[2], connectTimeout)
if err != nil {
return "", err
}
defer conn.Close() //nolint:errcheck
localAddr := conn.LocalAddr().(*net.TCPAddr)
return dtypes.InternalIP(strings.Split(localAddr.IP.String(), ":")[0]), nil
}),
node.Override(node.RunGateway, func(assetMgr *asset.Manager, validation *validation.Validation, apiSecret *jwt.HMACSHA) error {
opts := &httpserver.HttpServerOptions{
Asset: assetMgr, Scheduler: schedulerAPI,
PrivateKey: privateKey,
Validation: validation,
APISecret: apiSecret,
MaxSizeOfUploadFile: candidateCfg.MaxSizeOfUploadFile,
WebRedirect: candidateCfg.WebRedirect,
}
httpServer = httpserver.NewHttpServer(opts)
return nil
}),
node.Override(new(*rsa.PrivateKey), func() *rsa.PrivateKey {
return privateKey
}),
node.Override(node.SetApiEndpointKey, func(lr repo.LockedRepo) error {
return setEndpointAPI(lr, candidateCfg.Network.ListenAddress)
}),
)
if err != nil {
return xerrors.Errorf("creating node: %w", err)
}
tlsConfig, err := getTLSConfig(candidateCfg)
if err != nil {
return xerrors.Errorf("get tls config error: %w", err)
}
handler := CandidateHandler(candidateAPI.AuthVerify, candidateAPI, true)
handler = httpServer.NewHandler(handler)
httpSrv := &http.Server{
ReadHeaderTimeout: 30 * time.Second,
Handler: handler,
BaseContext: func(listener net.Listener) context.Context {
ctx, _ := tag.New(context.Background(), tag.Upsert(metrics.APIInterface, "titan-candidate"))
return ctx
},
TLSConfig: tlsConfig,
}
go startHTTP3Server(transport, handler, candidateCfg)
go func() {
<-ctx.Done()
log.Warn("Shutting down...")
if err := transport.Close(); err != nil {
log.Errorf("shutting down http3Srv failed: %s", err)
}
if err := httpSrv.Shutdown(context.TODO()); err != nil {
log.Errorf("shutting down httpSrv failed: %s", err)
}
stop(ctx) //nolint:errcheck
log.Warn("Graceful shutdown successful")
}()
nl, err := net.Listen("tcp", candidateCfg.Network.ListenAddress)
if err != nil {
return err
}
log.Infof("Candidate listen on %s", candidateCfg.Network.ListenAddress)
schedulerSession, err := schedulerAPI.Session(ctx)
if err != nil {
return xerrors.Errorf("getting scheduler session: %w", err)
}
_, port, err := net.SplitHostPort(candidateCfg.TCPSrvAddr)
if err != nil {
return xerrors.Errorf("split tcp server addr: %w", err)
}
tcpServerPort, err := strconv.Atoi(port)
if err != nil {
return xerrors.Errorf("convert tcp server port from string: %w", err)
}
token, err := candidateAPI.AuthNew(cctx.Context, &types.JWTPayload{Allow: []auth.Permission{api.RoleAdmin}, ID: nodeID})
if err != nil {
return xerrors.Errorf("generate token for scheduler error: %w", err)
}
waitQuietCh := func() chan struct{} {
out := make(chan struct{})
go func() {
ctx2 := context.Background()
err = candidateAPI.WaitQuiet(ctx2)
if err != nil {
log.Errorf("wait quiet error: %s", err.Error())
}
close(out)
}()
return out
}
go func() {
heartbeats := time.NewTicker(HeartbeatInterval)
defer heartbeats.Stop()
var readyCh chan struct{}
for {
// TODO: we could get rid of this, but that requires tracking resources for restarted tasks correctly
if readyCh == nil {
log.Info("Making sure no local tasks are running")
readyCh = waitQuietCh()
}
for {
select {
case <-readyCh:
opts := &types.ConnectOptions{ExternalURL: candidateCfg.ExternalURL, Token: token, TcpServerPort: tcpServerPort, IsPrivateMinioOnly: isPrivateMinioOnly(candidateCfg)}
err := schedulerAPI.CandidateConnect(ctx, opts)
if err != nil {
log.Errorf("Registering candidate failed: %s", err.Error())
cancel()
return
}
log.Info("Candidate registered successfully, waiting for tasks")
readyCh = nil
case <-heartbeats.C:
case <-ctx.Done():
return // graceful shutdown
case <-shutdownChan:
cancel()
return
}
curSession, err := keepalive(schedulerAPI, connectTimeout)
if err != nil {
log.Errorf("heartbeat: keepalive failed: %+v", err)
errNode, ok := err.(*api.ErrNode)
if ok {
if errNode.Code == int(terrors.NodeDeactivate) {
cancel()
return
} else if errNode.Code == int(terrors.NodeIPInconsistent) {
break
} else if errNode.Code == int(terrors.NodeOffline) && readyCh == nil {
break
}
}
} else if curSession != schedulerSession {
log.Warn("change session id")
schedulerSession = curSession
break
}
}
log.Errorf("TITAN-EDGE CONNECTION LOST")
}
}()
if isEnableTLS(candidateCfg) {
return httpSrv.ServeTLS(nl, "", "")
}
return httpSrv.Serve(nl)
},
}
// private minio storage only, not public storage
func isPrivateMinioOnly(config *config.CandidateCfg) bool {
if len(config.AccessKeyID) > 0 && len(config.SecretAccessKey) > 0 && len(config.Endpoint) > 0 {
return true
}
return false
}
func keepalive(api api.Scheduler, timeout time.Duration) (uuid.UUID, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return api.NodeKeepaliveV2(ctx)
}
func getSchedulerVersion(api api.Scheduler, timeout time.Duration) (api.APIVersion, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return api.Version(ctx)
}
func newAuthTokenFromScheduler(schedulerURL, nodeID string, privateKey *rsa.PrivateKey) (string, error) {
schedulerAPI, closer, err := client.NewScheduler(context.Background(), schedulerURL, nil, jsonrpc.WithHTTPClient(client.NewHTTP3Client()))
if err != nil {
return "", err
}
defer closer()
rsa := titanrsa.New(crypto.SHA256, crypto.SHA256.New())
sign, err := rsa.Sign(privateKey, []byte(nodeID))
if err != nil {
return "", err
}
return schedulerAPI.NodeLogin(context.Background(), nodeID, hex.EncodeToString(sign))
}
func getAccessPoint(cctx *cli.Context, locatorURL, nodeID, areaID string) (string, error) {
locator, close, err := client.NewLocator(cctx.Context, locatorURL, nil, jsonrpc.WithHTTPClient(client.NewHTTP3Client()))
if err != nil {
return "", err
}
defer close()
schedulerURLs, err := locator.GetAccessPoints(context.Background(), nodeID, areaID)
if err != nil {
return "", err
}
if len(schedulerURLs) <= 0 {
return "", fmt.Errorf("no access point in area %s for node %s", areaID, nodeID)
}
return schedulerURLs[0], nil
}
func newSchedulerAPI(cctx *cli.Context, tansport *quic.Transport, schedulerURL, nodeID string, privateKey *rsa.PrivateKey) (api.Scheduler, jsonrpc.ClientCloser, error) {
token, err := newAuthTokenFromScheduler(schedulerURL, nodeID, privateKey)
if err != nil {
return nil, nil, err
}
httpClient, err := client.NewHTTP3ClientWithPacketConn(tansport)
if err != nil {
return nil, nil, err
}
headers := http.Header{}
headers.Add("Authorization", "Bearer "+token)
headers.Add("Node-ID", nodeID)
schedulerAPI, closer, err := client.NewScheduler(context.Background(), schedulerURL, headers, jsonrpc.WithHTTPClient(httpClient))
if err != nil {
return nil, nil, err
}
log.Debugf("scheduler url:%s, token:%s", schedulerURL, token)
if err := os.Setenv("SCHEDULER_API_INFO", token+":"+schedulerURL); err != nil {
log.Errorf("set env error:%s", err.Error())
}
return schedulerAPI, closer, nil
}
func isEnableTLS(candidateCfg *config.CandidateCfg) bool {
if len(candidateCfg.CertificatePath) > 0 && len(candidateCfg.PrivateKeyPath) > 0 {
return true
}
return false
}
func getTLSConfig(candidateCfg *config.CandidateCfg) (*tls.Config, error) {
if isEnableTLS(candidateCfg) {
cert, err := tls.LoadX509KeyPair(candidateCfg.CertificatePath, candidateCfg.PrivateKeyPath)
if err != nil {
log.Errorf("LoadX509KeyPair error:%s", err.Error())
return nil, err
}
return &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
}, nil
}
return defaultTLSConfig()
}
func defaultTLSConfig() (*tls.Config, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
template := x509.Certificate{SerialNumber: big.NewInt(1)}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
return nil, err
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return nil, err
}
return &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{tlsCert},
NextProtos: []string{"h2", "h3"},
InsecureSkipVerify: true, //nolint:gosec // skip verify in default config
}, nil
}
func loadPrivateKey(r *repo.FsRepo) (*rsa.PrivateKey, error) {
pem, err := r.PrivateKey()
if err != nil {
return nil, err
}
return titanrsa.Pem2PrivateKey(pem)
}
func setEndpointAPI(lr repo.LockedRepo, address string) error {
a, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return xerrors.Errorf("parsing address: %w", err)
}
ma, err := manet.FromNetAddr(a)
if err != nil {
return xerrors.Errorf("creating api multiaddress: %w", err)
}
if err := lr.SetAPIEndpoint(ma); err != nil {
return xerrors.Errorf("setting api endpoint: %w", err)
}
return nil
}
func startHTTP3Server(transport *quic.Transport, handler http.Handler, config *config.CandidateCfg) error {
var tlsConfig *tls.Config
if len(config.CertificatePath) == 0 && len(config.PrivateKeyPath) == 0 {
config, err := defaultTLSConfig()
if err != nil {
log.Errorf("startUDPServer, defaultTLSConfig error:%s", err.Error())
return err
}
tlsConfig = config
} else {
cert, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
if err != nil {
log.Errorf("startUDPServer, LoadX509KeyPair error:%s", err.Error())
return err
}
tlsConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
NextProtos: []string{"h2", "h3"},
InsecureSkipVerify: false,
}
}
ln, err := transport.ListenEarly(tlsConfig, nil)
if err != nil {
return err
}
srv := http3.Server{
TLSConfig: tlsConfig,
Handler: handler,
}
return srv.ServeListener(ln)
}