-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
docker.go
509 lines (474 loc) · 14.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
* Copyright (c) 2021-present Fabien Potencier <fabien@symfony.com>
*
* This file is part of Symfony CLI project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package envs
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
docker "github.com/docker/docker/client"
"github.com/symfony-cli/terminal"
)
var (
dockerComposeNormalizeRegexp = regexp.MustCompile("[^-_a-z0-9]")
dockerComposeNormalizeRegexpLegacy = regexp.MustCompile("[^a-z0-9]")
)
type sortedPorts []types.Port
func (ps sortedPorts) Len() int { return len(ps) }
func (ps sortedPorts) Swap(i, j int) { ps[i], ps[j] = ps[j], ps[i] }
func (ps sortedPorts) Less(i, j int) bool { return ps[i].PrivatePort < ps[j].PrivatePort }
// Port of https://github.com/docker/compose/blob/615c01c50a51408a7fdfed66ecccf73781e87f2c/compose/cli/command.py#L153-L154
func normalizeDockerComposeProjectName(projectName string) string {
return dockerComposeNormalizeRegexp.ReplaceAllString(strings.ToLower(projectName), "")
}
// Port of https://github.com/docker/compose/blob/4e0fdd70bdae4f8d85e4ef9d0129ce445f3ece3c/compose/cli/command.py#L129-L130
// (prior to 615c01c50a51408a7fdfed66ecccf73781e87f2c)
// This was used in Docker Compose prior to 1.21.0, some users might still use
// versions older though, so we keep this BC in the mean time.
func normalizeDockerComposeProjectNameLegacy(projectName string) string {
return dockerComposeNormalizeRegexpLegacy.ReplaceAllString(strings.ToLower(projectName), "")
}
func (l *Local) RelationshipsFromDocker() Relationships {
project := l.getComposeProjectName()
if project == "" {
return nil
}
opts := [](docker.Opt){docker.FromEnv}
if host := os.Getenv("DOCKER_HOST"); host != "" && !strings.HasPrefix(host, "unix://") {
// Setting a dialer on top of a unix socket breaks the connection
// as the client then tries to connect to http:///path/to/socket and
// thus tries to resolve the /path/to/socket host
dialer := &net.Dialer{
Timeout: 2 * time.Second,
}
opts = append(opts, docker.WithDialer(dialer))
}
client, err := docker.NewClientWithOpts(opts...)
if err != nil {
if l.Debug {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
}
return nil
}
defer client.Close()
client.NegotiateAPIVersion(context.Background())
containers, err := client.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
if docker.IsErrConnectionFailed(err) {
terminal.Logger.Warn().Msg(err.Error())
} else if l.Debug {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
}
return nil
}
// To be in sync with Docker compose behavior we also normalize project name
// passed by the environment variable
projectLegacy := normalizeDockerComposeProjectNameLegacy(project)
project = normalizeDockerComposeProjectName(project)
relationships := Relationships{}
for _, container := range containers {
p, ok := container.Labels["com.docker.compose.project"]
if !ok {
continue
}
if p != project && p != projectLegacy {
continue
}
for suffix, relationship := range l.dockerServiceToRelationship(client, container) {
// get the service name
name, ok := container.Labels["com.symfony.server.service-prefix"]
if !ok {
name, ok = container.Labels["com.docker.compose.service"]
if !ok {
if l.Debug {
fmt.Fprintf(os.Stderr, "ERROR: unable to find the service name of the Docker container with id \"%s\"\n", container.ID)
}
continue
}
}
if l.Debug {
fmt.Fprintf(os.Stderr, " exposing service \"%s%s\"\n", name, suffix)
}
relationships[name+suffix] = append(relationships[name+suffix], relationship)
}
}
if len(relationships) != 0 {
l.DockerEnv = true
}
return relationships
}
func (l *Local) dockerServiceToRelationship(client *docker.Client, container types.Container) map[string]map[string]interface{} {
if l.Debug {
fmt.Fprintf(os.Stderr, `found Docker container "%s" for project "%s" (image "%s")`+"\n", container.Labels["com.docker.compose.service"], container.Labels["com.docker.compose.project"], container.Image)
}
if v, _ := strconv.ParseBool(container.Labels["com.symfony.server.service-ignore"]); v {
if l.Debug {
fmt.Fprintln(os.Stderr, " skipping as com.symfony.server.service-ignore is true")
}
return nil
}
var exposedPorts sortedPorts
for _, port := range container.Ports {
if port.PublicPort == 0 {
continue
}
if l.Debug {
fmt.Fprintf(os.Stderr, " port %d for private port %d\n", port.PublicPort, port.PrivatePort)
}
exposedPorts = append(exposedPorts, port)
}
if len(exposedPorts) == 0 {
if l.Debug && len(container.Ports) > 0 {
fmt.Fprintf(os.Stderr, "WARNING: Container %s has none of its ports exposed.\n", container.Names[0][1:])
}
return nil
}
c, err := client.ContainerInspect(context.Background(), container.ID)
if err != nil {
if l.Debug {
fmt.Fprintf(os.Stderr, " ERROR: error while inspecting container \"%s\": %s\n", container.Names[0][1:], err)
}
return nil
}
if l.Debug {
for _, env := range c.Config.Env {
fmt.Fprintf(os.Stderr, " env %s\n", env)
}
}
host := os.Getenv("DOCKER_HOST")
if host == "" || strings.HasPrefix(host, "unix://") {
host = "127.0.0.1"
} else {
u, err := url.Parse(host)
if err != nil {
fmt.Fprintf(os.Stderr, " ERROR: unable to parse DOCKER_HOST \"%s\", falling back to 127.0.0.1: %s\n", host, err)
host = "127.0.0.1"
} else {
host = u.Hostname()
}
}
sort.Sort(exposedPorts)
for _, p := range exposedPorts {
rels := make(map[string]map[string]interface{})
if p.PrivatePort == 1025 {
// recommended image: schickling/mailcatcher
for _, pw := range exposedPorts {
if pw.PrivatePort == 1080 || pw.PrivatePort == 8025 {
rels["-web"] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(pw.PublicPort),
"rel": "mailer",
"scheme": "http",
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "mailer",
"scheme": "smtp",
}
return rels
}
}
} else if p.PrivatePort == 25 {
// recommended image: djfarrelly/maildev
for _, pw := range exposedPorts {
if pw.PrivatePort == 80 {
rels["-web"] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(pw.PublicPort),
"rel": "mailer",
"scheme": "http",
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "mailer",
"scheme": "smtp",
}
return rels
}
}
} else if p.PrivatePort == 8707 || p.PrivatePort == 8307 {
// Blackfire
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "blackfire",
"scheme": "tcp",
}
return rels
} else if p.PrivatePort == 3306 {
username := ""
password := ""
path := ""
// MARIADB is used by bitnami/mariadb
for _, prefix := range []string{"MYSQL", "MARIADB"} {
for _, env := range c.Config.Env {
if strings.HasPrefix(env, prefix+"_ROOT_PASSWORD") && password == "" {
// *_PASSWORD has precedence over *_ROOT_PASSWORD
password = getEnvValue(env, prefix+"_ROOT_PASSWORD")
username = "root"
} else if strings.HasPrefix(env, prefix+"_USER") {
username = getEnvValue(env, prefix+"_USER")
} else if strings.HasPrefix(env, prefix+"_PASSWORD") {
password = getEnvValue(env, prefix+"_PASSWORD")
} else if strings.HasPrefix(env, prefix+"_DATABASE") {
path = getEnvValue(env, prefix+"_DATABASE")
}
}
}
if path == "" {
path = username
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"username": username,
"password": password,
"path": path,
"port": formatDockerPort(p.PublicPort),
"query": map[string]bool{
"is_master": true,
},
"rel": "mysql",
"scheme": "mysql",
}
return rels
} else if p.PrivatePort == 5432 {
username := ""
password := ""
path := ""
for _, env := range c.Config.Env {
if strings.HasPrefix(env, "POSTGRES_USER") {
username = getEnvValue(env, "POSTGRES_USER")
} else if strings.HasPrefix(env, "POSTGRES_PASSWORD") {
password = getEnvValue(env, "POSTGRES_PASSWORD")
} else if strings.HasPrefix(env, "POSTGRES_DB") {
path = getEnvValue(env, "POSTGRES_DB")
}
}
if path == "" {
path = username
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"username": username,
"password": password,
"path": path,
"port": formatDockerPort(p.PublicPort),
"query": map[string]bool{
"is_master": true,
},
"rel": "pgsql",
"scheme": "pgsql",
}
return rels
} else if p.PrivatePort == 6379 {
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "redis",
"scheme": "redis",
}
return rels
} else if p.PrivatePort == 11211 {
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "memcached",
"scheme": "memcached",
}
return rels
} else if p.PrivatePort == 5672 {
username := "guest"
password := "guest"
for _, env := range c.Config.Env {
// that's our local convention
if strings.HasPrefix(env, "RABBITMQ_DEFAULT_USER") {
username = getEnvValue(env, "RABBITMQ_DEFAULT_USER")
} else if strings.HasPrefix(env, "RABBITMQ_DEFAULT_PASS") {
password = getEnvValue(env, "RABBITMQ_DEFAULT_PASS")
}
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"username": username,
"password": password,
"rel": "amqp",
"scheme": "amqp",
}
// management plugin?
for _, pw := range exposedPorts {
if pw.PrivatePort == 15672 {
rels["-management"] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(pw.PublicPort),
"rel": "amqp",
"scheme": "http",
}
break
}
}
return rels
} else if p.PrivatePort == 9200 {
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"path": "/",
"rel": "elasticsearch",
"scheme": "http",
}
return rels
} else if p.PrivatePort == 27017 {
path := ""
for _, env := range c.Config.Env {
// that's our local convention
if strings.HasPrefix(env, "MONGO_DATABASE") {
path = getEnvValue(env, "MONGO_DATABASE")
}
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"username": "",
"password": "",
"path": path,
"port": formatDockerPort(p.PublicPort),
"rel": "mongodb",
"scheme": "mongodb",
}
return rels
} else if p.PrivatePort == 9092 {
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "kafka",
"scheme": "kafka",
}
return rels
} else if p.PrivatePort == 80 && container.Image == "dunglas/mercure" {
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "mercure",
"scheme": "http",
}
return rels
}
if l.Debug {
fmt.Fprintln(os.Stderr, " exposing port")
}
rels[""] = map[string]interface{}{
"host": host,
"ip": host,
"port": formatDockerPort(p.PublicPort),
"rel": "simple",
}
// Official HTTP(s) ports or well know alternatives
if p.PrivatePort == 80 || p.PrivatePort == 8008 || p.PrivatePort == 8080 || p.PrivatePort == 8081 {
rels[""]["scheme"] = "http"
} else if p.PrivatePort == 443 || p.PrivatePort == 8443 {
rels[""]["scheme"] = "https"
}
return rels
}
return nil
}
func formatDockerPort(port uint16) string {
return strconv.FormatInt(int64(port), 10)
}
func getEnvValue(env string, key string) string {
if len(key) == len(env) {
return ""
}
return env[len(key)+1:]
}
func (l *Local) getComposeProjectName() string {
// https://docs.docker.com/compose/reference/envvars/#compose_project_name
if project := os.Getenv("COMPOSE_PROJECT_NAME"); project != "" {
return project
}
composeDir := l.getComposeDir()
if composeDir == "" {
if l.Debug {
fmt.Fprintln(os.Stderr, "ERROR: unable to find a compose directory for the current directory")
}
return ""
}
// COMPOSE_PROJECT_NAME can be set in a .env file
if _, err := os.Stat(filepath.Join(composeDir, ".env")); err == nil {
if contents, err := ioutil.ReadFile(filepath.Join(composeDir, ".env")); err == nil {
for _, line := range bytes.Split(contents, []byte("\n")) {
if bytes.HasPrefix(line, []byte("COMPOSE_PROJECT_NAME=")) {
return string(line[len("COMPOSE_PROJECT_NAME="):])
}
}
}
}
return filepath.Base(composeDir)
}
func (l *Local) getComposeDir() string {
// https://docs.docker.com/compose/reference/envvars/#compose_file
if os.Getenv("COMPOSE_FILE") != "" {
return l.Dir
}
// look for the first dir up with a docker-composer.ya?ml file (in case of a multi-project)
dir := l.Dir
for {
if _, err := os.Stat(filepath.Join(dir, "docker-compose.yaml")); err == nil {
return dir
}
// both .yml and .yaml are supported by Docker composer
if _, err := os.Stat(filepath.Join(dir, "docker-compose.yml")); err == nil {
return dir
}
upDir := filepath.Dir(dir)
if upDir == dir || upDir == "." {
if l.Debug {
fmt.Fprintln(os.Stderr, "ERROR: unable to find a docker-compose.yaml or docker-compose.yml for the current directory")
}
return ""
}
dir = upDir
}
}