From cd49c1dac7079db2200801dedeb304bdbef5d811 Mon Sep 17 00:00:00 2001 From: Ori Newman Date: Mon, 14 Sep 2020 12:33:42 +0300 Subject: [PATCH] [NOD-1390] Add timeout to kaspactl (#929) * [NOD-1390] Add timeout to kaspactl * [NOD-1390] Fix grammar --- cmd/kaspactl/config.go | 8 +++++--- cmd/kaspactl/main.go | 26 ++++++++++++++++++++------ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/cmd/kaspactl/config.go b/cmd/kaspactl/config.go index 886227344..b1dfa1f82 100644 --- a/cmd/kaspactl/config.go +++ b/cmd/kaspactl/config.go @@ -1,18 +1,19 @@ package main import ( + "github.com/jessevdk/go-flags" "github.com/kaspanet/kaspad/infrastructure/config" "github.com/pkg/errors" - - "github.com/jessevdk/go-flags" ) var ( - defaultRPCServer = "localhost" + defaultRPCServer = "localhost" + defaultTimeout uint64 = 30 ) type configFlags struct { RPCServer string `short:"s" long:"rpcserver" description:"RPC server to connect to"` + Timeout uint64 `short:"t" long:"timeout" description:"Timeout for the request (in seconds)"` RequestJSON string `description:"The request in JSON format"` config.NetworkFlags } @@ -20,6 +21,7 @@ type configFlags struct { func parseConfig() (*configFlags, error) { cfg := &configFlags{ RPCServer: defaultRPCServer, + Timeout: defaultTimeout, } parser := flags.NewParser(cfg, flags.PrintErrors|flags.HelpFlag) args, err := parser.Parse() diff --git a/cmd/kaspactl/main.go b/cmd/kaspactl/main.go index 1a241b4f3..b16574c9d 100644 --- a/cmd/kaspactl/main.go +++ b/cmd/kaspactl/main.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/kaspanet/kaspad/infrastructure/network/rpcclient/grpcclient" "os" + "time" ) func main() { @@ -22,13 +23,26 @@ func main() { } defer client.Disconnect() - requestString := cfg.RequestJSON - responseString, err := client.PostJSON(requestString) - if err != nil { - printErrorAndExit(fmt.Sprintf("error posting the request to the RPC server: %s", err)) - } + var responseString string + done := make(chan struct{}) - fmt.Println(responseString) + go func() { + requestString := cfg.RequestJSON + var err error + responseString, err = client.PostJSON(requestString) + if err != nil { + printErrorAndExit(fmt.Sprintf("error posting the request to the RPC server: %s", err)) + } + done <- struct{}{} + }() + + timeout := time.Duration(cfg.Timeout) * time.Second + select { + case <-done: + fmt.Println(responseString) + case <-time.After(timeout): + printErrorAndExit(fmt.Sprintf("timeout of %s has been exceeded", timeout)) + } } func printErrorAndExit(message string) {