-
Notifications
You must be signed in to change notification settings - Fork 111
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
move leader election to different file
- Loading branch information
Showing
2 changed files
with
61 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"github.com/go-logr/logr" | ||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
clientset "k8s.io/client-go/kubernetes" | ||
"k8s.io/client-go/tools/leaderelection" | ||
"k8s.io/client-go/tools/leaderelection/resourcelock" | ||
"k8s.io/klog/v2" | ||
"os" | ||
"time" | ||
) | ||
|
||
var ( | ||
client *clientset.Clientset | ||
) | ||
|
||
func getNewLock(lockname, podname, namespace string) *resourcelock.LeaseLock { | ||
return &resourcelock.LeaseLock{ | ||
LeaseMeta: metav1.ObjectMeta{ | ||
Name: lockname, | ||
Namespace: namespace, | ||
}, | ||
Client: client.CoordinationV1(), | ||
LockConfig: resourcelock.ResourceLockConfig{ | ||
Identity: podname, | ||
}, | ||
} | ||
} | ||
|
||
func runLeaderElection(ctx context.Context, lock *resourcelock.LeaseLock, podname string, ctrlOpts Options, log logr.Logger) { | ||
// Start the leader election for running kapp-controller | ||
log.Info("Waiting for leader election") | ||
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{ | ||
Lock: lock, | ||
ReleaseOnCancel: true, | ||
LeaseDuration: 15 * time.Second, | ||
RenewDeadline: 10 * time.Second, | ||
RetryPeriod: 2 * time.Second, | ||
Callbacks: leaderelection.LeaderCallbacks{ | ||
OnStartedLeading: func(c context.Context) { | ||
err := Run(ctrlOpts, log.WithName("controller")) | ||
if err != nil { | ||
klog.Errorf("Error while running as leader: %v", err) | ||
} | ||
}, | ||
OnStoppedLeading: func() { | ||
klog.Fatalf("no longer the leader, staying inactive.") | ||
os.Exit(0) | ||
}, | ||
OnNewLeader: func(identity string) { | ||
//Notify when a new leader is elected | ||
if identity == podname { | ||
return | ||
} | ||
klog.InfoS("new leader elected", "id", identity) | ||
}, | ||
}, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters