Skip to content

Commit

Permalink
fix: exit leader-election when command fails
Browse files Browse the repository at this point in the history
  • Loading branch information
kvaps committed Jul 10, 2024
1 parent 08eadc4 commit 8fd97e2
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,6 @@ func (el *AwaitElection) createSessionAndElection(ctx context.Context) error {
func (el *AwaitElection) Run() error {
for {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Initialize session and election
err := el.createSessionAndElection(ctx)
Expand All @@ -274,14 +273,15 @@ func (el *AwaitElection) Run() error {
err = el.LeaderExec(ctx)
if err != nil {
log.Printf("Leader execution error: %v", err)
cancel()
return err
}
return err
} else {
log.Printf("Current leader is %s, not %s, will continue trying.", currentLeader, el.LeaderIdentity)
}
} else {
log.Printf("Failed to get current leader: %v, will campaign.", err)
// Continue with campaigning
}

err = el.Election.Campaign(ctx, el.LeaderIdentity)
Expand All @@ -297,6 +297,8 @@ func (el *AwaitElection) Run() error {
err = el.LeaderExec(ctx)
if err != nil {
log.Printf("Leader execution error: %v", err)
cancel()
return err
}

select {
Expand All @@ -306,7 +308,6 @@ func (el *AwaitElection) Run() error {
log.Printf("Session expired or lost, losing leadership")
cancel()
time.Sleep(el.RetryPeriod)
// Starting new election cycle
}
}
}
Expand Down

0 comments on commit 8fd97e2

Please sign in to comment.