From 92ece97bd028f41c9baec9f6f5223fefeba78c22 Mon Sep 17 00:00:00 2001 From: Javad Date: Sat, 2 Mar 2024 08:20:31 +0330 Subject: [PATCH] feat: add concurrent run staker --- main.go | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 31432be..281e375 100644 --- a/main.go +++ b/main.go @@ -1,12 +1,16 @@ package main import ( + "context" "encoding/json" "flag" "log" "os" "os/exec" + "os/signal" "strconv" + "sync" + "syscall" ) type Cfg struct { @@ -41,6 +45,14 @@ func main() { amount := strconv.FormatFloat(cfg.Amount, 'g', -1, 64) + var wg sync.WaitGroup + ctx, cancel := context.WithCancel(context.Background()) + + defer func() { + log.Println("Exiting...") + os.Exit(0) + }() + for _, val := range cfg.Validators { args := make([]string, 0) args = append(args, "--path", cfg.WalletPath, "tx", "bond") @@ -55,11 +67,35 @@ func main() { args = append(args, "--server", *rpc) } - out, err := exec.Command(cfg.PactusWalletExecPath, args...).Output() + wg.Add(1) + go runCmd(ctx, cfg.PactusWalletExecPath, val.Address, &wg, args...) + } + + go func() { + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) + + select { + case s := <-interrupt: + cancel() + log.Printf("task canceled by user, %s", s.String()) + } + }() + + wg.Wait() +} + +func runCmd(ctx context.Context, pactusWalletExecPath, validator string, wg *sync.WaitGroup, args ...string) { + defer wg.Done() + + select { + case <-ctx.Done(): + return + default: + out, err := exec.CommandContext(ctx, pactusWalletExecPath, args...).Output() if err != nil { - log.Fatalf("err: %s, msg: %s", err.Error(), string(out)) + log.Printf("validator: %s err: %s, msg: %s", validator, err.Error(), string(out)) } log.Println(string(out)) } - }