-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
246 lines (225 loc) · 6.53 KB
/
main.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
package main
import (
"errors"
"fmt"
"log"
"net"
"os"
"strings"
"time"
"github.com/ahmetalpbalkan/wagl/clusterdns"
"github.com/ahmetalpbalkan/wagl/rrstore"
"github.com/ahmetalpbalkan/wagl/server"
"github.com/ahmetalpbalkan/wagl/swarm"
"github.com/codegangsta/cli"
)
const (
defaultDnsDomain = "swarm."
defaultAddr = ":53"
defaultSwarm = "127.0.0.1:2376"
defaultRefreshInterval = time.Second * 15
defaultRefreshTimeout = time.Second * 10
defaultStalenessPeriod = time.Second * 60
)
type Options struct {
// User input
domain string
bindAddr string
swarmAddr string
tlsDir string
tlsVerify bool
recurse bool
nameservers []string
refreshInterval time.Duration
refreshTimeout time.Duration
stalenessPeriod time.Duration
}
func (o *Options) String() string {
return fmt.Sprintf(`Configuration:
- Domain: "%s"
- Listen: "%s"
- Swarm: %s
- TLS: %s (verify: %v)
- External: %v (ns: [%s])
- Refresh: Every %v (timeout: %v) (staleness: %v)
-------------------`,
o.domain,
o.bindAddr,
o.swarmAddr,
o.tlsDir,
o.tlsVerify,
o.recurse, strings.Join(o.nameservers, ","),
o.refreshInterval, o.refreshTimeout, o.stalenessPeriod)
}
func main() {
cmd := cli.NewApp()
cmd.Name = "wagl"
cmd.Version = "0.1"
cmd.Usage = "DNS service discovery for Docker Swarm clusters"
cli.AppHelpTemplate = usageTemplate
cmd.Flags = []cli.Flag{
cli.StringFlag{
Name: "bind",
Value: defaultAddr,
Usage: "IP:port on which the server shoud listen",
},
cli.StringFlag{
Name: "swarm",
Value: defaultSwarm,
Usage: "address of the Swarm manager", // TODO accept multiple
},
cli.StringFlag{
Name: "swarm-cert-path",
Value: "",
Usage: "directory TLS certs for Swarm manager is stored",
EnvVar: "DOCKER_CERT_PATH",
},
cli.BoolFlag{
Name: "swarm-tlsverify",
Usage: "verify remote Swarm's identity using TLS",
EnvVar: "DOCKER_TLS_VERIFY",
},
cli.StringFlag{
Name: "domain",
Value: defaultDnsDomain,
Usage: "DNS domain (FQDN suffix) for which this server is authoritative",
},
cli.BoolTFlag{
Name: "external",
Usage: "use external nameservers to resolve DNS requests outside the domain (true by default)",
},
cli.StringSliceFlag{
Name: "ns",
Usage: "external nameserver(s) to forward requests (default: nameservers in /etc/resolv.conf)",
},
cli.DurationFlag{
Name: "refresh",
Value: defaultRefreshInterval,
Usage: "how frequently refresh DNS table from cluster records",
},
cli.DurationFlag{
Name: "refresh-timeout",
Value: defaultRefreshTimeout,
Usage: "time alotted for Swarm to list containers in the cluster",
},
cli.DurationFlag{
Name: "staleness",
Value: defaultStalenessPeriod,
Usage: "how long to serve stale DNS records before exiting",
},
}
cmd.Action = func(c *cli.Context) {
opts := &Options{
domain: c.String("domain"),
bindAddr: c.String("bind"),
swarmAddr: c.String("swarm"),
tlsDir: c.String("swarm-cert-path"),
tlsVerify: c.Bool("swarm-tlsverify"),
recurse: c.BoolT("external"),
nameservers: c.StringSlice("ns"),
refreshInterval: c.Duration("refresh"),
refreshTimeout: c.Duration("refresh-timeout"),
stalenessPeriod: c.Duration("staleness"),
}
if err := validate(opts); err != nil {
log.Fatalf("Error: %v", err)
}
log.Printf("%s", opts)
serve(opts)
}
cmd.Run(os.Args)
}
// validate looks for logical correctness and consistency of the input arguments
// to the program.
func validate(opt *Options) error {
// No NS must be specified if recursion is off
if !opt.recurse && len(opt.nameservers) > 0 {
return errors.New("External querying disabled, but external nameservers specified")
}
// TLS verify can be used only if certs are specified
if opt.tlsVerify && opt.tlsDir == "" {
return errors.New("TLS verify specified; but not TLS cert path")
}
// No nameservers speficied, check resolv.conf, add it.
if opt.recurse && len(opt.nameservers) == 0 {
if ns, err := localNameservers(); err != nil {
return fmt.Errorf("Failed to load nameservers list: %v", err)
} else if len(ns) == 0 {
return fmt.Errorf("No nameservers found in /etc/resolv.conf")
} else {
opt.nameservers = ns
}
}
// Nameserver validations:
// - make sure nameservers are IP[:port]
// - add default DNS port to nameservers if missing
for i, v := range opt.nameservers {
host := v
if h, _, err := net.SplitHostPort(v); err != nil { // Missing port
opt.nameservers[i] = v + ":53"
} else {
host = h
}
// Make sure hostname is IP (do not support domain names as nameservers)
if ip := net.ParseIP(host); ip == nil {
return fmt.Errorf("Nameserver is not an IP address: '%s'", host)
}
}
// Refresh timeout < refresh interval
if opt.refreshTimeout >= opt.refreshInterval {
return fmt.Errorf("Refresh timeout (%v) should be less than refresh interval (%v)", opt.refreshTimeout, opt.refreshInterval)
}
return nil
}
// serve starts the DNS server and blocks.
func serve(opt *Options) {
dockerTLS, err := tlsConfig(opt.tlsDir, opt.tlsVerify)
if err != nil {
log.Fatalf("Error establishing TLS config: %v", err)
}
rrs := rrstore.New()
cluster, err := swarm.New(opt.swarmAddr, dockerTLS)
if err != nil {
log.Fatalf("Error initializing Swarm: %v", err)
}
dns := clusterdns.New(opt.domain, rrs, cluster)
cancel := make(chan struct{})
defer close(cancel)
errCh, okCh := dns.StartRefreshing(opt.refreshInterval, opt.refreshTimeout,
cancel)
go func() {
var lastSuccess time.Time
var start = time.Now()
var errs = 0
var ok = 0
for {
// Exit if records are stale. Here we prefer consistency over
// liveliness/availability.
if (ok > 0 && time.Since(lastSuccess) > opt.stalenessPeriod) ||
(ok == 0 && time.Since(start) > opt.stalenessPeriod) {
close(cancel)
var last string
if lastSuccess.IsZero() {
last = "never"
} else {
last = lastSuccess.String()
}
log.Fatalf("Fatal: exiting rather than serving stale records. Staleness period: %v, last success: %s", opt.stalenessPeriod, last)
}
select {
case err := <-errCh:
errs++
log.Printf("Refresh error (#%d): %v ", errs, err)
case <-okCh:
errs = 0 // reset errs
ok++
lastSuccess = time.Now()
log.Printf("Successfully refreshed records.")
case <-cancel:
log.Fatal("Fatal: Refreshing records cancelled.")
}
}
}()
srv := server.New(opt.domain, opt.bindAddr, rrs, opt.recurse, opt.nameservers)
log.Fatal(srv.ListenAndServe())
}