-
Notifications
You must be signed in to change notification settings - Fork 1
/
hostsfile.go
80 lines (64 loc) · 2.4 KB
/
hostsfile.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
package main
import (
"bytes"
"context"
"fmt"
"github.com/docker/docker/api/types/container"
"os"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
// refreshHostsfile reads the docker containers, creates the container list and starts writeHostsfile() to write the hosts file
func refreshHostsfile(cli *client.Client) error {
var dockerHosts []byte
containers, err := cli.ContainerList(context.Background(), container.ListOptions{})
if err != nil {
return err
}
dockerHosts = append(dockerHosts, []byte(HOSTLIST_PREFIX)...)
dockerHosts = append(dockerHosts, []byte(HOSTLIST_INFO)...)
if len(containers) > 0 {
for _, c := range containers {
if conf.onlyLabeledContainers && (strings.ToLower(c.Labels[DOCKER_LABEL+".enabled"]) != "true") {
// log.Println("Skipping c", c.Names[len(c.Names)-1], "because it is not labeled with", DOCKER_LABEL+".enabled=true")
continue
}
if strings.ToLower(c.Labels[DOCKER_LABEL+".exclude"]) == "true" {
// log.Println("Skipping c", c.Names[len(c.Names)-1], "because it is labeled with", DOCKER_LABEL+".exclude=true")
continue
}
containerHostList := getContainerHostList(c)
if containerHostList != "" {
for networkName, networkInfo := range c.NetworkSettings.Networks {
if networkRegexpCompiled.MatchString(networkName) && networkInfo.IPAddress != "" {
dockerHosts = append(dockerHosts, []byte(fmt.Sprintf("%-15s %-60s # %s\n", networkInfo.IPAddress, containerHostList, networkName))...)
}
}
}
}
}
dockerHosts = append(dockerHosts, []byte(HOSTLIST_SUFFIX)...)
return writeHostsfile(dockerHosts)
}
// writeHostsfile reads the hosts file until the HOSTLIST_PREFIX and appends the given byte slice
func writeHostsfile(bs []byte) error {
hf, err := os.ReadFile(conf.hostsfile)
if err != nil {
return err
}
hfnew := bytes.Split(hf, []byte(HOSTLIST_PREFIX))[0]
hfnew = append(hfnew, bs...)
return os.WriteFile(conf.hostsfile, hfnew, 0644) // #nosec G306 -- hostsfile has to be writable
}
// getContainerHostList returns the list of hostnames for a given container
func getContainerHostList(container types.Container) string {
var s string
if conf.hostnameFromContainername {
s = strings.TrimPrefix(container.Names[len(container.Names)-1], "/") + " "
}
if label, ok := container.Labels[DOCKER_LABEL+".name"]; ok && conf.hostnameFromLabel {
s = s + label
}
return strings.Trim(s, " ")
}