forked from traefik/traefik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
280 lines (248 loc) · 8.4 KB
/
docker.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
274
275
276
277
278
279
280
package provider
import (
"errors"
"fmt"
"strconv"
"strings"
"text/template"
"time"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff"
"github.com/containous/traefik/types"
"github.com/fsouza/go-dockerclient"
)
// Docker holds configurations of the Docker provider.
type Docker struct {
BaseProvider `mapstructure:",squash"`
Endpoint string
Domain string
TLS *DockerTLS
}
// DockerTLS holds TLS specific configurations
type DockerTLS struct {
CA string
Cert string
Key string
InsecureSkipVerify bool
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *Docker) Provide(configurationChan chan<- types.ConfigMessage) error {
go func() {
operation := func() error {
var dockerClient *docker.Client
var err error
if provider.TLS != nil {
dockerClient, err = docker.NewTLSClient(provider.Endpoint,
provider.TLS.Cert, provider.TLS.Key, provider.TLS.CA)
if err == nil {
dockerClient.TLSConfig.InsecureSkipVerify = provider.TLS.InsecureSkipVerify
}
} else {
dockerClient, err = docker.NewClient(provider.Endpoint)
}
if err != nil {
log.Errorf("Failed to create a client for docker, error: %s", err)
return err
}
err = dockerClient.Ping()
if err != nil {
log.Errorf("Docker connection error %+v", err)
return err
}
log.Debug("Docker connection established")
configuration := provider.loadDockerConfig(listContainers(dockerClient))
configurationChan <- types.ConfigMessage{
ProviderName: "docker",
Configuration: configuration,
}
if provider.Watch {
dockerEvents := make(chan *docker.APIEvents)
dockerClient.AddEventListener(dockerEvents)
log.Debug("Docker listening")
for {
event := <-dockerEvents
if event == nil {
return errors.New("Docker event nil")
// log.Fatalf("Docker connection error")
}
if event.Status == "start" || event.Status == "die" {
log.Debugf("Docker event receveived %+v", event)
configuration := provider.loadDockerConfig(listContainers(dockerClient))
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: "docker",
Configuration: configuration,
}
}
}
}
}
return nil
}
notify := func(err error, time time.Duration) {
log.Errorf("Docker connection error %+v, retrying in %s", err, time)
}
err := backoff.RetryNotify(operation, backoff.NewExponentialBackOff(), notify)
if err != nil {
log.Fatalf("Cannot connect to docker server %+v", err)
}
}()
return nil
}
func (provider *Docker) loadDockerConfig(containersInspected []docker.Container) *types.Configuration {
var DockerFuncMap = template.FuncMap{
"getBackend": provider.getBackend,
"getPort": provider.getPort,
"getWeight": provider.getWeight,
"getDomain": provider.getDomain,
"getProtocol": provider.getProtocol,
"getPassHostHeader": provider.getPassHostHeader,
"getEntryPoints": provider.getEntryPoints,
"getFrontendValue": provider.getFrontendValue,
"getFrontendRule": provider.getFrontendRule,
"replace": replace,
}
// filter containers
filteredContainers := fun.Filter(containerFilter, containersInspected).([]docker.Container)
frontends := map[string][]docker.Container{}
for _, container := range filteredContainers {
frontends[provider.getFrontendName(container)] = append(frontends[provider.getFrontendName(container)], container)
}
templateObjects := struct {
Containers []docker.Container
Frontends map[string][]docker.Container
Domain string
}{
filteredContainers,
frontends,
provider.Domain,
}
configuration, err := provider.getConfiguration("templates/docker.tmpl", DockerFuncMap, templateObjects)
if err != nil {
log.Error(err)
}
return configuration
}
func containerFilter(container docker.Container) bool {
if len(container.NetworkSettings.Ports) == 0 {
log.Debugf("Filtering container without port %s", container.Name)
return false
}
_, err := strconv.Atoi(container.Config.Labels["traefik.port"])
if len(container.NetworkSettings.Ports) > 1 && err != nil {
log.Debugf("Filtering container with more than 1 port and no traefik.port label %s", container.Name)
return false
}
if container.Config.Labels["traefik.enable"] == "false" {
log.Debugf("Filtering disabled container %s", container.Name)
return false
}
labels, err := getLabels(container, []string{"traefik.frontend.rule", "traefik.frontend.value"})
if len(labels) != 0 && err != nil {
log.Debugf("Filtering bad labeled container %s", container.Name)
return false
}
return true
}
func (provider *Docker) getFrontendName(container docker.Container) string {
// Replace '.' with '-' in quoted keys because of this issue https://github.com/BurntSushi/toml/issues/78
frontendName := fmt.Sprintf("%s-%s", provider.getFrontendRule(container), provider.getFrontendValue(container))
frontendName = strings.Replace(frontendName, "[", "", -1)
frontendName = strings.Replace(frontendName, "]", "", -1)
return strings.Replace(frontendName, ".", "-", -1)
}
// GetFrontendValue returns the frontend value for the specified container, using
// it's label. It returns a default one if the label is not present.
func (provider *Docker) getFrontendValue(container docker.Container) string {
if label, err := getLabel(container, "traefik.frontend.value"); err == nil {
return label
}
return getEscapedName(container.Name) + "." + provider.Domain
}
// GetFrontendRule returns the frontend rule for the specified container, using
// it's label. It returns a default one (Host) if the label is not present.
func (provider *Docker) getFrontendRule(container docker.Container) string {
if label, err := getLabel(container, "traefik.frontend.rule"); err == nil {
return label
}
return "Host"
}
func (provider *Docker) getBackend(container docker.Container) string {
if label, err := getLabel(container, "traefik.backend"); err == nil {
return label
}
return getEscapedName(container.Name)
}
func (provider *Docker) getPort(container docker.Container) string {
if label, err := getLabel(container, "traefik.port"); err == nil {
return label
}
for key := range container.NetworkSettings.Ports {
return key.Port()
}
return ""
}
func (provider *Docker) getWeight(container docker.Container) string {
if label, err := getLabel(container, "traefik.weight"); err == nil {
return label
}
return "0"
}
func (provider *Docker) getDomain(container docker.Container) string {
if label, err := getLabel(container, "traefik.domain"); err == nil {
return label
}
return provider.Domain
}
func (provider *Docker) getProtocol(container docker.Container) string {
if label, err := getLabel(container, "traefik.protocol"); err == nil {
return label
}
return "http"
}
func (provider *Docker) getPassHostHeader(container docker.Container) string {
if passHostHeader, err := getLabel(container, "traefik.frontend.passHostHeader"); err == nil {
return passHostHeader
}
return "false"
}
func (provider *Docker) getEntryPoints(container docker.Container) []string {
if entryPoints, err := getLabel(container, "traefik.frontend.entryPoints"); err == nil {
return strings.Split(entryPoints, ",")
}
return []string{}
}
func getLabel(container docker.Container, label string) (string, error) {
for key, value := range container.Config.Labels {
if key == label {
return value, nil
}
}
return "", errors.New("Label not found:" + label)
}
func getLabels(container docker.Container, labels []string) (map[string]string, error) {
var globalErr error
foundLabels := map[string]string{}
for _, label := range labels {
foundLabel, err := getLabel(container, label)
// Error out only if one of them is defined.
if err != nil {
globalErr = errors.New("Label not found: " + label)
continue
}
foundLabels[label] = foundLabel
}
return foundLabels, globalErr
}
func listContainers(dockerClient *docker.Client) []docker.Container {
containerList, _ := dockerClient.ListContainers(docker.ListContainersOptions{})
containersInspected := []docker.Container{}
// get inspect containers
for _, container := range containerList {
containerInspected, _ := dockerClient.InspectContainer(container.ID)
containersInspected = append(containersInspected, *containerInspected)
}
return containersInspected
}