2 Copyright 2016 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26 corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
29 type EndpointsLock struct {
30 // EndpointsMeta should contain a Name and a Namespace of an
31 // Endpoints object that the LeaderElector will attempt to lead.
32 EndpointsMeta metav1.ObjectMeta
33 Client corev1client.EndpointsGetter
34 LockConfig ResourceLockConfig
38 // Get returns the election record from a Endpoints Annotation
39 func (el *EndpointsLock) Get() (*LeaderElectionRecord, error) {
40 var record LeaderElectionRecord
42 el.e, err = el.Client.Endpoints(el.EndpointsMeta.Namespace).Get(el.EndpointsMeta.Name, metav1.GetOptions{})
46 if el.e.Annotations == nil {
47 el.e.Annotations = make(map[string]string)
49 if recordBytes, found := el.e.Annotations[LeaderElectionRecordAnnotationKey]; found {
50 if err := json.Unmarshal([]byte(recordBytes), &record); err != nil {
57 // Create attempts to create a LeaderElectionRecord annotation
58 func (el *EndpointsLock) Create(ler LeaderElectionRecord) error {
59 recordBytes, err := json.Marshal(ler)
63 el.e, err = el.Client.Endpoints(el.EndpointsMeta.Namespace).Create(&v1.Endpoints{
64 ObjectMeta: metav1.ObjectMeta{
65 Name: el.EndpointsMeta.Name,
66 Namespace: el.EndpointsMeta.Namespace,
67 Annotations: map[string]string{
68 LeaderElectionRecordAnnotationKey: string(recordBytes),
75 // Update will update and existing annotation on a given resource.
76 func (el *EndpointsLock) Update(ler LeaderElectionRecord) error {
78 return errors.New("endpoint not initialized, call get or create first")
80 recordBytes, err := json.Marshal(ler)
84 el.e.Annotations[LeaderElectionRecordAnnotationKey] = string(recordBytes)
85 el.e, err = el.Client.Endpoints(el.EndpointsMeta.Namespace).Update(el.e)
89 // RecordEvent in leader election while adding meta-data
90 func (el *EndpointsLock) RecordEvent(s string) {
91 events := fmt.Sprintf("%v %v", el.LockConfig.Identity, s)
92 el.LockConfig.EventRecorder.Eventf(&v1.Endpoints{ObjectMeta: el.e.ObjectMeta}, v1.EventTypeNormal, "LeaderElection", events)
95 // Describe is used to convert details on current resource lock
97 func (el *EndpointsLock) Describe() string {
98 return fmt.Sprintf("%v/%v", el.EndpointsMeta.Namespace, el.EndpointsMeta.Name)
101 // returns the Identity of the lock
102 func (el *EndpointsLock) Identity() string {
103 return el.LockConfig.Identity