示例#1
0
// IsLeader returns true if the current agent is the leader.
func (c *Candidate) IsLeader() bool {
	consul := c.consulClient()
	c.retrieveNode()
	c.retrieveSession()
	kv, _, err := consul.KV().Get(c.LeadershipKey, nil)
	if err != nil {
		logrus.Errorln("Unable to check for leadership:", err)
		return false
	}
	if kv == nil {
		logrus.Warnf("Leadership key '%s' is missing in Consuk KV.", c.LeadershipKey)
		return false
	}
	return c.node == string(kv.Value) && c.session == kv.Session
}
示例#2
0
// Resign forces the current agent to step down as the leader forcing a re-election. Nothing happens if the agent is not
// the current leader.
func (c *Candidate) Resign() {
	if c.IsLeader() {
		consul := c.consulClient()
		kvpair := &consulapi.KVPair{
			Key:     c.LeadershipKey,
			Value:   []byte(c.node),
			Session: c.session,
		}
		success, _, err := consul.KV().Release(kvpair, nil)
		if !success || err != nil {
			logrus.Warnf("%s was unable to step down as a leader", c.node)
		} else {
			logrus.Debugf("%s is no longer the leader.", c.node)
		}
	}
}