Пример #1
0
// Leader returns the node of the current cluster leader. This returns an empty string if there is no leader.
func (c *Candidate) Leader() string {
	consul := c.consulClient()
	kv, _, err := consul.KV().Get(c.LeadershipKey, nil)
	if kv == nil || err != nil {
		logrus.Warnln("There is no leader.")
		return ""
	}
	return string(kv.Value)
}
Пример #2
0
// RetrieveNode is a helper to retrieve the current node name of the agent.
func (c *Candidate) retrieveNode() {
	consul := c.consulClient()
	agent, err := consul.Agent().Self()
	if err != nil {
		logrus.Warnln("Unable to retrieve node name.")
		return
	}
	c.node = agent["Config"]["NodeName"].(string)
}
Пример #3
0
// RetrieveSession retrieves the existing session needed to run leader election. If a session does not exist, a new
// session is created with the LeadershipKey as the name.
func (c *Candidate) retrieveSession() {
	consul := c.consulClient()

	if sessions, _, err := consul.Session().List(nil); err != nil {
		logrus.Warnln("Unable to retrieve list of sessions.")
	} else {
		for _, session := range sessions {
			if session.Name == c.LeadershipKey && session.Node == c.node {
				c.session = session.ID
				return
			}
		}
	}

	newSession := &consulapi.SessionEntry{
		Name: c.LeadershipKey,
	}
	if sessionId, _, err := consul.Session().Create(newSession, nil); err != nil {
		logrus.Errorln("Unable to create new sessions:", err)
	} else {
		c.session = sessionId
	}
}