github.com/k8snetworkplumbingwg/sriov-network-operator@v1.2.1-0.20240408194816-2d2e5a45d453/pkg/leaderelection/leaderelection.go (about)

     1  package leaderelection
     2  
     3  import (
     4  	"time"
     5  
     6  	"k8s.io/client-go/tools/leaderelection"
     7  	"sigs.k8s.io/controller-runtime/pkg/client"
     8  	"sigs.k8s.io/controller-runtime/pkg/log"
     9  
    10  	"github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/utils"
    11  )
    12  
    13  const (
    14  	// Defaults follow conventions
    15  	// https://github.com/openshift/enhancements/blob/master/CONVENTIONS.md#high-availability
    16  	// Impl Calculations: https://github.com/openshift/library-go/commit/7e7d216ed91c3119800219c9194e5e57113d059a
    17  	defaultLeaseDuration = 137 * time.Second
    18  	defaultRenewDeadline = 107 * time.Second
    19  	defaultRetryPeriod   = 26 * time.Second
    20  )
    21  
    22  func GetLeaderElectionConfig(c client.Client, enabled bool) (defaultConfig leaderelection.LeaderElectionConfig) {
    23  	defaultConfig = leaderelection.LeaderElectionConfig{
    24  		LeaseDuration: defaultLeaseDuration,
    25  		RenewDeadline: defaultRenewDeadline,
    26  		RetryPeriod:   defaultRetryPeriod,
    27  	}
    28  
    29  	if enabled {
    30  		isSingleNode, err := utils.IsSingleNodeCluster(c)
    31  		if err != nil {
    32  			log.Log.Error(err, "warning, unable to get cluster infrastructure status, using HA cluster values for leader election")
    33  			return
    34  		}
    35  		if isSingleNode {
    36  			return leaderElectionSingleNodeConfig(defaultConfig)
    37  		}
    38  	}
    39  	return
    40  }
    41  
    42  // Default leader election for Single Node environments
    43  // Impl Calculations:
    44  // https://github.com/openshift/library-go/commit/2612981f3019479805ac8448b997266fc07a236a#diff-61dd95c7fd45fa18038e825205fbfab8a803f1970068157608b6b1e9e6c27248R127
    45  func leaderElectionSingleNodeConfig(config leaderelection.LeaderElectionConfig) leaderelection.LeaderElectionConfig {
    46  	config.LeaseDuration = 270 * time.Second
    47  	config.RenewDeadline = 240 * time.Second
    48  	config.RetryPeriod = 60 * time.Second
    49  	return config
    50  }