forked from jfrog/jfrog-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retryexecutor.go
56 lines (44 loc) · 1.29 KB
/
retryexecutor.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
package utils
import (
"fmt"
"github.com/shahiinn/jfrog-client-go/utils/log"
"time"
)
type ExecutionHandlerFunc func() (bool, error)
type RetryExecutor struct {
// The amount of retries to perform.
MaxRetries int
// Number of seconds to sleep between retries.
RetriesInterval int
// Message to display when retrying.
ErrorMessage string
// Prefix to print at the beginning of each log.
LogMsgPrefix string
// ExecutionHandler is the operation to run with retries.
ExecutionHandler ExecutionHandlerFunc
}
func (runner *RetryExecutor) Execute() error {
var err error
var shouldRetry bool
for i := 0; i <= runner.MaxRetries; i++ {
// Run ExecutionHandler
shouldRetry, err = runner.ExecutionHandler()
// If should not retry, return
if !shouldRetry {
return err
}
log.Warn(runner.getLogRetryMessage(i, err))
// Going to sleep for RetryInterval seconds
if runner.RetriesInterval > 0 && i < runner.MaxRetries {
time.Sleep(time.Second * time.Duration(runner.RetriesInterval))
}
}
return err
}
func (runner *RetryExecutor) getLogRetryMessage(attemptNumber int, err error) (message string) {
message = fmt.Sprintf("%sAttempt %v - %s", runner.LogMsgPrefix, attemptNumber, runner.ErrorMessage)
if err != nil {
message = fmt.Sprintf("%s - %s", message, err.Error())
}
return
}