// getDC is used to get the datacenter of the local agent
func getDC(client *consulapi.Client) (string, error) {
	info, err := client.Agent().Self()
	if err != nil {
		return "", fmt.Errorf("Failed to get datacenter from Consul agent: %v", err)
	}
	dc := info["Config"]["Datacenter"].(string)
	return dc, nil
}
Exemplo n.º 2
0
// getDC is used to get the datacenter of the local agent
func getDC(d *schema.ResourceData, client *consulapi.Client) (string, error) {
	if v, ok := d.GetOk("datacenter"); ok {
		return v.(string), nil
	}
	info, err := client.Agent().Self()
	if err != nil {
		return "", fmt.Errorf("Failed to get datacenter from Consul agent: %v", err)
	}
	return info["Config"]["Datacenter"].(string), nil
}
Exemplo n.º 3
0
// datacenter returns the datacenter of the local agent
func datacenter(c *api.Client) (string, error) {
	self, err := c.Agent().Self()
	if err != nil {
		return "", err
	}

	cfg, ok := self["Config"]
	if !ok {
		return "", errors.New("consul: self.Config not found")
	}
	dc, ok := cfg["Datacenter"].(string)
	if !ok {
		return "", errors.New("consul: self.Datacenter not found")
	}
	return dc, nil
}
Exemplo n.º 4
0
func newConsulClient(consulAgent string) (*consulapi.Client, error) {
	var (
		client *consulapi.Client
		err    error
	)

	consulConfig := consulapi.DefaultConfig()
	consulAgentUrl, err := url.Parse(consulAgent)
	if err != nil {
		glog.Infof("Error parsing Consul url")
		return nil, err
	}

	if consulAgentUrl.Host != "" {
		consulConfig.Address = consulAgentUrl.Host
	}

	if consulAgentUrl.Scheme != "" {
		consulConfig.Scheme = consulAgentUrl.Scheme
	}

	client, err = consulapi.NewClient(consulConfig)
	if err != nil {
		glog.Infof("Error creating Consul client")
		return nil, err
	}

	for attempt := 1; attempt <= maxConnectAttempts; attempt++ {
		if _, err = client.Agent().Self(); err == nil {
			break
		}

		if attempt == maxConnectAttempts {
			break
		}

		glog.Infof("[Attempt: %d] Attempting access to Consul after 5 second sleep", attempt)
		time.Sleep(5 * time.Second)
	}

	if err != nil {
		return nil, fmt.Errorf("failed to connect to Consul agent: %v, error: %v", consulAgent, err)
	}
	glog.Infof("Consul agent found: %v", consulAgent)

	return client, nil
}
Exemplo n.º 5
0
func consulDomain(client *consul.Client) string {
	domain := "consul"

	agentConfig, err := client.Agent().Self()
	if err != nil {
		log.Warnf("Could not get consul agent info: %v", err)
		return domain
	}

	if config, ok := agentConfig["Config"]; ok {
		if consulDomain, ok := config["Domain"]; ok {
			if consulDomain, ok := consulDomain.(string); ok {
				domain = consulDomain
			}
		}
	}

	return domain
}
Exemplo n.º 6
0
func ConsulRegisterService(client *consul.Client, name, endpoint string) (err error) {
	agent := client.Agent()
	uri, err := url.Parse(endpoint)
	if err != nil {
		return
	}
	_, port, err := net.SplitHostPort(uri.Host)
	if err != nil {
		return
	}
	port_i, err := strconv.ParseInt(port, 10, 32)
	if err != nil {
		return
	}

	service := &consul.AgentServiceRegistration{
		Name: name,
		Port: int(port_i),
	}
	err = agent.ServiceRegister(service)
	return
}
Exemplo n.º 7
0
func registerSession(healthPort int, healthCheckName string, client *api.Client, log logging.Logger) string {
	go setupHealthCheckEndpoint(healthPort, log)

	checkReg := &api.AgentCheckRegistration{
		Name: healthCheckName,
	}
	checkReg.AgentServiceCheck.HTTP = fmt.Sprintf("http://localhost:%d", healthPort)
	checkReg.AgentServiceCheck.Interval = "1s"

	err := client.Agent().CheckRegister(checkReg)
	if err != nil {
		log.Panic("Failed to register health check", err)
	}
	waitForHealthy(healthCheckName, client.Health(), log)

	sessionEntry := &api.SessionEntry{
		Checks: []string{checkReg.Name},
	}

	session, _, err := client.Session().Create(sessionEntry, nil)
	if err != nil {
		log.Panic("Unable to create session", err)
	}

	for {
		entry, _, err := client.Session().Info(session, nil)
		if err != nil {
			log.Panic("Unable to read session info", err)
		}
		if entry != nil {
			break
		}
	}

	return session
}
Exemplo n.º 8
0
// register keeps a service registered in consul.
//
// When a value is sent in the dereg channel the service is deregistered from
// consul. To wait for completion the caller should read the next value from
// the dereg channel.
//
//    dereg <- true // trigger deregistration
//    <-dereg       // wait for completion
//
func register(c *api.Client, service *api.AgentServiceRegistration) (dereg chan bool) {
	var serviceID string

	registered := func() bool {
		if serviceID == "" {
			return false
		}
		services, err := c.Agent().Services()
		if err != nil {
			log.Printf("[ERROR] consul: Cannot get service list. %s", err)
			return false
		}
		return services[serviceID] != nil
	}

	register := func() {
		if err := c.Agent().ServiceRegister(service); err != nil {
			log.Printf("[ERROR] consul: Cannot register fabio in consul. %s", err)
			return
		}

		log.Printf("[INFO] consul: Registered fabio with id %q", service.ID)
		log.Printf("[INFO] consul: Registered fabio with address %q", service.Address)
		log.Printf("[INFO] consul: Registered fabio with tags %q", strings.Join(service.Tags, ","))
		log.Printf("[INFO] consul: Registered fabio with health check to %q", service.Check.HTTP)

		serviceID = service.ID
	}

	deregister := func() {
		log.Printf("[INFO] consul: Deregistering fabio")
		c.Agent().ServiceDeregister(serviceID)
	}

	dereg = make(chan bool)
	go func() {
		register()
		for {
			select {
			case <-dereg:
				deregister()
				dereg <- true
				return
			case <-time.After(time.Second):
				if !registered() {
					register()
				}
			}
		}
	}()
	return dereg
}