/
api.go
273 lines (218 loc) · 6.7 KB
/
api.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package rancher
import (
"context"
"os"
"time"
"github.com/cenk/backoff"
"github.com/mitchellh/mapstructure"
rancher "github.com/rancher/go-rancher/v2"
"github.com/traefik/traefik/job"
"github.com/traefik/traefik/log"
"github.com/traefik/traefik/safe"
"github.com/traefik/traefik/types"
)
const (
labelRancherStackServiceName = "io.rancher.stack_service.name"
hostNetwork = "host"
)
var withoutPagination *rancher.ListOpts
// APIConfiguration contains configuration properties specific to the Rancher
// API provider.
type APIConfiguration struct {
Endpoint string `description:"Rancher server API HTTP(S) endpoint"`
AccessKey string `description:"Rancher server API access key"`
SecretKey string `description:"Rancher server API secret key"`
}
func init() {
withoutPagination = &rancher.ListOpts{
Filters: map[string]interface{}{"limit": 0},
}
}
func (p *Provider) createClient() (*rancher.RancherClient, error) {
rancherURL := getenv("CATTLE_URL", p.API.Endpoint)
accessKey := getenv("CATTLE_ACCESS_KEY", p.API.AccessKey)
secretKey := getenv("CATTLE_SECRET_KEY", p.API.SecretKey)
return rancher.NewRancherClient(&rancher.ClientOpts{
Url: rancherURL,
AccessKey: accessKey,
SecretKey: secretKey,
})
}
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
func (p *Provider) apiProvide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error {
if p.API == nil {
p.API = &APIConfiguration{}
}
safe.Go(func() {
operation := func() error {
rancherClient, err := p.createClient()
if err != nil {
log.Errorf("Failed to create a client for rancher, error: %s", err)
return err
}
ctx := context.Background()
stacks, err := listRancherStacks(rancherClient)
if err != nil {
return err
}
services, err := listRancherServices(rancherClient)
if err != nil {
return err
}
container, err := listRancherContainer(rancherClient)
if err != nil {
return err
}
var rancherData = parseAPISourcedRancherData(stacks, services, container)
configuration := p.buildConfiguration(rancherData)
configurationChan <- types.ConfigMessage{
ProviderName: "rancher",
Configuration: configuration,
}
if p.Watch {
_, cancel := context.WithCancel(ctx)
ticker := time.NewTicker(time.Second * time.Duration(p.RefreshSeconds))
pool.Go(func(stop chan bool) {
for {
select {
case <-ticker.C:
checkAPI, errAPI := rancherClient.ApiKey.List(withoutPagination)
if errAPI != nil {
log.Errorf("Cannot establish connection: %+v, Rancher API return: %+v; Skipping refresh Data from Rancher API.", errAPI, checkAPI)
continue
}
log.Debugf("Refreshing new Data from Rancher API")
stacks, err = listRancherStacks(rancherClient)
if err != nil {
continue
}
services, err = listRancherServices(rancherClient)
if err != nil {
continue
}
container, err = listRancherContainer(rancherClient)
if err != nil {
continue
}
rancherData := parseAPISourcedRancherData(stacks, services, container)
configuration := p.buildConfiguration(rancherData)
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: "rancher",
Configuration: configuration,
}
}
case <-stop:
ticker.Stop()
cancel()
return
}
}
})
}
return nil
}
notify := func(err error, time time.Duration) {
log.Errorf("Provider connection error %+v, retrying in %s", err, time)
}
err := backoff.RetryNotify(operation, job.NewBackOff(backoff.NewExponentialBackOff()), notify)
if err != nil {
log.Errorf("Cannot connect to Provider Endpoint %+v", err)
}
})
return nil
}
func listRancherStacks(client *rancher.RancherClient) ([]*rancher.Stack, error) {
var stackList []*rancher.Stack
stacks, err := client.Stack.List(withoutPagination)
if err != nil {
log.Errorf("Cannot get Provider Stacks %+v", err)
}
for k := range stacks.Data {
stackList = append(stackList, &stacks.Data[k])
}
return stackList, err
}
func listRancherServices(client *rancher.RancherClient) ([]*rancher.Service, error) {
var servicesList []*rancher.Service
services, err := client.Service.List(withoutPagination)
if err != nil {
log.Errorf("Cannot get Provider Services %+v", err)
}
for k := range services.Data {
servicesList = append(servicesList, &services.Data[k])
}
return servicesList, err
}
func listRancherContainer(client *rancher.RancherClient) ([]*rancher.Container, error) {
var containerList []*rancher.Container
container, err := client.Container.List(withoutPagination)
if err != nil {
log.Errorf("Cannot get Provider Services %+v", err)
return containerList, err
}
valid := true
for valid {
for k := range container.Data {
containerList = append(containerList, &container.Data[k])
}
container, err = container.Next()
if err != nil {
break
}
if container == nil || len(container.Data) == 0 {
valid = false
}
}
return containerList, err
}
func parseAPISourcedRancherData(stacks []*rancher.Stack, services []*rancher.Service, containers []*rancher.Container) []rancherData {
var rancherDataList []rancherData
for _, stack := range stacks {
for _, service := range services {
if service.StackId != stack.Id {
continue
}
rData := rancherData{
Name: service.Name + "/" + stack.Name,
Health: service.HealthState,
State: service.State,
Labels: make(map[string]string),
Containers: []string{},
}
if service.LaunchConfig == nil || service.LaunchConfig.Labels == nil {
log.Warnf("Rancher Service Labels are missing. Stack: %s, service: %s", stack.Name, service.Name)
} else {
for key, value := range service.LaunchConfig.Labels {
rData.Labels[key] = value.(string)
}
}
for _, container := range containers {
if container.Labels[labelRancherStackServiceName] == stack.Name+"/"+service.Name &&
containerFilter(container.Name, container.HealthState, container.State) {
if container.NetworkMode == hostNetwork {
var endpoints []*rancher.PublicEndpoint
err := mapstructure.Decode(service.PublicEndpoints, &endpoints)
if err != nil {
log.Errorf("Failed to decode PublicEndpoint: %v", err)
continue
}
if len(endpoints) > 0 {
rData.Containers = append(rData.Containers, endpoints[0].IpAddress)
}
} else {
rData.Containers = append(rData.Containers, container.PrimaryIpAddress)
}
}
}
rancherDataList = append(rancherDataList, rData)
}
}
return rancherDataList
}