// LeadershipClaimer returns a leadership.Claimer for units and applications in the
// state's model.
180030
func (st *State) LeadershipClaimer() leadership.Claimer {
	return leadershipClaimer{
		lazyLeaseClaimer{func() (lease.Claimer, error) {
			manager := st.workers.leadershipManager()
			return manager.Claimer(applicationLeadershipNamespace, st.modelUUID())
		}},
	}
}
695019
func (p *RBACPolicyEnforcer) EnforceClaims(claims jwt.Claims, rvals ...interface{}) bool {
	mapClaims, err := jwtutil.MapClaims(claims)
	if err != nil {
		return false
	}

	subject := jwtutil.GetField(mapClaims, "sub")
	// Check if the request is for an application resource. We have special enforcement which takes
	// into consideration the project's token and group bindings
	var runtimePolicy string
	proj := p.getProjectFromRequest(rvals...)
	if proj != nil {
		if strings.HasPrefix(subject, "proj:") {
			return p.enforceProjectToken(subject, mapClaims, proj, rvals...)
		}
		runtimePolicy = proj.ProjectPoliciesString()
	}

	// Check the subject. This is typically the 'admin' case.
	// NOTE: the call to EnforceRuntimePolicy will also consider the default role
	vals := append([]interface{}{subject}, rvals[1:]...)
	if p.enf.EnforceRuntimePolicy(runtimePolicy, vals...) {
		return true
	}

	// Finally check if any of the user's groups grant them permissions
	groups := jwtutil.GetGroups(mapClaims)
	for _, group := range groups {
		vals := append([]interface{}{group}, rvals[1:]...)
		if p.enf.EnforceRuntimePolicy(runtimePolicy, vals...) {
			return true
		}
	}
	logCtx := log.WithField("claims", claims).WithField("rval", rvals)
	logCtx.Debug("enforce failed")
	return false
}
150026
func (consumer *Consumer) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {

	// NOTE:
	// Do not move the code below to a goroutine.
	// The `ConsumeClaim` itself is called within a goroutine, see:
	// https://github.com/Shopify/sarama/blob/master/consumer_group.go#L27-L29
	for message := range claim.Messages() {
		log.Printf("Message claimed: value = %s, timestamp = %v, topic = %s", string(message.Value), message.Timestamp, message.Topic)
		session.MarkMessage(message, "")
	}

	return nil
}
1061095
func (c *client) ClaimLeadership(appId, unitId string, duration time.Duration) error {

	results, err := c.bulkClaimLeadership(c.prepareClaimLeadership(appId, unitId, duration))
	if err != nil {
		return err
	}

	// TODO(fwereade): this is not a rightful panic; we don't know who'll be using
	// this client, and/or whether or not we're running critical code in the same
	// process.
	if err := results.Results[0].Error; err != nil {
		if params.IsCodeLeadershipClaimDenied(err) {
			return leadership.ErrClaimDenied
		}
		return err
	}
	return nil
}
251438
func (c *Cluster) ChangeLeader(regionID, leaderPeerID uint64) {
	c.Lock()
	defer c.Unlock()

	c.regions[regionID].changeLeader(leaderPeerID)
}
625160
func (c *githubConnector) teamGroupClaims(t team) []string {
	switch c.teamNameField {
	case "both":
		return []string{t.Name, t.Slug}
	case "slug":
		return []string{t.Slug}
	default:
		return []string{t.Name}
	}
}
1131277
func (s *Store) ClaimLease(key lease.Key, req lease.Request, stop <-chan struct{}) error {
	return errors.Trace(s.runOnLeader(&Command{
		Version:   CommandVersion,
		Operation: OperationClaim,
		Namespace: key.Namespace,
		ModelUUID: key.ModelUUID,
		Lease:     key.Lease,
		Holder:    req.Holder,
		Duration:  req.Duration,
	}, stop))
}
597623
func (t *Tracker) setLeader(untilTime time.Time) error {
	if t.isMinion {
		// If we were a minion, we're now the leader, so we can record the transition.
		logger.Infof("%s promoted to leadership of %s", t.unitName, t.applicationName)
	}
	logger.Tracef("%s confirmed for %s leadership until %s", t.unitName, t.applicationName, untilTime)
	renewTime := untilTime.Add(-t.duration)
	logger.Tracef("%s will renew %s leadership at %s", t.unitName, t.applicationName, renewTime)
	t.isMinion = false
	t.claimLease = nil
	t.renewLease = t.clock.After(renewTime.Sub(t.clock.Now()))

	for len(t.waitingLeader) > 0 {
		logger.Tracef("notifying %s ticket of impending %s leadership", t.unitName, t.applicationName)
		var ticketCh chan bool
		ticketCh, t.waitingLeader = t.waitingLeader[0], t.waitingLeader[1:]
		defer close(ticketCh)
		if err := t.sendTrue(ticketCh); err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}
1349826
func determineLeader(node string, children []string) (isLeader bool, leaderNode string, err error) {
	err = func() error {
		if len(children) == 0 {
			return errors.New("no child nodes")
		}
		sequences, lookup, err := sortedChildrenSequences(children)
		if err != nil {
			return err
		}
		mySeq, err := sequencePart(node)
		if err != nil {
			return errors.Wrap(err, "invalid owner node")
		}
		leaderSeq := sequences[0]
		isLeader = mySeq == leaderSeq
		leaderNode = lookup[leaderSeq]
		return nil
	}()
	return isLeader, leaderNode, err
}
175352
func (r legacyLeadershipReader) Leaders() (map[string]string, error) {
	l, err := r.st.ApplicationLeaders()
	return l, errors.Trace(err)
}
1016198
func (m leadershipChecker) LeadershipCheck(applicationName, unitName string) leadership.Token {
	token := m.checker.Token(applicationName, unitName)
	return leadershipToken{
		applicationName: applicationName,
		unitName:        unitName,
		token:           token,
	}
}
212324
func (n *node) abdicateLeader(currentLead uint64) {
	status := n.Status()

	if status.Lead != raft.None && status.Lead != currentLead {
		n.logger.Warn("Leader has changed since asked to transfer leadership")
		return
	}

	ctx, cancel := context.WithTimeout(context.TODO(), time.Duration(n.config.ElectionTick)*n.tickInterval)
	defer cancel()

	// Leader initiates leader transfer
	if status.RaftState == raft.StateLeader {
		var transferee uint64
		for id, pr := range status.Progress {
			if id == status.ID {
				continue // skip self
			}

			if pr.RecentActive && !pr.Paused {
				transferee = id
				break
			}

			n.logger.Debugf("Node %d is not qualified as transferee because it's either paused or not active", id)
		}

		if transferee == raft.None {
			n.logger.Errorf("No follower is qualified as transferee, abort leader transfer")
			return
		}

		n.logger.Infof("Transferring leadership to %d", transferee)
		n.TransferLeadership(ctx, status.ID, transferee)
	}

	// Periodically check leader has changed till ElectionTimeout elapsed
	var newLeader uint64
	for newLeader = n.Status().Lead; newLeader == status.Lead || newLeader == raft.None; newLeader = n.Status().Lead {
		select {
		case <-ctx.Done():
			n.logger.Warn("Leader transfer timeout")
			return
		case <-time.After(n.tickInterval):
		case <-n.chain.doneC:
			return
		}
	}

	n.logger.Infof("Leader has been transferred from %d to %d", currentLead, newLeader)
}
134751
func (d *MasterDaemon) runLeader() {
	router := mux.NewRouter()

	// Create a new api controller
	apiConfig := &objApi.APIControllerConfig{
		NetForwardMode: d.NetForwardMode,
		NetInfraType:   d.NetInfraType,
	}
	d.apiController = objApi.NewAPIController(router, d.objdbClient, apiConfig)

	//Restore state from clusterStore
	d.restoreCache()

	// Register netmaster service
	d.registerService()

	// initialize policy manager
	mastercfg.InitPolicyMgr(d.stateDriver, d.ofnetMaster)

	// setup HTTP routes
	d.registerRoutes(router)

	d.startListeners(router, d.stopLeaderChan)

	log.Infof("Exiting Leader mode")
}
150636
func (manager *Manager) handleClaim(claim claim) (bool, error) {
	store := manager.config.Store
	request := lease.Request{Holder: claim.holderName, Duration: claim.duration}
	err := lease.ErrInvalid
	action := "unknown"
	select {
	case <-manager.catacomb.Dying():
		return false, manager.catacomb.ErrDying()
	default:
		info, found := manager.lookupLease(claim.leaseKey)
		switch {
		case !found:
			manager.config.Logger.Tracef("[%s] %s asked for lease %s, no lease found, claiming for %s",
				manager.logContext, claim.holderName, claim.leaseKey.Lease, claim.duration)
			action = "claiming"
			err = store.ClaimLease(claim.leaseKey, request, manager.catacomb.Dying())
		case info.Holder == claim.holderName:
			manager.config.Logger.Tracef("[%s] %s extending lease %s for %s",
				manager.logContext, claim.holderName, claim.leaseKey.Lease, claim.duration)
			action = "extending"
			err = store.ExtendLease(claim.leaseKey, request, manager.catacomb.Dying())
		default:
			// Note: (jam) 2017-10-31) We don't check here if the lease has
			// expired for the current holder. Should we?
			remaining := info.Expiry.Sub(manager.config.Clock.Now())
			manager.config.Logger.Tracef("[%s] %s asked for lease %s, held by %s for another %s, rejecting",
				manager.logContext, claim.holderName, claim.leaseKey.Lease, info.Holder, remaining)
			return false, nil
		}
	}
	if lease.IsAborted(err) {
		return false, manager.catacomb.ErrDying()
	}
	if err != nil {
		return false, errors.Trace(err)
	}
	manager.config.Logger.Tracef("[%s] %s %s lease %s for %s successful",
		manager.logContext, claim.holderName, action, claim.leaseKey.Lease, claim.duration)
	return true, nil
}
194904
func (m leadershipClaimer) ClaimLeadership(applicationname, unitName string, duration time.Duration) error {
	err := m.claimer.Claim(applicationname, unitName, duration)
	if errors.Cause(err) == lease.ErrClaimDenied {
		return leadership.ErrClaimDenied
	}
	return errors.Trace(err)
}
123680
func (m leadershipClaimer) BlockUntilLeadershipReleased(applicationName string, cancel <-chan struct{}) error {
	err := m.claimer.WaitUntilExpired(applicationName, cancel)
	if errors.Cause(err) == lease.ErrWaitCancelled {
		return leadership.ErrBlockCancelled
	}
	return errors.Trace(err)
}
290087
func (ctx *facadeContext) LeadershipReader(modelUUID string) (leadership.Reader, error) {
	if ctx.r.shared.featureEnabled(feature.LegacyLeases) {
		return legacyLeadershipReader{ctx.State()}, nil
	}
	reader, err := ctx.r.shared.leaseManager.Reader(
		lease.ApplicationLeadershipNamespace,
		modelUUID,
	)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return leadershipReader{reader}, nil
}