forked from skynetservices/skydns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
256 lines (222 loc) · 7.69 KB
/
Copy pathmain.go
File metadata and controls
256 lines (222 loc) · 7.69 KB
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
// Copyright (c) 2014 The SkyDNS Authors. All rights reserved.
// Use of this source code is governed by The MIT License (MIT) that can be
// found in the LICENSE file.
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
backendetcd "github.com/skynetservices/skydns/backends/etcd"
"github.com/skynetservices/skydns/metrics"
"github.com/skynetservices/skydns/msg"
"github.com/skynetservices/skydns/server"
etcd "github.com/coreos/etcd/client"
"github.com/coreos/etcd/pkg/transport"
"github.com/miekg/dns"
"golang.org/x/net/context"
)
var (
tlskey = ""
tlspem = ""
cacert = ""
username = ""
password = ""
config = &server.Config{ReadTimeout: 0, Domain: "", DnsAddr: "", DNSSEC: ""}
nameserver = ""
machine = ""
stub = false
ctx = context.Background()
)
func env(key, def string) string {
if x := os.Getenv(key); x != "" {
return x
}
return def
}
func intEnv(key string, def int) int {
if x := os.Getenv(key); x != "" {
if v, err := strconv.ParseInt(x, 10, 0); err == nil {
return int(v)
}
}
return def
}
func boolEnv(key string, def bool) bool {
if x := os.Getenv(key); x != "" {
if v, err := strconv.ParseBool(x); err == nil {
return v
}
}
return def
}
func init() {
flag.StringVar(&config.Domain, "domain", env("SKYDNS_DOMAIN", "skydns.local."), "domain to anchor requests to (SKYDNS_DOMAIN)")
flag.StringVar(&config.DnsAddr, "addr", env("SKYDNS_ADDR", "127.0.0.1:53"), "ip:port to bind to (SKYDNS_ADDR)")
flag.StringVar(&nameserver, "nameservers", env("SKYDNS_NAMESERVERS", ""), "nameserver address(es) to forward (non-local) queries to e.g. 8.8.8.8:53,8.8.4.4:53")
flag.BoolVar(&config.NoRec, "no-rec", false, "do not provide a recursive service")
flag.StringVar(&machine, "machines", env("ETCD_MACHINES", "http://127.0.0.1:2379"), "machine address(es) running etcd")
flag.StringVar(&config.DNSSEC, "dnssec", "", "basename of DNSSEC key file e.q. Kskydns.local.+005+38250")
flag.StringVar(&config.Local, "local", "", "optional unique value for this skydns instance")
flag.StringVar(&tlskey, "tls-key", env("ETCD_TLSKEY", ""), "SSL key file used to secure etcd communication")
flag.StringVar(&tlspem, "tls-pem", env("ETCD_TLSPEM", ""), "SSL certification file used to secure etcd communication")
flag.StringVar(&cacert, "ca-cert", env("ETCD_CACERT", ""), "SSL Certificate Authority file used to secure etcd communication")
flag.StringVar(&username, "username", env("ETCD_USERNAME", ""), "Username used to support etcd basic auth")
flag.StringVar(&password, "password", env("ETCD_PASSWORD", ""), "Password used to support etcd basic auth")
flag.DurationVar(&config.ReadTimeout, "rtimeout", 2*time.Second, "read timeout")
flag.BoolVar(&config.RoundRobin, "round-robin", true, "round robin A/AAAA replies")
flag.BoolVar(&config.NSRotate, "ns-rotate", true, "round robin selection of nameservers from among those listed")
flag.BoolVar(&stub, "stubzones", false, "support stub zones")
flag.BoolVar(&config.Verbose, "verbose", false, "log queries")
flag.BoolVar(&config.Systemd, "systemd", boolEnv("SKYDNS_SYSTEMD", false), "bind to socket(s) activated by systemd (ignore -addr)")
// Version
flag.BoolVar(&config.Version, "version", false, "Print the version and exit.")
// TTl
// Minttl
flag.StringVar(&config.Hostmaster, "hostmaster", "hostmaster@skydns.local.", "hostmaster email address to use")
flag.IntVar(&config.SCache, "scache", server.SCacheCapacity, "capacity of the signature cache")
flag.IntVar(&config.RCache, "rcache", 0, "capacity of the response cache") // default to 0 for now
flag.IntVar(&config.RCacheTtl, "rcache-ttl", server.RCacheTtl, "TTL of the response cache")
// Ndots
flag.IntVar(&config.Ndots, "ndots", intEnv("SKYDNS_NDOTS", server.Ndots), "How many labels a name should have before we allow forwarding")
flag.StringVar(&msg.PathPrefix, "path-prefix", env("SKYDNS_PATH_PREFIX", "skydns"), "backend(etcd) path prefix, default: skydns")
}
func main() {
flag.Parse()
if config.Version {
fmt.Printf("skydns server version: %s\n", server.Version)
os.Exit(0)
}
machines := strings.Split(machine, ",")
client, err := newEtcdClient(machines, tlspem, tlskey, cacert, username, password)
if err != nil {
panic(err)
}
if nameserver != "" {
for _, hostPort := range strings.Split(nameserver, ",") {
if err := validateHostPort(hostPort); err != nil {
log.Fatalf("skydns: nameserver is invalid: %s", err)
}
config.Nameservers = append(config.Nameservers, hostPort)
}
}
if err := validateHostPort(config.DnsAddr); err != nil {
log.Fatalf("skydns: addr is invalid: %s", err)
}
if err := loadConfig(client, config); err != nil {
log.Fatalf("skydns: %s", err)
}
if err := server.SetDefaults(config); err != nil {
log.Fatalf("skydns: defaults could not be set from /etc/resolv.conf: %v", err)
}
if config.Local != "" {
config.Local = dns.Fqdn(config.Local)
}
backend := backendetcd.NewBackend(client, ctx, &backendetcd.Config{
Ttl: config.Ttl,
Priority: config.Priority,
})
s := server.New(backend, config)
if stub {
s.UpdateStubZones()
go func() {
duration := 1 * time.Second
var watcher etcd.Watcher
watcher = client.Watcher(msg.Path(config.Domain)+"/dns/stub/", &etcd.WatcherOptions{AfterIndex: 0, Recursive: true})
for {
_, err := watcher.Next(ctx)
if err != nil {
//
log.Printf("skydns: stubzone update failed, sleeping %s + ~3s", duration)
time.Sleep(duration + (time.Duration(rand.Float32() * 3e9))) // Add some random.
duration *= 2
if duration > 32*time.Second {
duration = 32 * time.Second
}
} else {
s.UpdateStubZones()
log.Printf("skydns: stubzone update")
duration = 1 * time.Second // reset
}
}
}()
}
if err := metrics.Metrics(); err != nil {
log.Fatalf("skydns: %s", err)
} else {
log.Printf("skydns: metrics enabled on :%s%s", metrics.Port, metrics.Path)
}
if err := s.Run(); err != nil {
log.Fatalf("skydns: %s", err)
}
}
func loadConfig(client etcd.KeysAPI, config *server.Config) error {
// Override what isn't set yet from the command line.
configPath := "/" + msg.PathPrefix + "/config"
resp, err := client.Get(ctx, configPath, nil)
if err != nil {
log.Printf("skydns: falling back to default configuration, could not read from etcd: %s", err)
return nil
}
if err := json.Unmarshal([]byte(resp.Node.Value), config); err != nil {
return fmt.Errorf("failed to unmarshal config: %s", err.Error())
}
return nil
}
func validateHostPort(hostPort string) error {
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
return err
}
if ip := net.ParseIP(host); ip == nil {
return fmt.Errorf("bad IP address: %s", host)
}
if p, _ := strconv.Atoi(port); p < 1 || p > 65535 {
return fmt.Errorf("bad port number %s", port)
}
return nil
}
func newEtcdClient(machines []string, certFile, keyFile, caFile, username, password string) (etcd.KeysAPI, error) {
t, err := newHTTPSTransport(certFile, keyFile, caFile)
if err != nil {
return nil, err
}
cli, err := etcd.New(etcd.Config{
Endpoints: machines,
Transport: t,
Username: username,
Password: password,
})
if err != nil {
return nil, err
}
return etcd.NewKeysAPI(cli), nil
}
func newHTTPSTransport(certFile, keyFile, caFile string) (*http.Transport, error) {
info := transport.TLSInfo{
CertFile: certFile,
KeyFile: keyFile,
CAFile: caFile,
}
cfg, err := info.ClientConfig()
if err != nil {
return nil, err
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: cfg,
}
return tr, nil
}