Skip to content

Commit 94c42ff

Browse files
authored
chore: tidied up lease hijacking (#100)
1 parent bcfec8f commit 94c42ff

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

leaderelection/leasehijacker.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,35 @@ import (
1515
"sigs.k8s.io/controller-runtime/pkg/log"
1616
)
1717

18-
// LeaseHijacker implements lease stealing to accelerate development workflows
19-
// TODO: migrate to https://kubernetes.io/docs/concepts/cluster-administration/coordinated-leader-election/ when it's past alpha.
18+
/*
19+
LeaseHijacker implements lease stealing to accelerate development workflows.
20+
When starting your controller manager, your local process will forcibly
21+
become leader. This is useful when developing locally against a cluster
22+
which already has a controller running in it
23+
24+
TODO: migrate to https://kubernetes.io/docs/concepts/cluster-administration/coordinated-leader-election/ when it's past alpha.
25+
26+
Include this in your controller manager as follows:
27+
```
28+
controllerruntime.NewManager(..., controllerruntime.Options{
29+
30+
// Used if HIJACK_LEASE is not set
31+
LeaderElectionID: name,
32+
LeaderElectionNamespace: "namespace",
33+
34+
// Used if HIJACK_LEASE=true
35+
LeaderElectionResourceLockInterface: leaderelection.LeaseHijacker(...)
36+
}
37+
```
38+
*/
2039
func LeaseHijacker(ctx context.Context, config *rest.Config, namespace string, name string) resourcelock.Interface {
2140
if os.Getenv("HIJACK_LEASE") != "true" {
2241
return nil // If not set, fallback to other controller-runtime lease settings
2342
}
24-
id := fmt.Sprintf("%s_%s", lo.Must(os.Hostname()), uuid.NewUUID())
2543
log.FromContext(ctx).Info("hijacking lease", "namespace", namespace, "name", name)
2644
kubeClient := coordinationv1client.NewForConfigOrDie(config)
2745
lease := lo.Must(kubeClient.Leases(namespace).Get(ctx, name, metav1.GetOptions{}))
28-
lease.Spec.HolderIdentity = lo.ToPtr(id)
46+
lease.Spec.HolderIdentity = lo.ToPtr(fmt.Sprintf("%s_%s", lo.Must(os.Hostname()), uuid.NewUUID()))
2947
lease.Spec.AcquireTime = lo.ToPtr(metav1.NowMicro())
3048
lo.Must(kubeClient.Leases(namespace).Update(ctx, lease, metav1.UpdateOptions{}))
3149
return lo.Must(resourcelock.New(
@@ -34,6 +52,6 @@ func LeaseHijacker(ctx context.Context, config *rest.Config, namespace string, n
3452
name,
3553
corev1client.NewForConfigOrDie(config),
3654
coordinationv1client.NewForConfigOrDie(config),
37-
resourcelock.ResourceLockConfig{Identity: id},
55+
resourcelock.ResourceLockConfig{Identity: *lease.Spec.HolderIdentity},
3856
))
3957
}

0 commit comments

Comments
 (0)