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
|
package errors
import (
"context"
"fmt"
"strings"
"time"
"github.com/crc-org/crc/v2/pkg/crc/logging"
)
type vmNotExist string
func (v vmNotExist) Error() string {
return string(v)
}
const VMNotExist vmNotExist = "Machine does not exist. Use 'crc start' to create it"
type daemonNotRunning string
func (d daemonNotRunning) Error() string {
return string(d)
}
const DaemonNotRunning daemonNotRunning = "crc does not seem to be setup correctly, have you run 'crc setup'?"
type PreflightError struct {
Err error
}
func (p *PreflightError) Error() string {
return p.Err.Error()
}
func (p *PreflightError) Unwrap() error {
return p.Err
}
type MultiError struct {
Errors []error
}
func (m MultiError) Error() string {
if len(m.Errors) == 0 {
return ""
}
if len(m.Errors) == 1 {
return m.Errors[0].Error()
}
var aggregatedErrors []string
count := 1
current := m.Errors[0].Error()
for i := 1; i < len(m.Errors); i++ {
if m.Errors[i].Error() == current {
count++
continue
}
aggregatedErrors = append(aggregatedErrors, errorWithCount(current, count))
count = 1
current = m.Errors[i].Error()
}
aggregatedErrors = append(aggregatedErrors, errorWithCount(current, count))
return strings.Join(aggregatedErrors, "\n")
}
func (m *MultiError) Collect(err error) {
if err != nil {
m.Errors = append(m.Errors, err)
}
}
func errorWithCount(current string, count int) string {
if count == 1 {
return current
}
return fmt.Sprintf("%s (x%d)", current, count)
}
// RetriableError is an error that can be tried again
type RetriableError struct {
Err error
}
func (r *RetriableError) Error() string {
return "Temporary error: " + r.Err.Error()
}
// Retry retries for a certain duration, after a delay
func Retry(ctx context.Context, limit time.Duration, callback func() error, d time.Duration) error {
if ctx.Err() != nil {
return ctx.Err()
}
m := MultiError{}
timeLimit := time.Now().Add(limit)
attempt := 0
for time.Now().Before(timeLimit) || attempt < 2 {
logging.Debugf("retry loop: attempt %d", attempt)
err := callback()
if err == nil {
return nil
}
attempt++
m.Collect(err)
if _, ok := err.(*RetriableError); !ok {
logging.Debugf("non-retriable error: %v", err)
return m
}
logging.Debugf("error: %v - sleeping %s", err, d)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(d):
}
}
logging.Debugf("RetryAfter timeout after %d tries", attempt)
return m
}
|