github.com/banzaicloud/operator-tools@v0.28.10/pkg/reconciler/reconcileretry.go (about)

     1  // Copyright © 2020 Banzai Cloud
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package reconciler
    16  
    17  import (
    18  	"time"
    19  
    20  	"emperror.dev/errors"
    21  	"sigs.k8s.io/controller-runtime/pkg/reconcile"
    22  )
    23  
    24  type ReconcileRetry struct {
    25  	MaxRetries  int
    26  	DefaultWait time.Duration
    27  }
    28  
    29  func (r *ReconcileRetry) Reconcile(component func() (*reconcile.Result, error)) error {
    30  	i := 0
    31  	for ; i < r.MaxRetries || r.MaxRetries == -1; i++ {
    32  		result, err := component()
    33  		if err != nil {
    34  			return err
    35  		}
    36  		if result == nil {
    37  			return nil
    38  		}
    39  		if !result.Requeue && result.RequeueAfter == 0 {
    40  			break
    41  		} else {
    42  			if result.RequeueAfter > 0 {
    43  				time.Sleep(result.RequeueAfter)
    44  			} else {
    45  				time.Sleep(r.DefaultWait)
    46  			}
    47  		}
    48  	}
    49  	return errors.Errorf("reconciliation did not complete after %d retries", i)
    50  }