-
Notifications
You must be signed in to change notification settings - Fork 32
/
consul.go
231 lines (205 loc) · 6.48 KB
/
consul.go
1
2
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package consul
import (
"fmt"
"net/url"
log "github.com/Sirupsen/logrus"
"github.com/allegro/marathon-consul/apps"
"github.com/allegro/marathon-consul/metrics"
"github.com/allegro/marathon-consul/utils"
consulapi "github.com/hashicorp/consul/api"
)
type ConsulServices interface {
GetAllServices() ([]*consulapi.CatalogService, error)
GetServices(name string) ([]*consulapi.CatalogService, error)
Register(task *apps.Task, app *apps.App) error
Deregister(serviceId apps.TaskId, agentAddress string) error
GetAgent(agentAddress string) (*consulapi.Client, error)
}
type Consul struct {
agents Agents
config ConsulConfig
}
type ServicesProvider func(*consulapi.Client) ([]*consulapi.CatalogService, error)
func New(config ConsulConfig) *Consul {
return &Consul{
agents: NewAgents(&config),
config: config,
}
}
func (c *Consul) GetServices(name string) ([]*consulapi.CatalogService, error) {
return c.getServicesUsingProviderWithRetriesOnAgentFailure(func(agent *consulapi.Client) ([]*consulapi.CatalogService, error) {
return c.getServicesUsingAgent(name, agent)
})
}
func (c *Consul) getServicesUsingProviderWithRetriesOnAgentFailure(provide ServicesProvider) ([]*consulapi.CatalogService, error) {
var services []*consulapi.CatalogService = nil
for {
agent, agentAddress, err := c.agents.GetAnyAgent()
if err != nil {
return nil, err
}
if services, err = provide(agent); err != nil {
log.WithError(err).WithField("Address", agentAddress).Error("An error occurred getting services from Consul, retrying with another agent")
c.agents.RemoveAgent(agentAddress)
} else {
break
}
}
return services, nil
}
func (c *Consul) getServicesUsingAgent(name string, agent *consulapi.Client) ([]*consulapi.CatalogService, error) {
datacenters, err := agent.Catalog().Datacenters()
if err != nil {
return nil, err
}
var allServices []*consulapi.CatalogService
for _, dc := range datacenters {
dcAwareQuery := &consulapi.QueryOptions{
Datacenter: dc,
}
services, _, err := agent.Catalog().Service(name, c.config.Tag, dcAwareQuery)
if err != nil {
return nil, err
}
allServices = append(allServices, services...)
}
return allServices, nil
}
func (c *Consul) GetAllServices() ([]*consulapi.CatalogService, error) {
return c.getServicesUsingProviderWithRetriesOnAgentFailure(c.getAllServices)
}
func (c *Consul) getAllServices(agent *consulapi.Client) ([]*consulapi.CatalogService, error) {
datacenters, err := agent.Catalog().Datacenters()
if err != nil {
return nil, err
}
var allInstances []*consulapi.CatalogService
for _, dc := range datacenters {
dcAwareQuery := &consulapi.QueryOptions{
Datacenter: dc,
}
services, _, err := agent.Catalog().Services(dcAwareQuery)
if err != nil {
return nil, err
}
for service, tags := range services {
if contains(tags, c.config.Tag) {
serviceInstances, _, err := agent.Catalog().Service(service, c.config.Tag, dcAwareQuery)
if err != nil {
return nil, err
}
allInstances = append(allInstances, serviceInstances...)
}
}
}
return allInstances, nil
}
func contains(slice []string, search string) bool {
for _, element := range slice {
if element == search {
return true
}
}
return false
}
func (c *Consul) Register(task *apps.Task, app *apps.App) error {
service, err := c.marathonTaskToConsulService(task, app)
if err != nil {
return err
}
if value, ok := app.Labels["consul"]; ok && value == "true" {
log.WithField("Id", app.ID).Warn("Warning! Application configuration is deprecated (labeled as `consul:true`). Support for special `true` value will be removed in the future!")
}
metrics.Time("consul.register", func() { err = c.register(service) })
if err != nil {
metrics.Mark("consul.register.error")
} else {
metrics.Mark("consul.register.success")
}
return err
}
func (c *Consul) register(service *consulapi.AgentServiceRegistration) error {
agent, err := c.agents.GetAgent(service.Address)
if err != nil {
return err
}
fields := log.Fields{
"Name": service.Name,
"Id": service.ID,
"Tags": service.Tags,
"Address": service.Address,
"Port": service.Port,
}
log.WithFields(fields).Info("Registering")
err = agent.Agent().ServiceRegister(service)
if err != nil {
log.WithError(err).WithFields(fields).Error("Unable to register")
}
return err
}
func (c *Consul) Deregister(serviceId apps.TaskId, agentAddress string) error {
var err error
metrics.Time("consul.deregister", func() { err = c.deregister(serviceId, agentAddress) })
if err != nil {
metrics.Mark("consul.deregister.error")
} else {
metrics.Mark("consul.deregister.success")
}
return err
}
func (c *Consul) deregister(serviceId apps.TaskId, agentAddress string) error {
agent, err := c.agents.GetAgent(agentAddress)
if err != nil {
return err
}
log.WithField("Id", serviceId).WithField("Address", agentAddress).Info("Deregistering")
err = agent.Agent().ServiceDeregister(serviceId.String())
if err != nil {
log.WithError(err).WithField("Id", serviceId).WithField("Address", agentAddress).Error("Unable to deregister")
}
return err
}
func (c *Consul) GetAgent(agentAddress string) (*consulapi.Client, error) {
return c.agents.GetAgent(agentAddress)
}
func (c *Consul) marathonTaskToConsulService(task *apps.Task, app *apps.App) (*consulapi.AgentServiceRegistration, error) {
IP, err := utils.HostToIPv4(task.Host)
if err != nil {
return nil, err
}
serviceAddress := IP.String()
return &consulapi.AgentServiceRegistration{
ID: task.ID.String(),
Name: app.ConsulServiceName(),
Port: task.Ports[0],
Address: serviceAddress,
Tags: c.marathonLabelsToConsulTags(app.Labels),
Check: c.marathonToConsulCheck(task, app.HealthChecks, serviceAddress),
}, nil
}
func (c *Consul) marathonToConsulCheck(task *apps.Task, healthChecks []apps.HealthCheck, serviceAddress string) *consulapi.AgentServiceCheck {
// TODO: Handle all types of checks
for _, check := range healthChecks {
if check.Protocol == "HTTP" {
return &consulapi.AgentServiceCheck{
HTTP: (&url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", serviceAddress, task.Ports[check.PortIndex]),
Path: check.Path,
}).String(),
Interval: fmt.Sprintf("%ds", check.IntervalSeconds),
Timeout: fmt.Sprintf("%ds", check.TimeoutSeconds),
}
}
}
return nil
}
func (c *Consul) marathonLabelsToConsulTags(labels map[string]string) []string {
tags := []string{c.config.Tag}
for key, value := range labels {
if value == "tag" {
tags = append(tags, key)
}
}
return tags
}