github.com/cobalt77/jfrog-client-go@v0.14.5/utils/retryexecutor.go (about) 1 package utils 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/cobalt77/jfrog-client-go/utils/log" 8 ) 9 10 type ExecutionHandlerFunc func() (bool, error) 11 12 type RetryExecutor struct { 13 // The amount of retries to perform. 14 MaxRetries int 15 16 // Number of seconds to sleep between retries. 17 RetriesInterval int 18 19 // Message to display when retrying. 20 ErrorMessage string 21 22 // Prefix to print at the beginning of each log. 23 LogMsgPrefix string 24 25 // ExecutionHandler is the operation to run with retries. 26 ExecutionHandler ExecutionHandlerFunc 27 } 28 29 func (runner *RetryExecutor) Execute() error { 30 var err error 31 var shouldRetry bool 32 for i := 0; i <= runner.MaxRetries; i++ { 33 // Run ExecutionHandler 34 shouldRetry, err = runner.ExecutionHandler() 35 36 // If should not retry, return 37 if !shouldRetry { 38 return err 39 } 40 41 log.Warn(runner.getLogRetryMessage(i, err)) 42 // Going to sleep for RetryInterval seconds 43 if runner.RetriesInterval > 0 && i < runner.MaxRetries { 44 time.Sleep(time.Second * time.Duration(runner.RetriesInterval)) 45 } 46 } 47 48 return err 49 } 50 51 func (runner *RetryExecutor) getLogRetryMessage(attemptNumber int, err error) (message string) { 52 message = fmt.Sprintf("%sAttempt %v - %s", runner.LogMsgPrefix, attemptNumber, runner.ErrorMessage) 53 if err != nil { 54 message = fmt.Sprintf("%s - %s", message, err.Error()) 55 } 56 return 57 }