| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 
 | // tryAcquireOrRenew tries to acquire a leader lease if it is not already acquired,// else it tries to renew the lease if it has already been acquired. Returns true
 // on success else returns false.
 // 获取leader信息是否是本机
 func (le *LeaderElector) tryAcquireOrRenew() bool {
 now := metav1.Now()
 leaderElectionRecord := rl.LeaderElectionRecord{
 HolderIdentity:       le.config.Lock.Identity(),
 LeaseDurationSeconds: int(le.config.LeaseDuration / time.Second),
 RenewTime:            now,
 AcquireTime:          now,
 }
 
 // 1. obtain or create the ElectionRecord
 oldLeaderElectionRecord, err := le.config.Lock.Get()
 if err != nil {
 if !errors.IsNotFound(err) {
 glog.Errorf("error retrieving resource lock %v: %v", le.config.Lock.Describe(), err)
 return false
 }
 if err = le.config.Lock.Create(leaderElectionRecord); err != nil {
 glog.Errorf("error initially creating leader election record: %v", err)
 return false
 }
 le.observedRecord = leaderElectionRecord
 le.observedTime = time.Now()
 return true
 }
 
 // 2. Record obtained, check the Identity & Time
 if !reflect.DeepEqual(le.observedRecord, *oldLeaderElectionRecord) {
 le.observedRecord = *oldLeaderElectionRecord
 le.observedTime = time.Now()
 }
 if le.observedTime.Add(le.config.LeaseDuration).After(now.Time) &&
 oldLeaderElectionRecord.HolderIdentity != le.config.Lock.Identity() {
 glog.V(4).Infof("lock is held by %v and has not yet expired", oldLeaderElectionRecord.HolderIdentity)
 return false
 }
 
 // 3. We're going to try to update. The leaderElectionRecord is set to it's default
 // here. Let's correct it before updating.
 if oldLeaderElectionRecord.HolderIdentity == le.config.Lock.Identity() {
 leaderElectionRecord.AcquireTime = oldLeaderElectionRecord.AcquireTime
 leaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions
 } else {
 leaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions + 1
 }
 
 // update the lock itself
 if err = le.config.Lock.Update(leaderElectionRecord); err != nil {
 glog.Errorf("Failed to update lock: %v", err)
 return false
 }
 le.observedRecord = leaderElectionRecord
 le.observedTime = time.Now()
 return true
 }
 
 |