Merge pull request #118054 from johanoskarsson/johan_leader_election_lock_id_validate

Validate lock identity

Kubernetes-commit: 36d81a5818665b55c2b0f307c15572626d84b07a
This commit is contained in:
Kubernetes Publisher 2023-05-25 08:44:52 -07:00
commit 7a7ea20936
2 changed files with 42 additions and 0 deletions

View File

@ -99,6 +99,11 @@ func NewLeaderElector(lec LeaderElectionConfig) (*LeaderElector, error) {
if lec.Lock == nil {
return nil, fmt.Errorf("Lock must not be nil.")
}
id := lec.Lock.Identity()
if id == "" {
return nil, fmt.Errorf("Lock identity is empty")
}
le := LeaderElector{
config: lec,
clock: clock.RealClock{},

View File

@ -37,6 +37,8 @@ import (
rl "k8s.io/client-go/tools/leaderelection/resourcelock"
"k8s.io/client-go/tools/record"
"k8s.io/utils/clock"
"github.com/stretchr/testify/assert"
)
func createLockObject(t *testing.T, objectType, namespace, name string, record *rl.LeaderElectionRecord) (obj runtime.Object) {
@ -753,6 +755,41 @@ func testReleaseOnCancellation(t *testing.T, objectType string) {
}
}
func TestLeaderElectionConfigValidation(t *testing.T) {
resourceLockConfig := rl.ResourceLockConfig{
Identity: "baz",
}
lock := &rl.LeaseLock{
LockConfig: resourceLockConfig,
}
lec := LeaderElectionConfig{
Lock: lock,
LeaseDuration: 15 * time.Second,
RenewDeadline: 2 * time.Second,
RetryPeriod: 1 * time.Second,
ReleaseOnCancel: true,
Callbacks: LeaderCallbacks{
OnNewLeader: func(identity string) {},
OnStoppedLeading: func() {},
OnStartedLeading: func(context.Context) {},
},
}
_, err := NewLeaderElector(lec)
assert.NoError(t, err)
// Invalid lock identity
resourceLockConfig.Identity = ""
lock.LockConfig = resourceLockConfig
lec.Lock = lock
_, err = NewLeaderElector(lec)
assert.Error(t, err, fmt.Errorf("Lock identity is empty"))
}
func assertEqualEvents(t *testing.T, expected []string, actual <-chan string) {
c := time.After(wait.ForeverTestTimeout)
for _, e := range expected {