forked from filswan/go-computing-provider
-
Notifications
You must be signed in to change notification settings - Fork 11
/
run.go
628 lines (549 loc) · 18.4 KB
/
run.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/filswan/go-mcs-sdk/mcs/api/common/logs"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"github.com/itsjamie/gin-cors"
"github.com/olekukonko/tablewriter"
"github.com/swanchain/go-computing-provider/account"
"github.com/swanchain/go-computing-provider/conf"
"github.com/swanchain/go-computing-provider/internal/computing"
"github.com/swanchain/go-computing-provider/internal/initializer"
"github.com/swanchain/go-computing-provider/util"
"github.com/swanchain/go-computing-provider/wallet"
"github.com/swanchain/go-computing-provider/wallet/contract/collateral"
"github.com/urfave/cli/v2"
"io"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var runCmd = &cli.Command{
Name: "run",
Usage: "Start a cp process",
Action: func(cctx *cli.Context) error {
logs.GetLogger().Info("Start in computing provider mode.")
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
initializer.ProjectInit(cpRepoPath)
r := gin.Default()
r.Use(cors.Middleware(cors.Config{
Origins: "*",
Methods: "GET, PUT, POST, DELETE",
RequestHeaders: "Origin, Authorization, Content-Type",
ExposedHeaders: "",
MaxAge: 50 * time.Second,
ValidateHeaders: false,
}))
pprof.Register(r)
v1 := r.Group("/api/v1")
cpManager(v1.Group("/computing"))
shutdownChan := make(chan struct{})
httpStopper, err := util.ServeHttp(r, "cp-api", ":"+strconv.Itoa(conf.GetConfig().API.Port), true)
if err != nil {
logs.GetLogger().Fatal("failed to start cp-api endpoint: %s", err)
}
finishCh := util.MonitorShutdown(shutdownChan,
util.ShutdownHandler{Component: "cp-api", StopFunc: httpStopper},
)
<-finishCh
return nil
},
}
func cpManager(router *gin.RouterGroup) {
router.GET("/host/info", computing.GetServiceProviderInfo)
router.POST("/lagrange/jobs", computing.ReceiveJob)
router.POST("/lagrange/jobs/redeploy", computing.RedeployJob)
router.DELETE("/lagrange/jobs", computing.CancelJob)
router.GET("/lagrange/cp", computing.StatisticalSources)
router.POST("/lagrange/jobs/renew", computing.ReNewJob)
router.GET("/lagrange/spaces/log", computing.GetSpaceLog)
router.POST("/lagrange/cp/proof", computing.DoProof)
router.GET("/cp", computing.StatisticalSources)
router.GET("/cp/info", computing.GetCpInfo)
router.POST("/cp/ubi", computing.DoUbiTaskForK8s)
router.POST("/cp/receive/ubi", computing.ReceiveUbiProofForK8s)
}
var infoCmd = &cli.Command{
Name: "info",
Usage: "Print computing-provider info",
Action: func(cctx *cli.Context) error {
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, true); err != nil {
return fmt.Errorf("load config file failed, error: %+v", err)
}
localNodeId := computing.GetNodeId(cpRepoPath)
k8sService := computing.NewK8sService()
var count int
if k8sService.Version == "" {
count = 0
} else {
count, _ = k8sService.GetDeploymentActiveCount()
}
chainRpc, err := conf.GetRpcByName(conf.DefaultRpc)
if err != nil {
return err
}
client, err := ethclient.Dial(chainRpc)
if err != nil {
return err
}
defer client.Close()
var balance, collateralBalance, ownerBalance string
var contractAddress, ownerAddress, beneficiaryAddress, ubiFlag, chainNodeId string
cpStub, err := account.NewAccountStub(client)
if err == nil {
cpAccount, err := cpStub.GetCpAccountInfo()
if err != nil {
err = fmt.Errorf("get cpAccount failed, error: %v", err)
}
if cpAccount.UbiFlag == 1 {
ubiFlag = "Accept"
} else {
ubiFlag = "Reject"
}
contractAddress = cpStub.ContractAddress
ownerAddress = cpAccount.OwnerAddress
beneficiaryAddress = cpAccount.Beneficiary.BeneficiaryAddress
chainNodeId = cpAccount.NodeId
}
balance, err = wallet.Balance(context.TODO(), client, conf.GetConfig().HUB.WalletAddress)
collateralStub, err := collateral.NewCollateralStub(client, collateral.WithPublicKey(conf.GetConfig().HUB.WalletAddress))
if err == nil {
collateralBalance, err = collateralStub.Balances()
}
if ownerAddress != "" {
ownerBalance, err = wallet.Balance(context.TODO(), client, ownerAddress)
}
var domain = conf.GetConfig().API.Domain
if strings.HasPrefix(domain, ".") {
domain = domain[1:]
}
var taskData [][]string
taskData = append(taskData, []string{"Multi-Address:", conf.GetConfig().API.MultiAddress})
taskData = append(taskData, []string{"Node ID:", localNodeId})
taskData = append(taskData, []string{"ECP:"})
taskData = append(taskData, []string{" Contract Address:", contractAddress})
taskData = append(taskData, []string{" UBI FLAG:", ubiFlag})
taskData = append(taskData, []string{" Owner:", ownerAddress})
taskData = append(taskData, []string{" Beneficiary Address:", beneficiaryAddress})
taskData = append(taskData, []string{" Available(SWAN-ETH):", ownerBalance})
taskData = append(taskData, []string{" Collateral(SWAN-ETH):", "0"})
taskData = append(taskData, []string{"FCP:"})
taskData = append(taskData, []string{" Wallet:", conf.GetConfig().HUB.WalletAddress})
taskData = append(taskData, []string{" Domain:", domain})
taskData = append(taskData, []string{" Running deployments:", strconv.Itoa(count)})
taskData = append(taskData, []string{" Available(SWAN-ETH):", balance})
taskData = append(taskData, []string{" Collateral(SWAN-ETH):", collateralBalance})
var rowColor []tablewriter.Colors
if ubiFlag == "Accept" {
rowColor = []tablewriter.Colors{{tablewriter.Bold, tablewriter.FgGreenColor}}
} else {
rowColor = []tablewriter.Colors{{tablewriter.Bold, tablewriter.FgRedColor}}
}
var rowColorList []RowColor
rowColorList = append(rowColorList, RowColor{
row: 4,
column: []int{1},
color: rowColor,
})
header := []string{"Name:", conf.GetConfig().API.NodeName}
NewVisualTable(header, taskData, rowColorList).Generate(false)
if localNodeId != chainNodeId {
fmt.Printf("NodeId mismatch, local node id: %s, chain node id: %s.\n", localNodeId, chainNodeId)
}
return nil
},
}
var initCmd = &cli.Command{
Name: "init",
Usage: "Initialize a new cp",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "multi-address",
Usage: "The multiAddress for libp2p(public ip)",
},
&cli.StringFlag{
Name: "node-name",
Usage: "The name of cp",
},
&cli.IntFlag{
Name: "port",
Usage: "The cp listens on port, default: 9085",
},
},
Action: func(cctx *cli.Context) error {
multiAddr := cctx.String("multi-address")
port := cctx.Int("port")
if strings.TrimSpace(multiAddr) == "" {
return fmt.Errorf("the multi-address field required")
}
nodeName := cctx.String("node-name")
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, true); err != nil {
logs.GetLogger().Fatal(err)
}
return conf.UpdateConfigFile(cpRepoPath, multiAddr, nodeName, port)
},
}
var accountCmd = &cli.Command{
Name: "account",
Usage: "Manage account info of CP",
Subcommands: []*cli.Command{
createAccountCmd,
changeMultiAddressCmd,
changeOwnerAddressCmd,
changeBeneficiaryAddressCmd,
changeUbiFlagCmd,
},
}
var createAccountCmd = &cli.Command{
Name: "create",
Usage: "Create a cp account to chain",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "ownerAddress",
Usage: "Specify a OwnerAddress",
},
&cli.StringFlag{
Name: "beneficiaryAddress",
Usage: "Specify a beneficiaryAddress to receive rewards. If not specified, use the same address as ownerAddress",
},
&cli.BoolFlag{
Name: "ubi-flag",
Usage: "Whether to accept the UBI task",
Value: false,
},
},
Action: func(cctx *cli.Context) error {
ownerAddress := cctx.String("ownerAddress")
if strings.TrimSpace(ownerAddress) == "" {
return fmt.Errorf("ownerAddress is not empty")
}
beneficiaryAddress := cctx.String("beneficiaryAddress")
if strings.TrimSpace(beneficiaryAddress) == "" {
beneficiaryAddress = ownerAddress
}
ubiFlag := cctx.Bool("ubi-flag")
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, true); err != nil {
logs.GetLogger().Fatal(err)
}
return createAccount(cpRepoPath, ownerAddress, beneficiaryAddress, ubiFlag)
},
}
var changeMultiAddressCmd = &cli.Command{
Name: "changeMultiAddress",
Usage: "Update MultiAddress of CP (/ip4/<public_ip>/tcp/<port>)",
ArgsUsage: "[multiAddress]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "ownerAddress",
Usage: "Specify a OwnerAddress",
Required: true,
},
},
Action: func(cctx *cli.Context) error {
if cctx.NArg() != 1 {
return fmt.Errorf(" Requires a multiAddress")
}
ownerAddress := cctx.String("ownerAddress")
if strings.TrimSpace(ownerAddress) == "" {
return fmt.Errorf("ownerAddress is not empty")
}
multiAddr := cctx.Args().Get(0)
if strings.TrimSpace(multiAddr) == "" {
return fmt.Errorf("failed to parse : %s", multiAddr)
}
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, false); err != nil {
logs.GetLogger().Fatal(err)
}
return changeMultiAddress(ownerAddress, multiAddr)
},
}
var changeOwnerAddressCmd = &cli.Command{
Name: "changeOwnerAddress",
Usage: "Update OwnerAddress of CP",
ArgsUsage: "[newOwnerAddress]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "ownerAddress",
Usage: "Specify a OwnerAddress",
Required: true,
},
},
Action: func(cctx *cli.Context) error {
ownerAddress := cctx.String("oldOwnerAddress")
if strings.TrimSpace(ownerAddress) == "" {
return fmt.Errorf("ownerAddress is not empty")
}
if cctx.NArg() != 1 {
return fmt.Errorf(" Requires a ownerAddress")
}
newOwnerAddr := cctx.Args().Get(0)
if strings.TrimSpace(newOwnerAddr) == "" {
return fmt.Errorf("failed to parse : %s", newOwnerAddr)
}
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, false); err != nil {
logs.GetLogger().Fatal(err)
}
chainUrl, err := conf.GetRpcByName(conf.DefaultRpc)
if err != nil {
logs.GetLogger().Errorf("get rpc url failed, error: %v,", err)
return err
}
localWallet, err := wallet.SetupWallet(wallet.WalletRepo)
if err != nil {
logs.GetLogger().Errorf("setup wallet ubi failed, error: %v,", err)
return err
}
ki, err := localWallet.FindKey(ownerAddress)
if err != nil || ki == nil {
logs.GetLogger().Errorf("the old owner address: %s, private key %v,", ownerAddress, wallet.ErrKeyInfoNotFound)
return err
}
client, err := ethclient.Dial(chainUrl)
if err != nil {
logs.GetLogger().Errorf("dial rpc connect failed, error: %v,", err)
return err
}
defer client.Close()
cpStub, err := account.NewAccountStub(client, account.WithCpPrivateKey(ki.PrivateKey))
if err != nil {
logs.GetLogger().Errorf("create cp client failed, error: %v,", err)
return err
}
cpAccount, err := cpStub.GetCpAccountInfo()
if err != nil {
return fmt.Errorf("get cpAccount faile, error: %v", err)
}
if !strings.EqualFold(cpAccount.OwnerAddress, ownerAddress) {
return fmt.Errorf("the owner address is incorrect. The owner on the chain is %s, and the current address is %s", cpAccount.OwnerAddress, ownerAddress)
}
submitUBIProofTx, err := cpStub.ChangeOwnerAddress(common.HexToAddress(newOwnerAddr))
if err != nil {
logs.GetLogger().Errorf("change owner address tx failed, error: %v,", err)
return err
}
fmt.Printf("ChangeOwnerAddress: %s \n", submitUBIProofTx)
return nil
},
}
var changeBeneficiaryAddressCmd = &cli.Command{
Name: "changeBeneficiaryAddress",
Usage: "Update beneficiaryAddress of CP",
ArgsUsage: "[beneficiaryAddress]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "ownerAddress",
Usage: "Specify a OwnerAddress",
Required: true,
},
},
Action: func(cctx *cli.Context) error {
ownerAddress := cctx.String("ownerAddress")
if strings.TrimSpace(ownerAddress) == "" {
return fmt.Errorf("ownerAddress is not empty")
}
if cctx.NArg() != 1 {
return fmt.Errorf(" Requires a beneficiaryAddress")
}
beneficiaryAddress := cctx.Args().Get(0)
if strings.TrimSpace(beneficiaryAddress) == "" {
return fmt.Errorf("failed to parse target address: %s", beneficiaryAddress)
}
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, false); err != nil {
logs.GetLogger().Fatal(err)
}
chainUrl, err := conf.GetRpcByName(conf.DefaultRpc)
if err != nil {
logs.GetLogger().Errorf("get rpc url failed, error: %v,", err)
return err
}
localWallet, err := wallet.SetupWallet(wallet.WalletRepo)
if err != nil {
logs.GetLogger().Errorf("setup wallet ubi failed, error: %v,", err)
return err
}
ki, err := localWallet.FindKey(ownerAddress)
if err != nil || ki == nil {
logs.GetLogger().Errorf("the address: %s, private key %v. Please import the address into the wallet", ownerAddress, wallet.ErrKeyInfoNotFound)
return err
}
client, err := ethclient.Dial(chainUrl)
if err != nil {
logs.GetLogger().Errorf("dial rpc connect failed, error: %v,", err)
return err
}
defer client.Close()
cpStub, err := account.NewAccountStub(client, account.WithCpPrivateKey(ki.PrivateKey))
if err != nil {
logs.GetLogger().Errorf("create cp client failed, error: %v,", err)
return err
}
cpAccount, err := cpStub.GetCpAccountInfo()
if err != nil {
return fmt.Errorf("get cpAccount faile, error: %v", err)
}
if !strings.EqualFold(cpAccount.OwnerAddress, ownerAddress) {
return fmt.Errorf("the owner address is incorrect. The owner on the chain is %s, and the current address is %s", cpAccount.OwnerAddress, ownerAddress)
}
newQuota := big.NewInt(int64(0))
newExpiration := big.NewInt(int64(0))
changeBeneficiaryAddressTx, err := cpStub.ChangeBeneficiary(common.HexToAddress(beneficiaryAddress), newQuota, newExpiration)
if err != nil {
logs.GetLogger().Errorf("change owner address tx failed, error: %v,", err)
return err
}
fmt.Printf("changeBeneficiaryAddress Transaction hash: %s \n", changeBeneficiaryAddressTx)
return nil
},
}
var changeUbiFlagCmd = &cli.Command{
Name: "changeUbiFlag",
Usage: "Update ubiFlag of CP (0:Reject, 1:Accept)",
ArgsUsage: "[ubiFlag]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "ownerAddress",
Usage: "Specify a OwnerAddress",
Required: true,
},
},
Action: func(cctx *cli.Context) error {
ownerAddress := cctx.String("ownerAddress")
if strings.TrimSpace(ownerAddress) == "" {
return fmt.Errorf("ownerAddress is not empty")
}
if cctx.NArg() != 1 {
return fmt.Errorf(" Requires a beneficiaryAddress")
}
ubiFlag := cctx.Args().Get(0)
if strings.TrimSpace(ubiFlag) == "" {
return fmt.Errorf("ubiFlag is not empty")
}
if strings.TrimSpace(ubiFlag) != "0" && strings.TrimSpace(ubiFlag) != "1" {
return fmt.Errorf("ubiFlag must be 0 or 1")
}
cpRepoPath, ok := os.LookupEnv("CP_PATH")
if !ok {
return fmt.Errorf("missing CP_PATH env, please set export CP_PATH=<YOUR CP_PATH>")
}
if err := conf.InitConfig(cpRepoPath, false); err != nil {
logs.GetLogger().Fatal(err)
}
chainUrl, err := conf.GetRpcByName(conf.DefaultRpc)
if err != nil {
logs.GetLogger().Errorf("get rpc url failed, error: %v,", err)
return err
}
localWallet, err := wallet.SetupWallet(wallet.WalletRepo)
if err != nil {
logs.GetLogger().Errorf("setup wallet ubi failed, error: %v,", err)
return err
}
ki, err := localWallet.FindKey(ownerAddress)
if err != nil || ki == nil {
logs.GetLogger().Errorf("the address: %s, private key %v. Please import the address into the wallet", ownerAddress, wallet.ErrKeyInfoNotFound)
return err
}
client, err := ethclient.Dial(chainUrl)
if err != nil {
logs.GetLogger().Errorf("dial rpc connect failed, error: %v,", err)
return err
}
defer client.Close()
cpStub, err := account.NewAccountStub(client, account.WithCpPrivateKey(ki.PrivateKey))
if err != nil {
logs.GetLogger().Errorf("create cp client failed, error: %v,", err)
return err
}
cpAccount, err := cpStub.GetCpAccountInfo()
if err != nil {
return fmt.Errorf("get cpAccount faile, error: %v", err)
}
if !strings.EqualFold(cpAccount.OwnerAddress, ownerAddress) {
return fmt.Errorf("the owner address is incorrect. The owner on the chain is %s, and the current address is %s", cpAccount.OwnerAddress, ownerAddress)
}
newUbiFlag, _ := strconv.ParseUint(strings.TrimSpace(ubiFlag), 10, 64)
changeBeneficiaryAddressTx, err := cpStub.ChangeUbiFlag(uint8(newUbiFlag))
if err != nil {
logs.GetLogger().Errorf("change ubi flag tx failed, error: %v,", err)
return err
}
fmt.Printf("ChangeUbiFlag Transaction hash: %s \n", changeBeneficiaryAddressTx)
return nil
},
}
func DoSend(contractAddr, height string) error {
type ContractReq struct {
Addr string `json:"addr"`
Height int `json:"height"`
}
h, _ := strconv.ParseInt(height, 10, 64)
var contractReq ContractReq
contractReq.Addr = contractAddr
contractReq.Height = int(h)
jsonData, err := json.Marshal(contractReq)
if err != nil {
logs.GetLogger().Errorf("JSON encoding failed: %v", err)
return err
}
resp, err := http.Post(conf.GetConfig().UBI.UbiUrl+"/contracts", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
logs.GetLogger().Errorf("POST request failed: %v", err)
return err
}
defer resp.Body.Close()
var resultResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data,omitempty"`
}
body, err := io.ReadAll(resp.Body)
if err != nil {
logs.GetLogger().Errorf("read response failed: %v", err)
return err
}
err = json.Unmarshal(body, &resultResp)
if err != nil {
logs.GetLogger().Errorf("response convert to json failed: %v", err)
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("register cp to ubi hub failed, error: %s", resultResp.Msg)
}
return nil
}