-
Notifications
You must be signed in to change notification settings - Fork 100
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added the LeaderElection for backup-restore.
Added support to allow only backup-restore Leader to take/uploads the snapshots.
- Loading branch information
1 parent
43af3ca
commit 5b4d937
Showing
8 changed files
with
332 additions
and
27 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
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,37 @@ | ||
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package leaderelection | ||
|
||
import ( | ||
"github.com/gardener/etcd-backup-restore/pkg/wrappers" | ||
flag "github.com/spf13/pflag" | ||
) | ||
|
||
// NewElectionConfig returns the ElectionConfig. | ||
func NewElectionConfig() *ElectionConfig { | ||
return &ElectionConfig{ | ||
ReElectionPeriod: wrappers.Duration{Duration: DefaultReElectionPeriod}, | ||
} | ||
} | ||
|
||
// AddFlags adds the flags to flagset. | ||
func (e *ElectionConfig) AddFlags(fs *flag.FlagSet) { | ||
fs.DurationVar(&e.ReElectionPeriod.Duration, "election-period", e.ReElectionPeriod.Duration, "Period after election will be re-triggered to check the leadership status.") | ||
} | ||
|
||
// Validate validates the ElectionConfig. | ||
func (e *ElectionConfig) Validate() error { | ||
return nil | ||
} |
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,138 @@ | ||
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package leaderelection | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"time" | ||
|
||
"github.com/gardener/etcd-backup-restore/pkg/errors" | ||
"github.com/gardener/etcd-backup-restore/pkg/etcdutil" | ||
"github.com/sirupsen/logrus" | ||
) | ||
|
||
var emptyStruct struct{} | ||
|
||
// NewLeaderElector returns LeaderElector configurations. | ||
func NewLeaderElector(logger *logrus.Entry, etcdConnectionConfig *etcdutil.EtcdConnectionConfig, leaderElectionConfig *ElectionConfig, callbacks *LeaderCallbacks) (*LeaderElector, error) { | ||
return &LeaderElector{ | ||
logger: logger.WithField("actor", "leader-elector"), | ||
EtcdConnectionConfig: etcdConnectionConfig, | ||
CurrentState: DefaultCurrentState, | ||
StopCh: make(chan struct{}), | ||
ProbeEtcdch: make(chan struct{}), | ||
PrevElectionResult: ElectionLost, | ||
Config: leaderElectionConfig, | ||
Callbacks: callbacks, | ||
}, nil | ||
} | ||
|
||
// StartElection starts the LeaderElection to Elect the backup-restore's Leader. | ||
func (le *LeaderElector) StartElection(ctx context.Context) { | ||
le.logger.Infof("Starting LeaderElection...") | ||
|
||
for { | ||
select { | ||
case <-ctx.Done(): | ||
le.logger.Info("Shutting down LeaderElection...") | ||
return | ||
case <-le.StopCh: | ||
le.logger.Info("Shutting down LeaderElection...") | ||
return | ||
case <-time.After(le.Config.ReElectionPeriod.Duration): | ||
err := le.isLeader(ctx) | ||
if err != nil { | ||
le.CurrentState = StateUnknown | ||
le.logger.Errorf("Failed to elect the backup-restore leader: %v", err) | ||
} | ||
|
||
if le.CurrentState == StateUnknown { | ||
le.PrevElectionResult = ElectionLost | ||
le.logger.Info("backup-restore is in: ", StateUnknown) | ||
// stops the Running Snapshotter. | ||
if le.Callbacks.OnStoppedLeading != nil { | ||
le.Callbacks.OnStoppedLeading() | ||
le.logger.Info("backup-restore lost the election") | ||
le.logger.Info("waiting for Re-election...") | ||
} | ||
} else if le.PrevElectionResult == ElectionLost && le.CurrentState == StateLeader { | ||
// It becomes the Leader backup-restore sidecar. | ||
// Get the latest snapshotter object and start the snapshotter. | ||
le.PrevElectionResult = ElectionWon | ||
le.logger.Info("backup-restore become: ", StateLeader) | ||
if le.Callbacks.OnStartedLeading != nil { | ||
le.Callbacks.OnStartedLeading(ctx) | ||
} | ||
le.logger.Info("sending signal to ProbeEtcd to start the Snapshotter") | ||
le.ProbeEtcdch <- emptyStruct | ||
} else if le.PrevElectionResult == ElectionWon && le.CurrentState == StateLeader { | ||
le.logger.Info("no change in leadershipStatus...") | ||
} else if le.CurrentState == StateFollower { | ||
le.logger.Info("************ I'm not the Leader *************** ") | ||
|
||
le.PrevElectionResult = ElectionLost | ||
// stop the Running Snapshotter | ||
if le.Callbacks.OnStoppedLeading != nil { | ||
le.Callbacks.OnStoppedLeading() | ||
le.logger.Info("backup-restore lost the election") | ||
le.logger.Info("backup-restore become: ", StateFollower) | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
// isLeader checks whether the current backup-restore is leader or not and sets the currentState of backup-restore accordingly. | ||
func (le *LeaderElector) isLeader(ctx context.Context) error { | ||
le.logger.Info("checking for leadershipStatus...") | ||
var endPoint string | ||
client, err := etcdutil.GetTLSClientForEtcd(le.EtcdConnectionConfig) | ||
if err != nil { | ||
return &errors.EtcdError{ | ||
Message: fmt.Sprintf("Failed to create etcd client: %v", err), | ||
} | ||
} | ||
defer client.Close() | ||
|
||
le.logger.Debugf("Etcd Endpoint: %v", le.EtcdConnectionConfig.Endpoints) | ||
|
||
le.CurrentState = StateFollower | ||
|
||
if len(le.EtcdConnectionConfig.Endpoints) > 0 { | ||
endPoint = le.EtcdConnectionConfig.Endpoints[0] | ||
} else { | ||
return fmt.Errorf("Etcd endpoints are not passed correctly") | ||
} | ||
ctx, cancel := context.WithTimeout(ctx, le.EtcdConnectionConfig.ConnectionTimeout.Duration) | ||
response, err := client.Status(ctx, endPoint) | ||
cancel() | ||
if err != nil { | ||
le.logger.Errorf("Failed to get response header from etcd client: %v", err) | ||
return err | ||
} | ||
|
||
le.logger.Infof("MemberID: %v", response.Header.MemberId) | ||
le.logger.Infof("LeaderID: %v", response.Leader) | ||
|
||
if response.Header.MemberId == response.Leader { | ||
le.CurrentState = StateLeader | ||
} else if response.Leader == QuorumLostID { | ||
return &errors.EtcdError{ | ||
Message: fmt.Sprintf("Currently there is no Etcd-Leader present may be due to etcd quorum loss."), | ||
} | ||
} | ||
return nil | ||
} |
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,77 @@ | ||
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package leaderelection | ||
|
||
import ( | ||
"context" | ||
"time" | ||
|
||
"github.com/gardener/etcd-backup-restore/pkg/etcdutil" | ||
"github.com/gardener/etcd-backup-restore/pkg/wrappers" | ||
"github.com/sirupsen/logrus" | ||
) | ||
|
||
const ( | ||
// StateFollower defines currentState of backup-restore as "Follower". | ||
StateFollower = "Follower" | ||
// StateCandidate defines currentState of backup-restore as "Candidate". | ||
StateCandidate = "Candidate" | ||
// StateLeader defines currentState of backup-restore as "Leader". | ||
StateLeader = "Leader" | ||
// StateUnknown defines currentState of backup-restore as "UnknownState". | ||
StateUnknown = "UnknownState" | ||
|
||
// DefaultCurrentState defines default currentState of backup-restore as "Follower". | ||
DefaultCurrentState = StateFollower | ||
|
||
// ElectionLost defines the state of LeaderElection as ElectionLost. | ||
ElectionLost = "Lost" | ||
// ElectionWon defines the state of LeaderElection as ElectionWon. | ||
ElectionWon = "Won" | ||
|
||
// QuorumLostID defines the state when etcd returns LeaderID as 0. | ||
QuorumLostID = 0 | ||
|
||
// DefaultReElectionPeriod defines default ReElectionPEriod. | ||
DefaultReElectionPeriod = 5 * time.Second | ||
) | ||
|
||
// LeaderCallbacks are callbacks that are triggered when leader currentState changes to start/stop the snapshottter. | ||
type LeaderCallbacks struct { | ||
// OnStartedLeading is called when a LeaderElector client starts leading. | ||
OnStartedLeading func(context.Context) | ||
// OnStoppedLeading is called when a LeaderElector client stops leading. | ||
OnStoppedLeading func() | ||
} | ||
|
||
// ElectionConfig holds the LeaderElection configurations. | ||
type ElectionConfig struct { | ||
// ReElectionPeriod defines the Period after which leadership status is checked. | ||
ReElectionPeriod wrappers.Duration `json:"reElectionPeriod,omitempty"` | ||
} | ||
|
||
// LeaderElector holds the all configuration necessary to elect backup-restore Leader. | ||
type LeaderElector struct { | ||
// CurrentState defines currentState of backup-restore for LeaderElection. | ||
CurrentState string | ||
Config *ElectionConfig | ||
EtcdConnectionConfig *etcdutil.EtcdConnectionConfig | ||
logger *logrus.Entry | ||
StopCh chan struct{} | ||
ProbeEtcdch chan struct{} | ||
PrevElectionResult string | ||
Callbacks *LeaderCallbacks | ||
//leaderElectionCancel context.CancelFunc | ||
} |
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
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
Oops, something went wrong.