|
4 | 4 | "context"
|
5 | 5 | "fmt"
|
6 | 6 | "os"
|
| 7 | + "time" |
7 | 8 |
|
8 | 9 | "github.com/samber/lo"
|
9 | 10 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
@@ -40,12 +41,21 @@ func LeaseHijacker(ctx context.Context, config *rest.Config, namespace string, n
|
40 | 41 | if os.Getenv("HIJACK_LEASE") != "true" {
|
41 | 42 | return nil // If not set, fallback to other controller-runtime lease settings
|
42 | 43 | }
|
43 |
| - log.FromContext(ctx).Info("hijacking lease", "namespace", namespace, "name", name) |
44 | 44 | kubeClient := coordinationv1client.NewForConfigOrDie(config)
|
45 | 45 | lease := lo.Must(kubeClient.Leases(namespace).Get(ctx, name, metav1.GetOptions{}))
|
| 46 | + |
| 47 | + untilElection := time.Until(lease.Spec.RenewTime.Add(time.Duration(*lease.Spec.LeaseDurationSeconds) * time.Second)) |
| 48 | + |
46 | 49 | lease.Spec.HolderIdentity = lo.ToPtr(fmt.Sprintf("%s_%s", lo.Must(os.Hostname()), uuid.NewUUID()))
|
47 | 50 | lease.Spec.AcquireTime = lo.ToPtr(metav1.NowMicro())
|
| 51 | + lease.Spec.RenewTime = lo.ToPtr(metav1.NowMicro()) |
| 52 | + *lease.Spec.LeaseDurationSeconds += 5 // Make our lease longer to guarantee we win the next election |
| 53 | + *lease.Spec.LeaseTransitions += 1 |
48 | 54 | lo.Must(kubeClient.Leases(namespace).Update(ctx, lease, metav1.UpdateOptions{}))
|
| 55 | + |
| 56 | + log.FromContext(ctx).Info(fmt.Sprintf("hijacked lease, waiting %s for election", untilElection), "namespace", namespace, "name", name) |
| 57 | + time.Sleep(untilElection) |
| 58 | + |
49 | 59 | return lo.Must(resourcelock.New(
|
50 | 60 | resourcelock.LeasesResourceLock,
|
51 | 61 | namespace,
|
|
0 commit comments