sigs.k8s.io/controller-runtime@v0.18.2/pkg/leaderelection/fake/leader_election.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package fake 18 19 import ( 20 "context" 21 "encoding/json" 22 "os" 23 "time" 24 25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 26 "k8s.io/apimachinery/pkg/util/uuid" 27 "k8s.io/client-go/rest" 28 "k8s.io/client-go/tools/leaderelection/resourcelock" 29 "sigs.k8s.io/controller-runtime/pkg/leaderelection" 30 "sigs.k8s.io/controller-runtime/pkg/recorder" 31 ) 32 33 // NewResourceLock creates a new ResourceLock for use in testing 34 // leader election. 35 func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, options leaderelection.Options) (resourcelock.Interface, error) { 36 // Leader id, needs to be unique 37 id, err := os.Hostname() 38 if err != nil { 39 return nil, err 40 } 41 id = id + "_" + string(uuid.NewUUID()) 42 43 return &ResourceLock{ 44 id: id, 45 record: resourcelock.LeaderElectionRecord{ 46 HolderIdentity: id, 47 LeaseDurationSeconds: 15, 48 AcquireTime: metav1.NewTime(time.Now()), 49 RenewTime: metav1.NewTime(time.Now().Add(15 * time.Second)), 50 LeaderTransitions: 1, 51 }, 52 }, nil 53 } 54 55 // ResourceLock implements the ResourceLockInterface. 56 // By default returns that the current identity holds the lock. 57 type ResourceLock struct { 58 id string 59 record resourcelock.LeaderElectionRecord 60 } 61 62 // Get implements the ResourceLockInterface. 63 func (f *ResourceLock) Get(ctx context.Context) (*resourcelock.LeaderElectionRecord, []byte, error) { 64 recordBytes, err := json.Marshal(f.record) 65 if err != nil { 66 return nil, nil, err 67 } 68 return &f.record, recordBytes, nil 69 } 70 71 // Create implements the ResourceLockInterface. 72 func (f *ResourceLock) Create(ctx context.Context, ler resourcelock.LeaderElectionRecord) error { 73 f.record = ler 74 return nil 75 } 76 77 // Update implements the ResourceLockInterface. 78 func (f *ResourceLock) Update(ctx context.Context, ler resourcelock.LeaderElectionRecord) error { 79 f.record = ler 80 return nil 81 } 82 83 // RecordEvent implements the ResourceLockInterface. 84 func (f *ResourceLock) RecordEvent(s string) { 85 86 } 87 88 // Identity implements the ResourceLockInterface. 89 func (f *ResourceLock) Identity() string { 90 return f.id 91 } 92 93 // Describe implements the ResourceLockInterface. 94 func (f *ResourceLock) Describe() string { 95 return f.id 96 }