This repository has been archived by the owner on Dec 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_dns.go
100 lines (82 loc) · 1.74 KB
/
docker_dns.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
package main
import (
"net"
"regexp"
"sync"
"time"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"github.com/miekg/dns"
"golang.org/x/net/context"
)
// [forsale:wooQuoaL8a] This comment is for sale! Find more details at https://comment.forsale
var mu sync.Mutex
var active = map[string]types.Container{}
func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
// fmt.Println(">")
// fmt.Println(r)
m := new(dns.Msg)
m.SetReply(r)
for _, question := range r.Question {
re := regexp.MustCompile("(.*)\\.docker.")
matches := re.FindStringSubmatch(question.Name)
if len(matches) < 2 {
continue
}
id := matches[1]
mu.Lock()
c, ok := active[id]
mu.Unlock()
if !ok {
continue
}
network, ok := c.NetworkSettings.Networks["bridge"]
if !ok {
continue
}
m.Answer = append(m.Answer, &dns.A{
Hdr: dns.RR_Header{
Name: question.Name,
Rrtype: question.Qtype,
Class: question.Qclass,
Ttl: 10,
},
A: net.ParseIP(network.IPAddress),
})
}
w.WriteMsg(m)
// fmt.Println("<")
// fmt.Println(m)
}
func manageContainers(cli *client.Client) {
for {
options := types.ContainerListOptions{}
containers, err := cli.ContainerList(context.Background(), options)
if err != nil {
panic(err)
}
mu.Lock()
for _, c := range containers {
active[c.ID] = c
active[c.ID[:12]] = c
for _, name := range c.Names {
active[name[1:]] = c
}
}
mu.Unlock()
time.Sleep(3 * time.Second)
}
}
func main() {
cli, err := client.NewEnvClient()
if err != nil {
panic(err)
}
go manageContainers(cli)
server := &dns.Server{Addr: ":5300", Net: "udp"}
dns.HandleFunc("docker.", handleRequest)
err = server.ListenAndServe()
if err != nil {
panic(err)
}
}