|
| 1 | +package lease |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "time" |
| 6 | + |
| 7 | + coordinationv1 "k8s.io/api/coordination/v1" |
| 8 | + "k8s.io/apimachinery/pkg/api/errors" |
| 9 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 10 | + "k8s.io/apimachinery/pkg/util/wait" |
| 11 | + "k8s.io/client-go/kubernetes" |
| 12 | + "k8s.io/utils/ptr" |
| 13 | +) |
| 14 | + |
| 15 | +type KubeLock interface { |
| 16 | + Lock(ctx context.Context) error |
| 17 | + Unlock(ctx context.Context) error |
| 18 | +} |
| 19 | + |
| 20 | +type kubeLeaseLock struct { |
| 21 | + client kubernetes.Interface |
| 22 | + leaseName string |
| 23 | + namespace string |
| 24 | + holderIdentity string |
| 25 | + leaseDuration int // seconds |
| 26 | + cancelFunc context.CancelFunc |
| 27 | +} |
| 28 | + |
| 29 | +func NewKubeLeaseLock(client kubernetes.Interface, leaseName, namespace, holderIdentity string, leaseDurationSeconds int) KubeLock { |
| 30 | + return &kubeLeaseLock{ |
| 31 | + client: client, |
| 32 | + leaseName: leaseName, |
| 33 | + namespace: namespace, |
| 34 | + holderIdentity: holderIdentity, |
| 35 | + leaseDuration: leaseDurationSeconds, |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func (k *kubeLeaseLock) Lock(ctx context.Context) error { |
| 40 | + backoff := wait.Backoff{ |
| 41 | + Duration: time.Second, // start with 1 second |
| 42 | + Factor: 1.5, //nolint:gomnd // multiply by 1.5 on each retry |
| 43 | + Jitter: 0.5, //nolint:gomnd // add 50% jitter to wait time on each retry |
| 44 | + Steps: 100, //nolint:gomnd // retry 100 times |
| 45 | + Cap: time.Hour, // but never wait more than 1 hour |
| 46 | + } |
| 47 | + |
| 48 | + return wait.ExponentialBackoff(backoff, func() (bool, error) { //nolint:wrapcheck |
| 49 | + timestamp := metav1.MicroTime{Time: time.Now()} |
| 50 | + lease := &coordinationv1.Lease{ |
| 51 | + ObjectMeta: metav1.ObjectMeta{ |
| 52 | + Name: k.leaseName, |
| 53 | + Namespace: k.namespace, |
| 54 | + }, |
| 55 | + Spec: coordinationv1.LeaseSpec{ |
| 56 | + HolderIdentity: &k.holderIdentity, |
| 57 | + LeaseDurationSeconds: ptr.To(int32(k.leaseDuration)), |
| 58 | + AcquireTime: ×tamp, |
| 59 | + RenewTime: ×tamp, |
| 60 | + }, |
| 61 | + } |
| 62 | + |
| 63 | + _, err := k.client.CoordinationV1().Leases(k.namespace).Create(ctx, lease, metav1.CreateOptions{}) |
| 64 | + if err != nil { |
| 65 | + if errors.IsAlreadyExists(err) { |
| 66 | + // If the lease already exists, check if it's held by another holder |
| 67 | + existingLease, getErr := k.client.CoordinationV1().Leases(k.namespace).Get(ctx, k.leaseName, metav1.GetOptions{}) |
| 68 | + if getErr != nil { |
| 69 | + return false, getErr //nolint:wrapcheck |
| 70 | + } |
| 71 | + // check if the lease is expired |
| 72 | + if existingLease.Spec.RenewTime != nil && time.Since(existingLease.Spec.RenewTime.Time) > time.Duration(k.leaseDuration)*time.Second { |
| 73 | + // If the lease is expired, delete it and retry |
| 74 | + delErr := k.client.CoordinationV1().Leases(k.namespace).Delete(ctx, k.leaseName, metav1.DeleteOptions{}) |
| 75 | + if delErr != nil { |
| 76 | + return false, delErr //nolint:wrapcheck |
| 77 | + } |
| 78 | + return false, nil |
| 79 | + } |
| 80 | + // check if the lease is held by another holder |
| 81 | + if existingLease.Spec.HolderIdentity != nil && *existingLease.Spec.HolderIdentity != k.holderIdentity { |
| 82 | + // If the lease is held by another holder, return false to retry |
| 83 | + return false, nil |
| 84 | + } |
| 85 | + return true, nil |
| 86 | + } |
| 87 | + return false, err //nolint:wrapcheck |
| 88 | + } |
| 89 | + |
| 90 | + // Create a child context with cancellation |
| 91 | + ctx, k.cancelFunc = context.WithCancel(ctx) |
| 92 | + go k.renewLeasePeriodically(ctx) |
| 93 | + |
| 94 | + return true, nil |
| 95 | + }) |
| 96 | +} |
| 97 | + |
| 98 | +func (k *kubeLeaseLock) renewLeasePeriodically(ctx context.Context) { |
| 99 | + // let's renew the lease every 1/2 of the lease duration; use milliseconds for ticker |
| 100 | + ticker := time.NewTicker(time.Duration(k.leaseDuration*500) * time.Millisecond) //nolint:gomnd |
| 101 | + defer ticker.Stop() |
| 102 | + |
| 103 | + for { |
| 104 | + select { |
| 105 | + case <-ticker.C: |
| 106 | + lease, err := k.client.CoordinationV1().Leases(k.namespace).Get(ctx, k.leaseName, metav1.GetOptions{}) |
| 107 | + if err != nil || lease.Spec.HolderIdentity == nil || *lease.Spec.HolderIdentity != k.holderIdentity { |
| 108 | + return |
| 109 | + } |
| 110 | + |
| 111 | + lease.Spec.RenewTime = &metav1.MicroTime{Time: time.Now()} |
| 112 | + k.client.CoordinationV1().Leases(k.namespace).Update(ctx, lease, metav1.UpdateOptions{}) //nolint:errcheck |
| 113 | + case <-ctx.Done(): |
| 114 | + // Exit the goroutine when the context is cancelled |
| 115 | + return |
| 116 | + } |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +func (k *kubeLeaseLock) Unlock(ctx context.Context) error { |
| 121 | + // Call the cancel function to stop the lease renewal process |
| 122 | + if k.cancelFunc != nil { |
| 123 | + k.cancelFunc() |
| 124 | + } |
| 125 | + lease, err := k.client.CoordinationV1().Leases(k.namespace).Get(ctx, k.leaseName, metav1.GetOptions{}) |
| 126 | + if err != nil { |
| 127 | + return err //nolint:wrapcheck |
| 128 | + } |
| 129 | + |
| 130 | + if lease.Spec.HolderIdentity == nil || *lease.Spec.HolderIdentity != k.holderIdentity { |
| 131 | + return nil |
| 132 | + } |
| 133 | + |
| 134 | + return k.client.CoordinationV1().Leases(k.namespace).Delete(ctx, k.leaseName, metav1.DeleteOptions{}) //nolint:wrapcheck |
| 135 | +} |
0 commit comments