Skip to content

Commit bcfec8f

Browse files
authored
feat: Implemented leaderelection.LeaseHijacker (#99)
1 parent a2d2f27 commit bcfec8f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

leaderelection/leasehijacker.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package leaderelection
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"os"
7+
8+
"github.com/samber/lo"
9+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
10+
"k8s.io/apimachinery/pkg/util/uuid"
11+
coordinationv1client "k8s.io/client-go/kubernetes/typed/coordination/v1"
12+
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
13+
"k8s.io/client-go/rest"
14+
"k8s.io/client-go/tools/leaderelection/resourcelock"
15+
"sigs.k8s.io/controller-runtime/pkg/log"
16+
)
17+
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.
20+
func LeaseHijacker(ctx context.Context, config *rest.Config, namespace string, name string) resourcelock.Interface {
21+
if os.Getenv("HIJACK_LEASE") != "true" {
22+
return nil // If not set, fallback to other controller-runtime lease settings
23+
}
24+
id := fmt.Sprintf("%s_%s", lo.Must(os.Hostname()), uuid.NewUUID())
25+
log.FromContext(ctx).Info("hijacking lease", "namespace", namespace, "name", name)
26+
kubeClient := coordinationv1client.NewForConfigOrDie(config)
27+
lease := lo.Must(kubeClient.Leases(namespace).Get(ctx, name, metav1.GetOptions{}))
28+
lease.Spec.HolderIdentity = lo.ToPtr(id)
29+
lease.Spec.AcquireTime = lo.ToPtr(metav1.NowMicro())
30+
lo.Must(kubeClient.Leases(namespace).Update(ctx, lease, metav1.UpdateOptions{}))
31+
return lo.Must(resourcelock.New(
32+
resourcelock.LeasesResourceLock,
33+
namespace,
34+
name,
35+
corev1client.NewForConfigOrDie(config),
36+
coordinationv1client.NewForConfigOrDie(config),
37+
resourcelock.ResourceLockConfig{Identity: id},
38+
))
39+
}

0 commit comments

Comments
 (0)