@@ -35,8 +35,9 @@ import (
3535)
3636
3737const (
38- EnrollBackoffInit = time .Second * 5
39- EnrollBackoffMax = time .Minute * 10
38+ EnrollBackoffInit = time .Second * 5
39+ EnrollBackoffMax = time .Minute * 10
40+ EnrollInfiniteAttempts = - 1
4041
4142 maxRetriesstoreAgentInfo = 5
4243 defaultFleetServerHost = "0.0.0.0"
@@ -57,6 +58,7 @@ func EnrollWithBackoff(
5758 options EnrollOptions ,
5859 configStore saver ,
5960 backoffFactory func (done <- chan struct {}) backoff.Backoff ,
61+ maxAttempts int ,
6062) error {
6163 if backoffFactory == nil {
6264 backoffFactory = func (done <- chan struct {}) backoff.Backoff {
@@ -92,26 +94,37 @@ func EnrollWithBackoff(
9294 signal := make (chan struct {})
9395 defer close (signal )
9496 backExp := backoffFactory (signal )
97+ enrollFn := func () error {
98+ return enroll (ctx , log , persistentConfig , client , options , configStore )
99+ }
100+ err = retryEnroll (err , maxAttempts , log , enrollFn , client .URI (), backExp )
101+
102+ return err
103+ }
104+
105+ func retryEnroll (err error , maxAttempts int , log * logger.Logger , enrollFn func () error , clientURI string , backExp backoff.Backoff ) error {
106+ attemptNo := 1
95107
96108RETRYLOOP:
97109 for {
110+ attemptNo ++
98111 switch {
99112 case errors .Is (err , fleetapi .ErrTooManyRequests ):
100113 log .Warn ("Too many requests on the remote server, will retry in a moment." )
101114 case errors .Is (err , fleetapi .ErrConnRefused ):
102115 log .Warn ("Remote server is not ready to accept connections(Connection Refused), will retry in a moment." )
103116 case errors .Is (err , fleetapi .ErrTemporaryServerError ):
104117 log .Warnf ("Remote server failed to handle the request(%s), will retry in a moment." , err .Error ())
105- case errors .Is (err , context .Canceled ), errors .Is (err , context .DeadlineExceeded ), err == nil :
118+ case errors .Is (err , context .Canceled ), errors .Is (err , context .DeadlineExceeded ), errors . Is ( err , fleetapi . ErrInvalidToken ), err == nil , ( maxAttempts != EnrollInfiniteAttempts && attemptNo > maxAttempts ) :
106119 break RETRYLOOP
107120 case err != nil :
108121 log .Warnf ("Error detected: %s, will retry in a moment." , err .Error ())
109122 }
110123 if ! backExp .Wait () {
111124 break RETRYLOOP
112125 }
113- log .Infof ("Retrying enrollment to URL: %s" , client . URI () )
114- err = enroll ( ctx , log , persistentConfig , client , options , configStore )
126+ log .Infof ("Retrying enrollment to URL: %s" , clientURI )
127+ err = enrollFn ( )
115128 }
116129
117130 return err
0 commit comments