From 8c6c6929267854ad7a314935c6ea05b0d845107a Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Fri, 3 Jul 2015 13:39:47 +0100 Subject: [PATCH 001/180] Seed the math/rand generator from the time --- ipam/ring/ring.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ipam/ring/ring.go b/ipam/ring/ring.go index 1d55219e..2105939c 100644 --- a/ipam/ring/ring.go +++ b/ipam/ring/ring.go @@ -10,6 +10,7 @@ import ( "io" "math/rand" "sort" + "time" "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/ipam/address" @@ -518,3 +519,7 @@ func (r *Ring) PeerNames() map[router.PeerName]struct{} { return res } + +func init() { + rand.Seed(time.Now().UTC().UnixNano()) +} From 6097dc8aaaef343e8795118844d3aec77b017dfa Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Wed, 1 Jul 2015 16:48:46 +0100 Subject: [PATCH 002/180] Add wait forever capability to EnsureInterface --- net/if.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/net/if.go b/net/if.go index 9cea43bc..3cf3baab 100644 --- a/net/if.go +++ b/net/if.go @@ -2,6 +2,7 @@ package net import ( "fmt" + "math" "net" "time" ) @@ -10,11 +11,17 @@ const ( sleepTime = 100 * time.Millisecond ) +// Wait `wait` seconds for an interface to come up. Pass zero to check once +// and return immediately, or a negative value to wait indefinitely. func EnsureInterface(ifaceName string, wait int) (iface *net.Interface, err error) { if iface, err = findInterface(ifaceName); err == nil || wait == 0 { return } - for i := time.Duration(wait) * time.Second / sleepTime; err != nil && i > 0; i-- { + i := int64(math.MaxInt64) + if wait > 0 { + i = int64(time.Duration(wait) * time.Second / sleepTime) + } + for ; err != nil && i > 0; i-- { time.Sleep(sleepTime) iface, err = findInterface(ifaceName) } From 227cb11f255204517b9fa9c1c068d81e48017496 Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Wed, 1 Jul 2015 16:53:09 +0100 Subject: [PATCH 003/180] Router, DNS and proxy wait forever by default --- prog/weavedns/Dockerfile | 2 +- prog/weavedns/main.go | 2 +- prog/weaver/Dockerfile | 2 +- prog/weaver/main.go | 2 +- prog/weavewait/main.go | 8 ++++---- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/prog/weavedns/Dockerfile b/prog/weavedns/Dockerfile index d7af8837..883b34b8 100644 --- a/prog/weavedns/Dockerfile +++ b/prog/weavedns/Dockerfile @@ -3,4 +3,4 @@ MAINTAINER Weaveworks Inc WORKDIR /home/weave ADD ./weavedns /home/weave/ EXPOSE 53/udp -ENTRYPOINT ["/home/weave/weavedns", "-wait", "20"] +ENTRYPOINT ["/home/weave/weavedns"] diff --git a/prog/weavedns/main.go b/prog/weavedns/main.go index 21193da6..69832eaf 100644 --- a/prog/weavedns/main.go +++ b/prog/weavedns/main.go @@ -46,7 +46,7 @@ func main() { flag.StringVar(&ifaceName, "iface", "", "name of interface to use for multicast") flag.StringVar(&apiPath, "api", "unix:///var/run/docker.sock", "path to Docker API socket") flag.StringVar(&domain, "domain", weavedns.DefaultLocalDomain, "local domain (ie, 'weave.local.')") - flag.IntVar(&wait, "wait", 0, "number of seconds to wait for interface to be created and come up") + flag.IntVar(&wait, "wait", -1, "number of seconds to wait for interfaces to come up (0=don't wait, -1=wait forever)") flag.IntVar(&dnsPort, "dnsport", weavedns.DefaultServerPort, "port to listen to DNS requests") flag.StringVar(&httpIfaceName, "httpiface", "", "interface on which to listen for HTTP requests (defaults to empty string which listens on all interfaces)") flag.IntVar(&httpPort, "httpport", weavedns.DefaultHTTPPort, "port to listen to HTTP requests") diff --git a/prog/weaver/Dockerfile b/prog/weaver/Dockerfile index 437fc9e0..e91764e0 100644 --- a/prog/weaver/Dockerfile +++ b/prog/weaver/Dockerfile @@ -2,4 +2,4 @@ FROM scratch MAINTAINER Weaveworks Inc WORKDIR /home/weave ADD ./weaver /home/weave/ -ENTRYPOINT ["/home/weave/weaver", "-wait", "20"] +ENTRYPOINT ["/home/weave/weaver"] diff --git a/prog/weaver/main.go b/prog/weaver/main.go index d0ac8596..c17a7d46 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -64,7 +64,7 @@ func main() { flag.StringVar(&routerName, "name", "", "name of router (defaults to MAC of interface)") flag.StringVar(&nickName, "nickname", "", "nickname of peer (defaults to hostname)") flag.StringVar(&password, "password", "", "network password") - flag.IntVar(&wait, "wait", 0, "number of seconds to wait for interface to be created and come up (0 = don't wait)") + flag.IntVar(&wait, "wait", -1, "number of seconds to wait for interface to come up (0=don't wait, -1=wait forever)") flag.BoolVar(&debug, "debug", false, "enable debug logging") flag.BoolVar(&pktdebug, "pktdebug", false, "enable per-packet debug logging") flag.StringVar(&prof, "profile", "", "enable profiling and write profiles to given path") diff --git a/prog/weavewait/main.go b/prog/weavewait/main.go index 3cb78663..0acd5f74 100644 --- a/prog/weavewait/main.go +++ b/prog/weavewait/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "math" "os" "os/exec" "os/signal" @@ -17,20 +18,19 @@ func main() { } args := os.Args[1:] - signalWait := 20 + signalWait := time.Duration(math.MaxInt64) if args[0] == "-s" { signalWait = 0 args = args[1:] } - interfaceWait := 20 - signalWait usr2 := make(chan os.Signal) signal.Notify(usr2, syscall.SIGUSR2) select { case <-usr2: - case <-time.After(time.Duration(signalWait) * time.Second): + case <-time.After(signalWait): } - _, err := net.EnsureInterface("ethwe", interfaceWait) + _, err := net.EnsureInterface("ethwe", -1) checkErr(err) binary, err := exec.LookPath(args[0]) From a3a7a198702910afeac0bc2b8367bbd658167c4a Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Fri, 3 Jul 2015 14:28:18 +0100 Subject: [PATCH 004/180] simplifying refactor --- prog/weavewait/main.go | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/prog/weavewait/main.go b/prog/weavewait/main.go index 0acd5f74..9b1151bf 100644 --- a/prog/weavewait/main.go +++ b/prog/weavewait/main.go @@ -2,12 +2,10 @@ package main import ( "fmt" - "math" "os" "os/exec" "os/signal" "syscall" - "time" "github.com/weaveworks/weave/net" ) @@ -16,20 +14,16 @@ func main() { if len(os.Args) <= 1 { os.Exit(0) } - args := os.Args[1:] - signalWait := time.Duration(math.MaxInt64) + if args[0] == "-s" { - signalWait = 0 args = args[1:] + } else { + usr2 := make(chan os.Signal) + signal.Notify(usr2, syscall.SIGUSR2) + <-usr2 } - usr2 := make(chan os.Signal) - signal.Notify(usr2, syscall.SIGUSR2) - select { - case <-usr2: - case <-time.After(signalWait): - } _, err := net.EnsureInterface("ethwe", -1) checkErr(err) From 7821412bf786844919afd2d104671cbf11fd214b Mon Sep 17 00:00:00 2001 From: Paul Bellamy Date: Thu, 2 Jul 2015 15:43:03 +0100 Subject: [PATCH 005/180] [proxy] print all stderr from callWeave to the proxy logs, even if successful --- proxy/common.go | 9 ++++++--- proxy/proxy.go | 4 ++-- proxy/start_container_interceptor.go | 8 +++++--- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/proxy/common.go b/proxy/common.go index 7231226c..985fae9a 100644 --- a/proxy/common.go +++ b/proxy/common.go @@ -18,13 +18,16 @@ var ( weaveWaitEntrypoint = []string{"/w/w"} ) -func callWeave(args ...string) ([]byte, error) { +func callWeave(args ...string) ([]byte, []byte, error) { args = append([]string{"--local"}, args...) Log.Debug("Calling weave", args) cmd := exec.Command("./weave", args...) cmd.Env = []string{"PROCFS=/hostproc", "PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"} - out, err := cmd.CombinedOutput() - return out, err + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err := cmd.Run() + return stdout.Bytes(), stderr.Bytes(), err } func marshalRequestBody(r *http.Request, body interface{}) error { diff --git a/proxy/proxy.go b/proxy/proxy.go index 0812ab4b..2993d00d 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -57,9 +57,9 @@ func NewProxy(c Config) (*Proxy, error) { p.client = client if !p.WithoutDNS { - dockerBridgeIP, err := callWeave("docker-bridge-ip") + dockerBridgeIP, stderr, err := callWeave("docker-bridge-ip") if err != nil { - return nil, err + return nil, fmt.Errorf(string(stderr)) } p.dockerBridgeIP = string(dockerBridgeIP) } diff --git a/proxy/start_container_interceptor.go b/proxy/start_container_interceptor.go index b7da0505..1a4de456 100644 --- a/proxy/start_container_interceptor.go +++ b/proxy/start_container_interceptor.go @@ -30,9 +30,11 @@ func (i *startContainerInterceptor) InterceptResponse(r *http.Response) error { args := []string{"attach"} args = append(args, cidrs...) args = append(args, "--or-die", container.ID) - if output, err := callWeave(args...); err != nil { - Log.Warningf("Attaching container %s to weave network failed: %s", container.ID, string(output)) - return errors.New(string(output)) + if _, stderr, err := callWeave(args...); err != nil { + Log.Warningf("Attaching container %s to weave network failed: %s", container.ID, string(stderr)) + return errors.New(string(stderr)) + } else if len(stderr) > 0 { + Log.Warningf("Attaching container %s to weave network: %s", container.ID, string(stderr)) } return i.proxy.client.KillContainer(docker.KillContainerOptions{ID: container.ID, Signal: docker.SIGUSR2}) From 4dbd657a264657ec1a9fba8a26052af245662dce Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Fri, 3 Jul 2015 20:32:27 +0100 Subject: [PATCH 006/180] import gopacket from github instaead of google code The latter redirects to the former, which breaks `go get`. Closes #1071. --- prog/weaver/main.go | 2 +- router/ethernet_decoder.go | 4 ++-- router/forwarder.go | 4 ++-- router/pcap.go | 2 +- router/router.go | 2 +- router/udp_sender.go | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/prog/weaver/main.go b/prog/weaver/main.go index c17a7d46..03f2412c 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -11,8 +11,8 @@ import ( "runtime" "strings" - "code.google.com/p/gopacket/layers" "github.com/davecheney/profile" + "github.com/google/gopacket/layers" "github.com/gorilla/mux" . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" diff --git a/router/ethernet_decoder.go b/router/ethernet_decoder.go index 6588c0ad..4fe0481a 100644 --- a/router/ethernet_decoder.go +++ b/router/ethernet_decoder.go @@ -2,8 +2,8 @@ package router import ( "bytes" - "code.google.com/p/gopacket" - "code.google.com/p/gopacket/layers" + "github.com/google/gopacket" + "github.com/google/gopacket/layers" "log" "net" ) diff --git a/router/forwarder.go b/router/forwarder.go index a4cec472..e3386936 100644 --- a/router/forwarder.go +++ b/router/forwarder.go @@ -1,8 +1,8 @@ package router import ( - "code.google.com/p/gopacket" - "code.google.com/p/gopacket/layers" + "github.com/google/gopacket" + "github.com/google/gopacket/layers" "syscall" "time" ) diff --git a/router/pcap.go b/router/pcap.go index 761d4e1d..2b2c3b5d 100644 --- a/router/pcap.go +++ b/router/pcap.go @@ -1,8 +1,8 @@ package router import ( - "code.google.com/p/gopacket/pcap" "fmt" + "github.com/google/gopacket/pcap" ) type PcapIO struct { diff --git a/router/router.go b/router/router.go index ab671a0d..141dfc38 100644 --- a/router/router.go +++ b/router/router.go @@ -11,7 +11,7 @@ import ( "syscall" "time" - "code.google.com/p/gopacket/layers" + "github.com/google/gopacket/layers" . "github.com/weaveworks/weave/common" ) diff --git a/router/udp_sender.go b/router/udp_sender.go index 9e91ee0b..e591c9dc 100644 --- a/router/udp_sender.go +++ b/router/udp_sender.go @@ -1,8 +1,8 @@ package router import ( - "code.google.com/p/gopacket" - "code.google.com/p/gopacket/layers" + "github.com/google/gopacket" + "github.com/google/gopacket/layers" "log" "net" "syscall" From bf73029d152537ec5dd4a50d99c9f61e82f6007c Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Fri, 3 Jul 2015 20:41:35 +0100 Subject: [PATCH 007/180] cosmetic: goimports -w . --- ipam/allocate.go | 1 + ipam/paxos/paxos.go | 1 + ipam/paxos/paxos_test.go | 3 ++- router/crypto.go | 7 ++++--- router/ethernet_decoder.go | 5 +++-- router/forwarder.go | 5 +++-- router/handshake_test.go | 3 ++- router/mocks_test.go | 3 ++- router/pcap.go | 1 + router/peers_test.go | 3 ++- router/udp_sender.go | 5 +++-- 11 files changed, 24 insertions(+), 13 deletions(-) diff --git a/ipam/allocate.go b/ipam/allocate.go index f2da3c74..0e4a9e4b 100644 --- a/ipam/allocate.go +++ b/ipam/allocate.go @@ -2,6 +2,7 @@ package ipam import ( "fmt" + "github.com/weaveworks/weave/ipam/address" ) diff --git a/ipam/paxos/paxos.go b/ipam/paxos/paxos.go index a69b91da..61fda181 100644 --- a/ipam/paxos/paxos.go +++ b/ipam/paxos/paxos.go @@ -2,6 +2,7 @@ package paxos import ( "fmt" + "github.com/weaveworks/weave/router" ) diff --git a/ipam/paxos/paxos_test.go b/ipam/paxos/paxos_test.go index cd704c5c..c1d5bfe0 100644 --- a/ipam/paxos/paxos_test.go +++ b/ipam/paxos/paxos_test.go @@ -2,10 +2,11 @@ package paxos import ( "fmt" - "github.com/weaveworks/weave/router" "math/rand" "testing" "time" + + "github.com/weaveworks/weave/router" ) type TestNode struct { diff --git a/router/crypto.go b/router/crypto.go index 19b0bcfa..291603d1 100644 --- a/router/crypto.go +++ b/router/crypto.go @@ -1,15 +1,16 @@ package router import ( - "code.google.com/p/go-bit/bit" - "code.google.com/p/go.crypto/nacl/box" - "code.google.com/p/go.crypto/nacl/secretbox" "crypto/rand" "crypto/sha256" "encoding/binary" "encoding/gob" "fmt" "sync" + + "code.google.com/p/go-bit/bit" + "code.google.com/p/go.crypto/nacl/box" + "code.google.com/p/go.crypto/nacl/secretbox" ) func GenerateKeyPair() (publicKey, privateKey *[32]byte, err error) { diff --git a/router/ethernet_decoder.go b/router/ethernet_decoder.go index 4fe0481a..f04c53e4 100644 --- a/router/ethernet_decoder.go +++ b/router/ethernet_decoder.go @@ -2,10 +2,11 @@ package router import ( "bytes" - "github.com/google/gopacket" - "github.com/google/gopacket/layers" "log" "net" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" ) type EthernetDecoder struct { diff --git a/router/forwarder.go b/router/forwarder.go index e3386936..6c55c368 100644 --- a/router/forwarder.go +++ b/router/forwarder.go @@ -1,10 +1,11 @@ package router import ( - "github.com/google/gopacket" - "github.com/google/gopacket/layers" "syscall" "time" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" ) type ForwardedFrame struct { diff --git a/router/handshake_test.go b/router/handshake_test.go index a72bf17c..1630d343 100644 --- a/router/handshake_test.go +++ b/router/handshake_test.go @@ -1,8 +1,9 @@ package router import ( - wt "github.com/weaveworks/weave/testing" "testing" + + wt "github.com/weaveworks/weave/testing" ) func TestFieldValidator(t *testing.T) { diff --git a/router/mocks_test.go b/router/mocks_test.go index 674eaa3a..dc0ec6c3 100644 --- a/router/mocks_test.go +++ b/router/mocks_test.go @@ -6,8 +6,9 @@ package router import ( - wt "github.com/weaveworks/weave/testing" "testing" + + wt "github.com/weaveworks/weave/testing" ) // Add to peers a connection from peers.ourself to p diff --git a/router/pcap.go b/router/pcap.go index 2b2c3b5d..36962f20 100644 --- a/router/pcap.go +++ b/router/pcap.go @@ -2,6 +2,7 @@ package router import ( "fmt" + "github.com/google/gopacket/pcap" ) diff --git a/router/peers_test.go b/router/peers_test.go index daf1e944..bf221642 100644 --- a/router/peers_test.go +++ b/router/peers_test.go @@ -2,9 +2,10 @@ package router import ( "fmt" - wt "github.com/weaveworks/weave/testing" "math/rand" "testing" + + wt "github.com/weaveworks/weave/testing" ) // TODO we should also test: diff --git a/router/udp_sender.go b/router/udp_sender.go index e591c9dc..28ef917a 100644 --- a/router/udp_sender.go +++ b/router/udp_sender.go @@ -1,11 +1,12 @@ package router import ( - "github.com/google/gopacket" - "github.com/google/gopacket/layers" "log" "net" "syscall" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" ) type UDPSender interface { From b8aa1d473ba1523ed42dfb1f6201cd6e45329c57 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 4 Jul 2015 02:53:36 +0100 Subject: [PATCH 008/180] remove dead code --- test/290_dns_fallback_test.sh | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/290_dns_fallback_test.sh b/test/290_dns_fallback_test.sh index 0767e8d7..9eee0f8f 100755 --- a/test/290_dns_fallback_test.sh +++ b/test/290_dns_fallback_test.sh @@ -2,9 +2,6 @@ . ./config.sh -DNS_ARGS="--no-cache" -[ -n "$DEBUG" ] && DNS_ARGS="--debug" - start_suite "Resolve a non-weave address" launch_dns_on $HOST1 10.2.254.1/24 From 910b57731db06441377837da90e071ec25fc0ea3 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 4 Jul 2015 03:19:27 +0100 Subject: [PATCH 009/180] remove stray -debug in tests --- test/500_weave_multi_cidr_test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/500_weave_multi_cidr_test.sh b/test/500_weave_multi_cidr_test.sh index 884d7c74..4a665f52 100755 --- a/test/500_weave_multi_cidr_test.sh +++ b/test/500_weave_multi_cidr_test.sh @@ -73,7 +73,7 @@ start_suite "Weave run/start/attach/detach/expose/hide with multiple cidr argume # specific address, i.e. we are assuming that IPAM always returns the # lowest available address in the subnet -weave_on $HOST1 launch-router -debug -iprange 10.2.3.0/24 +weave_on $HOST1 launch-router -iprange 10.2.3.0/24 launch_dns_on $HOST1 10.254.254.254/24 # Run container with three cidrs From ff2d7451e2fa823939483d9c4799b1c803acd883 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Mon, 29 Jun 2015 15:04:22 +0100 Subject: [PATCH 010/180] Remove -debug option, superceded by --log-level --- common/init.go | 5 ----- common/logging.go | 32 +++++++++++++++++++------------- common/sched_queue_test.go | 6 +++--- ipam/allocator_test.go | 4 ---- ipam/http_test.go | 1 - nameserver/addrs_test.go | 2 +- nameserver/cache_test.go | 4 ++-- nameserver/dns_test.go | 2 +- nameserver/mdns_client_test.go | 2 +- nameserver/mdns_server_test.go | 2 +- nameserver/mdns_test.go | 4 ++-- nameserver/server_cache_test.go | 6 +++--- nameserver/server_test.go | 4 ++-- nameserver/zone_lookup_test.go | 2 +- nameserver/zone_test.go | 4 ++-- prog/weavedns/main.go | 6 +++--- prog/weaveproxy/main.go | 8 +++----- prog/weaver/main.go | 6 +++--- site/troubleshooting.md | 7 ++++--- test/config.sh | 2 +- 20 files changed, 52 insertions(+), 57 deletions(-) delete mode 100644 common/init.go diff --git a/common/init.go b/common/init.go deleted file mode 100644 index 297a339e..00000000 --- a/common/init.go +++ /dev/null @@ -1,5 +0,0 @@ -package common - -func init() { - InitDefaultLogging(false) -} diff --git a/common/logging.go b/common/logging.go index e2ef9d1a..2cf9cff5 100644 --- a/common/logging.go +++ b/common/logging.go @@ -41,22 +41,28 @@ var ( Log *logrus.Logger ) -func InitLogging(level logrus.Level) { - if Log == nil { - Log = &logrus.Logger{ - Out: os.Stderr, - Formatter: standardTextFormatter, - Hooks: make(logrus.LevelHooks), - Level: level, - } +func init() { + Log = &logrus.Logger{ + Out: os.Stderr, + Formatter: standardTextFormatter, + Hooks: make(logrus.LevelHooks), + } +} + +func SetLogLevel(levelname string) { + level, err := logrus.ParseLevel(levelname) + if err != nil { + Log.Fatal(err) } Log.Level = level } -func InitDefaultLogging(debug bool) { - level := logrus.InfoLevel - if debug { - level = logrus.DebugLevel +// For backwards-compatibility with code that only has a boolean +func EnableDebugLogging(flag bool) { + switch { + case flag && Log.Level < logrus.DebugLevel: + Log.Level = logrus.DebugLevel + case !flag && Log.Level >= logrus.DebugLevel: + Log.Level = logrus.InfoLevel } - InitLogging(level) } diff --git a/common/sched_queue_test.go b/common/sched_queue_test.go index 5c733355..d9eb6830 100644 --- a/common/sched_queue_test.go +++ b/common/sched_queue_test.go @@ -10,7 +10,7 @@ import ( // Ensure we can add new calls while forwarding the clock func TestSchedCallsBasic(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestSchedCallsBasic starting") const testSecs = 1000 @@ -36,7 +36,7 @@ func TestSchedCallsBasic(t *testing.T) { // Ensure we can create a 100 seconds gap in the middle of the time travel func TestSchedCallsGap(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestSchedCallsGap starting") const testSecs = 1000 @@ -64,7 +64,7 @@ func TestSchedCallsGap(t *testing.T) { } func TestSchedCallsStop(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestSchedCallsStop starting") const testSecs = 1000 diff --git a/ipam/allocator_test.go b/ipam/allocator_test.go index fcd3027a..37802495 100644 --- a/ipam/allocator_test.go +++ b/ipam/allocator_test.go @@ -71,7 +71,6 @@ func TestAllocFree(t *testing.T) { } func TestBootstrap(t *testing.T) { - common.InitDefaultLogging(false) const ( donateSize = 5 donateStart = "10.0.1.7" @@ -163,7 +162,6 @@ func (alloc *Allocator) pause() func() { } func TestCancel(t *testing.T) { - common.InitDefaultLogging(false) const ( CIDR = "10.0.1.7/26" ) @@ -276,7 +274,6 @@ func TestTransfer(t *testing.T) { } func TestFakeRouterSimple(t *testing.T) { - common.InitDefaultLogging(false) const ( cidr = "10.0.1.7/22" ) @@ -291,7 +288,6 @@ func TestFakeRouterSimple(t *testing.T) { } func TestAllocatorFuzz(t *testing.T) { - common.InitDefaultLogging(false) const ( firstpass = 1000 secondpass = 20000 diff --git a/ipam/http_test.go b/ipam/http_test.go index f00ea0b2..97ce7a24 100644 --- a/ipam/http_test.go +++ b/ipam/http_test.go @@ -151,7 +151,6 @@ func TestHTTPCancel(t *testing.T) { } func impTestHTTPCancel(t *testing.T) { - common.InitDefaultLogging(true) var ( containerID = "deadbeef" testCIDR1 = "10.0.3.0/29" diff --git a/nameserver/addrs_test.go b/nameserver/addrs_test.go index 2118832b..00d1ba7d 100644 --- a/nameserver/addrs_test.go +++ b/nameserver/addrs_test.go @@ -9,7 +9,7 @@ import ( ) func TestAddrs(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestAddrs starting") ip, err := addrToIPv4("10.13.12.11") diff --git a/nameserver/cache_test.go b/nameserver/cache_test.go index f3a14cb0..d6e29c25 100644 --- a/nameserver/cache_test.go +++ b/nameserver/cache_test.go @@ -14,7 +14,7 @@ import ( // Check that the cache keeps its intended capacity constant func TestCacheLength(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestCacheLength starting") const cacheLen = 128 @@ -55,7 +55,7 @@ func TestCacheLength(t *testing.T) { // Check that the cache entries are ok func TestCacheEntries(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestCacheEntries starting") Log.Infoln("Checking cache consistency") diff --git a/nameserver/dns_test.go b/nameserver/dns_test.go index 1ec25147..3e001e6e 100644 --- a/nameserver/dns_test.go +++ b/nameserver/dns_test.go @@ -11,7 +11,7 @@ import ( // Check that we can prune an answer func TestPrune(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestPrune starting") questionMsg := new(dns.Msg) diff --git a/nameserver/mdns_client_test.go b/nameserver/mdns_client_test.go index 11f0bc2d..edeb1bf1 100644 --- a/nameserver/mdns_client_test.go +++ b/nameserver/mdns_client_test.go @@ -78,7 +78,7 @@ func RunLocalMulticastServer() (*dns.Server, error) { } func setup(t *testing.T) (*MDNSClient, *dns.Server, error) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) server, err := RunLocalMulticastServer() if err != nil { diff --git a/nameserver/mdns_server_test.go b/nameserver/mdns_server_test.go index 3fe89fe0..5022af21 100644 --- a/nameserver/mdns_server_test.go +++ b/nameserver/mdns_server_test.go @@ -17,7 +17,7 @@ func TestServerSimpleQuery(t *testing.T) { testInAddr1 = "10.20.20.10.in-addr.arpa." ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestServerSimpleQuery starting") mzone := newMockedZoneWithRecords([]ZoneRecord{testRecord1, testRecord2}) diff --git a/nameserver/mdns_test.go b/nameserver/mdns_test.go index 867eedec..6acf1ac8 100644 --- a/nameserver/mdns_test.go +++ b/nameserver/mdns_test.go @@ -12,7 +12,7 @@ import ( // Check that we can use a regular mDNS server with a regular mDNS client func TestClientServerSimpleQuery(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) testRecord1 := Record{"test.weave.local.", net.ParseIP("10.2.2.1"), 0, 0, 0} testInAddr1 := "1.2.2.10.in-addr.arpa." @@ -86,7 +86,7 @@ func TestClientServerSimpleQuery(t *testing.T) { // Check that we can use a use "insistent" queries func TestClientServerInsistentQuery(t *testing.T) { - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) testRecord1 := Record{"test.weave.local.", net.ParseIP("10.2.2.1"), 0, 0, 0} testInAddr1 := "1.2.2.10.in-addr.arpa." diff --git a/nameserver/server_cache_test.go b/nameserver/server_cache_test.go index 35f3dc82..394710d6 100644 --- a/nameserver/server_cache_test.go +++ b/nameserver/server_cache_test.go @@ -19,7 +19,7 @@ func TestServerDbCacheInvalidation(t *testing.T) { testName2 = "second.weave.local." ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestServerDbCacheInvalidation starting") clk := newMockedClock() @@ -177,7 +177,7 @@ func TestServerCacheExpiration(t *testing.T) { negativeLocalTTL = 10 ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestServerCacheExpiration starting") clk := newMockedClock() @@ -265,7 +265,7 @@ func TestServerCacheRefresh(t *testing.T) { refreshInterval = int(DefaultLocalTTL) / 3 ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestServerCacheRefresh starting") clk := newMockedClock() diff --git a/nameserver/server_test.go b/nameserver/server_test.go index ab19362b..9c4a1976 100644 --- a/nameserver/server_test.go +++ b/nameserver/server_test.go @@ -40,7 +40,7 @@ func TestUDPDNSServer(t *testing.T) { ) testCIDR1 := testAddr1 + "/24" - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestUDPDNSServer starting") zone, err := NewZoneDb(ZoneConfig{}) @@ -137,7 +137,7 @@ func TestTCPDNSServer(t *testing.T) { nonLocalName = "weave.works." ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestTCPDNSServer starting") zone, err := NewZoneDb(ZoneConfig{}) diff --git a/nameserver/zone_lookup_test.go b/nameserver/zone_lookup_test.go index 5f86f34c..31789133 100644 --- a/nameserver/zone_lookup_test.go +++ b/nameserver/zone_lookup_test.go @@ -23,7 +23,7 @@ func TestZoneRefresh(t *testing.T) { addr4 = "10.2.8.7" ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) Log.Infoln("TestZoneRefresh starting") clk := newMockedClock() diff --git a/nameserver/zone_test.go b/nameserver/zone_test.go index 04a7e9d9..2a3a1467 100644 --- a/nameserver/zone_test.go +++ b/nameserver/zone_test.go @@ -20,7 +20,7 @@ func TestZone(t *testing.T) { revName1Addr1 = "1.2.9.10.in-addr.arpa." ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) zone, err := NewZoneDb(ZoneConfig{}) require.NoError(t, err) @@ -136,7 +136,7 @@ func TestDeleteRecords(t *testing.T) { addr2 = "10.2.7.8/24" ) - InitDefaultLogging(testing.Verbose()) + EnableDebugLogging(testing.Verbose()) zone, err := NewZoneDb(ZoneConfig{}) require.NoError(t, err) diff --git a/prog/weavedns/main.go b/prog/weavedns/main.go index 7320a5cf..1b0b46bb 100644 --- a/prog/weavedns/main.go +++ b/prog/weavedns/main.go @@ -38,7 +38,7 @@ func main() { cacheLen int cacheDisabled bool watch bool - debug bool + logLevel string err error ) @@ -53,7 +53,7 @@ func main() { flag.IntVar(&cacheLen, "cache", weavedns.DefaultCacheLen, "cache length") flag.IntVar(&ttl, "ttl", weavedns.DefaultLocalTTL, "TTL (in secs) for responses for local names") flag.BoolVar(&watch, "watch", true, "watch the docker socket for container events") - flag.BoolVar(&debug, "debug", false, "output debugging info to stderr") + flag.StringVar(&logLevel, "log-level", "info", "logging level (debug, info, warning, error)") // advanced options flag.IntVar(&negTTL, "neg-ttl", 0, "negative TTL (in secs) for unanswered queries for local names (0=same value as -ttl") flag.IntVar(&refreshInterval, "refresh", weavedns.DefaultRefreshInterval, "refresh interval (in secs) for local names (0=disable)") @@ -70,7 +70,7 @@ func main() { os.Exit(0) } - InitDefaultLogging(debug) + SetLogLevel(logLevel) Log.Infof("[main] WeaveDNS version %s\n", version) // first thing in log: the version var iface *net.Interface diff --git a/prog/weaveproxy/main.go b/prog/weaveproxy/main.go index 150b4788..23c78a29 100644 --- a/prog/weaveproxy/main.go +++ b/prog/weaveproxy/main.go @@ -17,14 +17,14 @@ var ( func main() { var ( - debug bool justVersion bool + logLevel = "info" c = proxy.Config{ListenAddrs: defaultListenAddrs} ) c.Version = version - getopt.BoolVarLong(&debug, "debug", 'd', "log debugging information") getopt.BoolVarLong(&justVersion, "version", 0, "print version and exit") + getopt.StringVarLong(&logLevel, "log-level", 0, "logging level (debug, info, warning, error)", "info") getopt.ListVar(&c.ListenAddrs, 'H', fmt.Sprintf("address on which to listen (default %s)", defaultListenAddrs)) getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipalloc", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR") getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipam", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR (deprecated; please use --no-default-ipalloc") @@ -46,9 +46,7 @@ func main() { Log.Fatalf("Cannot use both '--with-dns' and '--without-dns' flags") } - if debug { - InitDefaultLogging(true) - } + SetLogLevel(logLevel) Log.Infoln("weave proxy", version) Log.Infoln("Command line arguments:", strings.Join(os.Args[1:], " ")) diff --git a/prog/weaver/main.go b/prog/weaver/main.go index 970b97c6..be5e50ae 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -39,8 +39,8 @@ func main() { nickName string password string wait int - debug bool pktdebug bool + logLevel string prof string bufSzMB int noDiscovery bool @@ -59,7 +59,7 @@ func main() { flag.StringVar(&nickName, "nickname", "", "nickname of peer (defaults to hostname)") flag.StringVar(&password, "password", "", "network password") flag.IntVar(&wait, "wait", -1, "number of seconds to wait for interface to come up (0=don't wait, -1=wait forever)") - flag.BoolVar(&debug, "debug", false, "enable debug logging") + flag.StringVar(&logLevel, "log-level", "info", "logging level (debug, info, warning, error)") flag.BoolVar(&pktdebug, "pktdebug", false, "enable per-packet debug logging") flag.StringVar(&prof, "profile", "", "enable profiling and write profiles to given path") flag.IntVar(&config.ConnLimit, "connlimit", 30, "connection limit (0 for unlimited)") @@ -73,7 +73,7 @@ func main() { flag.Parse() peers = flag.Args() - InitDefaultLogging(debug) + SetLogLevel(logLevel) if justVersion { fmt.Printf("weave router %s\n", version) os.Exit(0) diff --git a/site/troubleshooting.md b/site/troubleshooting.md index 8c05a828..e83ecd36 100644 --- a/site/troubleshooting.md +++ b/site/troubleshooting.md @@ -20,9 +20,10 @@ Check the weave container logs with A reasonable amount of information, and all errors, get logged there. -The log verbosity can be increased by supplying the `-debug` flag when -launching weave. To log information on a per-packet basis use -`-pktdebug` - be warned, this can produce a lot of output. +The log verbosity can be increased by supplying the +`--log-level=debug` option when launching weave. To log information on +a per-packet basis use `-pktdebug` - be warned, this can produce a lot +of output. Another useful debugging technique is to attach standard packet capture and analysis tools, such as tcpdump and wireshark, to the diff --git a/test/config.sh b/test/config.sh index 71a4afa3..90a703cf 100644 --- a/test/config.sh +++ b/test/config.sh @@ -43,7 +43,7 @@ CHECK_ETHWE_UP="grep ^1$ /sys/class/net/ethwe/carrier" DOCKER_PORT=2375 WEAVEDNS_ARGS="--no-cache" -[ -n "$DEBUG" ] && WEAVEDNS_ARGS="$WEAVEDNS_ARGS --debug" +[ -n "$DEBUG" ] && WEAVEDNS_ARGS="$WEAVEDNS_ARGS --log-level=debug" upload_executable() { From d0641062c0342a747c102e381673eeaf4218d47f Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 4 Jul 2015 04:38:18 +0100 Subject: [PATCH 011/180] pass common `launch` args to all three components ATM that's just --loglevel=... Closes #1043. --- weave | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/weave b/weave index 49f786ac..cba1cef9 100755 --- a/weave +++ b/weave @@ -946,6 +946,18 @@ proxy_addr() { # launch helpers ###################################################################### +common_launch_args() { + args="" + while [ $# -gt 0 ] ; do + case "$1" in + --log-level=*) + args="$args $1" + esac + shift + done + echo "$args" +} + launch_router() { create_bridge # We set the router name to the bridge mac since that is @@ -1113,9 +1125,10 @@ case "$COMMAND" in check_not_running $CONTAINER_NAME $BASE_IMAGE check_not_running $DNS_CONTAINER_NAME $BASE_DNS_IMAGE check_not_running $PROXY_CONTAINER_NAME $EXEC_IMAGE + COMMON_ARGS=$(common_launch_args "$@") launch_router "$@" - launch_dns - launch_proxy + launch_dns $COMMON_ARGS + launch_proxy $COMMON_ARGS ;; launch-router) check_not_running $CONTAINER_NAME $BASE_IMAGE From 156597a9654751941797f79c49c24f5a137f147e Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 4 Jul 2015 18:04:25 +0100 Subject: [PATCH 012/180] small simplifying refactor: use shortcircuit boolean expressions --- weave | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/weave b/weave index 49f786ac..620e5e51 100755 --- a/weave +++ b/weave @@ -833,9 +833,7 @@ ipam_cidrs() { IPAM_CIDRs="" if [ $# -eq 0 ] ; then # If no addresses passed in, get one in the default subnet - if ! IPAM_CIDRS=$(call_weave POST /ip/$CONTAINER_ID) ; then - return 1 - fi + IPAM_CIDRS=$(call_weave POST /ip/$CONTAINER_ID) || return 1 if [ "$IPAM_CIDRS" = "404 page not found" ] ; then echo "No IP address supplied (use the -iprange option on 'weave launch' to enable IP address allocation)" >&2 return 1 @@ -849,9 +847,7 @@ ipam_cidrs() { else IPAM_URL=/ip/$CONTAINER_ID/"${1#net:}" fi - if ! CIDR=$(call_weave POST $IPAM_URL) ; then - return 1 - fi + CIDR=$(call_weave POST $IPAM_URL) || return 1 if [ "$CIDR" = "404 page not found" ] ; then echo "IP address allocation must be enabled to use 'net:'" >&2 return 1 From 5559f1df2e4d50b4f08d600a633e57ced5490b6b Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 4 Jul 2015 18:14:13 +0100 Subject: [PATCH 013/180] cosmetic: remove some unnecessary quoting for consistency, since we don't quote the same term anywhere else --- weave | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/weave b/weave index 620e5e51..adb97c8d 100755 --- a/weave +++ b/weave @@ -1279,7 +1279,7 @@ case "$COMMAND" in add_iptables_rule nat WEAVE -d $CIDR ! -s $CIDR -j MASQUERADE add_iptables_rule nat WEAVE -s $CIDR ! -d $CIDR -j MASQUERADE if [ -n "$FQDN" ] ; then - when_dns_running put_dns_fqdn 'weave:expose' $FQDN $CIDR + when_dns_running put_dns_fqdn weave:expose $FQDN $CIDR fi fi done @@ -1295,7 +1295,7 @@ case "$COMMAND" in ip addr del dev $BRIDGE $CIDR delete_iptables_rule nat WEAVE -d $CIDR ! -s $CIDR -j MASQUERADE delete_iptables_rule nat WEAVE -s $CIDR ! -d $CIDR -j MASQUERADE - when_dns_running delete_dns 'weave:expose' $CIDR + when_dns_running delete_dns weave:expose $CIDR fi done for CIDR in $IPAM_CIDRS ; do From 6596c8b1a7fa540439562625203878e2b87b5da3 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 4 Jul 2015 19:13:13 +0100 Subject: [PATCH 014/180] make container aliveness check part of the ipam & dns API ...rather than conducting it implicitly when an ID "looks like" a container ID. Closes #971 --- common/docker/client.go | 16 ---------------- ipam/http.go | 4 ++-- nameserver/http.go | 2 +- weave | 22 ++++++++++++++++------ 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/common/docker/client.go b/common/docker/client.go index 71cdf316..6774c213 100644 --- a/common/docker/client.go +++ b/common/docker/client.go @@ -1,20 +1,10 @@ package docker import ( - "regexp" - "github.com/fsouza/go-dockerclient" . "github.com/weaveworks/weave/common" ) -// Regexp that matches container IDs -var containerIDregexp = regexp.MustCompile("^[a-f0-9]+$") - -// IsContainerID returns True if the string provided is a valid container id -func IsContainerID(idStr string) bool { - return containerIDregexp.MatchString(idStr) -} - // An observer for container events type ContainerObserver interface { ContainerDied(ident string) error @@ -62,12 +52,6 @@ func (c *Client) AddObserver(ob ContainerObserver) error { // IsContainerNotRunning returns true if we have checked with Docker that the ID is not running func (c *Client) IsContainerNotRunning(idStr string) bool { - if !IsContainerID(idStr) { - Log.Debugf("[docker] '%s' does not seem to be a container id", idStr) - return false - } - - // check with Docker whether the container is really running container, err := c.InspectContainer(idStr) if err == nil { return !container.State.Running diff --git a/ipam/http.go b/ipam/http.go index 0b665385..911196aa 100644 --- a/ipam/http.go +++ b/ipam/http.go @@ -78,7 +78,7 @@ func (alloc *Allocator) HandleHTTP(router *mux.Router, defaultSubnet address.CID badRequest(w, fmt.Errorf("Unable to allocate: %s", err)) return } - if dockerCli != nil && dockerCli.IsContainerNotRunning(ident) { + if r.FormValue("check-alive") == "true" && dockerCli != nil && dockerCli.IsContainerNotRunning(ident) { common.Log.Infof("[allocator] '%s' is not running: freeing %s", ident, addr) alloc.Free(ident, addr) return @@ -95,7 +95,7 @@ func (alloc *Allocator) HandleHTTP(router *mux.Router, defaultSubnet address.CID badRequest(w, err) return } - if dockerCli != nil && dockerCli.IsContainerNotRunning(ident) { + if r.FormValue("check-alive") == "true" && dockerCli != nil && dockerCli.IsContainerNotRunning(ident) { common.Log.Infof("[allocator] '%s' is not running: freeing %s", ident, newAddr) alloc.Free(ident, newAddr) return diff --git a/nameserver/http.go b/nameserver/http.go index 42dd3231..02e1d380 100644 --- a/nameserver/http.go +++ b/nameserver/http.go @@ -74,7 +74,7 @@ func ServeHTTP(listener net.Listener, version string, server *DNSServer, dockerC } // oh, I already know this. whatever. } - if dockerCli != nil && dockerCli.IsContainerNotRunning(idStr) { + if r.FormValue("check-alive") == "true" && dockerCli != nil && dockerCli.IsContainerNotRunning(idStr) { Log.Infof("[http] '%s' is not running: removing", idStr) server.Zone.DeleteRecords(idStr, name, ip) } diff --git a/weave b/weave index adb97c8d..20564452 100755 --- a/weave +++ b/weave @@ -767,12 +767,17 @@ with_container_fqdn() { # Register FQDN in $2 as names for addresses $3.. under full container ID $1 put_dns_fqdn() { + CHECK_ALIVE="-d check-alive=true" + if [ "$1" = "--no-check-alive" ] ; then + CHECK_ALIVE= + shift 1 + fi CONTAINER_ID="$1" FQDN="$2" shift 2 for ADDR in "$@" ; do - call_dns PUT /name/$CONTAINER_ID/${ADDR%/*} --data-urlencode fqdn=$FQDN || true + call_dns PUT /name/$CONTAINER_ID/${ADDR%/*} --data-urlencode fqdn=$FQDN $CHECK_ALIVE || true done } @@ -827,13 +832,18 @@ ipam_claim() { # $1 is the full container id and following args are previously parsed CIDR_ARGS. # Returns ALL_CIDRS and IPAM_CIDRS ipam_cidrs() { + CHECK_ALIVE="?check-alive=true" + if [ "$1" = "--no-check-alive" ] ; then + CHECK_ALIVE= + shift 1 + fi CONTAINER_ID="$1" shift 1 ALL_CIDRS="" IPAM_CIDRs="" if [ $# -eq 0 ] ; then # If no addresses passed in, get one in the default subnet - IPAM_CIDRS=$(call_weave POST /ip/$CONTAINER_ID) || return 1 + IPAM_CIDRS=$(call_weave POST /ip/$CONTAINER_ID$CHECK_ALIVE) || return 1 if [ "$IPAM_CIDRS" = "404 page not found" ] ; then echo "No IP address supplied (use the -iprange option on 'weave launch' to enable IP address allocation)" >&2 return 1 @@ -847,7 +857,7 @@ ipam_cidrs() { else IPAM_URL=/ip/$CONTAINER_ID/"${1#net:}" fi - CIDR=$(call_weave POST $IPAM_URL) || return 1 + CIDR=$(call_weave POST $IPAM_URL$CHECK_ALIVE) || return 1 if [ "$CIDR" = "404 page not found" ] ; then echo "IP address allocation must be enabled to use 'net:'" >&2 return 1 @@ -1264,7 +1274,7 @@ case "$COMMAND" in expose) collect_cidr_args "$@" shift $CIDR_ARG_COUNT - ipam_cidrs weave:expose $CIDR_ARGS + ipam_cidrs --no-check-alive weave:expose $CIDR_ARGS if [ $# -eq 0 ] ; then FQDN="" else @@ -1279,7 +1289,7 @@ case "$COMMAND" in add_iptables_rule nat WEAVE -d $CIDR ! -s $CIDR -j MASQUERADE add_iptables_rule nat WEAVE -s $CIDR ! -d $CIDR -j MASQUERADE if [ -n "$FQDN" ] ; then - when_dns_running put_dns_fqdn weave:expose $FQDN $CIDR + when_dns_running put_dns_fqdn --no-check-alive weave:expose $FQDN $CIDR fi fi done @@ -1288,7 +1298,7 @@ case "$COMMAND" in hide) collect_cidr_args "$@" shift $CIDR_ARG_COUNT - ipam_cidrs weave:expose $CIDR_ARGS + ipam_cidrs --no-check-alive weave:expose $CIDR_ARGS create_bridge --without-ethtool for CIDR in $ALL_CIDRS ; do if ip addr show dev $BRIDGE | grep -qF $CIDR ; then From cab4a7e1eec7744bf62407045e77cd86fb6ca5e0 Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Sun, 5 Jul 2015 18:59:53 +0100 Subject: [PATCH 015/180] Explain how to create the test VMs from vagrant --- test/README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/README.md b/test/README.md index 9d7cbdc7..9155dff0 100644 --- a/test/README.md +++ b/test/README.md @@ -6,8 +6,13 @@ You need two VMs with docker >=1.3.1 installed and listening on TCP port 2375 (see below). You also need to be able to ssh to these VMs, preferably without having to input anything. -The `Vagrantfile` in this directory constructs two such VMs. To meet -the aforementioned ssh requirement you may want to +The `Vagrantfile` in this directory constructs two such VMs. + +To create the VMs, open a shell and in this directory and type + + vagrant up + +To meet the aforementioned ssh requirement you may want to cp ~/.vagrant.d/insecure_private_key . From 098fc8182509f28dbb05553615936170a501432f Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sun, 5 Jul 2015 19:19:02 +0100 Subject: [PATCH 016/180] output json status based on 'Accept' header ...instead if having a separate URL. Closes #1063. --- prog/weaver/main.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/prog/weaver/main.go b/prog/weaver/main.go index be5e50ae..717fad47 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -259,6 +259,11 @@ func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator allocator.HandleHTTP(muxRouter, defaultSubnet, docker) } + muxRouter.Methods("GET").Path("/status").Headers("Accept", "application/json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json, _ := router.StatusJSON(version) + w.Write(json) + }) + muxRouter.Methods("GET").Path("/status").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "weave router", version) fmt.Fprintln(w, router.Status()) @@ -268,11 +273,6 @@ func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator } }) - muxRouter.Methods("GET").Path("/status-json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - json, _ := router.StatusJSON(version) - w.Write(json) - }) - muxRouter.Methods("POST").Path("/connect").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, fmt.Sprint("unable to parse form: ", err), http.StatusBadRequest) From c8bd47e94829eb1e5dd89797d995badc6386698c Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sun, 5 Jul 2015 19:25:28 +0100 Subject: [PATCH 017/180] set correct content-type header when returning json status --- prog/weaver/main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/prog/weaver/main.go b/prog/weaver/main.go index 717fad47..4f4b68de 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -261,6 +261,7 @@ func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator muxRouter.Methods("GET").Path("/status").Headers("Accept", "application/json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json, _ := router.StatusJSON(version) + w.Header().Set("Content-Type", "application/json") w.Write(json) }) From 5c44f74475539e1ca179aab0f59e7a936d24fc5d Mon Sep 17 00:00:00 2001 From: Paul Bellamy Date: Mon, 6 Jul 2015 11:17:34 +0100 Subject: [PATCH 018/180] rename proxy-(env|config) to (env|config) Keep error message to stderr, as the proxy should be launched with 'weave launch'. 'proxy-(env|config)' are kept with a deprecation warning, for a while. --- site/features.md | 4 ++-- site/proxy.md | 6 +++--- site/weavedns.md | 6 +++--- test/650_proxy_env_test.sh | 14 +++++++++----- weave | 15 ++++++++------- 5 files changed, 25 insertions(+), 20 deletions(-) diff --git a/site/features.md b/site/features.md index 56d771d7..f3e05f41 100644 --- a/site/features.md +++ b/site/features.md @@ -143,9 +143,9 @@ Let's begin by configuring weave's allocator to manage multiple subnets: host1$ weave launch -iprange 10.2.0.0/16 -ipsubnet 10.2.1.0/24 - host1$ eval $(weave proxy-env) + host1$ eval $(weave env) host2$ weave launch -iprange 10.2.0.0/16 -ipsubnet 10.2.1.0/24 $HOST1 - host2$ eval $(weave proxy-env) + host2$ eval $(weave env) This delegates the entire 10.2.0.0/16 subnet to weave, and instructs it to allocate from 10.2.1.0/24 within that if no specific subnet is diff --git a/site/proxy.md b/site/proxy.md index d133f28c..77c3d28e 100644 --- a/site/proxy.md +++ b/site/proxy.md @@ -49,13 +49,13 @@ All docker commands can be run via the proxy, so it is safe to adjust your `DOCKER_HOST` to point at the proxy. Weave provides a convenient command for this: - host1$ eval "$(weave proxy-env)" + host1$ eval "$(weave env)" host1$ docker ps ... Alternatively, the proxy host can be set on a per-command basis with - host1$ docker $(weave proxy-config) ps + host1$ docker $(weave config) ps The proxy can be stopped independently with @@ -167,7 +167,7 @@ with $ mkdir -pv ~/.docker $ cp -v {ca,cert,key}.pem ~/.docker - $ eval "$(weave proxy-env)" + $ eval "$(weave env)" $ export DOCKER_TLS_VERIFY=1 $ docker version ... diff --git a/site/weavedns.md b/site/weavedns.md index 2efee67e..6e0a698d 100644 --- a/site/weavedns.md +++ b/site/weavedns.md @@ -33,13 +33,13 @@ Weave Docker API proxy via `launch`: ```bash host1$ weave launch -host1$ eval $(weave proxy-env) +host1$ eval $(weave env) ``` or independently via `launch-dns`: ```bash host1$ weave launch-router && weave launch-dns && weave launch-proxy -host1$ eval $(weave proxy-env) +host1$ eval $(weave env) ``` The first form is more convenient, however you can only pass weaveDNS @@ -128,7 +128,7 @@ container, this time on the 2nd host, and then run some ping tests... ```bash host2$ weave launch -host2$ eval $(weave proxy-env) +host2$ eval $(weave env) host2$ docker run -dti --name=pingme ubuntu root@ubuntu:/# ping -nq -c 1 pingme diff --git a/test/650_proxy_env_test.sh b/test/650_proxy_env_test.sh index 97e33084..f6c4fb65 100755 --- a/test/650_proxy_env_test.sh +++ b/test/650_proxy_env_test.sh @@ -4,15 +4,19 @@ start_suite "Configure the docker daemon for the proxy" +# No output when nothing running +assert "weave_on $HOST1 env" "" +assert "weave_on $HOST1 config" "" + weave_on $HOST1 launch-proxy CMD="run -e WEAVE_CIDR=10.2.1.4/24 $SMALL_IMAGE $CHECK_ETHWE_UP" -assert_raises "eval '$(weave_on $HOST1 proxy-env)' ; docker $CMD" -assert_raises "docker $(weave_on $HOST1 proxy-config) $CMD" +assert_raises "eval '$(weave_on $HOST1 env)' ; docker $CMD" +assert_raises "docker $(weave_on $HOST1 config) $CMD" # Check we can use the weave script through the proxy -assert_raises "eval '$(weave_on $HOST1 proxy-env)' ; $WEAVE version" -assert_raises "eval '$(weave_on $HOST1 proxy-env)' ; $WEAVE ps" -assert_raises "eval '$(weave_on $HOST1 proxy-env)' ; $WEAVE launch-router" +assert_raises "eval '$(weave_on $HOST1 env)' ; $WEAVE version" +assert_raises "eval '$(weave_on $HOST1 env)' ; $WEAVE ps" +assert_raises "eval '$(weave_on $HOST1 env)' ; $WEAVE launch-router" end_suite diff --git a/weave b/weave index adb97c8d..f5913d39 100755 --- a/weave +++ b/weave @@ -48,8 +48,8 @@ usage() { echo "weave hide [ ...]" echo "weave ps [ ...]" echo "weave status" - echo "weave proxy-env" - echo "weave proxy-config" + echo "weave env" + echo "weave config" echo "weave version" echo "weave stop" echo "weave stop-router" @@ -932,10 +932,9 @@ proxy_args() { proxy_addr() { if addr=$(docker logs $PROXY_CONTAINER_NAME 2>&1 | head -n3 | grep -oE "proxy listening on .*"); then echo "${1}${addr##* }" | sed "s/0.0.0.0/$PROXY_HOST/g" - return 0 + else + echo "$PROXY_CONTAINER_NAME container is not present. Have you launched it?" >&2 fi - echo "$PROXY_CONTAINER_NAME container is not present. Have you launched it?" >&2 - return 1 } ###################################################################### @@ -1128,10 +1127,12 @@ case "$COMMAND" in launch_proxy "$@" echo $PROXY_CONTAINER ;; - proxy-env) + env|proxy-env) + [ "$COMMAND" = "env" ] || echo "$COMMAND is deprecated, please use 'weave env'" >&2 proxy_addr "export DOCKER_HOST=" ;; - proxy-config) + config|proxy-config) + [ "$COMMAND" = "config" ] || echo "$COMMAND is deprecated, please use 'weave config'" >&2 proxy_addr "-H=" ;; connect) From e86d255a47a3511701436784c275ceec9ecabbad Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Mon, 6 Jul 2015 10:02:47 +0100 Subject: [PATCH 019/180] Add comment about running integration tests from the Vagrant build VM --- test/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/README.md b/test/README.md index 9155dff0..4e18f175 100644 --- a/test/README.md +++ b/test/README.md @@ -18,6 +18,9 @@ To meet the aforementioned ssh requirement you may want to ## Running tests +If you are [building weave using Vagrant](http://docs.weave.works/weave/latest_release/building.html), +it is recommended to run the tests from the build VM and not the host. + ./setup.sh uploads the weave images from where the Makefile puts them From 373d663b5ee8348951f4fe0cd616f7c3176bd825 Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Fri, 3 Jul 2015 13:11:04 +0100 Subject: [PATCH 020/180] Fix integration tests for OSX --- test/500_weave_multi_cidr_test.sh | 2 +- test/config.sh | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/500_weave_multi_cidr_test.sh b/test/500_weave_multi_cidr_test.sh index 4a665f52..320cb07b 100755 --- a/test/500_weave_multi_cidr_test.sh +++ b/test/500_weave_multi_cidr_test.sh @@ -28,7 +28,7 @@ assert_zone_records() { records=$(weave_on $HOST status | grep "^$CID") || true # Assert correct number of records exist - assert "echo $records | grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' | wc -l" $# + assert "echo $records | grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' | wc -l | tr -d '[:space:]'" $# # Assert correct records exist for ADDR; do diff --git a/test/config.sh b/test/config.sh index 90a703cf..3b5e8e1a 100644 --- a/test/config.sh +++ b/test/config.sh @@ -60,16 +60,16 @@ upload_executable() { remote() { rem=$1 shift 1 - "$@" > >(while read line; do echo -e "\e[0;34m$rem>\e[0m $line"; done) + "$@" > >(while read line; do echo -e $'\e[0;34m'"$rem>"$'\e[0m'" $line"; done) } colourise() { - [ -t 0 ] && echo -ne '\e['$1'm' || true + [ -t 0 ] && echo -ne $'\e['$1'm' || true shift # It's important that we don't do this in a subshell, as some # commands we execute need to modify global state "$@" - [ -t 0 ] && echo -ne '\e[0m' || true + [ -t 0 ] && echo -ne $'\e[0m' || true } whitely() { @@ -154,7 +154,7 @@ assert_dns_record() { container=$2 name=$3 shift 3 - exp_ips_regex=$(echo "$@" | sed -r 's/ /\\\|/g') + exp_ips_regex=$(echo "$@" | sed -e 's/ /\\\|/g') [ -z "$DEBUG" ] || greyly echo "Checking whether $name exists at $host:$container" assert_raises "exec_on $host $container getent hosts $name | grep -q '$exp_ips_regex'" From 80a232f44c1047557d2d55468dffd8774603c9f8 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Mon, 6 Jul 2015 15:09:23 +0100 Subject: [PATCH 021/180] copy latest random_mac() from weave script to bin/multiweave --- bin/multiweave | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/multiweave b/bin/multiweave index 1dd5dfd8..6a78230a 100755 --- a/bin/multiweave +++ b/bin/multiweave @@ -23,7 +23,7 @@ random_mac() { # In the first byte of the MAC, the 'multicast' bit should be # clear and 'locally administered' bit should be set. All other # bits should be random. - od -txC -An -N6 /dev/urandom | sed 's|^ ||;s| |:|;s|[0-3]:|2:|;s|[4-7]:|6:|;s|[89ab]:|a:|;s|[c-f]:|e:|;s| |:|g' + od -txC -An -N6 /dev/urandom | ( read a b c d e f && printf "%02x:$b:$c:$d:$e:$f" $((0x$a & ~1 | 2)) ) } case "$1" in From 03ac7a86c6244e596bc8c199afcd75753818debb Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Mon, 6 Jul 2015 15:13:21 +0100 Subject: [PATCH 022/180] make bin/multiweave work again in 'launch launches everything' world --- bin/multiweave | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/multiweave b/bin/multiweave index 6a78230a..df47f44a 100755 --- a/bin/multiweave +++ b/bin/multiweave @@ -30,7 +30,7 @@ case "$1" in launch) shift 1 for i in $(seq $START $FINISH); do - WEAVE_CONTAINER_NAME=weave$i WEAVE_PORT=$((5000+i)) $weavedir/weave launch -iface '' -name $(random_mac) -nickname weave$i -port $PORT "$@" + WEAVE_CONTAINER_NAME=weave$i WEAVE_PORT=$((5000+i)) $weavedir/weave launch-router -iface '' -name $(random_mac) -nickname weave$i -port $PORT "$@" done if [ $START -ne 1 ] ; then status=$(docker inspect --format='{{.State.Running}} {{.NetworkSettings.IPAddress}}' weave$((START-1))) @@ -48,7 +48,7 @@ case "$1" in stop) for i in $(seq $START $FINISH); do echo Stopping weave$i - WEAVE_CONTAINER_NAME=weave$i $weavedir/weave stop + WEAVE_CONTAINER_NAME=weave$i $weavedir/weave stop-router done ;; esac From f593c2fbf2c0dbffc77465c7a8acbe74e89f54eb Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Fri, 3 Jul 2015 17:27:40 +0100 Subject: [PATCH 023/180] Change default IP allocation range from 10.128/10 to 10.32/12 --- README.md | 4 ++-- site/features.md | 2 +- site/ipam.md | 2 +- site/proxy.md | 2 +- site/weavedns.md | 14 +++++++------- weave | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 1d7b7253..453f3ccf 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ can talk to each other... In the container started on `$HOST1`... root@a1:/# ping -c 1 -q a2 - PING a2.weave.local (10.160.0.2) 56(84) bytes of data. + PING a2.weave.local (10.40.0.2) 56(84) bytes of data. --- a2.weave.local ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.341/0.341/0.341/0.000 ms @@ -125,7 +125,7 @@ In the container started on `$HOST1`... Similarly, in the container started on `$HOST2`... root@a2:/# ping -c 1 -q a1 - PING a1.weave.local (10.128.0.2) 56(84) bytes of data. + PING a1.weave.local (10.32.0.2) 56(84) bytes of data. --- a1.weave.local ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.366/0.366/0.366/0.000 ms diff --git a/site/features.md b/site/features.md index f3e05f41..ea25cc40 100644 --- a/site/features.md +++ b/site/features.md @@ -71,7 +71,7 @@ across the weave network. You can see which address was allocated with [`weave ps`](troubleshooting.html#list-attached-containers): host1$ weave ps a1 - a7aee7233393 7a:44:d3:11:10:70 10.128.0.2/10 + a7aee7233393 7a:44:d3:11:10:70 10.32.0.2/12 Weave detects when a container has exited and releases its automatically allocated addresses so they can be re-used. diff --git a/site/ipam.md b/site/ipam.md index 295bbf93..42a4bc93 100644 --- a/site/ipam.md +++ b/site/ipam.md @@ -87,7 +87,7 @@ would be safe wrt weave's startup quorum: ## Choosing an allocation range -By default, weave will allocate IP addresses in the 10.128.0.0/10 +By default, weave will allocate IP addresses in the 10.32.0.0/12 range. This can be overridden with the `-iprange` option, e.g. host1$ weave launch -iprange 10.2.0.0/16 diff --git a/site/proxy.md b/site/proxy.md index 77c3d28e..c78aeb92 100644 --- a/site/proxy.md +++ b/site/proxy.md @@ -103,7 +103,7 @@ special environment variables or other options*. To use a specific subnet, we pass a `WEAVE_CIDR` to the container, e.g. - host1$ docker run -ti -e WEAVE_CIDR=net:10.128.0.0/24 ubuntu + host1$ docker run -ti -e WEAVE_CIDR=net:10.32.2.0/24 ubuntu To start a container without connecting it to the weave network, pass `WEAVE_CIDR=none`, e.g. diff --git a/site/weavedns.md b/site/weavedns.md index 6e0a698d..f41a7639 100644 --- a/site/weavedns.md +++ b/site/weavedns.md @@ -132,16 +132,16 @@ host2$ eval $(weave env) host2$ docker run -dti --name=pingme ubuntu root@ubuntu:/# ping -nq -c 1 pingme -PING pingme.weave.local (10.128.0.2) 56(84) bytes of data. +PING pingme.weave.local (10.32.0.2) 56(84) bytes of data. ... root@ubuntu:/# ping -nq -c 1 pingme -PING pingme.weave.local (10.160.0.1) 56(84) bytes of data. +PING pingme.weave.local (10.40.0.1) 56(84) bytes of data. ... root@ubuntu:/# ping -nq -c 1 pingme -PING pingme.weave.local (10.160.0.1) 56(84) bytes of data. +PING pingme.weave.local (10.40.0.1) 56(84) bytes of data. ... root@ubuntu:/# ping -nq -c 1 pingme -PING pingme.weave.local (10.128.0.2) 56(84) bytes of data. +PING pingme.weave.local (10.32.0.2) 56(84) bytes of data. ... ``` @@ -272,9 +272,9 @@ Fallback DNS config &{[10.0.2.3] [] 53 1 5 2} Local domain weave.local. Interface &{74 65535 ethwe 82:0c:92:84:0e:88 up|broadcast|multicast} Zone database: -144b75a9b873: pingme.weave.local.[10.160.0.1]/OBS:1 -74a5510a91ad: ubuntu.weave.local.[10.160.0.2] -weave:remote: pingme.weave.local.[10.128.0.2]/TTL:30 +144b75a9b873: pingme.weave.local.[10.40.0.1]/OBS:1 +74a5510a91ad: ubuntu.weave.local.[10.40.0.2] +weave:remote: pingme.weave.local.[10.32.0.2]/TTL:30 ... ```` diff --git a/weave b/weave index f5913d39..b494ca85 100755 --- a/weave +++ b/weave @@ -986,7 +986,7 @@ launch_router() { done eval "set -- $ARGS" if [ -z "$IPRANGE_SPECIFIED" ] ; then - IPRANGE="10.128.0.0/10" + IPRANGE="10.32.0.0/12" if command_exists netcheck && ! netcheck $IPRANGE ; then echo "Default -iprange $IPRANGE overlaps with existing route on host." >&2 echo "Please pick another range and set it on all hosts." >&2 From 706f9ee35266c1188d1d5030f3fc7a39673c4830 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Mon, 6 Jul 2015 17:22:42 +0100 Subject: [PATCH 024/180] detect `--dns-search ` ...and not just `--dns-search=` Fixes #1086. --- weave | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/weave b/weave index 9574975d..9b3efb21 100755 --- a/weave +++ b/weave @@ -664,7 +664,7 @@ dns_args() { WITHOUT_DNS= while [ $# -gt 0 ] ; do case "$1" in - --dns-search=*) + --dns-search|--dns-search=*) DNS_SEARCH_SPECIFIED=1 ;; --name) From 02715f88d5515fed5e017a926096af71ab3e55b8 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Mon, 6 Jul 2015 17:26:04 +0100 Subject: [PATCH 025/180] cosmetic: re-order option parsing to match the order in which we susequently process them. --- weave | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/weave b/weave index 9b3efb21..67d69d9f 100755 --- a/weave +++ b/weave @@ -664,8 +664,11 @@ dns_args() { WITHOUT_DNS= while [ $# -gt 0 ] ; do case "$1" in - --dns-search|--dns-search=*) - DNS_SEARCH_SPECIFIED=1 + --with-dns) + WITH_DNS=1 + ;; + --without-dns) + WITHOUT_DNS=1 ;; --name) NAME_ARG="$2" @@ -677,11 +680,8 @@ dns_args() { -h|--hostname|--hostname=*) HOSTNAME_SPECIFIED=1 ;; - --with-dns) - WITH_DNS=1 - ;; - --without-dns) - WITHOUT_DNS=1 + --dns-search|--dns-search=*) + DNS_SEARCH_SPECIFIED=1 ;; esac shift From 379b8c4e6bfdb8df7b7e68a3515c55ec83768ea6 Mon Sep 17 00:00:00 2001 From: Michael Bridgen Date: Fri, 3 Jul 2015 15:45:17 +0100 Subject: [PATCH 026/180] Standardise on options --like-this Hyphenate words, and always expect double dashes for long options. A small number of options have entirely new names. In general I have added aliases for the unhyphenated and single-dashed varieties, and used mflag's deprecation syntax to make it print a warning when it sees them. I left some abbreviated options unhyphenated (e.g., `bufsz`), and the TLS options as-is since they correspond with Docker options. NB the deprecation wanrings will mostly get printed to container logs, since mostly the executables are run in containers. The next step is to emit warnings from the script for the options mentioned in the script usage message. --- prog/weavedns/main.go | 44 ++++++++++++++-------------- prog/weaveproxy/main.go | 54 ++++++++++++++++++++++++---------- prog/weaver/main.go | 64 ++++++++++++++++++++++++----------------- weave | 29 +++++++++---------- 4 files changed, 112 insertions(+), 79 deletions(-) diff --git a/prog/weavedns/main.go b/prog/weavedns/main.go index 1b0b46bb..06aa0780 100644 --- a/prog/weavedns/main.go +++ b/prog/weavedns/main.go @@ -1,12 +1,12 @@ package main import ( - "flag" "fmt" "net" "os" "strconv" + "github.com/docker/docker/pkg/mflag" "github.com/miekg/dns" . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" @@ -42,28 +42,28 @@ func main() { err error ) - flag.BoolVar(&justVersion, "version", false, "print version and exit") - flag.StringVar(&ifaceName, "iface", "", "name of interface to use for multicast") - flag.StringVar(&apiPath, "api", "unix:///var/run/docker.sock", "path to Docker API socket") - flag.StringVar(&domain, "domain", weavedns.DefaultLocalDomain, "local domain (ie, 'weave.local.')") - flag.IntVar(&wait, "wait", -1, "number of seconds to wait for interfaces to come up (0=don't wait, -1=wait forever)") - flag.IntVar(&dnsPort, "dnsport", weavedns.DefaultServerPort, "port to listen to DNS requests") - flag.StringVar(&httpIfaceName, "httpiface", "", "interface on which to listen for HTTP requests (defaults to empty string which listens on all interfaces)") - flag.IntVar(&httpPort, "httpport", weavedns.DefaultHTTPPort, "port to listen to HTTP requests") - flag.IntVar(&cacheLen, "cache", weavedns.DefaultCacheLen, "cache length") - flag.IntVar(&ttl, "ttl", weavedns.DefaultLocalTTL, "TTL (in secs) for responses for local names") - flag.BoolVar(&watch, "watch", true, "watch the docker socket for container events") - flag.StringVar(&logLevel, "log-level", "info", "logging level (debug, info, warning, error)") + mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") + mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to use for multicast") + mflag.StringVar(&apiPath, []string{"#api", "-api"}, "unix:///var/run/docker.sock", "path to Docker API socket") + mflag.StringVar(&domain, []string{"#domain", "-domain"}, weavedns.DefaultLocalDomain, "local domain (ie, 'weave.local.')") + mflag.IntVar(&wait, []string{"#wait", "-wait"}, -1, "number of seconds to wait for interfaces to come up (0=don't wait, -1=wait forever)") + mflag.IntVar(&dnsPort, []string{"#dnsport", "#-dnsport", "-dns-port"}, weavedns.DefaultServerPort, "port to listen to DNS requests") + mflag.StringVar(&httpIfaceName, []string{"#httpiface", "#-httpiface", "-http-iface"}, "", "interface on which to listen for HTTP requests (empty string means listen on all interfaces)") + mflag.IntVar(&httpPort, []string{"#httpport", "#-httpport", "-http-port"}, weavedns.DefaultHTTPPort, "port to listen to HTTP requests") + mflag.IntVar(&cacheLen, []string{"#cache", "-cache"}, weavedns.DefaultCacheLen, "cache length") + mflag.IntVar(&ttl, []string{"#ttl", "-ttl"}, weavedns.DefaultLocalTTL, "TTL (in secs) for responses for local names") + mflag.BoolVar(&watch, []string{"#watch", "-watch"}, true, "watch the docker socket for container events") + mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") // advanced options - flag.IntVar(&negTTL, "neg-ttl", 0, "negative TTL (in secs) for unanswered queries for local names (0=same value as -ttl") - flag.IntVar(&refreshInterval, "refresh", weavedns.DefaultRefreshInterval, "refresh interval (in secs) for local names (0=disable)") - flag.IntVar(&maxAnswers, "max-answers", weavedns.DefaultMaxAnswers, "maximum number of answers returned to clients (0=unlimited)") - flag.IntVar(&relevantTime, "relevant", weavedns.DefaultRelevantTime, "life time for info in the absence of queries (in secs)") - flag.IntVar(&udpbuf, "udpbuf", weavedns.DefaultUDPBuflen, "UDP buffer length") - flag.IntVar(&timeout, "timeout", weavedns.DefaultTimeout, "timeout for resolutions (in millisecs)") - flag.BoolVar(&cacheDisabled, "no-cache", false, "disable the cache") - flag.StringVar(&fallback, "fallback", "", "force a fallback server (ie, '8.8.8.8:53') (instead of /etc/resolv.conf values)") - flag.Parse() + mflag.IntVar(&negTTL, []string{"#neg-ttl", "-neg-ttl"}, 0, "negative TTL (in secs) for unanswered queries for local names (0=same value as --ttl") + mflag.IntVar(&refreshInterval, []string{"#refresh", "-refresh"}, weavedns.DefaultRefreshInterval, "refresh interval (in secs) for local names (0=disable)") + mflag.IntVar(&maxAnswers, []string{"#max-answers", "#-max-answers", "-dns-max-answers"}, weavedns.DefaultMaxAnswers, "maximum number of answers returned to clients (0=unlimited)") + mflag.IntVar(&relevantTime, []string{"#relevant", "-relevant"}, weavedns.DefaultRelevantTime, "life time for info in the absence of queries (in secs)") + mflag.IntVar(&udpbuf, []string{"#udpbuf", "#-udpbuf", "-dns-udpbuf"}, weavedns.DefaultUDPBuflen, "UDP buffer length for DNS") + mflag.IntVar(&timeout, []string{"#timeout", "#-timeout", "-dns-timeout"}, weavedns.DefaultTimeout, "timeout for resolutions (in millisecs)") + mflag.BoolVar(&cacheDisabled, []string{"#no-cache", "-no-cache"}, false, "disable the cache") + mflag.StringVar(&fallback, []string{"#fallback", "#-fallback", "-dns-fallback"}, "", "force a fallback server (ie, '8.8.8.8:53') (instead of /etc/resolv.conf values)") + mflag.Parse() if justVersion { fmt.Printf("weave DNS %s\n", version) diff --git a/prog/weaveproxy/main.go b/prog/weaveproxy/main.go index 23c78a29..7a86bccd 100644 --- a/prog/weaveproxy/main.go +++ b/prog/weaveproxy/main.go @@ -5,7 +5,7 @@ import ( "os" "strings" - "github.com/pborman/getopt" + "github.com/docker/docker/pkg/mflag" . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/proxy" ) @@ -15,27 +15,51 @@ var ( defaultListenAddrs = []string{"tcp://0.0.0.0:12375", "unix:///var/run/weave.sock"} ) +type listOpts struct { + value *[]string + hasBeenSet bool +} + +func ListVar(p *[]string, names []string, value []string, usage string) { + *p = value + mflag.Var(&listOpts{p, false}, names, usage) +} + +func (opts *listOpts) Set(value string) error { + if opts.hasBeenSet { + (*opts.value) = append((*opts.value), value) + } else { + (*opts.value) = []string{value} + opts.hasBeenSet = true + } + return nil +} + +func (opts *listOpts) String() string { + return fmt.Sprintf("%v", []string(*opts.value)) +} + func main() { var ( justVersion bool logLevel = "info" - c = proxy.Config{ListenAddrs: defaultListenAddrs} + c = proxy.Config{ListenAddrs: []string{}} ) c.Version = version - getopt.BoolVarLong(&justVersion, "version", 0, "print version and exit") - getopt.StringVarLong(&logLevel, "log-level", 0, "logging level (debug, info, warning, error)", "info") - getopt.ListVar(&c.ListenAddrs, 'H', fmt.Sprintf("address on which to listen (default %s)", defaultListenAddrs)) - getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipalloc", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR") - getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipam", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR (deprecated; please use --no-default-ipalloc") - getopt.StringVarLong(&c.TLSConfig.CACert, "tlscacert", 0, "Trust certs signed only by this CA") - getopt.StringVarLong(&c.TLSConfig.Cert, "tlscert", 0, "Path to TLS certificate file") - getopt.BoolVarLong(&c.TLSConfig.Enabled, "tls", 0, "Use TLS; implied by --tlsverify") - getopt.StringVarLong(&c.TLSConfig.Key, "tlskey", 0, "Path to TLS key file") - getopt.BoolVarLong(&c.TLSConfig.Verify, "tlsverify", 0, "Use TLS and verify the remote") - getopt.BoolVarLong(&c.WithDNS, "with-dns", 'w', "instruct created containers to always use weaveDNS as their nameserver") - getopt.BoolVarLong(&c.WithoutDNS, "without-dns", 0, "instruct created containers to never use weaveDNS as their nameserver") - getopt.Parse() + + mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") + mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") + ListVar(&c.ListenAddrs, []string{"H"}, defaultListenAddrs, "addresses on which to listen") + mflag.BoolVar(&c.NoDefaultIPAM, []string{"#-no-default-ipam", "-no-default-ipalloc"}, false, "do not automatically allocate addresses for containers without a WEAVE_CIDR") + mflag.StringVar(&c.TLSConfig.CACert, []string{"#tlscacert", "-tlscacert"}, "", "Trust certs signed only by this CA") + mflag.StringVar(&c.TLSConfig.Cert, []string{"#tlscert", "-tlscert"}, "", "Path to TLS certificate file") + mflag.BoolVar(&c.TLSConfig.Enabled, []string{"#tls", "-tls"}, false, "Use TLS; implied by --tls-verify") + mflag.StringVar(&c.TLSConfig.Key, []string{"#tlskey", "-tlskey"}, "", "Path to TLS key file") + mflag.BoolVar(&c.TLSConfig.Verify, []string{"#tlsverify", "-tlsverify"}, false, "Use TLS and verify the remote") + mflag.BoolVar(&c.WithDNS, []string{"-with-dns", "w"}, false, "instruct created containers to always use weaveDNS as their nameserver") + mflag.BoolVar(&c.WithoutDNS, []string{"-without-dns"}, false, "instruct created containers to never use weaveDNS as their nameserver") + mflag.Parse() if justVersion { fmt.Printf("weave proxy %s\n", version) diff --git a/prog/weaver/main.go b/prog/weaver/main.go index 4f4b68de..43710a11 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -2,7 +2,6 @@ package main import ( "crypto/sha256" - "flag" "fmt" "net" "net/http" @@ -11,6 +10,7 @@ import ( "strings" "github.com/davecheney/profile" + "github.com/docker/docker/pkg/mflag" "github.com/gorilla/mux" . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" @@ -52,26 +52,26 @@ func main() { peers []string ) - flag.BoolVar(&justVersion, "version", false, "print version and exit") - flag.IntVar(&config.Port, "port", weave.Port, "router port") - flag.StringVar(&ifaceName, "iface", "", "name of interface to capture/inject from (disabled if blank)") - flag.StringVar(&routerName, "name", "", "name of router (defaults to MAC of interface)") - flag.StringVar(&nickName, "nickname", "", "nickname of peer (defaults to hostname)") - flag.StringVar(&password, "password", "", "network password") - flag.IntVar(&wait, "wait", -1, "number of seconds to wait for interface to come up (0=don't wait, -1=wait forever)") - flag.StringVar(&logLevel, "log-level", "info", "logging level (debug, info, warning, error)") - flag.BoolVar(&pktdebug, "pktdebug", false, "enable per-packet debug logging") - flag.StringVar(&prof, "profile", "", "enable profiling and write profiles to given path") - flag.IntVar(&config.ConnLimit, "connlimit", 30, "connection limit (0 for unlimited)") - flag.BoolVar(&noDiscovery, "nodiscovery", false, "disable peer discovery") - flag.IntVar(&bufSzMB, "bufsz", 8, "capture buffer size in MB") - flag.StringVar(&httpAddr, "httpaddr", fmt.Sprintf(":%d", weave.HTTPPort), "address to bind HTTP interface to (disabled if blank, absolute path indicates unix domain socket)") - flag.StringVar(&iprangeCIDR, "iprange", "", "IP address range reserved for automatic allocation, in CIDR notation") - flag.StringVar(&ipsubnetCIDR, "ipsubnet", "", "subnet to allocate within by default, in CIDR notation") - flag.IntVar(&peerCount, "initpeercount", 0, "number of peers in network (for IP address allocation)") - flag.StringVar(&apiPath, "api", "unix:///var/run/docker.sock", "Path to Docker API socket") - flag.Parse() - peers = flag.Args() + mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") + mflag.IntVar(&config.Port, []string{"#port", "-port"}, weave.Port, "router port") + mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to capture/inject from (disabled if blank)") + mflag.StringVar(&routerName, []string{"#name", "-name"}, "", "name of router (defaults to MAC of interface)") + mflag.StringVar(&nickName, []string{"#nickname", "-nickname"}, "", "nickname of peer (defaults to hostname)") + mflag.StringVar(&password, []string{"#password", "-password"}, "", "network password") + mflag.IntVar(&wait, []string{"#wait", "-wait"}, -1, "number of seconds to wait for interface to come up (0=don't wait, -1=wait forever)") + mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") + mflag.BoolVar(&pktdebug, []string{"#pktdebug", "#-pktdebug", "-pkt-debug"}, false, "enable per-packet debug logging") + mflag.StringVar(&prof, []string{"#profile", "-profile"}, "", "enable profiling and write profiles to given path") + mflag.IntVar(&config.ConnLimit, []string{"#connlimit", "#-connlimit", "-conn-limit"}, 30, "connection limit (0 for unlimited)") + mflag.BoolVar(&noDiscovery, []string{"#nodiscovery", "#-nodiscovery", "-no-discovery"}, false, "disable peer discovery") + mflag.IntVar(&bufSzMB, []string{"#bufsz", "-bufsz"}, 8, "capture buffer size in MB") + mflag.StringVar(&httpAddr, []string{"#httpaddr", "#-httpaddr", "-http-addr"}, fmt.Sprintf(":%d", weave.HTTPPort), "address to bind HTTP interface to (disabled if blank, absolute path indicates unix domain socket)") + mflag.StringVar(&iprangeCIDR, []string{"#iprange", "#-iprange", "-ipalloc-range"}, "", "IP address range reserved for automatic allocation, in CIDR notation") + mflag.StringVar(&ipsubnetCIDR, []string{"#ipsubnet", "#-ipsubnet", "-ipalloc-default-subnet"}, "", "subnet to allocate within by default, in CIDR notation") + mflag.IntVar(&peerCount, []string{"#initpeercount", "#-initpeercount", "-init-peer-count"}, 0, "number of peers in network (for IP address allocation)") + mflag.StringVar(&apiPath, []string{"#api", "-api"}, "unix:///var/run/docker.sock", "Path to Docker API socket") + mflag.Parse() + peers = mflag.Args() SetLogLevel(logLevel) if justVersion { @@ -93,7 +93,7 @@ func main() { if routerName == "" { if config.Iface == nil { - Log.Fatal("Either an interface must be specified with -iface or a name with -name") + Log.Fatal("Either an interface must be specified with --iface or a name with -name") } routerName = config.Iface.HardwareAddr.String() } @@ -146,7 +146,7 @@ func main() { Log.Fatal("Unable to start watcher", err) } } else if peerCount > 0 { - Log.Fatal("-initpeercount flag specified without -iprange") + Log.Fatal("--init-peer-count flag specified without --ipalloc-range") } router.Start() @@ -155,7 +155,7 @@ func main() { } // The weave script always waits for a status call to succeed, - // so there is no point in doing "weave launch -httpaddr ''". + // so there is no point in doing "weave launch --http-addr ''". // This is here to support stand-alone use of weaver. if httpAddr != "" { go handleHTTP(router, httpAddr, allocator, defaultSubnet, dockerCli) @@ -174,16 +174,26 @@ func errorMessages(errors []error) string { func options() map[string]string { options := make(map[string]string) - flag.Visit(func(f *flag.Flag) { + mflag.Visit(func(f *mflag.Flag) { value := f.Value.String() - if f.Name == "password" { + name := canonicalName(f) + if name == "password" { value = "" } - options[f.Name] = value + options[name] = value }) return options } +func canonicalName(f *mflag.Flag) string { + for _, n := range f.Names { + if n[0] != '#' { + return strings.TrimLeft(n, "#-") + } + } + return "" +} + func logFrameFunc(debug bool) weave.LogFrameFunc { if !debug { return func(prefix string, frame []byte, dec *weave.EthernetDecoder) {} diff --git a/weave b/weave index b35ffbbe..4b9e1b75 100755 --- a/weave +++ b/weave @@ -890,9 +890,8 @@ show_addrs() { # TODO: Handle relative paths for args # TODO: Handle args with spaces tls_arg() { - filename=${3:-$2} - PROXY_VOLUMES="$PROXY_VOLUMES -v $1:/home/weave/tls/$filename.pem" - PROXY_ARGS="$PROXY_ARGS --tls$2 /home/weave/tls/$filename.pem" + PROXY_VOLUMES="$PROXY_VOLUMES -v $2:/home/weave/tls/$3.pem" + PROXY_ARGS="$PROXY_ARGS $1 /home/weave/tls/$3.pem" } proxy_args() { @@ -901,25 +900,25 @@ proxy_args() { while [ $# -gt 0 ]; do case "$1" in --tlscacert) + tls_arg "$1" "$2" ca shift - tls_arg "$1" cacert ca ;; --tlscacert=*) - tls_arg "${1#*=}" cacert ca + tls_arg "${1%%=*}" "${1#*=}" ca ;; --tlscert) + tls_arg "$1" "$2" cert shift - tls_arg "$1" cert ;; --tlscert=*) - tls_arg "${1#*=}" cert + tls_arg "${1%%=*}" "${1#*=}" cert ;; --tlskey) + tls_arg "$1" "$2" key shift - tls_arg "$1" key ;; --tlskey=*) - tls_arg "${1#*=}" key + tls_arg "${1%%=*}" "${1#*=}" key ;; *) PROXY_ARGS="$PROXY_ARGS $1" @@ -973,18 +972,18 @@ launch_router() { IPRANGE_SPECIFIED= while [ $# -gt 0 ] ; do case "$1" in - -password) + -password|--password) [ $# -gt 1 ] || usage WEAVE_PASSWORD="$2" export WEAVE_PASSWORD shift 2 ;; - -port) + -port|--port) [ $# -gt 1 ] || usage CONTAINER_PORT="$2" shift 2 ;; - -iprange) + -iprange|--iprange|--ipalloc-range) [ $# -gt 1 ] || usage IPRANGE="$2" IPRANGE_SPECIFIED=1 @@ -1000,7 +999,7 @@ launch_router() { if [ -z "$IPRANGE_SPECIFIED" ] ; then IPRANGE="10.32.0.0/12" if command_exists netcheck && ! netcheck $IPRANGE ; then - echo "Default -iprange $IPRANGE overlaps with existing route on host." >&2 + echo "Default --ipalloc-range $IPRANGE overlaps with existing route on host." >&2 echo "Please pick another range and set it on all hosts." >&2 exit 1 fi @@ -1013,7 +1012,7 @@ launch_router() { -v /var/run/docker.sock:/var/run/docker.sock \ -e WEAVE_PASSWORD \ -e WEAVE_CIDR=none \ - $WEAVE_DOCKER_ARGS $IMAGE -iface $CONTAINER_IFNAME -port $CONTAINER_PORT -name "$PEERNAME" -nickname "$(hostname)" -iprange "$IPRANGE" "$@") + $WEAVE_DOCKER_ARGS $IMAGE --iface $CONTAINER_IFNAME --port $CONTAINER_PORT --name "$PEERNAME" --nickname "$(hostname)" --ipalloc-range "$IPRANGE" "$@") with_container_netns_or_die $CONTAINER launch wait_for_status $CONTAINER_NAME $HTTP_PORT if [ -n "$IPRANGE" ] ; then @@ -1035,7 +1034,7 @@ launch_dns() { -p $DOCKER_BRIDGE_IP:53:53/udp \ -e WEAVE_CIDR=none \ -v /var/run/docker.sock:/var/run/docker.sock \ - $WEAVEDNS_DOCKER_ARGS $DNS_IMAGE -iface $CONTAINER_IFNAME -httpiface "$DNS_HTTP_IFNAME" "$@") + $WEAVEDNS_DOCKER_ARGS $DNS_IMAGE --iface $CONTAINER_IFNAME --http-iface "$DNS_HTTP_IFNAME" "$@") ipam_cidrs_or_die $DNS_CONTAINER $CIDR_ARGS with_container_netns_or_die $DNS_CONTAINER attach $ALL_CIDRS populate_dns From ebbb5d379d6646de72fb74f016c6a75397def477 Mon Sep 17 00:00:00 2001 From: Michael Bridgen Date: Mon, 6 Jul 2015 09:28:56 +0100 Subject: [PATCH 027/180] Usage and deprecation warnings in script The usage is rearranged slightly to avoid wrapping at 80 characters. This will tend to overestimate warnings, since it doesn't try very hard to ignore values that are not intended to be options; in particular, arguments that are intended for `docker run`. (Using `--` to delimit these arguments would make this easier!) It does ignore values that follow known options though, for instance in weave -nickname "-password" (-nickname results in a deprecation warning, -password does not) and weave --password "-iprange" (no deprecation warning, since -iprange is ignored) --- weave | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 90 insertions(+), 10 deletions(-) diff --git a/weave b/weave index 4b9e1b75..1b80bd88 100755 --- a/weave +++ b/weave @@ -26,19 +26,19 @@ CIDR_REGEXP="$IP_REGEXP/[0-9]{1,2}" usage() { echo "Usage:" echo "weave setup" - echo "weave launch [-password ] [-nickname ] [-nodiscovery]" - echo " [-iprange [-ipsubnet ]]" - echo " [-initpeercount ] ..." - echo "weave launch-router [-password ] [-nickname ] [-nodiscovery]" - echo " [-iprange [-ipsubnet ]]" - echo " [-initpeercount ] ..." + echo "weave launch [--password ] [--nickname ]" + echo " [--ipalloc-range [--ipalloc-default-subnet ]]" + echo " [--no-discovery] [--init-peer-count ] ..." + echo "weave launch-router [--password ] [--nickname ]" + echo " [--ipalloc-range [--ipalloc-default-subnet ]]" + echo " [--no-discovery] [--init-peer-count ] ..." echo "weave launch-dns []" echo "weave launch-proxy [-H ] [--with-dns | --without-dns]" - echo " [--no-default-ipalloc]" + echo " [--no-default-ipalloc]" echo "weave connect [--replace] [ ...]" echo "weave forget ..." echo "weave run [--with-dns | --without-dns] [ ...]" - echo " ..." + echo " ..." echo "weave start [ ...] " echo "weave attach [ ...] " echo "weave detach [ ...] " @@ -1100,6 +1100,83 @@ DOCKER_VERSION_MAJOR=$(echo "$DOCKER_VERSION" | cut -d. -f 1) DOCKER_VERSION_MINOR=$(echo "$DOCKER_VERSION" | cut -d. -f 2) DOCKER_VERSION_PATCH=$(echo "$DOCKER_VERSION" | cut -d. -f 3) +deprecation_warning() { + echo "Warning: ${1%=*} is deprecated; please use $2" >&2 +} + +deprecation_warnings() { + while [ $# -gt 0 ]; do + case "$1" in + -password|-password=*) + deprecation_warning $1 "--password" + [ "$1" == "-password" ] && shift + ;; + --password) + shift + ;; + -nickname|-nickname=*) + deprecation_warning $1 "--nickname" + [ "$1" == "-nickname" ] && shift + ;; + --nickname) + shift + ;; + -nodiscovery|--nodiscovery) + deprecation_warning $1 "--no-discovery" + ;; + -iprange|--iprange|-iprange=*|--iprange=*) + deprecation_warning $1 "--ipalloc-range" + [ ${1#--} == "iprange" ] && shift + ;; + --ipalloc-range) + shift + ;; + -ipsubnet|--ipsubnet|-ipsubnet=*|--ipsubnet=*) + deprecation_warning $1 "--ipalloc-default-subnet" + [ ${1#--} == "ipsubnet" ] && shift + ;; + --ipalloc-default-subnet) + shift + ;; + -initpeercount|--initpeercount|-initpeercount=*|--initpeercount=*) + deprecation_warning $1 "--init-peer-count" + [ ${1#--} == "initpeercount" ] && shift + ;; + --init-peer-count) + shift + ;; + -no-default-ipam|--no-default-ipam) + deprecation_warning $1 "--no-default-ipalloc" + ;; + --tlscacert|--tlscacert=*) + deprecation_warning "--tlscacert" "--tls-cacert" + [ "$1" == "--tlscacert" ] && shift + ;; + --tls-cacert) + shift + ;; + --tlscert|--tlscert=*) + deprecation_warning "--tlscert" "--tls-cert" + [ "$1" == "--tlscert" ] && shift + ;; + --tls-cert) + shift + ;; + --tlskey|--tlskey=*) + deprecation_warning "--tlskey" "--tls-key" + [ "$1" == "--tlskey" ] && shift + ;; + --tls-key) + shift + ;; + --tlsverify) + deprecation_warning "--tlsverify" "--tls-verify" + ;; + esac + shift + done +} + [ $# -gt 0 ] || usage COMMAND=$1 shift 1 @@ -1116,6 +1193,7 @@ case "$COMMAND" in create_bridge --without-ethtool ;; launch) + deprecation_warnings "$@" check_not_running $CONTAINER_NAME $BASE_IMAGE check_not_running $DNS_CONTAINER_NAME $BASE_DNS_IMAGE check_not_running $PROXY_CONTAINER_NAME $EXEC_IMAGE @@ -1125,6 +1203,7 @@ case "$COMMAND" in launch_proxy $COMMON_ARGS ;; launch-router) + deprecation_warnings "$@" check_not_running $CONTAINER_NAME $BASE_IMAGE launch_router "$@" echo $CONTAINER @@ -1135,16 +1214,17 @@ case "$COMMAND" in echo $DNS_CONTAINER ;; launch-proxy) + deprecation_warnings "$@" check_not_running $PROXY_CONTAINER_NAME $EXEC_IMAGE launch_proxy "$@" echo $PROXY_CONTAINER ;; env|proxy-env) - [ "$COMMAND" = "env" ] || echo "$COMMAND is deprecated, please use 'weave env'" >&2 + [ "$COMMAND" = "env" ] || deprecation_warning "$COMMAND" "'weave env'" proxy_addr "export DOCKER_HOST=" ;; config|proxy-config) - [ "$COMMAND" = "config" ] || echo "$COMMAND is deprecated, please use 'weave config'" >&2 + [ "$COMMAND" = "config" ] || deprecation_warning "$COMMAND" "'weave config'" proxy_addr "-H=" ;; connect) From 4ede33468ef33f37e9db61352d10be5318152474 Mon Sep 17 00:00:00 2001 From: Michael Bridgen Date: Mon, 6 Jul 2015 11:16:58 +0100 Subject: [PATCH 028/180] Update docs and smoke-tests with new option names --- bin/multiweave | 2 +- docs/dockerless.txt | 4 +-- site/features.md | 14 ++++---- site/ipam.md | 40 +++++++++++------------ site/proxy.md | 8 ++--- site/troubleshooting.md | 6 ++-- test/100_cross_hosts_test.sh | 4 +-- test/110_encryption_test.sh | 4 +-- test/130_expose_test.sh | 2 +- test/140_weave_local_test.sh | 2 +- test/210_dns_multicast_test.sh | 4 +-- test/270_use_name_as_hostname_test.sh | 2 +- test/500_weave_multi_cidr_test.sh | 2 +- test/620_proxy_entrypoint_command_test.sh | 2 +- test/660_proxy_ipam_test.sh | 4 +-- weave | 24 -------------- 16 files changed, 50 insertions(+), 74 deletions(-) diff --git a/bin/multiweave b/bin/multiweave index df47f44a..ec8d569c 100755 --- a/bin/multiweave +++ b/bin/multiweave @@ -30,7 +30,7 @@ case "$1" in launch) shift 1 for i in $(seq $START $FINISH); do - WEAVE_CONTAINER_NAME=weave$i WEAVE_PORT=$((5000+i)) $weavedir/weave launch-router -iface '' -name $(random_mac) -nickname weave$i -port $PORT "$@" + WEAVE_CONTAINER_NAME=weave$i WEAVE_PORT=$((5000+i)) $weavedir/weave launch-router --iface '' --name $(random_mac) --nickname weave$i --port $PORT "$@" done if [ $START -ne 1 ] ; then status=$(docker inspect --format='{{.State.Running}} {{.NetworkSettings.IPAddress}}' weave$((START-1))) diff --git a/docs/dockerless.txt b/docs/dockerless.txt index f4071150..9332ce43 100644 --- a/docs/dockerless.txt +++ b/docs/dockerless.txt @@ -125,8 +125,8 @@ VM2> nc 192.168.122.2 6783 If all is well, you should now be able to launch weave on VM1 then on VM2: -VM1> weaver -iface veth6 -name vm1 -VM2> weaver -iface veth6 -name vm2 192.168.122.2 +VM1> weaver --iface veth6 --name vm1 +VM2> weaver --iface veth6 --name vm2 192.168.122.2 Once the connection is up and running, you should be able to connect from VM1/ns2 to VM2/ns2 and vice versa: diff --git a/site/features.md b/site/features.md index ea25cc40..a58578e5 100644 --- a/site/features.md +++ b/site/features.md @@ -142,9 +142,9 @@ To accomplish that, we assign each application a different subnet. Let's begin by configuring weave's allocator to manage multiple subnets: - host1$ weave launch -iprange 10.2.0.0/16 -ipsubnet 10.2.1.0/24 + host1$ weave launch --ipalloc-range 10.2.0.0/16 --ipalloc-default-subnet 10.2.1.0/24 host1$ eval $(weave env) - host2$ weave launch -iprange 10.2.0.0/16 -ipsubnet 10.2.1.0/24 $HOST1 + host2$ weave launch --ipalloc-range 10.2.0.0/16 --ipalloc-default-subnet 10.2.1.0/24 $HOST1 host2$ eval $(weave env) This delegates the entire 10.2.0.0/16 subnet to weave, and instructs @@ -251,10 +251,10 @@ invocation: ### Security In order to connect containers across untrusted networks, weave peers -can be told to encrypt traffic by supplying a `-password` option or +can be told to encrypt traffic by supplying a `--password` option or `WEAVE_PASSWORD` environment variable when launching weave, e.g. - host1$ weave launch -password wEaVe + host1$ weave launch --password wEaVe or @@ -496,9 +496,9 @@ and the new hosts will be added, when one runs host# weave connect --replace $NEW_HOST1 $NEW_HOST2 For complete control over the peer topology, automatic discovery can -be disabled with the `-nodiscovery` option to `weave launch`. In this -mode, weave will only connect to the addresses specified at launch -time and with `weave connect`. +be disabled with the `--no-discovery` option to `weave launch`. In +this mode, weave will only connect to the addresses specified at +launch time and with `weave connect`. ### Container mobility diff --git a/site/ipam.md b/site/ipam.md index 42a4bc93..694ad24a 100644 --- a/site/ipam.md +++ b/site/ipam.md @@ -26,8 +26,8 @@ in the whole network, weave needs a majority of peers to be present in order to avoid formation of isolated groups, which could lead to inconsistency, i.e. the same IP address being allocated to two different containers. Therefore, you must either supply the list of -all peers in the network to `weave launch` or add the `-initpeercount` -flag to specify how many peers there will be. +all peers in the network to `weave launch` or add the +`--init-peer-count` flag to specify how many peers there will be. To illustrate, suppose you have three hosts, accessible to each other as `$HOST1`, `$HOST2` and `$HOST3`. You can start weave on those three @@ -42,13 +42,13 @@ hosts with these three commands: Or, if it is not convenient to name all the other hosts at launch time, you can give the number of peers like this: - host1$ weave launch -initpeercount 3 + host1$ weave launch --init-peer-count 3 - host2$ weave launch -initpeercount 3 $HOST3 + host2$ weave launch --init-peer-count 3 $HOST3 - host3$ weave launch -initpeercount 3 $HOST2 + host3$ weave launch --init-peer-count 3 $HOST2 -### More on `-initpeercount` +### More on `--init-peer-count` TL;DR: it isn't a problem to over-estimate by a bit, but if you supply a number that is too small then multiple independent groups may form. @@ -88,9 +88,9 @@ would be safe wrt weave's startup quorum: ## Choosing an allocation range By default, weave will allocate IP addresses in the 10.32.0.0/12 -range. This can be overridden with the `-iprange` option, e.g. +range. This can be overridden with the `--ipalloc-range` option, e.g. - host1$ weave launch -iprange 10.2.0.0/16 + host1$ weave launch --ipalloc-range 10.2.0.0/16 and must be the same on every host. @@ -135,13 +135,13 @@ for instance: When working with multiple subnets in this way, it is usually desirable to constrain the default subnet - i.e. the one chosen by the allocator when no subnet is supplied - so that it does not overlap -with others. One can specify that with `-ipsubnet`: +with others. One can specify that with `--ipalloc-default-subnet`: - host1$ weave launch -iprange 10.2.0.0/16 -ipsubnet 10.2.3.0/24 + host1$ weave launch --ipalloc-range 10.2.0.0/16 --ipalloc-default-subnet 10.2.3.0/24 -`-iprange` should cover the entire range that you will ever use for -allocation, and `-ipsubnet` is the subnet that will be used when you -don't explicitly specify one. +`--ipalloc-range` should cover the entire range that you will ever use +for allocation, and `--ipalloc-default-subnet` is the subnet that will +be used when you don't explicitly specify one. When specifying addresses, the default subnet can be denoted symbolically with `net:default`. @@ -151,10 +151,10 @@ symbolically with `net:default`. If you want to start containers with a mixture of automatically-allocated addresses and manually-chosen addresses, *and have the containers communicate with each other*, you can choose a -`-iprange` that is smaller than `-ipsubnet`, For example, if you -launch weave with: +`--ipalloc-range` that is smaller than `--ip-default-subnet`, For +example, if you launch weave with: - host1$ weave launch -iprange 10.9.0.0/17 -ipsubnet 10.9.0.0/16 + host1$ weave launch --ipalloc-range 10.9.0.0/17 --ipalloc-default-subnet 10.9.0.0/16 then you can run all containers in the 10.9.0.0/16 subnet, with automatic allocation using the lower half, leaving the upper half free @@ -213,8 +213,8 @@ The first section covers the router; see the [troubleshooting guide](troubleshooting.html#status-report) for full details. The 'Allocator' section, which is only present if weave has been -started with the `-iprange` option, summarises the overall position and -lists which address ranges have been assigned to which peer. Each -range begins at the address shown and ends just before the next -address, or wraps around at the end of the subnet. The 'v' number +started with the `--ipalloc-range` option, summarises the overall +position and lists which address ranges have been assigned to which +peer. Each range begins at the address shown and ends just before the +next address, or wraps around at the end of the subnet. The 'v' number denotes how many times that entry has been updated. diff --git a/site/proxy.md b/site/proxy.md index c78aeb92..453c81de 100644 --- a/site/proxy.md +++ b/site/proxy.md @@ -140,8 +140,8 @@ TLS-related command-line flags as supplied to the docker daemon. For example, if you have generated your certificates and keys into the docker host's `/tls` directory, we can launch the proxy with: - host1$ weave launch-proxy --tlsverify --tlscacert=/tls/ca.pem \ - --tlscert=/tls/server-cert.pem --tlskey=/tls/server-key.pem + host1$ weave launch-proxy --tls-verify --tls-cacert=/tls/ca.pem \ + --tls-cert=/tls/server-cert.pem --tls-key=/tls/server-key.pem The paths to your certificates and key must be provided as absolute paths which exist on the docker host. @@ -157,8 +157,8 @@ for an example. With the proxy running over TLS, we can configure our regular docker client to use TLS on a per-invocation basis with - $ docker --tlsverify --tlscacert=ca.pem --tlscert=cert.pem \ - --tlskey=key.pem -H=tcp://host1:12375 version + $ docker --tls-verify --tls-cacert=ca.pem --tls-cert=cert.pem \ + --tls-key=key.pem -H=tcp://host1:12375 version ... or, diff --git a/site/troubleshooting.md b/site/troubleshooting.md index e83ecd36..30da1e07 100644 --- a/site/troubleshooting.md +++ b/site/troubleshooting.md @@ -22,8 +22,8 @@ A reasonable amount of information, and all errors, get logged there. The log verbosity can be increased by supplying the `--log-level=debug` option when launching weave. To log information on -a per-packet basis use `-pktdebug` - be warned, this can produce a lot -of output. +a per-packet basis use `--pktdebug` - be warned, this can produce a +lot of output. Another useful debugging technique is to attach standard packet capture and analysis tools, such as tcpdump and wireshark, to the @@ -96,7 +96,7 @@ The 'Our name' line identifies the local weave router as a peer in the weave network, displaying the peer name followed by the peer's nickname in parenthesis. The nickname defaults to the name of the host on which the weave container was launched; if desired it can be overriden by -supplying the `-nickname` argument to `weave launch`. +supplying the `--nickname` argument to `weave launch`. The 'Sniffing traffic' line shows details of the virtual ethernet interface that weave is using to receive packets on the local diff --git a/test/100_cross_hosts_test.sh b/test/100_cross_hosts_test.sh index 81be0c6a..4ea28f74 100755 --- a/test/100_cross_hosts_test.sh +++ b/test/100_cross_hosts_test.sh @@ -10,8 +10,8 @@ SUBNET_2=10.2.3.0/24 start_suite "Ping over cross-host weave network (with and without IPAM)" -weave_on $HOST1 launch -iprange $UNIVERSE -ipsubnet $SUBNET_1 -weave_on $HOST2 launch -iprange $UNIVERSE -ipsubnet $SUBNET_1 $HOST1 +weave_on $HOST1 launch --ipalloc-range $UNIVERSE --ipalloc-default-subnet $SUBNET_1 +weave_on $HOST2 launch --ipalloc-range $UNIVERSE --ipalloc-default-subnet $SUBNET_1 $HOST1 start_container $HOST1 $C1/24 --name=c1 start_container $HOST2 ip:$C2/24 --name=c2 diff --git a/test/110_encryption_test.sh b/test/110_encryption_test.sh index 967e0003..7d4686aa 100755 --- a/test/110_encryption_test.sh +++ b/test/110_encryption_test.sh @@ -7,8 +7,8 @@ C2=10.2.1.7 start_suite "Ping over encrypted cross-host weave network" -weave_on $HOST1 launch -password notverysecure -weave_on $HOST2 launch -password notverysecure $HOST1 +weave_on $HOST1 launch --password notverysecure +weave_on $HOST2 launch --password notverysecure $HOST1 start_container $HOST1 $C1/24 --name=c1 start_container $HOST2 $C2/24 --name=c2 diff --git a/test/130_expose_test.sh b/test/130_expose_test.sh index 5079deb4..9cc216eb 100755 --- a/test/130_expose_test.sh +++ b/test/130_expose_test.sh @@ -40,7 +40,7 @@ run_on1 " $PING $EXP" weave_on1 "hide $EXP/24" run_on1 "! $PING $EXP" -weave_on $HOST1 launch -iprange $UNIVERSE +weave_on $HOST1 launch --ipalloc-range $UNIVERSE start_container $HOST1 $C1/24 --name=c1 start_container $HOST1 $C2/24 --name=c2 diff --git a/test/140_weave_local_test.sh b/test/140_weave_local_test.sh index f3d00d6d..4e392370 100755 --- a/test/140_weave_local_test.sh +++ b/test/140_weave_local_test.sh @@ -6,7 +6,7 @@ start_suite "Run weave with --local" run_on $HOST1 sudo weave --local reset -run_on $HOST1 sudo weave --local launch -iprange 10.2.5.0/24 +run_on $HOST1 sudo weave --local launch --ipalloc-range 10.2.5.0/24 assert_raises "docker_on $HOST1 ps | grep weave" run_on $HOST1 sudo weave --local run 10.2.6.5/24 -ti --name=c1 $SMALL_IMAGE /bin/sh diff --git a/test/210_dns_multicast_test.sh b/test/210_dns_multicast_test.sh index fb47f334..e8619703 100755 --- a/test/210_dns_multicast_test.sh +++ b/test/210_dns_multicast_test.sh @@ -29,8 +29,8 @@ check() { start_suite "Resolve names across hosts (with and without IPAM), and repopulate on restart" -weave_on $HOST1 launch-router -iprange $UNIVERSE -weave_on $HOST2 launch-router -iprange $UNIVERSE $HOST1 +weave_on $HOST1 launch-router --ipalloc-range $UNIVERSE +weave_on $HOST2 launch-router --ipalloc-range $UNIVERSE $HOST1 start_container $HOST2 $C2/24 --name=c2 -h $NAME2 start_container_with_dns $HOST1 $C1/24 --name=c1 diff --git a/test/270_use_name_as_hostname_test.sh b/test/270_use_name_as_hostname_test.sh index 9d59bbe9..4ef841b9 100755 --- a/test/270_use_name_as_hostname_test.sh +++ b/test/270_use_name_as_hostname_test.sh @@ -22,7 +22,7 @@ assert_expected_fqdn() { start_suite "Use container name as hostname" -weave_on $HOST1 launch -iprange 10.2.0.0/24 +weave_on $HOST1 launch --ipalloc-range 10.2.0.0/24 assert_expected_fqdn "$NAME.$DOMAIN" --name=$NAME assert_expected_fqdn "$NAME.$DOMAIN" --name $NAME diff --git a/test/500_weave_multi_cidr_test.sh b/test/500_weave_multi_cidr_test.sh index 320cb07b..83bc20c8 100755 --- a/test/500_weave_multi_cidr_test.sh +++ b/test/500_weave_multi_cidr_test.sh @@ -73,7 +73,7 @@ start_suite "Weave run/start/attach/detach/expose/hide with multiple cidr argume # specific address, i.e. we are assuming that IPAM always returns the # lowest available address in the subnet -weave_on $HOST1 launch-router -iprange 10.2.3.0/24 +weave_on $HOST1 launch-router --ipalloc-range 10.2.3.0/24 launch_dns_on $HOST1 10.254.254.254/24 # Run container with three cidrs diff --git a/test/620_proxy_entrypoint_command_test.sh b/test/620_proxy_entrypoint_command_test.sh index 20316d32..fad4b868 100755 --- a/test/620_proxy_entrypoint_command_test.sh +++ b/test/620_proxy_entrypoint_command_test.sh @@ -26,7 +26,7 @@ run_container "grep ^1$ /sys/class/net/ethwe/carrier" build_image false '["/bin/false"]' '' run_container "--entrypoint='grep' false ^1$ /sys/class/net/ethwe/carrier" -weave_on $HOST1 launch-router -iprange 10.2.2.0/24 +weave_on $HOST1 launch-router --ipalloc-range 10.2.2.0/24 docker_on $HOST1 kill weaveproxy weave_on $HOST1 launch-proxy diff --git a/test/660_proxy_ipam_test.sh b/test/660_proxy_ipam_test.sh index 72a4ceed..0e27b5ec 100755 --- a/test/660_proxy_ipam_test.sh +++ b/test/660_proxy_ipam_test.sh @@ -17,8 +17,8 @@ assert_no_ethwe() { start_suite "Ping proxied containers over cross-host weave network (with IPAM)" -weave_on $HOST1 launch-router -iprange $UNIVERSE -weave_on $HOST2 launch-router -iprange $UNIVERSE $HOST1 +weave_on $HOST1 launch-router --ipalloc-range $UNIVERSE +weave_on $HOST2 launch-router --ipalloc-range $UNIVERSE $HOST1 weave_on $HOST1 launch-proxy weave_on $HOST2 launch-proxy --no-default-ipalloc diff --git a/weave b/weave index 1b80bd88..95a34e02 100755 --- a/weave +++ b/weave @@ -1148,30 +1148,6 @@ deprecation_warnings() { -no-default-ipam|--no-default-ipam) deprecation_warning $1 "--no-default-ipalloc" ;; - --tlscacert|--tlscacert=*) - deprecation_warning "--tlscacert" "--tls-cacert" - [ "$1" == "--tlscacert" ] && shift - ;; - --tls-cacert) - shift - ;; - --tlscert|--tlscert=*) - deprecation_warning "--tlscert" "--tls-cert" - [ "$1" == "--tlscert" ] && shift - ;; - --tls-cert) - shift - ;; - --tlskey|--tlskey=*) - deprecation_warning "--tlskey" "--tls-key" - [ "$1" == "--tlskey" ] && shift - ;; - --tls-key) - shift - ;; - --tlsverify) - deprecation_warning "--tlsverify" "--tls-verify" - ;; esac shift done From 4fdb14293bf42c0594425be80bb07b931019d0bd Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Tue, 7 Jul 2015 10:33:20 +0000 Subject: [PATCH 029/180] Move ipam/address to net/address --- ipam/allocate.go | 2 +- ipam/allocator.go | 2 +- ipam/allocator_test.go | 2 +- ipam/claim.go | 2 +- ipam/http.go | 2 +- ipam/http_test.go | 2 +- ipam/ring/entry.go | 2 +- ipam/ring/ring.go | 2 +- ipam/ring/ring_test.go | 2 +- ipam/space/space.go | 2 +- ipam/space/space_test.go | 2 +- ipam/testutils_test.go | 2 +- {ipam => net}/address/address.go | 0 prog/weaver/main.go | 2 +- 14 files changed, 13 insertions(+), 13 deletions(-) rename {ipam => net}/address/address.go (100%) diff --git a/ipam/allocate.go b/ipam/allocate.go index 0e4a9e4b..f85c6579 100644 --- a/ipam/allocate.go +++ b/ipam/allocate.go @@ -3,7 +3,7 @@ package ipam import ( "fmt" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" ) type allocateResult struct { diff --git a/ipam/allocator.go b/ipam/allocator.go index a63ecb5b..50795d19 100644 --- a/ipam/allocator.go +++ b/ipam/allocator.go @@ -8,10 +8,10 @@ import ( "time" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" "github.com/weaveworks/weave/ipam/paxos" "github.com/weaveworks/weave/ipam/ring" "github.com/weaveworks/weave/ipam/space" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/allocator_test.go b/ipam/allocator_test.go index 37802495..3c9075e1 100644 --- a/ipam/allocator_test.go +++ b/ipam/allocator_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/claim.go b/ipam/claim.go index 8d96e6e2..8b34812b 100644 --- a/ipam/claim.go +++ b/ipam/claim.go @@ -3,7 +3,7 @@ package ipam import ( "fmt" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/http.go b/ipam/http.go index 0b665385..1ea48c32 100644 --- a/ipam/http.go +++ b/ipam/http.go @@ -8,7 +8,7 @@ import ( "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" ) func badRequest(w http.ResponseWriter, err error) { diff --git a/ipam/http_test.go b/ipam/http_test.go index 97ce7a24..36183b56 100644 --- a/ipam/http_test.go +++ b/ipam/http_test.go @@ -13,7 +13,7 @@ import ( "github.com/gorilla/mux" "github.com/stretchr/testify/require" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" wt "github.com/weaveworks/weave/testing" ) diff --git a/ipam/ring/entry.go b/ipam/ring/entry.go index 358216ec..e33bd488 100644 --- a/ipam/ring/entry.go +++ b/ipam/ring/entry.go @@ -4,7 +4,7 @@ import ( "sort" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/ring/ring.go b/ipam/ring/ring.go index 2105939c..fbeeb21b 100644 --- a/ipam/ring/ring.go +++ b/ipam/ring/ring.go @@ -13,7 +13,7 @@ import ( "time" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/ring/ring_test.go b/ipam/ring/ring_test.go index 852f060e..e29c3a5e 100644 --- a/ipam/ring/ring_test.go +++ b/ipam/ring/ring_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/space/space.go b/ipam/space/space.go index 1d912370..06e1bb34 100644 --- a/ipam/space/space.go +++ b/ipam/space/space.go @@ -6,7 +6,7 @@ import ( "sort" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" ) type Space struct { diff --git a/ipam/space/space_test.go b/ipam/space/space_test.go index 1a096fe3..7c17a3bc 100644 --- a/ipam/space/space_test.go +++ b/ipam/space/space_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" wt "github.com/weaveworks/weave/testing" ) diff --git a/ipam/testutils_test.go b/ipam/testutils_test.go index cab3daea..37855666 100644 --- a/ipam/testutils_test.go +++ b/ipam/testutils_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/ipam/address" + "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" ) diff --git a/ipam/address/address.go b/net/address/address.go similarity index 100% rename from ipam/address/address.go rename to net/address/address.go diff --git a/prog/weaver/main.go b/prog/weaver/main.go index 4f4b68de..1b900003 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -15,8 +15,8 @@ import ( . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" "github.com/weaveworks/weave/ipam" - "github.com/weaveworks/weave/ipam/address" weavenet "github.com/weaveworks/weave/net" + "github.com/weaveworks/weave/net/address" weave "github.com/weaveworks/weave/router" ) From 22446ffc19b6422f96558445a256d164db9b90bf Mon Sep 17 00:00:00 2001 From: Michael Bridgen Date: Tue, 7 Jul 2015 12:44:37 +0100 Subject: [PATCH 030/180] Handle --option=value as well as --option value In any place we munge options, treat the form with an equals the same as the form without. The exes ultimately invoked by the script handle both forms, so unless we need to do something with the option in the script, we can just let options fall through. --- weave | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/weave b/weave index 95a34e02..610878d2 100755 --- a/weave +++ b/weave @@ -944,8 +944,14 @@ common_launch_args() { args="" while [ $# -gt 0 ] ; do case "$1" in + --log-level) + [ $# -gt 1 ] || usage + args="$args $1 $2" + shift + ;; --log-level=*) args="$args $1" + ;; esac shift done @@ -978,17 +984,31 @@ launch_router() { export WEAVE_PASSWORD shift 2 ;; + --password=*) + WEAVE_PASSWORD="${1#*=}" + export WEAVE_PASSWORD + shift + ;; -port|--port) [ $# -gt 1 ] || usage CONTAINER_PORT="$2" shift 2 ;; + --port=*) + CONTAINER_PORT="${1#*=}" + shift + ;; -iprange|--iprange|--ipalloc-range) [ $# -gt 1 ] || usage IPRANGE="$2" IPRANGE_SPECIFIED=1 shift 2 ;; + --ipalloc-range=*) + IPRANGE="${1#*=}" + IPRANGE_SPECIFIED=1 + shift + ;; *) ARGS="$ARGS '$(echo "$1" | sed "s|'|'\"'\"'|g")'" shift From e621aca77e4f5b6f820b5bf2eba71cc7b3dde8f7 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Mon, 6 Jul 2015 18:05:13 +0100 Subject: [PATCH 031/180] Added --ignore-iface option to netcheck and use it to ignore weave bridge route --- net/route.go | 11 +++++++++-- prog/netcheck/netcheck.go | 17 ++++++++++++----- weave | 4 ++-- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/net/route.go b/net/route.go index 6d1722ad..bff99e2d 100644 --- a/net/route.go +++ b/net/route.go @@ -9,13 +9,17 @@ import ( // A network is considered free if it does not overlap any existing // routes on this host. This is the same approach taken by Docker. -func CheckNetworkFree(subnet *net.IPNet) error { +func CheckNetworkFree(subnet *net.IPNet, ignoreIfName string) error { routes, err := netlink.RouteList(nil, netlink.FAMILY_V4) if err != nil { return err } for _, route := range routes { if route.Dst != nil && overlaps(route.Dst, subnet) { + if link, err := netlink.LinkByIndex(route.LinkIndex); err == nil && link.Attrs().Name == ignoreIfName { + continue + } + return fmt.Errorf("Network %s overlaps with existing route %s on host.", subnet, route.Dst) } } @@ -29,13 +33,16 @@ func overlaps(n1, n2 *net.IPNet) bool { // For a specific address, we only care if it is actually *inside* an // existing route, because weave-local traffic never hits IP routing. -func CheckAddressOverlap(addr net.IP) error { +func CheckAddressOverlap(addr net.IP, ignoreIfName string) error { routes, err := netlink.RouteList(nil, netlink.FAMILY_V4) if err != nil { return err } for _, route := range routes { if route.Dst != nil && route.Dst.Contains(addr) { + if link, err := netlink.LinkByIndex(route.LinkIndex); err == nil && link.Attrs().Name == ignoreIfName { + continue + } return fmt.Errorf("Address %s overlaps with existing route %s on host.", addr, route.Dst) } } diff --git a/prog/netcheck/netcheck.go b/prog/netcheck/netcheck.go index 96a26ed4..78261a0e 100644 --- a/prog/netcheck/netcheck.go +++ b/prog/netcheck/netcheck.go @@ -6,6 +6,7 @@ import ( "net" "os" + "github.com/docker/docker/pkg/mflag" weavenet "github.com/weaveworks/weave/net" ) @@ -15,19 +16,25 @@ func fatal(err error) { } func main() { - if len(os.Args) <= 1 { - os.Exit(0) + var ignoreIfaceName string + + mflag.StringVar(&ignoreIfaceName, []string{"-ignore-iface"}, "", "name of interface to ignore)") + mflag.Parse() + + if len(mflag.Args()) < 1 { + fmt.Fprintln(os.Stderr, "usage: netcheck [--ignore-iface ] network-cidr") + os.Exit(1) } - cidrStr := os.Args[1] + cidrStr := mflag.Args()[0] addr, ipnet, err := net.ParseCIDR(cidrStr) if err != nil { fatal(err) } if ipnet.IP.Equal(addr) { - err = weavenet.CheckNetworkFree(ipnet) + err = weavenet.CheckNetworkFree(ipnet, ignoreIfaceName) } else { - err = weavenet.CheckAddressOverlap(addr) + err = weavenet.CheckAddressOverlap(addr, ignoreIfaceName) } if err != nil { fatal(err) diff --git a/weave b/weave index 479ff2c5..9a10adb6 100755 --- a/weave +++ b/weave @@ -860,7 +860,7 @@ ipam_cidrs() { ALL_CIDRS="$ALL_CIDRS $CIDR" else # This is a plain IP address; warn if it clashes but carry on - command_exists netcheck && netcheck $1 || true + command_exists netcheck && netcheck --ignore-iface=$BRIDGE $1 || true ALL_CIDRS="$ALL_CIDRS $1" fi shift 1 @@ -998,7 +998,7 @@ launch_router() { eval "set -- $ARGS" if [ -z "$IPRANGE_SPECIFIED" ] ; then IPRANGE="10.32.0.0/12" - if command_exists netcheck && ! netcheck $IPRANGE ; then + if command_exists netcheck && ! netcheck --ignore-iface=$BRIDGE $IPRANGE ; then echo "Default --ipalloc-range $IPRANGE overlaps with existing route on host." >&2 echo "Please pick another range and set it on all hosts." >&2 exit 1 From 6666fd14ac15866fc07c9bb27e620069f58dc3c6 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Tue, 7 Jul 2015 10:00:44 +0100 Subject: [PATCH 032/180] Allow multiple --ignore-iface arguments --- net/route.go | 35 +++++++++++++++++++---------------- prog/netcheck/netcheck.go | 21 ++++++++++++++++----- 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/net/route.go b/net/route.go index bff99e2d..463f843b 100644 --- a/net/route.go +++ b/net/route.go @@ -9,21 +9,13 @@ import ( // A network is considered free if it does not overlap any existing // routes on this host. This is the same approach taken by Docker. -func CheckNetworkFree(subnet *net.IPNet, ignoreIfName string) error { - routes, err := netlink.RouteList(nil, netlink.FAMILY_V4) - if err != nil { - return err - } - for _, route := range routes { +func CheckNetworkFree(subnet *net.IPNet, ignoreIfaceNames map[string]struct{}) error { + return forEachRoute(ignoreIfaceNames, func(route netlink.Route) error { if route.Dst != nil && overlaps(route.Dst, subnet) { - if link, err := netlink.LinkByIndex(route.LinkIndex); err == nil && link.Attrs().Name == ignoreIfName { - continue - } - return fmt.Errorf("Network %s overlaps with existing route %s on host.", subnet, route.Dst) } - } - return nil + return nil + }) } // Two networks overlap if the start-point of one is inside the other. @@ -33,17 +25,28 @@ func overlaps(n1, n2 *net.IPNet) bool { // For a specific address, we only care if it is actually *inside* an // existing route, because weave-local traffic never hits IP routing. -func CheckAddressOverlap(addr net.IP, ignoreIfName string) error { +func CheckAddressOverlap(addr net.IP, ignoreIfaceNames map[string]struct{}) error { + return forEachRoute(ignoreIfaceNames, func(route netlink.Route) error { + if route.Dst != nil && route.Dst.Contains(addr) { + return fmt.Errorf("Address %s overlaps with existing route %s on host.", addr, route.Dst) + } + return nil + }) +} + +func forEachRoute(ignoreIfaceNames map[string]struct{}, check func(netlink.Route) error) error { routes, err := netlink.RouteList(nil, netlink.FAMILY_V4) if err != nil { return err } for _, route := range routes { - if route.Dst != nil && route.Dst.Contains(addr) { - if link, err := netlink.LinkByIndex(route.LinkIndex); err == nil && link.Attrs().Name == ignoreIfName { + if link, err := netlink.LinkByIndex(route.LinkIndex); err == nil { + if _, found := ignoreIfaceNames[link.Attrs().Name]; found { continue } - return fmt.Errorf("Address %s overlaps with existing route %s on host.", addr, route.Dst) + } + if err := check(route); err != nil { + return err } } return nil diff --git a/prog/netcheck/netcheck.go b/prog/netcheck/netcheck.go index 78261a0e..fe822f2e 100644 --- a/prog/netcheck/netcheck.go +++ b/prog/netcheck/netcheck.go @@ -15,10 +15,21 @@ func fatal(err error) { os.Exit(1) } -func main() { - var ignoreIfaceName string +type stringList map[string]struct{} - mflag.StringVar(&ignoreIfaceName, []string{"-ignore-iface"}, "", "name of interface to ignore)") +func (ss *stringList) Set(value string) error { + (*ss)[value] = struct{}{} + return nil +} + +func (ss *stringList) String() string { + return fmt.Sprintf("%v", *ss) +} + +func main() { + ignoreIfaceNames := make(stringList) + + mflag.Var(&ignoreIfaceNames, []string{"-ignore-iface"}, "name of interface to ignore)") mflag.Parse() if len(mflag.Args()) < 1 { @@ -32,9 +43,9 @@ func main() { fatal(err) } if ipnet.IP.Equal(addr) { - err = weavenet.CheckNetworkFree(ipnet, ignoreIfaceName) + err = weavenet.CheckNetworkFree(ipnet, ignoreIfaceNames) } else { - err = weavenet.CheckAddressOverlap(addr, ignoreIfaceName) + err = weavenet.CheckAddressOverlap(addr, ignoreIfaceNames) } if err != nil { fatal(err) From 8eb092c7548c1300ab327131039a21c345d44592 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Mon, 6 Jul 2015 20:32:50 +0100 Subject: [PATCH 033/180] display usage on stderr so that the likes of $(weave proxy-typo-env) don't do weird things Closes #1082. --- weave | 81 +++++++++++++++++++++++++++++++---------------------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/weave b/weave index 4e065a5b..ba4f2f17 100755 --- a/weave +++ b/weave @@ -24,45 +24,48 @@ IP_REGEXP="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" CIDR_REGEXP="$IP_REGEXP/[0-9]{1,2}" usage() { - echo "Usage:" - echo "weave setup" - echo "weave launch [--password ] [--nickname ]" - echo " [--ipalloc-range [--ipalloc-default-subnet ]]" - echo " [--no-discovery] [--init-peer-count ] ..." - echo "weave launch-router [--password ] [--nickname ]" - echo " [--ipalloc-range [--ipalloc-default-subnet ]]" - echo " [--no-discovery] [--init-peer-count ] ..." - echo "weave launch-dns []" - echo "weave launch-proxy [-H ] [--with-dns | --without-dns]" - echo " [--no-default-ipalloc]" - echo "weave connect [--replace] [ ...]" - echo "weave forget ..." - echo "weave run [--with-dns | --without-dns] [ ...]" - echo " ..." - echo "weave start [ ...] " - echo "weave attach [ ...] " - echo "weave detach [ ...] " - echo "weave dns-add [ ...] [-h ]" - echo "weave dns-remove [ ...] [-h ]" - echo "weave expose [ ...] [-h ]" - echo "weave hide [ ...]" - echo "weave ps [ ...]" - echo "weave status" - echo "weave env" - echo "weave config" - echo "weave version" - echo "weave stop" - echo "weave stop-router" - echo "weave stop-dns" - echo "weave stop-proxy" - echo "weave reset" - echo "weave rmpeer " - echo - echo "where = [:]" - echo " = /" - echo " = [ip:] | net: | net:default" - echo " = [tcp://][]: | [unix://]/path/to/socket" - echo " = or weave internal peer ID" + cat >&2 <] [--nickname ] + [--ipalloc-range [--ipalloc-default-subnet ]] + [--no-discovery] [--init-peer-count ] ... +weave launch-router [--password ] [--nickname ] + [--ipalloc-range [--ipalloc-default-subnet ]] + [--no-discovery] [--init-peer-count ] ... +weave launch-dns [] +weave launch-proxy [-H ] [--with-dns | --without-dns] + [--no-default-ipalloc] +weave connect [--replace] [ ...] +weave forget ... +weave run [--with-dns | --without-dns] [ ...] + ... +weave start [ ...] +weave attach [ ...] +weave detach [ ...] +weave dns-add [ ...] [-h ] +weave dns-remove [ ...] [-h ] +weave expose [ ...] [-h ] +weave hide [ ...] +weave ps [ ...] +weave status +weave env +weave config +weave version +weave stop +weave stop-router +weave stop-dns +weave stop-proxy +weave reset +weave rmpeer + +where = [:] + = / + = [ip:] | net: | net:default + = [tcp://][]: | [unix://]/path/to/socket + = or weave internal peer ID +EOF exit 1 } From a6a74001bda3a447f7afaae0ae4f611142b8a7be Mon Sep 17 00:00:00 2001 From: David Wragg Date: Mon, 29 Jun 2015 17:28:04 +0100 Subject: [PATCH 034/180] Make TCPReceiver more closely mirror TCPSender --- router/connection.go | 23 ++++++----------------- router/crypto.go | 25 +++++++++++++++++-------- router/handshake.go | 7 +++++-- 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/router/connection.go b/router/connection.go index 03c69a94..9fe080ff 100644 --- a/router/connection.go +++ b/router/connection.go @@ -2,7 +2,6 @@ package router import ( "encoding/binary" - "encoding/gob" "fmt" "net" "sync" @@ -284,7 +283,7 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch conn.TCPConn.SetLinger(0) - dec, err := conn.handshake(acceptNewPeer) + tcpReceiver, err := conn.handshake(acceptNewPeer) if err != nil { return } @@ -303,7 +302,7 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch if err = conn.initHeartbeats(); err != nil { return } - go conn.receiveTCP(dec) + go conn.receiveTCP(tcpReceiver) err = conn.actorLoop(actionChan) } @@ -422,23 +421,13 @@ func (conn *LocalConnection) sendProtocolMsg(m ProtocolMsg) error { return conn.tcpSender.Send(Concat([]byte{byte(m.tag)}, m.msg)) } -func (conn *LocalConnection) receiveTCP(decoder *gob.Decoder) { - usingPassword := conn.SessionKey != nil - var receiver TCPReceiver - if usingPassword { - receiver = NewEncryptedTCPReceiver(conn.SessionKey, conn.outbound) - } else { - receiver = NewSimpleTCPReceiver() - } +func (conn *LocalConnection) receiveTCP(receiver TCPReceiver) { var err error for { - var msg []byte conn.extendReadDeadline() - if err = decoder.Decode(&msg); err != nil { - break - } - msg, err = receiver.Decode(msg) - if err != nil { + + var msg []byte + if msg, err = receiver.Receive(); err != nil { break } if len(msg) < 1 { diff --git a/router/crypto.go b/router/crypto.go index b66d2b73..c77f6250 100644 --- a/router/crypto.go +++ b/router/crypto.go @@ -370,10 +370,11 @@ func (sender *EncryptedTCPSender) Send(msg []byte) error { } type TCPReceiver interface { - Decode([]byte) ([]byte, error) + Receive() ([]byte, error) } type SimpleTCPReceiver struct { + decoder *gob.Decoder } type EncryptedTCPReceiver struct { @@ -381,25 +382,33 @@ type EncryptedTCPReceiver struct { state *TCPCryptoState } -func NewSimpleTCPReceiver() *SimpleTCPReceiver { - return &SimpleTCPReceiver{} +func NewSimpleTCPReceiver(decoder *gob.Decoder) *SimpleTCPReceiver { + return &SimpleTCPReceiver{decoder: decoder} } -func (receiver *SimpleTCPReceiver) Decode(msg []byte) ([]byte, error) { - return msg, nil +func (receiver *SimpleTCPReceiver) Receive() ([]byte, error) { + var msg []byte + err := receiver.decoder.Decode(&msg) + return msg, err } -func NewEncryptedTCPReceiver(sessionKey *[32]byte, outbound bool) *EncryptedTCPReceiver { +func NewEncryptedTCPReceiver(decoder *gob.Decoder, sessionKey *[32]byte, outbound bool) *EncryptedTCPReceiver { return &EncryptedTCPReceiver{ - SimpleTCPReceiver: *NewSimpleTCPReceiver(), + SimpleTCPReceiver: *NewSimpleTCPReceiver(decoder), state: NewTCPCryptoState(sessionKey, !outbound)} } -func (receiver *EncryptedTCPReceiver) Decode(msg []byte) ([]byte, error) { +func (receiver *EncryptedTCPReceiver) Receive() ([]byte, error) { + msg, err := receiver.SimpleTCPReceiver.Receive() + if err != nil { + return nil, err + } + decodedMsg, success := secretbox.Open(nil, msg, &receiver.state.nonce, receiver.state.sessionKey) if !success { return nil, fmt.Errorf("Unable to decrypt TCP msg") } + receiver.state.advance() return decodedMsg, nil } diff --git a/router/handshake.go b/router/handshake.go index d90423e7..2411ae72 100644 --- a/router/handshake.go +++ b/router/handshake.go @@ -45,7 +45,7 @@ func (fv *FieldValidator) Err() error { return fv.err } -func (conn *LocalConnection) handshake(acceptNewPeer bool) (*gob.Decoder, error) { +func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) { // We do not need to worry about locking in here as at this point // the connection is not reachable by any go-routine other than // ourself. Only when we add this connection to the conn.local @@ -99,6 +99,7 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (*gob.Decoder, error) } conn.uid = localConnID ^ remoteConnID + var tcpReceiver TCPReceiver remotePublicStr, rpErr := fv.Value("PublicKey") if usingPassword { if rpErr != nil { @@ -114,16 +115,18 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (*gob.Decoder, error) } conn.SessionKey = FormSessionKey(&remotePublic, private, conn.Router.Password) conn.tcpSender = NewEncryptedTCPSender(enc, conn.SessionKey, conn.outbound) + tcpReceiver = NewEncryptedTCPReceiver(dec, conn.SessionKey, conn.outbound) conn.Decryptor = NewNaClDecryptor(conn.SessionKey, conn.outbound) } else { if rpErr == nil { return nil, fmt.Errorf("Remote network is encrypted. Password required.") } conn.tcpSender = NewSimpleTCPSender(enc) + tcpReceiver = NewSimpleTCPReceiver(dec) conn.Decryptor = NewNonDecryptor() } - return dec, conn.setRemote(NewPeer(name, nickNameStr, uid, 0)) + return tcpReceiver, conn.setRemote(NewPeer(name, nickNameStr, uid, 0)) } func (conn *LocalConnection) exchangeHandshake(localConnID uint64, usingPassword bool, enc *gob.Encoder, dec *gob.Decoder) (*FieldValidator, *[32]byte, error) { From 5e10b901a3837495fb052277f90b8b6955dd44c4 Mon Sep 17 00:00:00 2001 From: David Wragg Date: Wed, 1 Jul 2015 12:11:31 +0100 Subject: [PATCH 035/180] Drop the check for duplicate connections in the handshake Duplicate connections are also detected and handled in AddConnection, I have not been able to reproduce #182 without the check, so although it may once have been necessary, it doesn't seem to be needed now. --- router/handshake.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/router/handshake.go b/router/handshake.go index 2411ae72..dd57d5df 100644 --- a/router/handshake.go +++ b/router/handshake.go @@ -86,9 +86,6 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) return nil, fmt.Errorf("Found unknown remote name: %s at %s", name, conn.remoteTCPAddr) } } - if existingConn, found := conn.Router.Ourself.ConnectionTo(name); found && existingConn.Established() { - return nil, fmt.Errorf("Already have connection to %s at %s", existingConn.Remote(), existingConn.RemoteTCPAddr()) - } uid, err := ParsePeerUID(uidStr) if err != nil { return nil, err From e50b1f1fe70e6e2f571206ecba848358c31aa137 Mon Sep 17 00:00:00 2001 From: David Wragg Date: Tue, 7 Jul 2015 12:19:37 +0100 Subject: [PATCH 036/180] Remove the "found" return value from Peers Fetch method Callers can simply check whether the returned *Peer is nil. --- router/gossip_test.go | 4 ++-- router/handshake.go | 2 +- router/mocks_test.go | 2 +- router/peers.go | 5 ++--- router/router.go | 11 ++++------- 5 files changed, 10 insertions(+), 14 deletions(-) diff --git a/router/gossip_test.go b/router/gossip_test.go index c6936a09..b5d18f93 100644 --- a/router/gossip_test.go +++ b/router/gossip_test.go @@ -60,8 +60,8 @@ func (router *Router) DeleteTestChannelConnection(r *Router) { fromName := router.Ourself.Peer.Name toName := r.Ourself.Peer.Name - fromPeer, _ := r.Peers.Fetch(fromName) - toPeer, _ := router.Peers.Fetch(toName) + fromPeer := r.Peers.Fetch(fromName) + toPeer := router.Peers.Fetch(toName) r.Peers.Dereference(fromPeer) router.Peers.Dereference(toPeer) diff --git a/router/handshake.go b/router/handshake.go index dd57d5df..b9f54831 100644 --- a/router/handshake.go +++ b/router/handshake.go @@ -82,7 +82,7 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) return nil, err } if !acceptNewPeer { - if _, found := conn.Router.Peers.Fetch(name); !found { + if conn.Router.Peers.Fetch(name) != nil { return nil, fmt.Errorf("Found unknown remote name: %s at %s", name, conn.remoteTCPAddr) } } diff --git a/router/mocks_test.go b/router/mocks_test.go index 7dacd9e9..183f642b 100644 --- a/router/mocks_test.go +++ b/router/mocks_test.go @@ -34,7 +34,7 @@ func (peers *Peers) AddTestRemoteConnection(p1, p2 *Peer) { func (peers *Peers) DeleteTestConnection(p *Peer) { toName := p.Name - toPeer, _ := peers.Fetch(toName) + toPeer := peers.Fetch(toName) peers.Dereference(toPeer) conn, _ := peers.ourself.ConnectionTo(toName) peers.ourself.deleteConnection(conn) diff --git a/router/peers.go b/router/peers.go index 5b11099e..9f10e99d 100644 --- a/router/peers.go +++ b/router/peers.go @@ -61,11 +61,10 @@ func (peers *Peers) FetchWithDefault(peer *Peer) *Peer { return peer } -func (peers *Peers) Fetch(name PeerName) (*Peer, bool) { +func (peers *Peers) Fetch(name PeerName) *Peer { peers.RLock() defer peers.RUnlock() - peer, found := peers.table[name] - return peer, found // GRRR, why can't I inline this!? + return peers.table[name] } func (peers *Peers) Dereference(peer *Peer) { diff --git a/router/router.go b/router/router.go index 00f53588..f4a254fc 100644 --- a/router/router.go +++ b/router/router.go @@ -281,12 +281,9 @@ func (router *Router) udpReader(conn *net.UDPConn, po PacketSink) { func (router *Router) handleUDPPacketFunc(relayConn *LocalConnection, dec *EthernetDecoder, sender *net.UDPAddr, po PacketSink) FrameConsumer { return func(srcNameByte, dstNameByte []byte, frame []byte) { - srcPeer, found := router.Peers.Fetch(PeerNameFromBin(srcNameByte)) - if !found { - return - } - dstPeer, found := router.Peers.Fetch(PeerNameFromBin(dstNameByte)) - if !found { + srcPeer := router.Peers.Fetch(PeerNameFromBin(srcNameByte)) + dstPeer := router.Peers.Fetch(PeerNameFromBin(dstNameByte)) + if srcPeer == nil || dstPeer == nil { return } @@ -335,7 +332,7 @@ func (router *Router) handleUDPPacketFunc(relayConn *LocalConnection, dec *Ether checkWarn(po.WritePacket(frame)) } - dstPeer, found = router.Macs.Lookup(dstMac) + dstPeer, found := router.Macs.Lookup(dstMac) if !found || dstPeer != router.Ourself.Peer { router.LogFrame("Relaying broadcast", frame, dec) router.Ourself.RelayBroadcast(srcPeer, frame, dec) From 56863c3d0eccfb0d065e3c51f8f41e5801be3d3e Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Wed, 8 Jul 2015 14:43:21 +0000 Subject: [PATCH 037/180] Ensure bin/lint doesn't complain about removed files when used as a git precommit script. --- bin/lint | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/bin/lint b/bin/lint index 4e50906c..32e791fb 100755 --- a/bin/lint +++ b/bin/lint @@ -56,6 +56,11 @@ function lint { return fi + # Don't lint files that don't exist + if ! [ -a "${filename}" ]; then + return + fi + case "$ext" in go) lint_go "${filename}" ;; From c8718d85dc0f274efd1f9cc6817516ffd8666ca9 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Wed, 8 Jul 2015 14:47:02 +0000 Subject: [PATCH 038/180] Extend router/peers.go to allow multiple OnGC callbacks, and call the callbacks outside of the peers lock. --- router/peers.go | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/router/peers.go b/router/peers.go index 9f10e99d..b48662f0 100644 --- a/router/peers.go +++ b/router/peers.go @@ -12,7 +12,7 @@ type Peers struct { sync.RWMutex ourself *LocalPeer table map[PeerName]*Peer - onGC func(*Peer) + onGC []func(*Peer) } type UnknownPeerError struct { @@ -43,7 +43,21 @@ func NewPeers(ourself *LocalPeer, onGC func(*Peer)) *Peers { return &Peers{ ourself: ourself, table: make(map[PeerName]*Peer), - onGC: onGC} + onGC: []func(*Peer){onGC}} +} + +func (peers *Peers) OnGC(callback func(*Peer)) { + peers.Lock() + defer peers.Unlock() + peers.onGC = append(peers.onGC, callback) +} + +func (peers *Peers) invokeOnGCCallbacks(removed []*Peer) { + for _, callback := range peers.onGC { + for _, peer := range removed { + callback(peer) + } + } } func (peers *Peers) FetchWithDefault(peer *Peer) *Peer { @@ -105,13 +119,14 @@ func (peers *Peers) ApplyUpdate(update []byte) (PeerNameSet, PeerNameSet, error) // Now apply the updates newUpdate := peers.applyUpdate(decodedUpdate, decodedConns) - - for _, peerRemoved := range peers.garbageCollect() { + removed := peers.garbageCollect() + for _, peerRemoved := range removed { delete(newUpdate, peerRemoved.Name) } // Don't need to hold peers lock any longer peers.Unlock() + peers.invokeOnGCCallbacks(removed) updateNames := make(PeerNameSet) for _, peer := range decodedUpdate { @@ -145,8 +160,10 @@ func (peers *Peers) EncodePeers(names PeerNameSet) []byte { func (peers *Peers) GarbageCollect() []*Peer { peers.Lock() - defer peers.Unlock() - return peers.garbageCollect() + removed := peers.garbageCollect() + peers.Unlock() + peers.invokeOnGCCallbacks(removed) + return removed } func (peers *Peers) String() string { @@ -185,7 +202,6 @@ func (peers *Peers) garbageCollect() []*Peer { for name, peer := range peers.table { if _, found := reached[peer.Name]; !found && peer.localRefCount == 0 { delete(peers.table, name) - peers.onGC(peer) removed = append(removed, peer) } } From 89ad7e1ba210a2db3b093ac8a50acd830d4360af Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Wed, 8 Jul 2015 14:56:58 +0000 Subject: [PATCH 039/180] Move test gossip router out of ipam code for use in gossip dns code. --- ipam/allocator_test.go | 21 +++---- ipam/testutils_test.go | 121 ++------------------------------------ testing/gossip/mocks.go | 125 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 126 deletions(-) create mode 100644 testing/gossip/mocks.go diff --git a/ipam/allocator_test.go b/ipam/allocator_test.go index 3c9075e1..cb5c4b41 100644 --- a/ipam/allocator_test.go +++ b/ipam/allocator_test.go @@ -8,9 +8,10 @@ import ( "time" "github.com/stretchr/testify/require" + "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/net/address" - "github.com/weaveworks/weave/router" + "github.com/weaveworks/weave/testing/gossip" ) const ( @@ -166,13 +167,13 @@ func TestCancel(t *testing.T) { CIDR = "10.0.1.7/26" ) - router := TestGossipRouter{make(map[router.PeerName]chan interface{}), 0.0} + router := gossip.NewTestRouter(0.0) alloc1, subnet := makeAllocator("01:00:00:02:00:00", CIDR, 2) - alloc1.SetInterfaces(router.connect(alloc1.ourName, alloc1)) + alloc1.SetInterfaces(router.Connect(alloc1.ourName, alloc1)) alloc2, _ := makeAllocator("02:00:00:02:00:00", CIDR, 2) - alloc2.SetInterfaces(router.connect(alloc2.ourName, alloc2)) + alloc2.SetInterfaces(router.Connect(alloc2.ourName, alloc2)) alloc1.claimRingForTesting(alloc1, alloc2) alloc2.claimRingForTesting(alloc1, alloc2) @@ -254,17 +255,17 @@ func TestTransfer(t *testing.T) { require.True(t, err == nil, "Failed to get address") router.GossipBroadcast(alloc2.Gossip()) - router.flush() + router.Flush() router.GossipBroadcast(alloc3.Gossip()) - router.flush() - router.removePeer(alloc2.ourName) - router.removePeer(alloc3.ourName) + router.Flush() + router.RemovePeer(alloc2.ourName) + router.RemovePeer(alloc3.ourName) alloc2.Stop() alloc3.Stop() - router.flush() + router.Flush() require.NoError(t, alloc1.AdminTakeoverRanges(alloc2.ourName.String())) require.NoError(t, alloc1.AdminTakeoverRanges(alloc3.ourName.String())) - router.flush() + router.Flush() require.Equal(t, address.Offset(1022), alloc1.NumFreeAddresses(subnet)) diff --git a/ipam/testutils_test.go b/ipam/testutils_test.go index 37855666..294444d6 100644 --- a/ipam/testutils_test.go +++ b/ipam/testutils_test.go @@ -8,9 +8,9 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/router" + "github.com/weaveworks/weave/testing/gossip" ) type mockMessage struct { @@ -194,119 +194,8 @@ func AssertNothingSentErr(t *testing.T, ch <-chan error) { } } -// Router to convey gossip from one gossiper to another, for testing -type unicastMessage struct { - sender router.PeerName - buf []byte -} -type broadcastMessage struct { - data router.GossipData -} -type exitMessage struct { - exitChan chan struct{} -} -type flushMessage struct { - flushChan chan struct{} -} - -type TestGossipRouter struct { - gossipChans map[router.PeerName]chan interface{} - loss float32 // 0.0 means no loss -} - -func (grouter *TestGossipRouter) GossipBroadcast(update router.GossipData) error { - for _, gossipChan := range grouter.gossipChans { - select { - case gossipChan <- broadcastMessage{data: update}: - default: // drop the message if we cannot send it - } - } - return nil -} - -func (grouter *TestGossipRouter) flush() { - for _, gossipChan := range grouter.gossipChans { - flushChan := make(chan struct{}) - gossipChan <- flushMessage{flushChan: flushChan} - <-flushChan - } -} - -func (grouter *TestGossipRouter) removePeer(peer router.PeerName) { - gossipChan := grouter.gossipChans[peer] - resultChan := make(chan struct{}) - gossipChan <- exitMessage{exitChan: resultChan} - <-resultChan - delete(grouter.gossipChans, peer) -} - -type TestGossipRouterClient struct { - router *TestGossipRouter - sender router.PeerName -} - -func (grouter *TestGossipRouter) run(gossiper router.Gossiper, gossipChan chan interface{}) { - gossipTimer := time.Tick(10 * time.Second) - for { - select { - case gossip := <-gossipChan: - switch message := gossip.(type) { - case exitMessage: - close(message.exitChan) - return - - case flushMessage: - close(message.flushChan) - - case unicastMessage: - if rand.Float32() > (1.0 - grouter.loss) { - continue - } - if err := gossiper.OnGossipUnicast(message.sender, message.buf); err != nil { - panic(fmt.Sprintf("Error doing gossip unicast to %s: %s", message.sender, err)) - } - - case broadcastMessage: - if rand.Float32() > (1.0 - grouter.loss) { - continue - } - for _, msg := range message.data.Encode() { - if _, err := gossiper.OnGossipBroadcast(msg); err != nil { - panic(fmt.Sprintf("Error doing gossip broadcast: %s", err)) - } - } - } - case <-gossipTimer: - grouter.GossipBroadcast(gossiper.Gossip()) - } - } -} - -func (grouter *TestGossipRouter) connect(sender router.PeerName, gossiper router.Gossiper) router.Gossip { - gossipChan := make(chan interface{}, 100) - - go grouter.run(gossiper, gossipChan) - - grouter.gossipChans[sender] = gossipChan - return TestGossipRouterClient{grouter, sender} -} - -func (client TestGossipRouterClient) GossipUnicast(dstPeerName router.PeerName, buf []byte) error { - select { - case client.router.gossipChans[dstPeerName] <- unicastMessage{sender: client.sender, buf: buf}: - default: // drop the message if we cannot send it - common.Log.Errorf("Dropping message") - } - return nil -} - -func (client TestGossipRouterClient) GossipBroadcast(update router.GossipData) error { - return client.router.GossipBroadcast(update) -} - -func makeNetworkOfAllocators(size int, cidr string) ([]*Allocator, TestGossipRouter, address.Range) { - - gossipRouter := TestGossipRouter{make(map[router.PeerName]chan interface{}), 0.0} +func makeNetworkOfAllocators(size int, cidr string) ([]*Allocator, *gossip.TestRouter, address.Range) { + gossipRouter := gossip.NewTestRouter(0.0) allocs := make([]*Allocator, size) var subnet address.Range @@ -314,13 +203,13 @@ func makeNetworkOfAllocators(size int, cidr string) ([]*Allocator, TestGossipRou var alloc *Allocator alloc, subnet = makeAllocator(fmt.Sprintf("%02d:00:00:02:00:00", i), cidr, uint(size/2+1)) - alloc.SetInterfaces(gossipRouter.connect(alloc.ourName, alloc)) + alloc.SetInterfaces(gossipRouter.Connect(alloc.ourName, alloc)) alloc.Start() allocs[i] = alloc } gossipRouter.GossipBroadcast(allocs[size-1].Gossip()) - gossipRouter.flush() + gossipRouter.Flush() return allocs, gossipRouter, subnet } diff --git a/testing/gossip/mocks.go b/testing/gossip/mocks.go new file mode 100644 index 00000000..d3aad9f3 --- /dev/null +++ b/testing/gossip/mocks.go @@ -0,0 +1,125 @@ +package gossip + +import ( + "fmt" + "math/rand" + "time" + + "github.com/weaveworks/weave/common" + "github.com/weaveworks/weave/router" +) + +// Router to convey gossip from one gossiper to another, for testing +type unicastMessage struct { + sender router.PeerName + buf []byte +} +type broadcastMessage struct { + data router.GossipData +} +type exitMessage struct { + exitChan chan struct{} +} +type flushMessage struct { + flushChan chan struct{} +} + +type TestRouter struct { + gossipChans map[router.PeerName]chan interface{} + loss float32 // 0.0 means no loss +} + +func NewTestRouter(loss float32) *TestRouter { + return &TestRouter{make(map[router.PeerName]chan interface{}, 100), loss} +} + +func (grouter *TestRouter) GossipBroadcast(update router.GossipData) error { + for _, gossipChan := range grouter.gossipChans { + select { + case gossipChan <- broadcastMessage{data: update}: + default: // drop the message if we cannot send it + common.Log.Errorf("Dropping message") + } + } + return nil +} + +func (grouter *TestRouter) Flush() { + for _, gossipChan := range grouter.gossipChans { + flushChan := make(chan struct{}) + gossipChan <- flushMessage{flushChan: flushChan} + <-flushChan + } +} + +func (grouter *TestRouter) RemovePeer(peer router.PeerName) { + gossipChan := grouter.gossipChans[peer] + resultChan := make(chan struct{}) + gossipChan <- exitMessage{exitChan: resultChan} + <-resultChan + delete(grouter.gossipChans, peer) +} + +type TestRouterClient struct { + router *TestRouter + sender router.PeerName +} + +func (grouter *TestRouter) run(gossiper router.Gossiper, gossipChan chan interface{}) { + gossipTimer := time.Tick(10 * time.Second) + for { + select { + case gossip := <-gossipChan: + switch message := gossip.(type) { + case exitMessage: + close(message.exitChan) + return + + case flushMessage: + close(message.flushChan) + + case unicastMessage: + if rand.Float32() > (1.0 - grouter.loss) { + continue + } + if err := gossiper.OnGossipUnicast(message.sender, message.buf); err != nil { + panic(fmt.Sprintf("Error doing gossip unicast to %s: %s", message.sender, err)) + } + + case broadcastMessage: + if rand.Float32() > (1.0 - grouter.loss) { + continue + } + for _, msg := range message.data.Encode() { + if _, err := gossiper.OnGossipBroadcast(msg); err != nil { + panic(fmt.Sprintf("Error doing gossip broadcast: %s", err)) + } + } + } + case <-gossipTimer: + grouter.GossipBroadcast(gossiper.Gossip()) + } + } +} + +func (grouter *TestRouter) Connect(sender router.PeerName, gossiper router.Gossiper) router.Gossip { + gossipChan := make(chan interface{}, 100) + + go grouter.run(gossiper, gossipChan) + + grouter.gossipChans[sender] = gossipChan + return TestRouterClient{grouter, sender} +} + +func (client TestRouterClient) GossipUnicast(dstPeerName router.PeerName, buf []byte) error { + select { + case client.router.gossipChans[dstPeerName] <- unicastMessage{sender: client.sender, buf: buf}: + default: // drop the message if we cannot send it + common.Log.Errorf("Dropping message") + } + return nil +} + +func (client TestRouterClient) GossipBroadcast(update router.GossipData) error { + return client.router.GossipBroadcast(update) +} From 26c1bcf866dbebba5a3ed89c63d2fb8c7f46fb2b Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Wed, 8 Jul 2015 16:51:25 +0100 Subject: [PATCH 040/180] clarify role of IP allocator range Part of #1035. --- site/ipam.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/site/ipam.md b/site/ipam.md index 295bbf93..09f2a2b3 100644 --- a/site/ipam.md +++ b/site/ipam.md @@ -94,6 +94,14 @@ range. This can be overridden with the `-iprange` option, e.g. and must be the same on every host. +> The specified range is for *exclusive* use by the IP allocator. In +> particular, when starting containers with manually assigned IP +> addresses, these must be outside the IP allocator's range. If, in +> our example, you subsequently executed `docker run -e +> WEAVE_CIDR=10.2.3.1/24 -ti ubuntu`, the IP allocator might assign +> the same address to another container, which will break IP routing +> for the containers sharing an address. + The range parameter is written in [CIDR notation](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) - in this example "/16" means the first 16 bits of the address form the @@ -108,14 +116,6 @@ the rest (a partition), they can continue to work with the address ranges they had before isolation, and can subsequently be re-connected to the rest of the network without any conflicts arising. -Once you have given a range of addresses to the IP allocator, you must -not use any addresses in that range for anything else. If, in our -example, you subsequently executed `docker run -e WEAVE_CIDR=10.2.3.1/24 -ti ubuntu`, -you run the risk that the IP allocator will assign the same address to -another container, which will make network traffic delivery -intermittent or non-existent for the containers that share the same IP -address. - ## Automatic allocation across multiple subnets When From 501f40d9c171efb4f970964b999f956e00d8b706 Mon Sep 17 00:00:00 2001 From: David Wragg Date: Wed, 8 Jul 2015 14:15:47 +0100 Subject: [PATCH 041/180] Consolidate remote peer checks --- router/connection.go | 28 +++++++++++++++++++++++++++- router/handshake.go | 41 +++++++++++------------------------------ router/peers.go | 13 ++++++++++--- 3 files changed, 48 insertions(+), 34 deletions(-) diff --git a/router/connection.go b/router/connection.go index 9fe080ff..5bc3a08a 100644 --- a/router/connection.go +++ b/router/connection.go @@ -283,10 +283,15 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch conn.TCPConn.SetLinger(0) - tcpReceiver, err := conn.handshake(acceptNewPeer) + tcpReceiver, remote, err := conn.handshake() if err != nil { return } + + if err = conn.registerRemote(remote, acceptNewPeer); err != nil { + return + } + conn.Log("completed handshake; using protocol version", conn.version) // The ordering of the following is very important. [1] @@ -351,6 +356,27 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch // prevent that completely, since, for example, forwarder can only be // created when we know the remote UDP address, but it helps to try. +func (conn *LocalConnection) registerRemote(remote *Peer, acceptNewPeer bool) error { + if acceptNewPeer { + conn.remote = conn.Router.Peers.FetchWithDefault(remote) + } else { + conn.remote = conn.Router.Peers.FetchAndAddRef(remote.Name) + if conn.remote == nil { + return fmt.Errorf("Found unknown remote name: %s at %s", remote.Name, conn.remoteTCPAddr) + } + } + + if conn.remote.UID != remote.UID { + return fmt.Errorf("Connection appears to be with different version of a peer we already know of") + } + + if conn.remote == conn.local { + return fmt.Errorf("Cannot connect to ourself") + } + + return nil +} + func (conn *LocalConnection) initHeartbeats() error { conn.heartbeatTCP = time.NewTicker(TCPHeartbeat) conn.heartbeatTimeout = time.NewTimer(HeartbeatTimeout) diff --git a/router/handshake.go b/router/handshake.go index b9f54831..0e39585f 100644 --- a/router/handshake.go +++ b/router/handshake.go @@ -45,7 +45,7 @@ func (fv *FieldValidator) Err() error { return fv.err } -func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) { +func (conn *LocalConnection) handshake() (TCPReceiver, *Peer, error) { // We do not need to worry about locking in here as at this point // the connection is not reachable by any go-routine other than // ourself. Only when we add this connection to the conn.local @@ -54,7 +54,7 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) conn.TCPConn.SetDeadline(time.Now().Add(HeaderTimeout)) version, err := exchangeProtocolHeader(conn.TCPConn, conn.TCPConn) if err != nil { - return nil, err + return nil, nil, err } conn.version = version conn.TCPConn.SetDeadline(time.Time{}) @@ -66,7 +66,7 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) dec := gob.NewDecoder(conn.TCPConn) fv, private, err := conn.exchangeHandshake(localConnID, usingPassword, enc, dec) if err != nil { - return nil, err + return nil, nil, err } nameStr, _ := fv.Value("Name") @@ -74,25 +74,20 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) uidStr, _ := fv.Value("UID") remoteConnIDStr, _ := fv.Value("ConnID") if err := fv.Err(); err != nil { - return nil, err + return nil, nil, err } name, err := PeerNameFromString(nameStr) if err != nil { - return nil, err - } - if !acceptNewPeer { - if conn.Router.Peers.Fetch(name) != nil { - return nil, fmt.Errorf("Found unknown remote name: %s at %s", name, conn.remoteTCPAddr) - } + return nil, nil, err } uid, err := ParsePeerUID(uidStr) if err != nil { - return nil, err + return nil, nil, err } remoteConnID, err := strconv.ParseUint(remoteConnIDStr, 10, 64) if err != nil { - return nil, err + return nil, nil, err } conn.uid = localConnID ^ remoteConnID @@ -100,11 +95,11 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) remotePublicStr, rpErr := fv.Value("PublicKey") if usingPassword { if rpErr != nil { - return nil, rpErr + return nil, nil, rpErr } remotePublicSlice, rpErr := hex.DecodeString(remotePublicStr) if rpErr != nil { - return nil, rpErr + return nil, nil, rpErr } remotePublic := [32]byte{} for idx, elem := range remotePublicSlice { @@ -116,14 +111,14 @@ func (conn *LocalConnection) handshake(acceptNewPeer bool) (TCPReceiver, error) conn.Decryptor = NewNaClDecryptor(conn.SessionKey, conn.outbound) } else { if rpErr == nil { - return nil, fmt.Errorf("Remote network is encrypted. Password required.") + return nil, nil, fmt.Errorf("Remote network is encrypted. Password required.") } conn.tcpSender = NewSimpleTCPSender(enc) tcpReceiver = NewSimpleTCPReceiver(dec) conn.Decryptor = NewNonDecryptor() } - return tcpReceiver, conn.setRemote(NewPeer(name, nickNameStr, uid, 0)) + return tcpReceiver, NewPeer(name, nickNameStr, uid, 0), nil } func (conn *LocalConnection) exchangeHandshake(localConnID uint64, usingPassword bool, enc *gob.Encoder, dec *gob.Decoder) (*FieldValidator, *[32]byte, error) { @@ -151,17 +146,3 @@ func (conn *LocalConnection) exchangeHandshake(localConnID uint64, usingPassword fv.CheckEqual("PeerNameFlavour", PeerNameFlavour) return fv, private, nil } - -func (conn *LocalConnection) setRemote(toPeer *Peer) error { - toPeer = conn.Router.Peers.FetchWithDefault(toPeer) - switch toPeer { - case nil: - return fmt.Errorf("Connection appears to be with different version of a peer we already know of") - case conn.local: - conn.remote = toPeer // have to do assigment here to ensure Shutdown releases ref count - return fmt.Errorf("Cannot connect to ourself") - default: - conn.remote = toPeer - return nil - } -} diff --git a/router/peers.go b/router/peers.go index b48662f0..3f2d0582 100644 --- a/router/peers.go +++ b/router/peers.go @@ -64,9 +64,6 @@ func (peers *Peers) FetchWithDefault(peer *Peer) *Peer { peers.Lock() defer peers.Unlock() if existingPeer, found := peers.table[peer.Name]; found { - if existingPeer.UID != peer.UID { - return nil - } existingPeer.localRefCount++ return existingPeer } @@ -81,6 +78,16 @@ func (peers *Peers) Fetch(name PeerName) *Peer { return peers.table[name] } +func (peers *Peers) FetchAndAddRef(name PeerName) *Peer { + peers.Lock() + defer peers.Unlock() + peer := peers.table[name] + if peer != nil { + peer.localRefCount++ + } + return peer +} + func (peers *Peers) Dereference(peer *Peer) { peers.Lock() defer peers.Unlock() From 78c4b06492c0db83aad654aed84f8d81670d5647 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Wed, 8 Jul 2015 16:35:21 +0100 Subject: [PATCH 042/180] Don't wait for certainty before responding to Claim Conflicts: ipam/claim.go --- ipam/claim.go | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/ipam/claim.go b/ipam/claim.go index 8d96e6e2..750ad950 100644 --- a/ipam/claim.go +++ b/ipam/claim.go @@ -3,6 +3,7 @@ package ipam import ( "fmt" + "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/ipam/address" "github.com/weaveworks/weave/router" ) @@ -14,6 +15,18 @@ type claim struct { hasBeenCancelled func() bool } +func (c *claim) sendResult(result error) { + // Make sure we only send a result once, since listener stops listening after that + if c.resultChan != nil { + c.resultChan <- result + close(c.resultChan) + c.resultChan = nil + } + if result != nil { + common.Error.Println("[allocator] " + result.Error()) + } +} + // Try returns true for success (or failure), false if we need to try again later func (c *claim) Try(alloc *Allocator) bool { if (c.hasBeenCancelled)() { @@ -24,7 +37,7 @@ func (c *claim) Try(alloc *Allocator) bool { if !alloc.ring.Contains(c.addr) { // Address not within our universe; assume user knows what they are doing alloc.infof("Ignored address %s claimed by %s - not in our universe\n", c.addr, c.ident) - c.resultChan <- nil + c.sendResult(nil) return true } @@ -34,6 +47,7 @@ func (c *claim) Try(alloc *Allocator) bool { owner := alloc.ring.Owner(c.addr) if owner == router.UnknownPeerName { alloc.infof("Ring is empty; will try later.\n", c.addr, owner) + c.sendResult(nil) // don't make the caller wait return false } if owner != alloc.ourName { @@ -41,34 +55,34 @@ func (c *claim) Try(alloc *Allocator) bool { if found { name = " (" + name + ")" } - c.resultChan <- fmt.Errorf("address %s is owned by other peer %s%s", c.addr.String(), owner, name) + c.sendResult(fmt.Errorf("address %s is owned by other peer %s%s", c.addr.String(), owner, name)) return true } // We are the owner, check we haven't given it to another container existingIdent := alloc.findOwner(c.addr) if existingIdent == c.ident { // same identifier is claiming same address; that's OK - c.resultChan <- nil + c.sendResult(nil) return true } if existingIdent == "" { err := alloc.space.Claim(c.addr) if err != nil { - c.resultChan <- err + c.sendResult(err) return true } alloc.debugln("Claimed", c.addr, "for", c.ident) alloc.addOwned(c.ident, c.addr) - c.resultChan <- nil + c.sendResult(nil) return true } // Addr already owned by container on this machine - c.resultChan <- fmt.Errorf("address %s is already owned by %s", c.addr.String(), existingIdent) + c.sendResult(fmt.Errorf("address %s is already owned by %s", c.addr.String(), existingIdent)) return true } func (c *claim) Cancel() { - c.resultChan <- fmt.Errorf("Operation cancelled.") + c.sendResult(fmt.Errorf("Operation cancelled.")) } func (c *claim) String() string { From cf4ce0a07d311bed450c6a93e3d2fa1f425706b7 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Thu, 9 Jul 2015 10:42:30 +0100 Subject: [PATCH 043/180] Don't cancel address claim when caller closes socket --- ipam/allocator.go | 5 ++--- ipam/allocator_test.go | 2 +- ipam/claim.go | 12 +++--------- ipam/http.go | 3 +-- 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/ipam/allocator.go b/ipam/allocator.go index 98f36f3d..9dee326a 100644 --- a/ipam/allocator.go +++ b/ipam/allocator.go @@ -202,10 +202,9 @@ func (alloc *Allocator) Lookup(ident string, r address.Range) (address.Address, } // Claim an address that we think we should own (Sync) -func (alloc *Allocator) Claim(ident string, addr address.Address, cancelChan <-chan bool) error { +func (alloc *Allocator) Claim(ident string, addr address.Address) error { resultChan := make(chan error) - op := &claim{resultChan: resultChan, ident: ident, addr: addr, - hasBeenCancelled: hasBeenCancelled(cancelChan)} + op := &claim{resultChan: resultChan, ident: ident, addr: addr} alloc.doOperation(op, &alloc.pendingClaims) return <-resultChan } diff --git a/ipam/allocator_test.go b/ipam/allocator_test.go index 33bed602..8f6683ce 100644 --- a/ipam/allocator_test.go +++ b/ipam/allocator_test.go @@ -143,7 +143,7 @@ func TestAllocatorClaim(t *testing.T) { alloc.claimRingForTesting() addr1, _ := address.ParseIP(testAddr1) - err := alloc.Claim(container3, addr1, nil) + err := alloc.Claim(container3, addr1) wt.AssertNoErr(t, err) // Check we get this address back if we try an allocate addr3, _ := alloc.Allocate(container3, subnet, nil) diff --git a/ipam/claim.go b/ipam/claim.go index 750ad950..c1dbc529 100644 --- a/ipam/claim.go +++ b/ipam/claim.go @@ -9,10 +9,9 @@ import ( ) type claim struct { - resultChan chan<- error - ident string - addr address.Address - hasBeenCancelled func() bool + resultChan chan<- error + ident string + addr address.Address } func (c *claim) sendResult(result error) { @@ -29,11 +28,6 @@ func (c *claim) sendResult(result error) { // Try returns true for success (or failure), false if we need to try again later func (c *claim) Try(alloc *Allocator) bool { - if (c.hasBeenCancelled)() { - c.Cancel() - return true - } - if !alloc.ring.Contains(c.addr) { // Address not within our universe; assume user knows what they are doing alloc.infof("Ignored address %s claimed by %s - not in our universe\n", c.addr, c.ident) diff --git a/ipam/http.go b/ipam/http.go index 8164d8c8..c81ee2ba 100644 --- a/ipam/http.go +++ b/ipam/http.go @@ -19,14 +19,13 @@ func badRequest(w http.ResponseWriter, err error) { // HandleHTTP wires up ipams HTTP endpoints to the provided mux. func (alloc *Allocator) HandleHTTP(router *mux.Router, defaultSubnet address.CIDR, dockerCli *docker.Client) { router.Methods("PUT").Path("/ip/{id}/{ip}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - closedChan := w.(http.CloseNotifier).CloseNotify() vars := mux.Vars(r) ident := vars["id"] ipStr := vars["ip"] if ip, err := address.ParseIP(ipStr); err != nil { badRequest(w, err) return - } else if err := alloc.Claim(ident, ip, closedChan); err != nil { + } else if err := alloc.Claim(ident, ip); err != nil { badRequest(w, fmt.Errorf("Unable to claim: %s", err)) return } From cbcd5da680479c5eb02fb5ad4598c1a0f9db1f9e Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Thu, 9 Jul 2015 12:33:39 +0100 Subject: [PATCH 044/180] Fix log message on peer move --- router/connection.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/router/connection.go b/router/connection.go index 5bc3a08a..3f5396f7 100644 --- a/router/connection.go +++ b/router/connection.go @@ -231,7 +231,7 @@ func (conn *LocalConnection) ReceivedHeartbeat(remoteUDPAddr *net.UDPAddr, connU if oldRemoteUDPAddr == nil { return conn.sendFastHeartbeats() } else if oldRemoteUDPAddr.String() != remoteUDPAddr.String() { - Log.Println("Peer", conn.remote, "moved from", old, "to", remoteUDPAddr) + Log.Println("Peer", conn.remote, "moved from", oldRemoteUDPAddr, "to", remoteUDPAddr) } return nil }) From b93070f91ad1222404a330922fe0761ee05ae0b5 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Thu, 9 Jul 2015 12:51:52 +0100 Subject: [PATCH 045/180] Fix log message on peer move --- router/connection.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/router/connection.go b/router/connection.go index adf9e04c..81c74d30 100644 --- a/router/connection.go +++ b/router/connection.go @@ -231,7 +231,7 @@ func (conn *LocalConnection) ReceivedHeartbeat(remoteUDPAddr *net.UDPAddr, connU if oldRemoteUDPAddr == nil { return conn.sendFastHeartbeats() } else if oldRemoteUDPAddr.String() != remoteUDPAddr.String() { - log.Println("Peer", conn.remote, "moved from", old, "to", remoteUDPAddr) + log.Println("Peer", conn.remote, "moved from", oldRemoteUDPAddr, "to", remoteUDPAddr) } return nil }) From 882f14d50c710772648599ae0855b86c44cf3267 Mon Sep 17 00:00:00 2001 From: David Wragg Date: Tue, 7 Jul 2015 12:46:32 +0100 Subject: [PATCH 046/180] Version 2 protocol, which encrypts the features map With V1 compatibility --- router/connection.go | 98 ++++++++++- router/consts.go | 1 - router/handshake.go | 148 ----------------- router/handshake_test.go | 30 ---- router/protocol.go | 339 +++++++++++++++++++++++++++++++++++---- router/protocol_test.go | 92 +++++++++++ 6 files changed, 496 insertions(+), 212 deletions(-) delete mode 100644 router/handshake.go delete mode 100644 router/handshake_test.go create mode 100644 router/protocol_test.go diff --git a/router/connection.go b/router/connection.go index 5bc3a08a..65c18935 100644 --- a/router/connection.go +++ b/router/connection.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "net" + "strconv" "sync" "time" @@ -117,6 +118,7 @@ func StartLocalConnection(connRemote *RemoteConnection, tcpConn *net.TCPConn, ud TCPConn: tcpConn, remoteUDPAddr: udpAddr, effectivePMTU: DefaultPMTU, + uid: randUint64(), actionChan: actionChan, finished: finished} go conn.run(actionChan, finished, acceptNewPeer) @@ -282,8 +284,21 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch defer close(finished) conn.TCPConn.SetLinger(0) + intro, err := ProtocolIntroParams{ + Features: conn.makeFeatures(), + Conn: conn.TCPConn, + Password: conn.Router.Password, + Outbound: conn.outbound, + }.DoIntro() + if err != nil { + return + } - tcpReceiver, remote, err := conn.handshake() + conn.SessionKey = intro.SessionKey + conn.tcpSender = intro.Sender + conn.version = intro.Version + + remote, err := conn.parseFeatures(intro.Features) if err != nil { return } @@ -292,7 +307,13 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch return } - conn.Log("completed handshake; using protocol version", conn.version) + if conn.SessionKey == nil { + conn.Decryptor = NewNonDecryptor() + } else { + conn.Decryptor = NewNaClDecryptor(conn.SessionKey, conn.outbound) + } + + conn.Log("connection ready; using protocol version", conn.version) // The ordering of the following is very important. [1] @@ -307,7 +328,8 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch if err = conn.initHeartbeats(); err != nil { return } - go conn.receiveTCP(tcpReceiver) + + go conn.receiveTCP(intro.Receiver) err = conn.actorLoop(actionChan) } @@ -356,6 +378,76 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch // prevent that completely, since, for example, forwarder can only be // created when we know the remote UDP address, but it helps to try. +func (conn *LocalConnection) makeFeatures() map[string]string { + return map[string]string{ + "PeerNameFlavour": PeerNameFlavour, + "Name": conn.local.Name.String(), + "NickName": conn.local.NickName, + "UID": fmt.Sprint(conn.local.UID), + "ConnID": fmt.Sprint(conn.uid), + } +} + +type features map[string]string + +func (features features) Get(key string) (string, error) { + val, ok := features[key] + if !ok { + return "", fmt.Errorf("Field %s is missing", key) + } + + return val, nil +} + +func (conn *LocalConnection) parseFeatures(features features) (*Peer, error) { + str, err := features.Get("PeerNameFlavour") + if err != nil { + return nil, err + } + + if str != PeerNameFlavour { + return nil, fmt.Errorf("Peer name flavour mismatch (ours: \"%s\", theirs: \"%s\")", PeerNameFlavour, str) + } + + str, err = features.Get("Name") + if err != nil { + return nil, err + } + + name, err := PeerNameFromString(str) + if err != nil { + return nil, err + } + + nickName, err := features.Get("NickName") + if err != nil { + return nil, err + } + + str, err = features.Get("UID") + if err != nil { + return nil, err + } + + uid, err := ParsePeerUID(str) + if err != nil { + return nil, err + } + + str, err = features.Get("ConnID") + if err != nil { + return nil, err + } + + remoteConnID, err := strconv.ParseUint(str, 10, 64) + if err != nil { + return nil, err + } + + conn.uid ^= remoteConnID + return NewPeer(name, nickName, uid, 0), nil +} + func (conn *LocalConnection) registerRemote(remote *Peer, acceptNewPeer bool) error { if acceptNewPeer { conn.remote = conn.Router.Peers.FetchWithDefault(remote) diff --git a/router/consts.go b/router/consts.go index 1909498c..1acfc18b 100644 --- a/router/consts.go +++ b/router/consts.go @@ -24,7 +24,6 @@ const ( PMTUVerifyTimeout = 10 * time.Millisecond // gets doubled with every attempt MaxDuration = time.Duration(math.MaxInt64) MaxMissedHeartbeats = 6 - HeaderTimeout = 10 * time.Second HeartbeatTimeout = MaxMissedHeartbeats * SlowHeartbeat ) diff --git a/router/handshake.go b/router/handshake.go deleted file mode 100644 index 0e39585f..00000000 --- a/router/handshake.go +++ /dev/null @@ -1,148 +0,0 @@ -package router - -import ( - "encoding/gob" - "encoding/hex" - "fmt" - "strconv" - "time" -) - -type FieldValidator struct { - fields map[string]string - err error -} - -func NewFieldValidator(fields map[string]string) *FieldValidator { - return &FieldValidator{fields, nil} -} - -func (fv *FieldValidator) Value(fieldName string) (string, error) { - if fv.err != nil { - return "", fv.err - } - val, found := fv.fields[fieldName] - if !found { - fv.err = fmt.Errorf("Field %s is missing", fieldName) - return "", fv.err - } - return val, nil -} - -func (fv *FieldValidator) CheckEqual(fieldName, expectedValue string) error { - val, err := fv.Value(fieldName) - if err != nil { - return err - } - if val != expectedValue { - fv.err = fmt.Errorf("Field %s has wrong value; expected '%s', received '%s'", fieldName, expectedValue, val) - return fv.err - } - return nil -} - -func (fv *FieldValidator) Err() error { - return fv.err -} - -func (conn *LocalConnection) handshake() (TCPReceiver, *Peer, error) { - // We do not need to worry about locking in here as at this point - // the connection is not reachable by any go-routine other than - // ourself. Only when we add this connection to the conn.local - // peer will it be visible from multiple go-routines. - - conn.TCPConn.SetDeadline(time.Now().Add(HeaderTimeout)) - version, err := exchangeProtocolHeader(conn.TCPConn, conn.TCPConn) - if err != nil { - return nil, nil, err - } - conn.version = version - conn.TCPConn.SetDeadline(time.Time{}) - conn.extendReadDeadline() - - localConnID := randUint64() - usingPassword := conn.Router.UsingPassword() - enc := gob.NewEncoder(conn.TCPConn) - dec := gob.NewDecoder(conn.TCPConn) - fv, private, err := conn.exchangeHandshake(localConnID, usingPassword, enc, dec) - if err != nil { - return nil, nil, err - } - - nameStr, _ := fv.Value("Name") - nickNameStr, _ := fv.Value("NickName") - uidStr, _ := fv.Value("UID") - remoteConnIDStr, _ := fv.Value("ConnID") - if err := fv.Err(); err != nil { - return nil, nil, err - } - - name, err := PeerNameFromString(nameStr) - if err != nil { - return nil, nil, err - } - uid, err := ParsePeerUID(uidStr) - if err != nil { - return nil, nil, err - } - remoteConnID, err := strconv.ParseUint(remoteConnIDStr, 10, 64) - if err != nil { - return nil, nil, err - } - conn.uid = localConnID ^ remoteConnID - - var tcpReceiver TCPReceiver - remotePublicStr, rpErr := fv.Value("PublicKey") - if usingPassword { - if rpErr != nil { - return nil, nil, rpErr - } - remotePublicSlice, rpErr := hex.DecodeString(remotePublicStr) - if rpErr != nil { - return nil, nil, rpErr - } - remotePublic := [32]byte{} - for idx, elem := range remotePublicSlice { - remotePublic[idx] = elem - } - conn.SessionKey = FormSessionKey(&remotePublic, private, conn.Router.Password) - conn.tcpSender = NewEncryptedTCPSender(enc, conn.SessionKey, conn.outbound) - tcpReceiver = NewEncryptedTCPReceiver(dec, conn.SessionKey, conn.outbound) - conn.Decryptor = NewNaClDecryptor(conn.SessionKey, conn.outbound) - } else { - if rpErr == nil { - return nil, nil, fmt.Errorf("Remote network is encrypted. Password required.") - } - conn.tcpSender = NewSimpleTCPSender(enc) - tcpReceiver = NewSimpleTCPReceiver(dec) - conn.Decryptor = NewNonDecryptor() - } - - return tcpReceiver, NewPeer(name, nickNameStr, uid, 0), nil -} - -func (conn *LocalConnection) exchangeHandshake(localConnID uint64, usingPassword bool, enc *gob.Encoder, dec *gob.Decoder) (*FieldValidator, *[32]byte, error) { - handshakeSend := map[string]string{ - "PeerNameFlavour": PeerNameFlavour, - "Name": conn.local.Name.String(), - "NickName": conn.local.NickName, - "UID": fmt.Sprint(conn.local.UID), - "ConnID": fmt.Sprint(localConnID)} - handshakeRecv := map[string]string{} - var public, private *[32]byte - var err error - if usingPassword { - public, private, err = GenerateKeyPair() - if err != nil { - return nil, nil, err - } - handshakeSend["PublicKey"] = hex.EncodeToString(public[:]) - } - enc.Encode(handshakeSend) - if err = dec.Decode(&handshakeRecv); err != nil { - return nil, nil, err - } - fv := NewFieldValidator(handshakeRecv) - fv.CheckEqual("PeerNameFlavour", PeerNameFlavour) - return fv, private, nil -} diff --git a/router/handshake_test.go b/router/handshake_test.go deleted file mode 100644 index 2139e080..00000000 --- a/router/handshake_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package router - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestFieldValidator(t *testing.T) { - testMap := map[string]string{"a": "a"} - - fv := NewFieldValidator(testMap) - val, err := fv.Value("a") - require.NoError(t, err) - require.NoError(t, fv.Err()) - require.Equal(t, "a", val, "") - _, err = fv.Value("x") - require.False(t, err == nil || fv.Err() == nil, "Expected error") - _, err = fv.Value("a") - require.False(t, err == nil || fv.Err() == nil, "Previous error should be retained") - - fv = NewFieldValidator(testMap) - err = fv.CheckEqual("a", "a") - require.NoError(t, err) - require.NoError(t, fv.Err()) - err = fv.CheckEqual("a", "b") - require.False(t, err == nil || fv.Err() == nil, "Expected error") - err = fv.CheckEqual("a", "a") - require.False(t, err == nil || fv.Err() == nil, "Previous error should be retained") -} diff --git a/router/protocol.go b/router/protocol.go index bb2ebfa0..58af0da4 100644 --- a/router/protocol.go +++ b/router/protocol.go @@ -2,56 +2,335 @@ package router import ( "bytes" + "encoding/gob" + "encoding/hex" "fmt" "io" + "time" ) const ( Protocol = "weave" - ProtocolVersion byte = 1 - ProtocolMinVersion byte = ProtocolVersion + ProtocolMinVersion byte = 1 + ProtocolVersion byte = 2 ) var ( - ProtocolBytes = []byte(Protocol) - ProtocolLen = len(ProtocolBytes) - ProtocolHeader = append(ProtocolBytes, ProtocolMinVersion, ProtocolVersion) - ProtocolHeaderLen = len(ProtocolHeader) + ProtocolBytes = []byte(Protocol) + + HeaderTimeout = 10 * time.Second + + ProtocolV1Features = []string{ + "ConnID", + "Name", + "NickName", + "PeerNameFlavour", + "UID", + } + + ErrExpectedCrypto = fmt.Errorf("Password specified, but peer requested an unencrypted connection") + ErrExpectedNoCrypto = fmt.Errorf("No password specificed, but peer requested an encrypted connection") ) -func exchangeProtocolHeader(w io.Writer, r io.Reader) (byte, error) { - if n, err := w.Write(ProtocolHeader); err != nil { - return 0, err - } else if n != ProtocolHeaderLen { - return 0, fmt.Errorf("failed to send complete protocol header") +// We don't need the full net.TCPConn to do the protocol intro. This +// interface contains just the parts we do need, to support testing +type ProtocolIntroConn interface { + // io.Reader + Read(b []byte) (n int, err error) + + // io.Writer + Write(b []byte) (n int, err error) + + // net.Conn's deadline methods + SetDeadline(t time.Time) error + SetReadDeadline(t time.Time) error + SetWriteDeadline(t time.Time) error +} + +type ProtocolIntroParams struct { + Features map[string]string + Conn ProtocolIntroConn + Password []byte + Outbound bool +} + +type ProtocolIntroResults struct { + Features map[string]string + Receiver TCPReceiver + Sender TCPSender + SessionKey *[32]byte + Version byte +} + +func (params ProtocolIntroParams) DoIntro() (res ProtocolIntroResults, err error) { + return params.doIntro(ProtocolVersion) +} + +func (params ProtocolIntroParams) doIntro(maxVersion byte) (res ProtocolIntroResults, err error) { + if err = params.Conn.SetDeadline(time.Now().Add(HeaderTimeout)); err != nil { + return } - header := make([]byte, ProtocolHeaderLen) - if n, err := io.ReadFull(r, header); err != nil && n == 0 { + + if res.Version, err = params.exchangeProtocolHeader(maxVersion); err != nil { + return + } + + var pubKey, privKey *[32]byte + if params.Password != nil { + if pubKey, privKey, err = GenerateKeyPair(); err != nil { + return + } + } + + if err = params.Conn.SetWriteDeadline(time.Time{}); err != nil { + return + } + if err = params.Conn.SetReadDeadline(time.Now().Add(TCPHeartbeat * 2)); err != nil { + return + } + + switch res.Version { + case 1: + err = res.doIntroV1(params, pubKey, privKey) + case 2: + err = res.doIntroV2(params, pubKey, privKey) + default: + panic("unhandled protocol version") + } + + return +} + +func (params ProtocolIntroParams) exchangeProtocolHeader(maxVersion byte) (byte, error) { + // Write in a separate goroutine to avoid the possibility of + // deadlock. The result channel is of size 1 so that the + // goroutine does not linger even if we encounter an error on + // the read side. + sendHeader := append(ProtocolBytes, ProtocolMinVersion, maxVersion) + writeDone := make(chan error, 1) + go func() { + _, err := params.Conn.Write(sendHeader) + writeDone <- err + }() + + header := make([]byte, len(ProtocolBytes)+2) + if n, err := io.ReadFull(params.Conn, header); err != nil && n == 0 { return 0, fmt.Errorf("failed to receive remote protocol header: %s", err) } else if err != nil { return 0, fmt.Errorf("received incomplete remote protocol header (%d octets instead of %d): %v; error: %s", - n, ProtocolHeaderLen, header[:n], err) + n, len(header), header[:n], err) } - if !bytes.Equal(ProtocolBytes, header[:ProtocolLen]) { - return 0, fmt.Errorf("remote protocol header not recognised: %v", header[:ProtocolHeaderLen]) + + if !bytes.Equal(ProtocolBytes, header[:len(ProtocolBytes)]) { + return 0, fmt.Errorf("remote protocol header not recognised: %v", header[:len(ProtocolBytes)]) } - var ( - remoteMinVersion = header[ProtocolLen] - remoteVersion = header[ProtocolLen+1] - ) - minVersion := ProtocolMinVersion - if remoteMinVersion > minVersion { - minVersion = remoteMinVersion + + theirMinVersion := header[len(ProtocolBytes)] + minVersion := theirMinVersion + if ProtocolMinVersion > minVersion { + minVersion = ProtocolMinVersion } - maxVersion := ProtocolVersion - if remoteVersion < maxVersion { - maxVersion = remoteVersion + + theirVersion := header[len(ProtocolBytes)+1] + version := theirVersion + if version > maxVersion { + version = maxVersion } - if minVersion > maxVersion { - return 0, fmt.Errorf("remote version [%d,%d] is incompatible with our version [%d,%d]", - remoteMinVersion, remoteVersion, ProtocolMinVersion, ProtocolVersion) + + if minVersion > version { + return 0, fmt.Errorf("remote version range [%d,%d] is incompatible with ours [%d,%d]", + theirMinVersion, theirVersion, + ProtocolMinVersion, maxVersion) } - return maxVersion, nil + + if err := <-writeDone; err != nil { + return 0, err + } + + return version, nil +} + +// The V1 procotol consists of the protocol identification/version +// header, followed by a stream of gobified values. The first value +// is the encoded features map (never encrypted). The subsequent +// values are the messages on the connection (encrypted for an +// encrypted connection). For an encrypted connection, the public key +// is passed in the "PublicKey" feature as a string of hex digits. +func (res *ProtocolIntroResults) doIntroV1(params ProtocolIntroParams, pubKey, privKey *[32]byte) error { + features := filterV1Features(params.Features) + if pubKey != nil { + features["PublicKey"] = hex.EncodeToString(pubKey[:]) + } + + enc := gob.NewEncoder(params.Conn) + dec := gob.NewDecoder(params.Conn) + + // Encode in a separate goroutine to avoid the possibility of + // deadlock. The result channel is of size 1 so that the + // goroutine does not linger even if we encounter an error on + // the read side. + encodeDone := make(chan error, 1) + go func() { + encodeDone <- enc.Encode(features) + }() + + if err := dec.Decode(&res.Features); err != nil { + return err + } + + if err := <-encodeDone; err != nil { + return err + } + + if pubKey == nil { + if _, present := res.Features["PublicKey"]; present { + return ErrExpectedNoCrypto + } + + res.setupNoCrypto(enc, dec) + } else { + remotePubKeyStr, ok := res.Features["PublicKey"] + if !ok { + return ErrExpectedCrypto + } + + remotePubKey, err := hex.DecodeString(remotePubKeyStr) + if err != nil { + return err + } + + res.setupCrypto(params, enc, dec, remotePubKey, privKey) + } + + res.Features = filterV1Features(res.Features) + return nil +} + +// In the V1 protocol, the intro fields are sent unencrypted. So we +// restrict them to an established subset of fields that are assumed +// to be safe. +func filterV1Features(intro map[string]string) map[string]string { + safe := make(map[string]string) + for _, k := range ProtocolV1Features { + if val, ok := intro[k]; ok { + safe[k] = val + } + } + + return safe +} + +// The V2 procotol consists of the protocol identification/version +// header, followed by: +// +// - A single "encryption flag" byte: 0 for no encryption, 1 for +// encryption. +// +// - When the connection is encrypted, 32 bytes follow containing the +// public key. +// +// - Then a stream of gobified values. +// +// The gobified values are the messages on the connection (encrypted +// for an encrypted connection). The first message contains the +// encoded features map (so in contrast to V1, it will be encrypted on +// an encrypted connection). +func (res *ProtocolIntroResults) doIntroV2(params ProtocolIntroParams, pubKey, privKey *[32]byte) error { + // Public key exchange + var wbuf []byte + if pubKey == nil { + wbuf = []byte{0} + } else { + wbuf = make([]byte, 1+len(*pubKey)) + wbuf[0] = 1 + copy(wbuf[1:], (*pubKey)[:]) + } + + // Write in a separate goroutine to avoid the possibility of + // deadlock. The result channel is of size 1 so that the + // goroutine does not linger even if we encounter an error on + // the read side. + writeDone := make(chan error, 1) + go func() { + _, err := params.Conn.Write(wbuf) + writeDone <- err + }() + + rbuf := make([]byte, 1) + if _, err := io.ReadFull(params.Conn, rbuf); err != nil { + return err + } + + switch rbuf[0] { + case 0: + if pubKey != nil { + return ErrExpectedCrypto + } + + res.setupNoCrypto(gob.NewEncoder(params.Conn), + gob.NewDecoder(params.Conn)) + + case 1: + if pubKey == nil { + return ErrExpectedNoCrypto + } + + rbuf = make([]byte, len(pubKey)) + if _, err := io.ReadFull(params.Conn, rbuf); err != nil { + return err + } + + res.setupCrypto(params, gob.NewEncoder(params.Conn), + gob.NewDecoder(params.Conn), rbuf, privKey) + + default: + return fmt.Errorf("Bad encryption flag %d", rbuf[0]) + } + + if err := <-writeDone; err != nil { + return err + } + + // Features exchange + go func() { + buf := new(bytes.Buffer) + if err := gob.NewEncoder(buf).Encode(¶ms.Features); err != nil { + writeDone <- err + return + } + + writeDone <- res.Sender.Send(buf.Bytes()) + }() + + rbuf, err := res.Receiver.Receive() + if err != nil { + return err + } + + if err := gob.NewDecoder(bytes.NewReader(rbuf)).Decode(&res.Features); err != nil { + return err + } + + if err := <-writeDone; err != nil { + return err + } + + return nil +} + +func (res *ProtocolIntroResults) setupNoCrypto(enc *gob.Encoder, dec *gob.Decoder) { + res.Sender = NewSimpleTCPSender(enc) + res.Receiver = NewSimpleTCPReceiver(dec) +} + +func (res *ProtocolIntroResults) setupCrypto(params ProtocolIntroParams, + enc *gob.Encoder, dec *gob.Decoder, remotePubKey []byte, + privKey *[32]byte) { + var remotePubKeyArr [32]byte + copy(remotePubKeyArr[:], remotePubKey) + res.SessionKey = FormSessionKey(&remotePubKeyArr, privKey, params.Password) + res.Sender = NewEncryptedTCPSender(enc, res.SessionKey, params.Outbound) + res.Receiver = NewEncryptedTCPReceiver(dec, res.SessionKey, params.Outbound) } type ProtocolTag byte diff --git a/router/protocol_test.go b/router/protocol_test.go new file mode 100644 index 00000000..6cd36939 --- /dev/null +++ b/router/protocol_test.go @@ -0,0 +1,92 @@ +package router + +import ( + "io" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type testConn struct { + io.Writer + io.Reader +} + +func (testConn) SetDeadline(t time.Time) error { + return nil +} + +func (testConn) SetReadDeadline(t time.Time) error { + return nil +} + +func (testConn) SetWriteDeadline(t time.Time) error { + return nil +} + +func connPair() (ProtocolIntroConn, ProtocolIntroConn) { + a := testConn{} + b := testConn{} + a.Reader, b.Writer = io.Pipe() + b.Reader, a.Writer = io.Pipe() + return &a, &b +} + +func doIntro(t *testing.T, ver byte, params ProtocolIntroParams) <-chan ProtocolIntroResults { + ch := make(chan ProtocolIntroResults, 1) + go func() { + res, err := params.doIntro(ver) + require.Nil(t, err) + ch <- res + }() + return ch +} + +func doProtocolIntro(t *testing.T, aver, bver byte, password []byte) byte { + aconn, bconn := connPair() + aresch := doIntro(t, aver, ProtocolIntroParams{ + Features: map[string]string{"Name": "A"}, + Conn: aconn, + Outbound: true, + Password: password, + }) + bresch := doIntro(t, bver, ProtocolIntroParams{ + Features: map[string]string{"Name": "B"}, + Conn: bconn, + Outbound: false, + Password: password, + }) + ares := <-aresch + bres := <-bresch + + // Check that features were conveyed + require.Equal(t, "B", ares.Features["Name"]) + require.Equal(t, "A", bres.Features["Name"]) + + // Check that Senders and Receivers work + go func() { + require.Nil(t, ares.Sender.Send([]byte("Hello from A"))) + require.Nil(t, bres.Sender.Send([]byte("Hello from B"))) + }() + + data, err := bres.Receiver.Receive() + require.Nil(t, err) + require.Equal(t, "Hello from A", string(data)) + + data, err = ares.Receiver.Receive() + require.Nil(t, err) + require.Equal(t, "Hello from B", string(data)) + + require.Equal(t, ares.Version, bres.Version) + return ares.Version +} + +func TestProtocolIntro(t *testing.T) { + require.Equal(t, 2, int(doProtocolIntro(t, 2, 2, nil))) + require.Equal(t, 2, int(doProtocolIntro(t, 2, 2, []byte("sekr1t")))) + require.Equal(t, 1, int(doProtocolIntro(t, 1, 2, nil))) + require.Equal(t, 1, int(doProtocolIntro(t, 1, 2, []byte("pa55")))) + require.Equal(t, 1, int(doProtocolIntro(t, 2, 1, nil))) + require.Equal(t, 1, int(doProtocolIntro(t, 2, 1, []byte("w0rd")))) +} From 14d346db8b29f079a43b0b7239395ddbed28832d Mon Sep 17 00:00:00 2001 From: David Wragg Date: Thu, 9 Jul 2015 14:36:45 +0100 Subject: [PATCH 047/180] Add a --protocol-min-version option to router To allow users to forgo compatibility with Weave Net 1.0 in order to avoid #912, by setting --protocol-min-version=2. Defaults to --protocol-min-version=1, i.e. compatible but vulnerable. --- prog/weaver/main.go | 43 ++++++++++++++++++++++---------------- router/connection.go | 10 +++++---- router/protocol.go | 46 ++++++++++++++++++++--------------------- router/protocol_test.go | 28 ++++++++++++++----------- router/router.go | 15 +++++++------- 5 files changed, 77 insertions(+), 65 deletions(-) diff --git a/prog/weaver/main.go b/prog/weaver/main.go index e35ac49c..c59d1c48 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -32,28 +32,30 @@ func main() { runtime.GOMAXPROCS(procs) var ( - config weave.Config - justVersion bool - ifaceName string - routerName string - nickName string - password string - wait int - pktdebug bool - logLevel string - prof string - bufSzMB int - noDiscovery bool - httpAddr string - iprangeCIDR string - ipsubnetCIDR string - peerCount int - apiPath string - peers []string + config weave.Config + justVersion bool + protocolMinVersion int + ifaceName string + routerName string + nickName string + password string + wait int + pktdebug bool + logLevel string + prof string + bufSzMB int + noDiscovery bool + httpAddr string + iprangeCIDR string + ipsubnetCIDR string + peerCount int + apiPath string + peers []string ) mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.IntVar(&config.Port, []string{"#port", "-port"}, weave.Port, "router port") + mflag.IntVar(&protocolMinVersion, []string{"-min-protocol-version"}, weave.ProtocolMinVersion, "minimum weave protocol version") mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to capture/inject from (disabled if blank)") mflag.StringVar(&routerName, []string{"#name", "-name"}, "", "name of router (defaults to MAC of interface)") mflag.StringVar(&nickName, []string{"#nickname", "-nickname"}, "", "nickname of peer (defaults to hostname)") @@ -82,6 +84,11 @@ func main() { Log.Println("Command line options:", options()) Log.Println("Command line peers:", peers) + if protocolMinVersion < weave.ProtocolMinVersion || protocolMinVersion > weave.ProtocolMaxVersion { + Log.Fatalf("--min-protocol-version must be in range [%d,%d]", weave.ProtocolMinVersion, weave.ProtocolMaxVersion) + } + config.ProtocolMinVersion = byte(protocolMinVersion) + var err error if ifaceName != "" { diff --git a/router/connection.go b/router/connection.go index 65c18935..17d05b77 100644 --- a/router/connection.go +++ b/router/connection.go @@ -285,10 +285,12 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch conn.TCPConn.SetLinger(0) intro, err := ProtocolIntroParams{ - Features: conn.makeFeatures(), - Conn: conn.TCPConn, - Password: conn.Router.Password, - Outbound: conn.outbound, + MinVersion: conn.Router.ProtocolMinVersion, + MaxVersion: ProtocolMaxVersion, + Features: conn.makeFeatures(), + Conn: conn.TCPConn, + Password: conn.Router.Password, + Outbound: conn.outbound, }.DoIntro() if err != nil { return diff --git a/router/protocol.go b/router/protocol.go index 58af0da4..878491a2 100644 --- a/router/protocol.go +++ b/router/protocol.go @@ -10,9 +10,9 @@ import ( ) const ( - Protocol = "weave" - ProtocolMinVersion byte = 1 - ProtocolVersion byte = 2 + Protocol = "weave" + ProtocolMinVersion = 1 + ProtocolMaxVersion = 2 ) var ( @@ -48,10 +48,12 @@ type ProtocolIntroConn interface { } type ProtocolIntroParams struct { - Features map[string]string - Conn ProtocolIntroConn - Password []byte - Outbound bool + MinVersion byte + MaxVersion byte + Features map[string]string + Conn ProtocolIntroConn + Password []byte + Outbound bool } type ProtocolIntroResults struct { @@ -63,15 +65,11 @@ type ProtocolIntroResults struct { } func (params ProtocolIntroParams) DoIntro() (res ProtocolIntroResults, err error) { - return params.doIntro(ProtocolVersion) -} - -func (params ProtocolIntroParams) doIntro(maxVersion byte) (res ProtocolIntroResults, err error) { if err = params.Conn.SetDeadline(time.Now().Add(HeaderTimeout)); err != nil { return } - if res.Version, err = params.exchangeProtocolHeader(maxVersion); err != nil { + if res.Version, err = params.exchangeProtocolHeader(); err != nil { return } @@ -101,12 +99,12 @@ func (params ProtocolIntroParams) doIntro(maxVersion byte) (res ProtocolIntroRes return } -func (params ProtocolIntroParams) exchangeProtocolHeader(maxVersion byte) (byte, error) { +func (params ProtocolIntroParams) exchangeProtocolHeader() (byte, error) { // Write in a separate goroutine to avoid the possibility of // deadlock. The result channel is of size 1 so that the // goroutine does not linger even if we encounter an error on // the read side. - sendHeader := append(ProtocolBytes, ProtocolMinVersion, maxVersion) + sendHeader := append(ProtocolBytes, params.MinVersion, params.MaxVersion) writeDone := make(chan error, 1) go func() { _, err := params.Conn.Write(sendHeader) @@ -127,27 +125,27 @@ func (params ProtocolIntroParams) exchangeProtocolHeader(maxVersion byte) (byte, theirMinVersion := header[len(ProtocolBytes)] minVersion := theirMinVersion - if ProtocolMinVersion > minVersion { - minVersion = ProtocolMinVersion + if params.MinVersion > minVersion { + minVersion = params.MinVersion } - theirVersion := header[len(ProtocolBytes)+1] - version := theirVersion - if version > maxVersion { - version = maxVersion + theirMaxVersion := header[len(ProtocolBytes)+1] + maxVersion := theirMaxVersion + if maxVersion > params.MaxVersion { + maxVersion = params.MaxVersion } - if minVersion > version { + if minVersion > maxVersion { return 0, fmt.Errorf("remote version range [%d,%d] is incompatible with ours [%d,%d]", - theirMinVersion, theirVersion, - ProtocolMinVersion, maxVersion) + theirMinVersion, theirMaxVersion, + params.MinVersion, params.MaxVersion) } if err := <-writeDone; err != nil { return 0, err } - return version, nil + return maxVersion, nil } // The V1 procotol consists of the protocol identification/version diff --git a/router/protocol_test.go b/router/protocol_test.go index 6cd36939..1a56079a 100644 --- a/router/protocol_test.go +++ b/router/protocol_test.go @@ -33,10 +33,10 @@ func connPair() (ProtocolIntroConn, ProtocolIntroConn) { return &a, &b } -func doIntro(t *testing.T, ver byte, params ProtocolIntroParams) <-chan ProtocolIntroResults { +func doIntro(t *testing.T, params ProtocolIntroParams) <-chan ProtocolIntroResults { ch := make(chan ProtocolIntroResults, 1) go func() { - res, err := params.doIntro(ver) + res, err := params.DoIntro() require.Nil(t, err) ch <- res }() @@ -45,17 +45,21 @@ func doIntro(t *testing.T, ver byte, params ProtocolIntroParams) <-chan Protocol func doProtocolIntro(t *testing.T, aver, bver byte, password []byte) byte { aconn, bconn := connPair() - aresch := doIntro(t, aver, ProtocolIntroParams{ - Features: map[string]string{"Name": "A"}, - Conn: aconn, - Outbound: true, - Password: password, + aresch := doIntro(t, ProtocolIntroParams{ + MinVersion: ProtocolMinVersion, + MaxVersion: aver, + Features: map[string]string{"Name": "A"}, + Conn: aconn, + Outbound: true, + Password: password, }) - bresch := doIntro(t, bver, ProtocolIntroParams{ - Features: map[string]string{"Name": "B"}, - Conn: bconn, - Outbound: false, - Password: password, + bresch := doIntro(t, ProtocolIntroParams{ + MinVersion: ProtocolMinVersion, + MaxVersion: bver, + Features: map[string]string{"Name": "B"}, + Conn: bconn, + Outbound: false, + Password: password, }) ares := <-aresch bres := <-bresch diff --git a/router/router.go b/router/router.go index f4a254fc..9d9df0a9 100644 --- a/router/router.go +++ b/router/router.go @@ -28,13 +28,14 @@ const ( type LogFrameFunc func(string, []byte, *EthernetDecoder) type Config struct { - Port int - Iface *net.Interface - Password []byte - ConnLimit int - PeerDiscovery bool - BufSz int - LogFrame LogFrameFunc + Port int + ProtocolMinVersion byte + Iface *net.Interface + Password []byte + ConnLimit int + PeerDiscovery bool + BufSz int + LogFrame LogFrameFunc } type Router struct { From a05c65c73bf9f94413d2006ca12d0e0ec21e3de0 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Thu, 9 Jul 2015 11:39:57 +0100 Subject: [PATCH 048/180] simplify feature extraction --- router/connection.go | 58 +++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 36 deletions(-) diff --git a/router/connection.go b/router/connection.go index 17d05b77..b154e3d9 100644 --- a/router/connection.go +++ b/router/connection.go @@ -392,56 +392,42 @@ func (conn *LocalConnection) makeFeatures() map[string]string { type features map[string]string -func (features features) Get(key string) (string, error) { - val, ok := features[key] - if !ok { - return "", fmt.Errorf("Field %s is missing", key) +func (features features) MustHave(keys []string) error { + for _, key := range keys { + if _, ok := features[key]; !ok { + return fmt.Errorf("Field %s is missing", key) + } } + return nil +} - return val, nil +func (features features) Get(key string) string { + return features[key] } func (conn *LocalConnection) parseFeatures(features features) (*Peer, error) { - str, err := features.Get("PeerNameFlavour") + if err := features.MustHave([]string{"PeerNameFlavour", "Name", "NickName", "UID", "ConnID"}); err != nil { + return nil, err + } + + remotePeerNameFlavour := features.Get("PeerNameFlavour") + if remotePeerNameFlavour != PeerNameFlavour { + return nil, fmt.Errorf("Peer name flavour mismatch (ours: '%s', theirs: '%s')", PeerNameFlavour, remotePeerNameFlavour) + } + + name, err := PeerNameFromString(features.Get("Name")) if err != nil { return nil, err } - if str != PeerNameFlavour { - return nil, fmt.Errorf("Peer name flavour mismatch (ours: \"%s\", theirs: \"%s\")", PeerNameFlavour, str) - } + nickName := features.Get("NickName") - str, err = features.Get("Name") + uid, err := ParsePeerUID(features.Get("UID")) if err != nil { return nil, err } - name, err := PeerNameFromString(str) - if err != nil { - return nil, err - } - - nickName, err := features.Get("NickName") - if err != nil { - return nil, err - } - - str, err = features.Get("UID") - if err != nil { - return nil, err - } - - uid, err := ParsePeerUID(str) - if err != nil { - return nil, err - } - - str, err = features.Get("ConnID") - if err != nil { - return nil, err - } - - remoteConnID, err := strconv.ParseUint(str, 10, 64) + remoteConnID, err := strconv.ParseUint(features.Get("ConnID"), 10, 64) if err != nil { return nil, err } From e4458372e86901df99e1c077824ad051b20cea19 Mon Sep 17 00:00:00 2001 From: Paul Bellamy Date: Fri, 3 Jul 2015 17:15:19 +0100 Subject: [PATCH 049/180] [proxy] weavewait rewrites /etc/hosts so weave ip is returned first from 'hostname -i' Adds a --no-rewrite-hosts flag to the proxy, and be default, removes the docker IP from hosts. We only discard the docker host when it exists, so --net=none works. --- prog/weaveproxy/main.go | 1 + prog/weavewait/main.go | 108 +++++++++++++++++++++++++- proxy/create_container_interceptor.go | 6 +- proxy/proxy.go | 13 ++-- test/610_proxy_wait_for_weave_test.sh | 3 + weave | 2 +- 6 files changed, 121 insertions(+), 12 deletions(-) diff --git a/prog/weaveproxy/main.go b/prog/weaveproxy/main.go index 7a86bccd..815b1ef5 100644 --- a/prog/weaveproxy/main.go +++ b/prog/weaveproxy/main.go @@ -52,6 +52,7 @@ func main() { mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") ListVar(&c.ListenAddrs, []string{"H"}, defaultListenAddrs, "addresses on which to listen") mflag.BoolVar(&c.NoDefaultIPAM, []string{"#-no-default-ipam", "-no-default-ipalloc"}, false, "do not automatically allocate addresses for containers without a WEAVE_CIDR") + mflag.BoolVar(&c.NoRewriteHosts, []string{"no-rewrite-hosts"}, false, "do not automatically rewrite /etc/hosts. Use if you need the docker IP to remain in /etc/hosts") mflag.StringVar(&c.TLSConfig.CACert, []string{"#tlscacert", "-tlscacert"}, "", "Trust certs signed only by this CA") mflag.StringVar(&c.TLSConfig.Cert, []string{"#tlscert", "-tlscert"}, "", "Path to TLS certificate file") mflag.BoolVar(&c.TLSConfig.Enabled, []string{"#tls", "-tls"}, false, "Use TLS; implied by --tls-verify") diff --git a/prog/weavewait/main.go b/prog/weavewait/main.go index 9b1151bf..5ba92c5d 100644 --- a/prog/weavewait/main.go +++ b/prog/weavewait/main.go @@ -1,32 +1,56 @@ package main import ( + "bufio" + "bytes" "fmt" + "io/ioutil" + "net" "os" "os/exec" "os/signal" + "sort" + "strings" "syscall" - "github.com/weaveworks/weave/net" + weavenet "github.com/weaveworks/weave/net" ) func main() { if len(os.Args) <= 1 { os.Exit(0) } - args := os.Args[1:] + + var ( + args = os.Args[1:] + notInExec = true + rewriteHosts = true + ) if args[0] == "-s" { + notInExec = false + rewriteHosts = false args = args[1:] - } else { + } + + if args[0] == "-h" { + rewriteHosts = false + args = args[1:] + } + + if notInExec { usr2 := make(chan os.Signal) signal.Notify(usr2, syscall.SIGUSR2) <-usr2 } - _, err := net.EnsureInterface("ethwe", -1) + iface, err := weavenet.EnsureInterface("ethwe", -1) checkErr(err) + if rewriteHosts { + updateHosts(iface) + } + binary, err := exec.LookPath(args[0]) checkErr(err) @@ -39,3 +63,79 @@ func checkErr(err error) { os.Exit(1) } } + +// Prepend the addresses to /etc/hosts, removing the docker address +func updateHosts(iface *net.Interface) { + addrs, err := iface.Addrs() + checkErr(err) + if len(addrs) == 0 { + return + } + hostname, err := os.Hostname() + checkErr(err) + + hosts := parseHosts() + + // Remove existing ips pointing to our hostname + toRemove := []string{} + for ip, addrs := range hosts { + for _, addr := range addrs { + if addr == hostname { + toRemove = append(toRemove, ip) + break + } + } + } + for _, ip := range toRemove { + delete(hosts, ip) + } + + // Add the weave ip(s) + for _, addr := range addrs { + if addr, ok := addr.(*net.IPNet); ok { + ip := addr.IP.String() + hosts[ip] = append(hosts[ip], hostname) + } + } + + writeHosts(hosts) +} + +func parseHosts() map[string][]string { + f, err := os.Open("/etc/hosts") + checkErr(err) + defer f.Close() + ips := map[string][]string{} + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := scanner.Text() + + // Remove any comments + if i := strings.IndexByte(line, '#'); i != -1 { + line = line[:i] + } + + fields := strings.Fields(line) + if len(fields) > 0 { + ips[fields[0]] = fields[1:] + } + } + checkErr(scanner.Err()) + return ips +} + +func writeHosts(contents map[string][]string) { + ips := []string{} + for ip := range contents { + ips = append(ips, ip) + } + sort.Strings(ips) + + buf := &bytes.Buffer{} + for _, ip := range ips { + if addrs := contents[ip]; len(addrs) > 0 { + fmt.Fprintf(buf, "%s\t%s\n", ip, strings.Join(addrs, " ")) + } + } + checkErr(ioutil.WriteFile("/etc/hosts", buf.Bytes(), 644)) +} diff --git a/proxy/create_container_interceptor.go b/proxy/create_container_interceptor.go index 723a3d0b..8e3cca04 100644 --- a/proxy/create_container_interceptor.go +++ b/proxy/create_container_interceptor.go @@ -92,7 +92,11 @@ func (i *createContainerInterceptor) setWeaveWaitEntrypoint(container *docker.Co } if len(container.Entrypoint) == 0 || container.Entrypoint[0] != weaveWaitEntrypoint[0] { - container.Entrypoint = append(weaveWaitEntrypoint, container.Entrypoint...) + entrypoint := weaveWaitEntrypoint + if i.proxy.NoRewriteHosts { + entrypoint = append(entrypoint, "-h") + } + container.Entrypoint = append(entrypoint, container.Entrypoint...) } return nil diff --git a/proxy/proxy.go b/proxy/proxy.go index 2993d00d..0e1969f2 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -29,12 +29,13 @@ var ( ) type Config struct { - ListenAddrs []string - NoDefaultIPAM bool - TLSConfig TLSConfig - Version string - WithDNS bool - WithoutDNS bool + ListenAddrs []string + NoDefaultIPAM bool + NoRewriteHosts bool + TLSConfig TLSConfig + Version string + WithDNS bool + WithoutDNS bool } type Proxy struct { diff --git a/test/610_proxy_wait_for_weave_test.sh b/test/610_proxy_wait_for_weave_test.sh index acb748d5..7376a70d 100755 --- a/test/610_proxy_wait_for_weave_test.sh +++ b/test/610_proxy_wait_for_weave_test.sh @@ -19,4 +19,7 @@ COMMITTED_IMAGE=$(proxy docker_on $HOST1 commit c1) assert_raises "proxy docker_on $HOST1 run --name c2 $COMMITTED_IMAGE" assert "entrypoint c2" "$(entrypoint $COMMITTED_IMAGE)" +# Check weave IP is first ip returned, so java (etc) prefer weave. +assert "proxy docker_on $HOST1 run -e 'WEAVE_CIDR=10.2.1.1/24' $BASE_IMAGE hostname -i | cut -d' ' -f1" "10.2.1.1" + end_suite diff --git a/weave b/weave index ba4f2f17..89e4aab5 100755 --- a/weave +++ b/weave @@ -36,7 +36,7 @@ weave launch-router [--password ] [--nickname ] [--no-discovery] [--init-peer-count ] ... weave launch-dns [] weave launch-proxy [-H ] [--with-dns | --without-dns] - [--no-default-ipalloc] + [--no-default-ipalloc] [--no-rewrite-hosts] weave connect [--replace] [ ...] weave forget ... weave run [--with-dns | --without-dns] [ ...] From da41604229762d2832760e4b81e81b407a7c30e3 Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Fri, 10 Jul 2015 15:43:28 +0100 Subject: [PATCH 050/180] Fix IPAM test compilation --- ipam/allocator_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ipam/allocator_test.go b/ipam/allocator_test.go index cb5c4b41..a2778248 100644 --- a/ipam/allocator_test.go +++ b/ipam/allocator_test.go @@ -143,7 +143,7 @@ func TestAllocatorClaim(t *testing.T) { alloc.claimRingForTesting() addr1, _ := address.ParseIP(testAddr1) - err := alloc.Claim(container3, addr1, nil) + err := alloc.Claim(container3, addr1) require.NoError(t, err) // Check we get this address back if we try an allocate addr3, _ := alloc.Allocate(container3, subnet, nil) From 00a7490a1d1086a202e9b50038cdf46d86a418a9 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Thu, 9 Jul 2015 10:44:42 +0000 Subject: [PATCH 051/180] Code coverage for smoke tests. Allow non-circle people to build coverage reports. --- Makefile | 23 +++++++- circle.yml | 11 +++- common/signals.go | 6 +- prog/weaver/main.go | 1 + prog/weaver/main_test.go | 12 ++++ test/140_weave_local_test.sh | 8 +-- test/150_connect_forget_test.sh | 2 +- test/config.sh | 22 ++++++++ test/gen_coverage_reports.sh | 15 +++++ testing/cover/cover.go | 97 +++++++++++++++++++++++++++++++++ testing/util.go | 15 +++++ weave | 13 ++++- 12 files changed, 211 insertions(+), 14 deletions(-) create mode 100644 prog/weaver/main_test.go create mode 100755 test/gen_coverage_reports.sh create mode 100644 testing/cover/cover.go diff --git a/Makefile b/Makefile index 37c7871c..2a0f741e 100644 --- a/Makefile +++ b/Makefile @@ -35,6 +35,7 @@ WEAVE_EXPORT=weave.tar WEAVEEXEC_DOCKER_VERSION=1.3.1 DOCKER_DISTRIB=prog/weaveexec/docker-$(WEAVEEXEC_DOCKER_VERSION).tgz DOCKER_DISTRIB_URL=https://get.docker.com/builds/Linux/x86_64/docker-$(WEAVEEXEC_DOCKER_VERSION).tgz +COVERAGE_MODULES=./common,./common/docker,./ipam,./ipam/paxos,./ipam/ring,./ipam/space,./net,./net/address,./router all: $(WEAVE_EXPORT) @@ -43,7 +44,25 @@ travis: $(EXES) update: go get -u -f -v -tags -netgo $(addprefix ./,$(dir $(EXES))) -$(WEAVER_EXE) $(WEAVEDNS_EXE) $(WEAVEPROXY_EXE) $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go +$(WEAVER_EXE): common/*.go common/*/*.go net/*.go +ifeq ($(COVERAGE),true) + go get -t -tags netgo ./$(@D) + go test -c -o ./$@ -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" \ + -tags netgo -v -covermode=atomic -coverpkg $(COVERAGE_MODULES) ./$(@D)/ +else + go get -tags netgo ./$(@D) + go build -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" -tags netgo -o $@ ./$(@D) +endif + @strings $@ | grep cgo_stub\\\.go >/dev/null || { \ + rm $@; \ + echo "\nYour go standard library was built without the 'netgo' build tag."; \ + echo "To fix that, run"; \ + echo " sudo go clean -i net"; \ + echo " sudo go install -tags netgo std"; \ + false; \ + } + +$(WEAVEDNS_EXE) $(WEAVEPROXY_EXE) $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go go get -tags netgo ./$(@D) go build -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" -tags netgo -o $@ ./$(@D) @strings $@ | grep cgo_stub\\\.go >/dev/null || { \ @@ -96,7 +115,7 @@ $(DOCKER_DISTRIB): tests: echo "mode: count" > profile.cov fail=0 ; \ - for dir in $$(find . -type f -name '*_test.go' | xargs -n1 dirname | sort -u); do \ + for dir in $$(find . -type f -name '*_test.go' | xargs -n1 dirname | grep -v prog | sort -u); do \ go get -t -tags netgo $$dir ; \ output=$$(mktemp cover.XXXXXXXXXX) ; \ if ! go test -cpu 4 -tags netgo \ diff --git a/circle.yml b/circle.yml index 2a01b19f..5ac5cc3d 100644 --- a/circle.yml +++ b/circle.yml @@ -35,15 +35,22 @@ dependencies: test: override: - - docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go weaveworks/weave-build: + - docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go -e COVERAGE=true weaveworks/weave-build: parallel: true - cd $SRCDIR/test; ./gce.sh setup: parallel: true - cd $SRCDIR/test; . ./gce.sh hosts; ./setup.sh: parallel: true - - cd $SRCDIR/test; . ./gce.sh hosts; ./run_all.sh: + - cd $SRCDIR/test; . ./gce.sh hosts; export COVERAGE=true; ./run_all.sh: parallel: true timeout: 300 post: - cd $SRCDIR/test; ./gce.sh destroy: parallel: true + +teardown: + pre: + - test "$CIRCLE_NODE_INDEX" != "0" || (cd $SRCDIR/test; ./gen_coverage_reports.sh): + parallel: true + - test "$CIRCLE_NODE_INDEX" != "0" || (cd $SRCDIR/test; cp coverage.* $CIRCLE_ARTIFACTS): + parallel: true diff --git a/common/signals.go b/common/signals.go index e750a8ea..c2e2a683 100644 --- a/common/signals.go +++ b/common/signals.go @@ -15,12 +15,12 @@ type SignalReceiver interface { func SignalHandlerLoop(ss ...SignalReceiver) { sigs := make(chan os.Signal, 1) - signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGUSR1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGTERM) buf := make([]byte, 1<<20) for { switch <-sigs { - case syscall.SIGINT: - Log.Infof("=== received SIGINT ===\n*** exiting\n") + case syscall.SIGINT, syscall.SIGTERM: + Log.Infof("=== received SIGINT/SIGTERM ===\n*** exiting\n") for _, subsystem := range ss { subsystem.Stop() } diff --git a/prog/weaver/main.go b/prog/weaver/main.go index e35ac49c..04cf76c5 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -12,6 +12,7 @@ import ( "github.com/davecheney/profile" "github.com/docker/docker/pkg/mflag" "github.com/gorilla/mux" + . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" "github.com/weaveworks/weave/ipam" diff --git a/prog/weaver/main_test.go b/prog/weaver/main_test.go new file mode 100644 index 00000000..1873f4a3 --- /dev/null +++ b/prog/weaver/main_test.go @@ -0,0 +1,12 @@ +package main + +import ( + "testing" + + weavetest "github.com/weaveworks/weave/testing" +) + +func TestMain(t *testing.T) { + weavetest.TrimTestArgs() + main() +} diff --git a/test/140_weave_local_test.sh b/test/140_weave_local_test.sh index 4e392370..7912001a 100755 --- a/test/140_weave_local_test.sh +++ b/test/140_weave_local_test.sh @@ -4,15 +4,15 @@ start_suite "Run weave with --local" -run_on $HOST1 sudo weave --local reset +run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local reset -run_on $HOST1 sudo weave --local launch --ipalloc-range 10.2.5.0/24 +run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local launch --ipalloc-range 10.2.5.0/24 assert_raises "docker_on $HOST1 ps | grep weave" -run_on $HOST1 sudo weave --local run 10.2.6.5/24 -ti --name=c1 $SMALL_IMAGE /bin/sh +run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local run 10.2.6.5/24 -ti --name=c1 $SMALL_IMAGE /bin/sh assert_raises "exec_on $HOST1 c1 $CHECK_ETHWE_UP" -run_on $HOST1 sudo weave --local run -ti --name=c2 $SMALL_IMAGE /bin/sh +run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local run -ti --name=c2 $SMALL_IMAGE /bin/sh assert_raises "exec_on $HOST1 c2 $CHECK_ETHWE_UP" end_suite diff --git a/test/150_connect_forget_test.sh b/test/150_connect_forget_test.sh index 984e70e7..72130d74 100755 --- a/test/150_connect_forget_test.sh +++ b/test/150_connect_forget_test.sh @@ -33,7 +33,7 @@ assert_raises "exec_on $HOST1 c1 $PING $C2" # Forget everyone and disconnect assert_raises "weave_on $HOST2 forget $HOST1 $HOST2" -assert_raises "weave_on $HOST1 stop-router" +assert_raises "weave_stop_router $HOST1" assert_raises "weave_on $HOST1 launch-router" assert_peers $HOST2 "" assert_raises "exec_on $HOST1 c1 sh -c '! $PING $C2'" diff --git a/test/config.sh b/test/config.sh index 3b5e8e1a..542cb1df 100644 --- a/test/config.sh +++ b/test/config.sh @@ -113,6 +113,15 @@ weave_on() { DOCKER_HOST=tcp://$host:$DOCKER_PORT $WEAVE "$@" } +weave_stop_router() { + host=$1 + shift 1 + docker_on $host stop weave 1>/dev/null 2>&1 || true + if [ -n "$COVERAGE" ] ; then + collect_coverage $host + fi +} + exec_on() { host=$1 container=$2 @@ -196,6 +205,19 @@ start_suite() { end_suite() { whitely assert_end + for host in $HOSTS; do + weave_stop_router $host + done +} + +collect_coverage() { + host=$1 + rm -f cover.router.prof + docker_on $host cp weave:/home/weave/cover.router.prof . || true + + # ideally we'd know the name of the test here, and put that in the filename + mkdir -p ./coverage + mv cover.router.prof $(mktemp -u ./coverage/integration.XXXXXXXX) || true } WEAVE=$DIR/../weave diff --git a/test/gen_coverage_reports.sh b/test/gen_coverage_reports.sh new file mode 100755 index 00000000..b15248ab --- /dev/null +++ b/test/gen_coverage_reports.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +set -eux + +if [ -n "$CIRCLECI" ]; then + for i in $(seq 1 $(($CIRCLE_NODE_TOTAL - 1))); do + scp node$i:/home/ubuntu/src/github.com/weaveworks/weave/test/coverage/* ./coverage/ || true + done +fi + +go get github.com/weaveworks/weave/testing/cover +cover ./coverage/* >profile.cov +go tool cover -html=profile.cov -o coverage.html +go tool cover -func=profile.cov -o coverage.txt +tar czf coverage.tar.gz ./coverage diff --git a/testing/cover/cover.go b/testing/cover/cover.go new file mode 100644 index 00000000..4c5fcfd7 --- /dev/null +++ b/testing/cover/cover.go @@ -0,0 +1,97 @@ +package main + +import ( + "fmt" + "os" + "sort" + + "golang.org/x/tools/cover" +) + +func merge(p1, p2 *cover.Profile) *cover.Profile { + output := cover.Profile{ + FileName: p1.FileName, + Mode: p1.Mode, + } + + i, j := 0, 0 + for i < len(p1.Blocks) && j < len(p2.Blocks) { + bi, bj := p1.Blocks[i], p2.Blocks[j] + if bi.StartLine == bj.StartLine && bi.StartCol == bj.StartCol { + + if bi.EndLine != bj.EndLine || + bi.EndCol != bj.EndCol || + bi.NumStmt != bj.NumStmt { + panic("Not run on same source!") + } + + output.Blocks = append(output.Blocks, cover.ProfileBlock{ + StartLine: bi.StartLine, + StartCol: bi.StartCol, + EndLine: bi.EndLine, + EndCol: bi.EndCol, + NumStmt: bi.NumStmt, + Count: bi.Count + bj.Count, + }) + i++ + j++ + } else if bi.StartLine < bj.StartLine || bi.StartLine == bj.StartLine && bi.StartCol < bj.StartCol { + output.Blocks = append(output.Blocks, bi) + i++ + } else { + output.Blocks = append(output.Blocks, bj) + j++ + } + } + + for ; i < len(p1.Blocks); i++ { + output.Blocks = append(output.Blocks, p1.Blocks[i]) + } + + for ; j < len(p2.Blocks); j++ { + output.Blocks = append(output.Blocks, p2.Blocks[j]) + } + + return &output +} + +func print(profiles []*cover.Profile) { + fmt.Println("mode: atomic") + for _, profile := range profiles { + for _, block := range profile.Blocks { + fmt.Printf("%s:%d.%d,%d.%d %d %d\n", profile.FileName, block.StartLine, block.StartCol, + block.EndLine, block.EndCol, block.NumStmt, block.Count) + } + } +} + +// Copied from https://github.com/golang/tools/blob/master/cover/profile.go +type byFileName []*cover.Profile + +func (p byFileName) Len() int { return len(p) } +func (p byFileName) Less(i, j int) bool { return p[i].FileName < p[j].FileName } +func (p byFileName) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +func main() { + outputProfiles := map[string]*cover.Profile{} + for _, input := range os.Args[1:] { + inputProfiles, err := cover.ParseProfiles(input) + if err != nil { + panic(fmt.Sprintf("Error parsing %s: %v", input, err)) + } + for _, ip := range inputProfiles { + op := outputProfiles[ip.FileName] + if op == nil { + outputProfiles[ip.FileName] = ip + } else { + outputProfiles[ip.FileName] = merge(op, ip) + } + } + } + profiles := make([]*cover.Profile, 0, len(outputProfiles)) + for _, profile := range outputProfiles { + profiles = append(profiles, profile) + } + sort.Sort(byFileName(profiles)) + print(profiles) +} diff --git a/testing/util.go b/testing/util.go index 7ce98cb5..42f39cee 100644 --- a/testing/util.go +++ b/testing/util.go @@ -2,6 +2,7 @@ package testing import ( "fmt" + "os" "reflect" "runtime" "testing" @@ -50,3 +51,17 @@ func RunWithTimeout(t *testing.T, d time.Duration, f func()) { }() <-ch } + +// TrimTestArgs finds the first -- in os.Args and trim all args before that +func TrimTestArgs() { + i, l := 0, len(os.Args) + for ; i < l; i++ { + if os.Args[i] == "--" { + break + } + } + if i == l { + panic("Specify weave args after --") + } + os.Args = append(os.Args[:1], os.Args[i+1:l]...) +} diff --git a/weave b/weave index ba4f2f17..625e2ec0 100755 --- a/weave +++ b/weave @@ -86,6 +86,7 @@ exec_remote() { -e DOCKER_BRIDGE \ -e PROXY_HOST="$PROXY_HOST" \ -e WEAVE_CIDR=none \ + -e COVERAGE \ $WEAVEEXEC_DOCKER_ARGS $EXEC_IMAGE --local "$@" } @@ -412,7 +413,11 @@ ask_version() { echo "Unable to find $2 image." >&2 fi fi - [ -n "$DOCKERIMAGE" ] && docker run --rm -e WEAVE_CIDR=none $DOCKERIMAGE --version + COVERAGE_ARGS="" + if [ -n "$COVERAGE" -a "$1" = "$CONTAINER_NAME" ] ; then + COVERAGE_ARGS="-test.coverprofile=/home/weave/cover.router.prof --" + fi + [ -n "$DOCKERIMAGE" ] && docker run --rm -e WEAVE_CIDR=none $DOCKERIMAGE $COVERAGE_ARGS --version } ###################################################################### @@ -1037,6 +1042,10 @@ launch_router() { exit 1 fi fi + COVERAGE_ARGS="" + if [ -n "$COVERAGE" ] ; then + COVERAGE_ARGS="-test.coverprofile=/home/weave/cover.router.prof --" + fi # Set WEAVE_DOCKER_ARGS in the environment in order to supply # additional parameters, such as resource limits, to docker # when launching the weave container. @@ -1045,7 +1054,7 @@ launch_router() { -v /var/run/docker.sock:/var/run/docker.sock \ -e WEAVE_PASSWORD \ -e WEAVE_CIDR=none \ - $WEAVE_DOCKER_ARGS $IMAGE --iface $CONTAINER_IFNAME --port $CONTAINER_PORT --name "$PEERNAME" --nickname "$(hostname)" --ipalloc-range "$IPRANGE" "$@") + $WEAVE_DOCKER_ARGS $IMAGE $COVERAGE_ARGS --iface $CONTAINER_IFNAME --port $CONTAINER_PORT --name "$PEERNAME" --nickname "$(hostname)" --ipalloc-range "$IPRANGE" "$@") with_container_netns_or_die $CONTAINER launch wait_for_status $CONTAINER_NAME $HTTP_PORT if [ -n "$IPRANGE" ] ; then From bf814739ba352f78799a2cb2c4884b7ad286cfff Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Fri, 10 Jul 2015 15:03:54 +0000 Subject: [PATCH 052/180] Reduce repetition in Makefile. --- Makefile | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/Makefile b/Makefile index 2a0f741e..c4a4cb8a 100644 --- a/Makefile +++ b/Makefile @@ -36,6 +36,14 @@ WEAVEEXEC_DOCKER_VERSION=1.3.1 DOCKER_DISTRIB=prog/weaveexec/docker-$(WEAVEEXEC_DOCKER_VERSION).tgz DOCKER_DISTRIB_URL=https://get.docker.com/builds/Linux/x86_64/docker-$(WEAVEEXEC_DOCKER_VERSION).tgz COVERAGE_MODULES=./common,./common/docker,./ipam,./ipam/paxos,./ipam/ring,./ipam/space,./net,./net/address,./router +NETGO_CHECK=@strings $@ | grep cgo_stub\\\.go >/dev/null || { \ + rm $@; \ + echo "\nYour go standard library was built without the 'netgo' build tag."; \ + echo "To fix that, run"; \ + echo " sudo go clean -i net"; \ + echo " sudo go install -tags netgo std"; \ + false; \ +} all: $(WEAVE_EXPORT) @@ -53,26 +61,12 @@ else go get -tags netgo ./$(@D) go build -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" -tags netgo -o $@ ./$(@D) endif - @strings $@ | grep cgo_stub\\\.go >/dev/null || { \ - rm $@; \ - echo "\nYour go standard library was built without the 'netgo' build tag."; \ - echo "To fix that, run"; \ - echo " sudo go clean -i net"; \ - echo " sudo go install -tags netgo std"; \ - false; \ - } + $(NETGO_CHECK) $(WEAVEDNS_EXE) $(WEAVEPROXY_EXE) $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go go get -tags netgo ./$(@D) go build -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" -tags netgo -o $@ ./$(@D) - @strings $@ | grep cgo_stub\\\.go >/dev/null || { \ - rm $@; \ - echo "\nYour go standard library was built without the 'netgo' build tag."; \ - echo "To fix that, run"; \ - echo " sudo go clean -i net"; \ - echo " sudo go install -tags netgo std"; \ - false; \ - } + $(NETGO_CHECK) $(WEAVER_EXE): router/*.go ipam/*.go ipam/*/*.go prog/weaver/main.go $(WEAVEDNS_EXE): nameserver/*.go prog/weavedns/main.go From f5186e74c07ddfadfbbfc97026966fe453cc5677 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Fri, 10 Jul 2015 15:33:00 +0000 Subject: [PATCH 053/180] Review feedback --- Makefile | 2 +- test/140_weave_local_test.sh | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index c4a4cb8a..79a465ef 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,7 @@ WEAVE_EXPORT=weave.tar WEAVEEXEC_DOCKER_VERSION=1.3.1 DOCKER_DISTRIB=prog/weaveexec/docker-$(WEAVEEXEC_DOCKER_VERSION).tgz DOCKER_DISTRIB_URL=https://get.docker.com/builds/Linux/x86_64/docker-$(WEAVEEXEC_DOCKER_VERSION).tgz -COVERAGE_MODULES=./common,./common/docker,./ipam,./ipam/paxos,./ipam/ring,./ipam/space,./net,./net/address,./router +COVERAGE_MODULES=$(shell go list -f '{{join .Deps "\n"}}' ./prog/weaver | grep "weaveworks" | paste -s -d,) NETGO_CHECK=@strings $@ | grep cgo_stub\\\.go >/dev/null || { \ rm $@; \ echo "\nYour go standard library was built without the 'netgo' build tag."; \ diff --git a/test/140_weave_local_test.sh b/test/140_weave_local_test.sh index 7912001a..d198b727 100755 --- a/test/140_weave_local_test.sh +++ b/test/140_weave_local_test.sh @@ -4,15 +4,21 @@ start_suite "Run weave with --local" -run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local reset +weave_local_on() { + host=$1 + shift 1 + run_on $host sudo COVERAGE=$COVERAGE weave --local $@ +} -run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local launch --ipalloc-range 10.2.5.0/24 +weave_local_on $HOST1 reset + +weave_local_on $HOST1 launch --ipalloc-range 10.2.5.0/24 assert_raises "docker_on $HOST1 ps | grep weave" -run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local run 10.2.6.5/24 -ti --name=c1 $SMALL_IMAGE /bin/sh +weave_local_on $HOST1 run 10.2.6.5/24 -ti --name=c1 $SMALL_IMAGE /bin/sh assert_raises "exec_on $HOST1 c1 $CHECK_ETHWE_UP" -run_on $HOST1 sudo COVERAGE=$COVERAGE weave --local run -ti --name=c2 $SMALL_IMAGE /bin/sh +weave_local_on $HOST1 run -ti --name=c2 $SMALL_IMAGE /bin/sh assert_raises "exec_on $HOST1 c2 $CHECK_ETHWE_UP" end_suite From fa6777004f3020e4fade938c8b39f42c4d3539c5 Mon Sep 17 00:00:00 2001 From: Paul Bellamy Date: Fri, 10 Jul 2015 17:34:06 +0100 Subject: [PATCH 054/180] Review feedback --- prog/weavewait/main.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/prog/weavewait/main.go b/prog/weavewait/main.go index 5ba92c5d..24904f2b 100644 --- a/prog/weavewait/main.go +++ b/prog/weavewait/main.go @@ -64,7 +64,6 @@ func checkErr(err error) { } } -// Prepend the addresses to /etc/hosts, removing the docker address func updateHosts(iface *net.Interface) { addrs, err := iface.Addrs() checkErr(err) @@ -117,7 +116,7 @@ func parseHosts() map[string][]string { fields := strings.Fields(line) if len(fields) > 0 { - ips[fields[0]] = fields[1:] + ips[fields[0]] = append(ips[fields[0]], fields[1:]...) } } checkErr(scanner.Err()) @@ -132,10 +131,24 @@ func writeHosts(contents map[string][]string) { sort.Strings(ips) buf := &bytes.Buffer{} + fmt.Fprintln(buf, "# modified by weave") for _, ip := range ips { if addrs := contents[ip]; len(addrs) > 0 { - fmt.Fprintf(buf, "%s\t%s\n", ip, strings.Join(addrs, " ")) + fmt.Fprintf(buf, "%s\t%s\n", ip, strings.Join(uniqueStrs(addrs), " ")) } } checkErr(ioutil.WriteFile("/etc/hosts", buf.Bytes(), 644)) } + +func uniqueStrs(s []string) []string { + m := map[string]struct{}{} + result := []string{} + for _, str := range s { + if _, ok := m[str]; !ok { + m[str] = struct{}{} + result = append(result, str) + } + } + sort.Strings(result) + return result +} From f8718dcc5d584a17156483be1b92528e49a5e887 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Fri, 10 Jul 2015 16:09:43 +0000 Subject: [PATCH 055/180] Remove duplication of coverage stanza in weave script. --- weave | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/weave b/weave index 625e2ec0..f69bcb9a 100755 --- a/weave +++ b/weave @@ -181,7 +181,10 @@ DNS_HTTP_PORT=6785 DNS_HTTP_IFNAME=eth0 PROXY_PORT=12375 PROXY_CONTAINER_NAME=weaveproxy - +COVERAGE_ARGS="" +if [ -n "$COVERAGE" ] ; then + COVERAGE_ARGS="-test.coverprofile=/home/weave/cover.router.prof --" +fi ###################################################################### # general helpers; independent of docker and weave @@ -413,11 +416,11 @@ ask_version() { echo "Unable to find $2 image." >&2 fi fi - COVERAGE_ARGS="" - if [ -n "$COVERAGE" -a "$1" = "$CONTAINER_NAME" ] ; then - COVERAGE_ARGS="-test.coverprofile=/home/weave/cover.router.prof --" + VERSION_COVERAGE_ARGS="" + if [ "$1" = "$CONTAINER_NAME" ] ; then + VERSION_COVERAGE_ARGS="$COVERAGE_ARGS" fi - [ -n "$DOCKERIMAGE" ] && docker run --rm -e WEAVE_CIDR=none $DOCKERIMAGE $COVERAGE_ARGS --version + [ -n "$DOCKERIMAGE" ] && docker run --rm -e WEAVE_CIDR=none $DOCKERIMAGE $VERSION_COVERAGE_ARGS --version } ###################################################################### @@ -1042,10 +1045,6 @@ launch_router() { exit 1 fi fi - COVERAGE_ARGS="" - if [ -n "$COVERAGE" ] ; then - COVERAGE_ARGS="-test.coverprofile=/home/weave/cover.router.prof --" - fi # Set WEAVE_DOCKER_ARGS in the environment in order to supply # additional parameters, such as resource limits, to docker # when launching the weave container. From 3d72670105bf299d5cb1d193898906fd95e20f9f Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Fri, 10 Jul 2015 18:24:19 +0100 Subject: [PATCH 056/180] don't complain in coverage collection when weave container is absent --- test/config.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/config.sh b/test/config.sh index 542cb1df..8c733f1f 100644 --- a/test/config.sh +++ b/test/config.sh @@ -213,7 +213,7 @@ end_suite() { collect_coverage() { host=$1 rm -f cover.router.prof - docker_on $host cp weave:/home/weave/cover.router.prof . || true + docker_on $host cp weave:/home/weave/cover.router.prof . || return 0 # ideally we'd know the name of the test here, and put that in the filename mkdir -p ./coverage From 0e94e3e07be88dc57a15825a6c001b2f89feed86 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Fri, 10 Jul 2015 18:30:13 +0100 Subject: [PATCH 057/180] complain even less about absent weave container in coverage collection --- test/config.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/config.sh b/test/config.sh index 8c733f1f..ecfaf9a1 100644 --- a/test/config.sh +++ b/test/config.sh @@ -213,7 +213,7 @@ end_suite() { collect_coverage() { host=$1 rm -f cover.router.prof - docker_on $host cp weave:/home/weave/cover.router.prof . || return 0 + docker_on $host cp weave:/home/weave/cover.router.prof . 2>/dev/null || return 0 # ideally we'd know the name of the test here, and put that in the filename mkdir -p ./coverage From ce5052305d7fe3414960a6266d665c5acfd1fb15 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Fri, 10 Jul 2015 18:44:30 +0100 Subject: [PATCH 058/180] fix CircleCI breakage --- test/config.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/config.sh b/test/config.sh index ecfaf9a1..15edb2e3 100644 --- a/test/config.sh +++ b/test/config.sh @@ -212,11 +212,10 @@ end_suite() { collect_coverage() { host=$1 + mkdir -p ./coverage rm -f cover.router.prof docker_on $host cp weave:/home/weave/cover.router.prof . 2>/dev/null || return 0 - # ideally we'd know the name of the test here, and put that in the filename - mkdir -p ./coverage mv cover.router.prof $(mktemp -u ./coverage/integration.XXXXXXXX) || true } From 32b2ec4038f337231e5914a50053e11d4276f027 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Fri, 10 Jul 2015 17:05:59 +0000 Subject: [PATCH 059/180] Run unit tests in circle and include their coverage in the report. Report coveralls.io from Circle. --- .travis.yml | 1 - Makefile | 18 ++---------------- build/build.sh | 9 +++++++-- circle.yml | 3 +++ test/units.sh | 28 ++++++++++++++++++++++++++++ 5 files changed, 40 insertions(+), 19 deletions(-) create mode 100755 test/units.sh diff --git a/.travis.yml b/.travis.yml index 3e39eef0..3242a3db 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,5 +26,4 @@ script: after_success: - go get github.com/mattn/goveralls - - $HOME/gopath/bin/goveralls -coverprofile=profile.cov -service=travis-ci - test "${TRAVIS_PULL_REQUEST}" = "false" && site/build-and-publish.sh diff --git a/Makefile b/Makefile index 79a465ef..6adf7dea 100644 --- a/Makefile +++ b/Makefile @@ -107,22 +107,7 @@ $(DOCKER_DISTRIB): curl -o $(DOCKER_DISTRIB) $(DOCKER_DISTRIB_URL) tests: - echo "mode: count" > profile.cov - fail=0 ; \ - for dir in $$(find . -type f -name '*_test.go' | xargs -n1 dirname | grep -v prog | sort -u); do \ - go get -t -tags netgo $$dir ; \ - output=$$(mktemp cover.XXXXXXXXXX) ; \ - if ! go test -cpu 4 -tags netgo \ - -covermode=count -coverprofile=$$output $$dir ; then \ - fail=1 ; \ - fi ; \ - if [ -f $$output ]; then \ - tail -n +2 <$$output >>profile.cov; \ - rm $$output; \ - fi \ - done ; \ - exit $$fail - go tool cover -html=profile.cov -o=coverage.html + @test/units.sh $(PUBLISH): publish_%: $(SUDO) docker tag -f $(DOCKERHUB_USER)/$* $(DOCKERHUB_USER)/$*:$(WEAVE_VERSION) @@ -133,6 +118,7 @@ publish: $(PUBLISH) clean: -$(SUDO) docker rmi $(IMAGES) + go clean -r ./... rm -f $(EXES) $(IMAGES_UPTODATE) $(WEAVE_EXPORT) rm -f test/tls/*.pem diff --git a/build/build.sh b/build/build.sh index 7c6d13a4..25d3515b 100644 --- a/build/build.sh +++ b/build/build.sh @@ -6,7 +6,7 @@ export GOPATH WEAVE_SRC=$GOPATH/src/github.com/weaveworks/weave -if [ $# -eq 0 ] ; then +if [ $# -eq 0 -o "$1" = "tests" ] ; then # No arguments. Expect that the weave repo will be bind-mounted # into $GOPATH if ! [ -e $WEAVE_SRC ] ; then @@ -35,7 +35,12 @@ EOF echo "weave:x:$uid:$gid::$WEAVE_SRC:/bin/sh" >>/etc/passwd echo "weave:*:::::::" >>/etc/shadow echo "weave ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers - su weave -c "PATH=$PATH make -C $WEAVE_SRC build" + + if [ "$1" = "tests" ] ; then + su weave -c "PATH=$PATH make -C $WEAVE_SRC tests" + else + su weave -c "PATH=$PATH make -C $WEAVE_SRC build" + fi else # There are arguments to pass to git-clone mkdir -p ${WEAVE_SRC%/*} diff --git a/circle.yml b/circle.yml index 5ac5cc3d..0d1298f8 100644 --- a/circle.yml +++ b/circle.yml @@ -35,6 +35,8 @@ dependencies: test: override: + - test "$CIRCLE_NODE_INDEX" != "0" || (docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go -e "COVERDIR=test/coverage" weaveworks/weave-build tests): + parallel: true - docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go -e COVERAGE=true weaveworks/weave-build: parallel: true - cd $SRCDIR/test; ./gce.sh setup: @@ -52,5 +54,6 @@ teardown: pre: - test "$CIRCLE_NODE_INDEX" != "0" || (cd $SRCDIR/test; ./gen_coverage_reports.sh): parallel: true + - test "$CIRCLE_NODE_INDEX" != "0" || (go get github.com/mattn/goveralls && goveralls -repotoken $COVERALLS_REPO_TOKEN -coverprofile=$SRCDIR/test/profile.cov -service=circleci || true) - test "$CIRCLE_NODE_INDEX" != "0" || (cd $SRCDIR/test; cp coverage.* $CIRCLE_ARTIFACTS): parallel: true diff --git a/test/units.sh b/test/units.sh new file mode 100755 index 00000000..2a383c7a --- /dev/null +++ b/test/units.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +go get github.com/weaveworks/weave/testing/cover + +if [ -n "$COVERDIR" ] ; then + coverdir="$COVERDIR" +else + coverdir=$(mktemp -d coverage.XXXXXXXXXX) +fi + +mkdir -p $coverdir +fail=0 + +for dir in $(find . -type f -name '*_test.go' | xargs -n1 dirname | grep -v prog | sort -u); do + go get -t -tags netgo $dir + output=$(mktemp $coverdir/unit.XXXXXXXXXX) + if ! go test -cpu 4 -tags netgo -covermode=count -coverprofile=$output $dir ; then + fail=1 + fi +done + +if [ -z "$COVERDIR" ] ; then + cover $coverdir/* >profile.cov + rm -rf $coverdir + go tool cover -html=profile.cov -o=coverage.html +fi + +exit $fail From aaba681db1fcb5cb4e9ff924d95a333fced4cbfd Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 01:54:37 +0100 Subject: [PATCH 060/180] remove dead code --- router/crypto.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/router/crypto.go b/router/crypto.go index c77f6250..3f172caf 100644 --- a/router/crypto.go +++ b/router/crypto.go @@ -31,7 +31,6 @@ func FormSessionKey(remotePublicKey, localPrivateKey *[32]byte, secretKey []byte type Encryptor interface { FrameOverhead() int PacketOverhead() int - IsEmpty() bool Bytes() ([]byte, error) AppendFrame(src []byte, dst []byte, frame []byte) TotalLen() int @@ -72,10 +71,6 @@ func (ne *NonEncryptor) FrameOverhead() int { return NameSize + NameSize + 2 } -func (ne *NonEncryptor) IsEmpty() bool { - return ne.buffered == ne.prefixLen -} - func (ne *NonEncryptor) Bytes() ([]byte, error) { buf := ne.buf[:ne.buffered] ne.buffered = ne.prefixLen From c4f516655d14fbf8372a6341d197010e1bf40982 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 02:28:14 +0100 Subject: [PATCH 061/180] refactor: simplify ipam claim try --- ipam/claim.go | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/ipam/claim.go b/ipam/claim.go index d5bb8746..a73c1fd9 100644 --- a/ipam/claim.go +++ b/ipam/claim.go @@ -38,13 +38,14 @@ func (c *claim) Try(alloc *Allocator) bool { // If our ring doesn't know, it must be empty. We will have initiated the // bootstrap of the ring, so wait until we find some owner for this // range (might be us). - owner := alloc.ring.Owner(c.addr) - if owner == router.UnknownPeerName { + switch owner := alloc.ring.Owner(c.addr); owner { + case alloc.ourName: + // success + case router.UnknownPeerName: alloc.infof("Ring is empty; will try later.\n", c.addr, owner) c.sendResult(nil) // don't make the caller wait return false - } - if owner != alloc.ourName { + default: name, found := alloc.nicknames[owner] if found { name = " (" + name + ")" @@ -52,26 +53,24 @@ func (c *claim) Try(alloc *Allocator) bool { c.sendResult(fmt.Errorf("address %s is owned by other peer %s%s", c.addr.String(), owner, name)) return true } + // We are the owner, check we haven't given it to another container - existingIdent := alloc.findOwner(c.addr) - if existingIdent == c.ident { + switch existingIdent := alloc.findOwner(c.addr); existingIdent { + case "": + if err := alloc.space.Claim(c.addr); err != nil { + c.sendResult(err) + } else { + alloc.debugln("Claimed", c.addr, "for", c.ident) + alloc.addOwned(c.ident, c.addr) + c.sendResult(nil) + } + case c.ident: // same identifier is claiming same address; that's OK c.sendResult(nil) - return true + default: + // Addr already owned by container on this machine + c.sendResult(fmt.Errorf("address %s is already owned by %s", c.addr.String(), existingIdent)) } - if existingIdent == "" { - err := alloc.space.Claim(c.addr) - if err != nil { - c.sendResult(err) - return true - } - alloc.debugln("Claimed", c.addr, "for", c.ident) - alloc.addOwned(c.ident, c.addr) - c.sendResult(nil) - return true - } - // Addr already owned by container on this machine - c.sendResult(fmt.Errorf("address %s is already owned by %s", c.addr.String(), existingIdent)) return true } From 76943f0b1704575b93783f57554e71e05d96a47c Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 02:52:30 +0100 Subject: [PATCH 062/180] cosmetic --- ipam/claim.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ipam/claim.go b/ipam/claim.go index a73c1fd9..bf5dafcc 100644 --- a/ipam/claim.go +++ b/ipam/claim.go @@ -57,12 +57,12 @@ func (c *claim) Try(alloc *Allocator) bool { // We are the owner, check we haven't given it to another container switch existingIdent := alloc.findOwner(c.addr); existingIdent { case "": - if err := alloc.space.Claim(c.addr); err != nil { - c.sendResult(err) - } else { + if err := alloc.space.Claim(c.addr); err == nil { alloc.debugln("Claimed", c.addr, "for", c.ident) alloc.addOwned(c.ident, c.addr) c.sendResult(nil) + } else { + c.sendResult(err) } case c.ident: // same identifier is claiming same address; that's OK From 7042c1506a61e47a674d6e76ba8ddd7b36e080ee Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 03:36:21 +0100 Subject: [PATCH 063/180] cosmetic: consistency with other tests --- test/140_weave_local_test.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/140_weave_local_test.sh b/test/140_weave_local_test.sh index d198b727..aaa3aaf9 100755 --- a/test/140_weave_local_test.sh +++ b/test/140_weave_local_test.sh @@ -2,14 +2,14 @@ . ./config.sh -start_suite "Run weave with --local" - weave_local_on() { host=$1 shift 1 run_on $host sudo COVERAGE=$COVERAGE weave --local $@ } +start_suite "Run weave with --local" + weave_local_on $HOST1 reset weave_local_on $HOST1 launch --ipalloc-range 10.2.5.0/24 From 982c9d765050dc1d1846db108b792b89dd77790a Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 11:17:44 +0100 Subject: [PATCH 064/180] remove dead code --- ipam/ring/entry.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ipam/ring/entry.go b/ipam/ring/entry.go index e33bd488..d1d832ed 100644 --- a/ipam/ring/entry.go +++ b/ipam/ring/entry.go @@ -68,10 +68,6 @@ func (es entries) get(token address.Address) (*entry, bool) { return nil, false } -func (es *entries) remove(i int) { - *es = (*es)[:i+copy((*es)[i:], (*es)[i+1:])] -} - // Is token between entries at i and j? // NB i and j can overflow and will wrap // NBB this function does not work very well if there is only one From a44a3a41589da9dc441344651730825eb93a8e61 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 11:46:49 +0100 Subject: [PATCH 065/180] cure "./gen_coverage_reports.sh: line 5: CIRCLECI: unbound variable" --- test/gen_coverage_reports.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/gen_coverage_reports.sh b/test/gen_coverage_reports.sh index b15248ab..523d09d1 100755 --- a/test/gen_coverage_reports.sh +++ b/test/gen_coverage_reports.sh @@ -1,6 +1,6 @@ #!/bin/bash -set -eux +set -ex if [ -n "$CIRCLECI" ]; then for i in $(seq 1 $(($CIRCLE_NODE_TOTAL - 1))); do From c22d824db8dc50e3f41d0185ad98093ef2ebfd9a Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 11:57:01 +0100 Subject: [PATCH 066/180] .gitignore and clean up coverage reports --- .gitignore | 2 ++ Makefile | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 609b440f..36eeb6b2 100644 --- a/.gitignore +++ b/.gitignore @@ -51,3 +51,5 @@ prog/weaveexec/netcheck prog/weaveexec/docker*.tgz Vagrantfile.local test/tls/*.pem +test/coverage +test/coverage.* diff --git a/Makefile b/Makefile index 6adf7dea..ac9515bc 100644 --- a/Makefile +++ b/Makefile @@ -120,7 +120,7 @@ clean: -$(SUDO) docker rmi $(IMAGES) go clean -r ./... rm -f $(EXES) $(IMAGES_UPTODATE) $(WEAVE_EXPORT) - rm -f test/tls/*.pem + rm -rf test/tls/*.pem test/coverage.* test/coverage build: $(SUDO) go clean -i net From 25486f7b4db99c6ac03d58a1c4db2e1402f8a2dc Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 11:57:52 +0100 Subject: [PATCH 067/180] cosmetic: s/weave_stop_router/stop_router_on Also run `weave stop-router` as part of this, so conntrack cleanup happens. --- test/150_connect_forget_test.sh | 2 +- test/config.sh | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/test/150_connect_forget_test.sh b/test/150_connect_forget_test.sh index 72130d74..d84fbfe9 100755 --- a/test/150_connect_forget_test.sh +++ b/test/150_connect_forget_test.sh @@ -33,7 +33,7 @@ assert_raises "exec_on $HOST1 c1 $PING $C2" # Forget everyone and disconnect assert_raises "weave_on $HOST2 forget $HOST1 $HOST2" -assert_raises "weave_stop_router $HOST1" +assert_raises "weave_stop_on $HOST1" assert_raises "weave_on $HOST1 launch-router" assert_peers $HOST2 "" assert_raises "exec_on $HOST1 c1 sh -c '! $PING $C2'" diff --git a/test/config.sh b/test/config.sh index 15edb2e3..10cc3fc7 100644 --- a/test/config.sh +++ b/test/config.sh @@ -113,13 +113,14 @@ weave_on() { DOCKER_HOST=tcp://$host:$DOCKER_PORT $WEAVE "$@" } -weave_stop_router() { +stop_router_on() { host=$1 shift 1 docker_on $host stop weave 1>/dev/null 2>&1 || true if [ -n "$COVERAGE" ] ; then collect_coverage $host fi + weave_on $host stop-router 2>/dev/null } exec_on() { @@ -206,7 +207,7 @@ start_suite() { end_suite() { whitely assert_end for host in $HOSTS; do - weave_stop_router $host + stop_router_on $host done } From a3dff7e1e9e968cbdeecc2055794988b03c1c69e Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 11:59:34 +0100 Subject: [PATCH 068/180] cope with more than two test hosts --- test/config.sh | 2 +- test/sanity_check.sh | 36 ++++++++++++++++-------------------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/test/config.sh b/test/config.sh index 10cc3fc7..2ddfe115 100644 --- a/test/config.sh +++ b/test/config.sh @@ -196,7 +196,7 @@ assert_dns_ptr_record() { } start_suite() { - for host in $HOST1 $HOST2; do + for host in $HOSTS; do [ -z "$DEBUG" ] || echo "Cleaning up on $host: removing all containers and resetting weave" weave_on $host reset 2>/dev/null rm_containers $host $(docker_on $host ps -aq 2>/dev/null) diff --git a/test/sanity_check.sh b/test/sanity_check.sh index 1ec566bc..592a6b77 100755 --- a/test/sanity_check.sh +++ b/test/sanity_check.sh @@ -5,26 +5,22 @@ set -e whitely echo Ping each host from the other -run_on $HOST2 $PING $HOST1 -run_on $HOST1 $PING $HOST2 +for host in $HOSTS; do + for other in $HOSTS; do + [ $host = $other ] || run_on $host $PING $other + done +done whitely echo Check we can reach docker -echo -echo Host Version Info: $HOST1 -echo ===================================== -echo "# docker version" -docker_on $HOST1 version -echo "# docker info" -docker_on $HOST1 info -echo "# weave version" -weave_on $HOST1 version -echo -echo Host Version Info: $HOST2 -echo ===================================== -echo "# docker version" -docker_on $HOST2 version -echo "# docker info" -docker_on $HOST2 info -echo "# weave version" -weave_on $HOST2 version +for host in $HOSTS; do + echo + echo Host Version Info: $host + echo ===================================== + echo "# docker version" + docker_on $host version + echo "# docker info" + docker_on $host info + echo "# weave version" + weave_on $host version +done From 603f34e944e87bcf33f28fe52aca1326f7da4ddf Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 12:14:43 +0100 Subject: [PATCH 069/180] oops, forgot to commit this --- test/150_connect_forget_test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/150_connect_forget_test.sh b/test/150_connect_forget_test.sh index d84fbfe9..194d176b 100755 --- a/test/150_connect_forget_test.sh +++ b/test/150_connect_forget_test.sh @@ -33,7 +33,7 @@ assert_raises "exec_on $HOST1 c1 $PING $C2" # Forget everyone and disconnect assert_raises "weave_on $HOST2 forget $HOST1 $HOST2" -assert_raises "weave_stop_on $HOST1" +assert_raises "stop_router_on $HOST1" assert_raises "weave_on $HOST1 launch-router" assert_peers $HOST2 "" assert_raises "exec_on $HOST1 c1 sh -c '! $PING $C2'" From 710eabeff3813548418ff01cb86e101ab25f5246 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 12:15:46 +0100 Subject: [PATCH 070/180] reduce test vm memory --- test/Vagrantfile | 1 + 1 file changed, 1 insertion(+) diff --git a/test/Vagrantfile b/test/Vagrantfile index 57ef1097..73be67e3 100644 --- a/test/Vagrantfile +++ b/test/Vagrantfile @@ -45,6 +45,7 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--natdnshostresolver1", "off"] vb.customize ["modifyvm", :id, "--natdnsproxy1", "off"] + vb.memory = 384 end # Disable Vagrant 1.7 per host insecure key replacement From 9a089a111fd0f0af6777722915cbb79d0f9ad08a Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 14:56:11 +0100 Subject: [PATCH 071/180] don't invoke `weave stop-router` at end of tests since that removes the container, rather than just stopping it. --- test/config.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/config.sh b/test/config.sh index 2ddfe115..31159e4a 100644 --- a/test/config.sh +++ b/test/config.sh @@ -116,11 +116,13 @@ weave_on() { stop_router_on() { host=$1 shift 1 + # we don't invoke `weave stop-router` here because that removes + # the weave container, which means we a) can't grab coverage + # stats, and b) can't inspect the logs when tests fail. docker_on $host stop weave 1>/dev/null 2>&1 || true if [ -n "$COVERAGE" ] ; then collect_coverage $host fi - weave_on $host stop-router 2>/dev/null } exec_on() { From 210b9260647e404627df8a5277b275f1c4cc747c Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 12:31:00 +0100 Subject: [PATCH 072/180] increase number of test VMs from 2 to 3 --- test/Vagrantfile | 2 +- test/config.sh | 3 ++- test/gce.sh | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/test/Vagrantfile b/test/Vagrantfile index 73be67e3..1a888f40 100644 --- a/test/Vagrantfile +++ b/test/Vagrantfile @@ -5,7 +5,7 @@ VAGRANTFILE_API_VERSION = "2" Vagrant.require_version ">= 1.7.0" # these ought to match what is in config.sh -n_machines = 2 +n_machines = 3 ip_prefix = "192.168.48" ip_suffix_base = 10 diff --git a/test/config.sh b/test/config.sh index 31159e4a..3d136999 100644 --- a/test/config.sh +++ b/test/config.sh @@ -12,7 +12,7 @@ fi SOURCED_CONFIG_SH=true # these ought to match what is in Vagrantfile -N_MACHINES=${N_MACHINES:-2} +N_MACHINES=${N_MACHINES:-3} IP_PREFIX=${IP_PREFIX:-192.168.48} IP_SUFFIX_BASE=${IP_SUFFIX_BASE:-10} @@ -26,6 +26,7 @@ fi # these are used by the tests HOST1=$(echo $HOSTS | cut -f 1 -d ' ') HOST2=$(echo $HOSTS | cut -f 2 -d ' ') +HOST3=$(echo $HOSTS | cut -f 3 -d ' ') . "$DIR/assert.sh" diff --git a/test/gce.sh b/test/gce.sh index 02738928..192af733 100755 --- a/test/gce.sh +++ b/test/gce.sh @@ -13,7 +13,7 @@ PROJECT=${PROJECT:-positive-cocoa-90213} IMAGE=ubuntu-14-04 TEMPLATE_NAME="test-template-2" ZONE=us-central1-a -NUM_HOSTS=2 +NUM_HOSTS=3 SUFFIX="" if [ -n "$CIRCLECI" ]; then SUFFIX="-${CIRCLE_BUILD_NUM}-$CIRCLE_NODE_INDEX" From 2a0bc91f86f8d5485a3487f16902f80ef547f6fc Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 12:33:25 +0100 Subject: [PATCH 073/180] add test for peer discovery and multi-hop routing --- test/120_discovery_test.sh | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100755 test/120_discovery_test.sh diff --git a/test/120_discovery_test.sh b/test/120_discovery_test.sh new file mode 100755 index 00000000..2d6e313f --- /dev/null +++ b/test/120_discovery_test.sh @@ -0,0 +1,34 @@ +#! /bin/bash + +. ./config.sh + +C1=10.2.1.41 +C3=10.2.1.71 + +launch_all() { + weave_on $HOST1 launch-router $1 + weave_on $HOST2 launch-router $1 $HOST1 + weave_on $HOST3 launch-router $1 $HOST2 +} + +start_suite "Peer discovery and multi-hop routing" + +launch_all + +start_container $HOST1 $C1/24 --name=c1 +start_container $HOST3 $C3/24 --name=c3 + +assert_raises "exec_on $HOST1 c1 $PING $C3" +stop_router_on $HOST2 +assert_raises "exec_on $HOST1 c1 $PING $C3" + +stop_router_on $HOST1 +stop_router_on $HOST3 + +launch_all --no-discovery + +assert_raises "exec_on $HOST1 c1 $PING $C3" +stop_router_on $HOST2 +assert_raises "exec_on $HOST1 c1 sh -c '! $PING $C3'" + +end_suite From 1d2e6b4c565c961524579f3bb3f25b999114942c Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 14:13:40 +0100 Subject: [PATCH 074/180] test gossip forwarding --- test/120_discovery_test.sh | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/test/120_discovery_test.sh b/test/120_discovery_test.sh index 2d6e313f..c774ad16 100755 --- a/test/120_discovery_test.sh +++ b/test/120_discovery_test.sh @@ -7,11 +7,11 @@ C3=10.2.1.71 launch_all() { weave_on $HOST1 launch-router $1 - weave_on $HOST2 launch-router $1 $HOST1 - weave_on $HOST3 launch-router $1 $HOST2 + weave_on $HOST2 launch-router $1 --ipalloc-range="" $HOST1 + weave_on $HOST3 launch-router $1 $HOST2 } -start_suite "Peer discovery and multi-hop routing" +start_suite "Peer discovery, multi-hop routing and gossip forwarding" launch_all @@ -28,6 +28,11 @@ stop_router_on $HOST3 launch_all --no-discovery assert_raises "exec_on $HOST1 c1 $PING $C3" + +# this stalls if gossip forwarding doesn't work. We wait for slightly +# longer than the gossip interval (30s) before giving up. +assert_raises "timeout 40 cat <( start_container $HOST3 )" + stop_router_on $HOST2 assert_raises "exec_on $HOST1 c1 sh -c '! $PING $C3'" From 57a4371e9f7b84787b7ed91296e11bf5c7017bc0 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 16:31:16 +0100 Subject: [PATCH 075/180] attempt to cure spurious test failures --- test/120_discovery_test.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/120_discovery_test.sh b/test/120_discovery_test.sh index c774ad16..447b3721 100755 --- a/test/120_discovery_test.sh +++ b/test/120_discovery_test.sh @@ -27,6 +27,8 @@ stop_router_on $HOST3 launch_all --no-discovery +sleep 5 # give topology gossip some time to propagate + assert_raises "exec_on $HOST1 c1 $PING $C3" # this stalls if gossip forwarding doesn't work. We wait for slightly From 2b61bc91df9ea19dd98b81a2fecdc6d760e4e05c Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 16:43:33 +0100 Subject: [PATCH 076/180] cosmetic: remove blank log lines --- common/signals.go | 6 +++--- ipam/claim.go | 4 ++-- ipam/ring/ring.go | 2 +- prog/weavedns/main.go | 2 +- router/connection.go | 2 +- router/connection_maker.go | 4 ++-- router/ethernet_decoder.go | 2 +- router/local_peer.go | 2 +- router/router.go | 2 +- 9 files changed, 13 insertions(+), 13 deletions(-) diff --git a/common/signals.go b/common/signals.go index c2e2a683..48ed747c 100644 --- a/common/signals.go +++ b/common/signals.go @@ -20,17 +20,17 @@ func SignalHandlerLoop(ss ...SignalReceiver) { for { switch <-sigs { case syscall.SIGINT, syscall.SIGTERM: - Log.Infof("=== received SIGINT/SIGTERM ===\n*** exiting\n") + Log.Infof("=== received SIGINT/SIGTERM ===\n*** exiting") for _, subsystem := range ss { subsystem.Stop() } return case syscall.SIGQUIT: stacklen := runtime.Stack(buf, true) - Log.Infof("=== received SIGQUIT ===\n*** goroutine dump...\n%s\n*** end\n", buf[:stacklen]) + Log.Infof("=== received SIGQUIT ===\n*** goroutine dump...\n%s\n*** end", buf[:stacklen]) case syscall.SIGUSR1: for _, subsystem := range ss { - Log.Infof("=== received SIGUSR1 ===\n*** status...\n%s\n*** end\n", subsystem.Status()) + Log.Infof("=== received SIGUSR1 ===\n*** status...\n%s\n*** end", subsystem.Status()) } } } diff --git a/ipam/claim.go b/ipam/claim.go index bf5dafcc..63212cd7 100644 --- a/ipam/claim.go +++ b/ipam/claim.go @@ -30,7 +30,7 @@ func (c *claim) sendResult(result error) { func (c *claim) Try(alloc *Allocator) bool { if !alloc.ring.Contains(c.addr) { // Address not within our universe; assume user knows what they are doing - alloc.infof("Ignored address %s claimed by %s - not in our universe\n", c.addr, c.ident) + alloc.infof("Ignored address %s claimed by %s - not in our universe", c.addr, c.ident) c.sendResult(nil) return true } @@ -42,7 +42,7 @@ func (c *claim) Try(alloc *Allocator) bool { case alloc.ourName: // success case router.UnknownPeerName: - alloc.infof("Ring is empty; will try later.\n", c.addr, owner) + alloc.infof("Ring is empty; will try later.", c.addr, owner) c.sendResult(nil) // don't make the caller wait return false default: diff --git a/ipam/ring/ring.go b/ipam/ring/ring.go index fbeeb21b..11d53126 100644 --- a/ipam/ring/ring.go +++ b/ipam/ring/ring.go @@ -218,7 +218,7 @@ func (r *Ring) Merge(gossip Ring) error { switch { case mine.Version >= theirs.Version: if mine.Version == theirs.Version && !mine.Equal(theirs) { - common.Log.Debugf("Error merging entries at %s - %v != %v\n", mine.Token, mine, theirs) + common.Log.Debugf("Error merging entries at %s - %v != %v", mine.Token, mine, theirs) return ErrInvalidEntry } addToResult(*mine) diff --git a/prog/weavedns/main.go b/prog/weavedns/main.go index 06aa0780..c8217656 100644 --- a/prog/weavedns/main.go +++ b/prog/weavedns/main.go @@ -71,7 +71,7 @@ func main() { } SetLogLevel(logLevel) - Log.Infof("[main] WeaveDNS version %s\n", version) // first thing in log: the version + Log.Infof("[main] WeaveDNS version %s", version) // first thing in log: the version var iface *net.Interface if ifaceName != "" { diff --git a/router/connection.go b/router/connection.go index 3f5396f7..709d02cc 100644 --- a/router/connection.go +++ b/router/connection.go @@ -408,7 +408,7 @@ func (conn *LocalConnection) actorLoop(actionChan <-chan ConnectionAction) (err func (conn *LocalConnection) shutdown(err error) { if conn.remote == nil { - Log.Errorf("->[%s] connection shutting down due to error during handshake: %v\n", conn.remoteTCPAddr, err) + Log.Errorf("->[%s] connection shutting down due to error during handshake: %v", conn.remoteTCPAddr, err) } else { conn.ErrorLog("connection shutting down due to error:", err) } diff --git a/router/connection_maker.go b/router/connection_maker.go index acb1102d..9c65ce28 100644 --- a/router/connection_maker.go +++ b/router/connection_maker.go @@ -299,9 +299,9 @@ func (cm *ConnectionMaker) connectToTargets(validTarget map[string]struct{}, dir } func (cm *ConnectionMaker) attemptConnection(address string, acceptNewPeer bool) { - Log.Printf("->[%s] attempting connection\n", address) + Log.Printf("->[%s] attempting connection", address) if err := cm.ourself.CreateConnection(address, acceptNewPeer); err != nil { - Log.Errorf("->[%s] error during connection attempt: %v\n", address, err) + Log.Errorf("->[%s] error during connection attempt: %v", address, err) cm.ConnectionTerminated(address, err) } } diff --git a/router/ethernet_decoder.go b/router/ethernet_decoder.go index 0404f182..84a96d0d 100644 --- a/router/ethernet_decoder.go +++ b/router/ethernet_decoder.go @@ -61,7 +61,7 @@ func (dec *EthernetDecoder) sendICMPFragNeeded(mtu int, sendFrame func([]byte) e return err } - Log.Printf("Sending ICMP 3,4 (%v -> %v): PMTU= %v\n", dec.IP.DstIP, dec.IP.SrcIP, mtu) + Log.Printf("Sending ICMP 3,4 (%v -> %v): PMTU= %v", dec.IP.DstIP, dec.IP.SrcIP, mtu) return sendFrame(buf.Bytes()) } diff --git a/router/local_peer.go b/router/local_peer.go index 3c9ac880..183afed5 100644 --- a/router/local_peer.go +++ b/router/local_peer.go @@ -71,7 +71,7 @@ func (peer *LocalPeer) RelayBroadcast(srcPeer *Peer, frame []byte, dec *Ethernet dec) if err != nil { if ftbe, ok := err.(FrameTooBigError); ok { - Log.Warningf("dropping too big DF broadcast frame (%v -> %v): PMTU= %v\n", dec.IP.DstIP, dec.IP.SrcIP, ftbe.EPMTU) + Log.Warningf("dropping too big DF broadcast frame (%v -> %v): PMTU= %v", dec.IP.DstIP, dec.IP.SrcIP, ftbe.EPMTU) } else { Log.Errorln(err) } diff --git a/router/router.go b/router/router.go index f4a254fc..4a1ae62d 100644 --- a/router/router.go +++ b/router/router.go @@ -215,7 +215,7 @@ func (router *Router) acceptTCP(tcpConn *net.TCPConn) { // on router.Port and we wait for them to send us something on UDP to // start. remoteAddrStr := tcpConn.RemoteAddr().String() - Log.Printf("->[%s] connection accepted\n", remoteAddrStr) + Log.Printf("->[%s] connection accepted", remoteAddrStr) connRemote := NewRemoteConnection(router.Ourself.Peer, nil, remoteAddrStr, false, false) StartLocalConnection(connRemote, tcpConn, nil, router, true) } From 7aab5cc5b448d4a80b74762d65ffaf13df4ca062 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Sat, 11 Jul 2015 17:46:57 +0100 Subject: [PATCH 077/180] refactor: simplify NewPeers --- router/peers.go | 7 ++----- router/peers_test.go | 2 +- router/router.go | 3 ++- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/router/peers.go b/router/peers.go index 3f2d0582..82b7d3d8 100644 --- a/router/peers.go +++ b/router/peers.go @@ -39,11 +39,8 @@ type ConnectionSummary struct { Established bool } -func NewPeers(ourself *LocalPeer, onGC func(*Peer)) *Peers { - return &Peers{ - ourself: ourself, - table: make(map[PeerName]*Peer), - onGC: []func(*Peer){onGC}} +func NewPeers(ourself *LocalPeer) *Peers { + return &Peers{ourself: ourself, table: make(map[PeerName]*Peer)} } func (peers *Peers) OnGC(callback func(*Peer)) { diff --git a/router/peers_test.go b/router/peers_test.go index 2c0fbfb1..698502ad 100644 --- a/router/peers_test.go +++ b/router/peers_test.go @@ -19,7 +19,7 @@ import ( func newNode(name PeerName) (*Peer, *Peers) { peer := NewLocalPeer(name, "", nil) - peers := NewPeers(peer, func(*Peer) {}) + peers := NewPeers(peer) peers.FetchWithDefault(peer.Peer) return peer.Peer, peers } diff --git a/router/router.go b/router/router.go index 4a1ae62d..44da7ca4 100644 --- a/router/router.go +++ b/router/router.go @@ -74,7 +74,8 @@ func NewRouter(config Config, name PeerName, nickName string) *Router { } router.Ourself = NewLocalPeer(name, nickName, router) router.Macs = NewMacCache(macMaxAge, onMacExpiry) - router.Peers = NewPeers(router.Ourself, onPeerGC) + router.Peers = NewPeers(router.Ourself) + router.Peers.OnGC(onPeerGC) router.Peers.FetchWithDefault(router.Ourself.Peer) router.Routes = NewRoutes(router.Ourself, router.Peers) router.ConnectionMaker = NewConnectionMaker(router.Ourself, router.Peers, router.Port, router.PeerDiscovery) From 9463ceb87395f7faceb6a2ef471b62dc224ff51b Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Mon, 13 Jul 2015 10:31:20 +0100 Subject: [PATCH 078/180] test that large packets can be transmitted over weave --- test/100_cross_hosts_test.sh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/100_cross_hosts_test.sh b/test/100_cross_hosts_test.sh index 4ea28f74..a2f77068 100755 --- a/test/100_cross_hosts_test.sh +++ b/test/100_cross_hosts_test.sh @@ -27,4 +27,10 @@ start_container $HOST2 net:$SUBNET_2 --name=c6 C6=$(container_ip $HOST2 c6) assert_raises "exec_on $HOST1 c5 $PING $C6" +# check large packets get through. The first attempt typically fails, +# since the PMTU hasn't been discovered yet. The 2nd attempt should +# succeed. +exec_on $HOST1 c1 $PING -s 65000 $C2 2>&1 1>/dev/null || true +assert_raises "exec_on $HOST1 c1 $PING -s 65000 $C2" + end_suite From 13f1239a3e5736e298975fd27161b90f1fb26723 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Sun, 12 Jul 2015 09:34:52 +0000 Subject: [PATCH 079/180] Various improvements to unit test running - units.sh should exit on error. - Add race detector to unit test runner. - Use local testing/cover/cover tool in gen_coverage_report.sh and units.sh - Use the scheduler to parallelise the unit tests. - Make test run id a string and differentiate between unit runs and integration runs in the scheduler. - Pipe circle env vars through to build container so we can detect when to use the scheduler - Add python requests to the weave build container. - Quote test names in urls, make flask handle url segments with slashes in. --- .gitignore | 1 + Makefile | 12 ++++--- build/Dockerfile | 2 +- circle.yml | 5 +-- test/gen_coverage_reports.sh | 3 +- test/run_all.sh | 2 +- test/sched | 8 ++--- test/scheduler/.gitignore | 7 ++++ test/scheduler/README.md | 6 ++++ test/scheduler/main.py | 6 ++-- test/scheduler/requirements.txt | 1 + test/units.sh | 62 ++++++++++++++++++++++++--------- 12 files changed, 82 insertions(+), 33 deletions(-) create mode 100644 test/scheduler/.gitignore create mode 100644 test/scheduler/README.md create mode 100644 test/scheduler/requirements.txt diff --git a/.gitignore b/.gitignore index 36eeb6b2..b7906352 100644 --- a/.gitignore +++ b/.gitignore @@ -36,6 +36,7 @@ prog/weaveproxy/weaveproxy prog/sigproxy/sigproxy prog/weavewait/weavewait prog/netcheck/netcheck +testing/cover/cover tools/bin tools/build releases diff --git a/Makefile b/Makefile index ac9515bc..1a203884 100644 --- a/Makefile +++ b/Makefile @@ -15,8 +15,9 @@ WEAVEPROXY_EXE=prog/weaveproxy/weaveproxy SIGPROXY_EXE=prog/sigproxy/sigproxy WEAVEWAIT_EXE=prog/weavewait/weavewait NETCHECK_EXE=prog/netcheck/netcheck +COVER_EXE=testing/cover/cover -EXES=$(WEAVER_EXE) $(WEAVEDNS_EXE) $(SIGPROXY_EXE) $(WEAVEPROXY_EXE) $(WEAVEWAIT_EXE) $(NETCHECK_EXE) +EXES=$(WEAVER_EXE) $(WEAVEDNS_EXE) $(SIGPROXY_EXE) $(WEAVEPROXY_EXE) $(WEAVEWAIT_EXE) $(NETCHECK_EXE) $(COVER_EXE) WEAVER_UPTODATE=.weaver.uptodate WEAVEDNS_UPTODATE=.weavedns.uptodate @@ -75,11 +76,12 @@ $(NETCHECK_EXE): prog/netcheck/netcheck.go # Sigproxy and weavewait need separate rules as they fail the netgo check in # the main build stanza due to not importing net package - $(SIGPROXY_EXE): prog/sigproxy/main.go - go build -o $@ ./$(@D) - $(WEAVEWAIT_EXE): prog/weavewait/main.go +$(COVER_EXE): testing/cover/cover.go + +$(WEAVEWAIT_EXE) $(SIGPROXY_EXE) $(COVER_EXE): + go get ./$(@D) go build -o $@ ./$(@D) $(WEAVER_UPTODATE): prog/weaver/Dockerfile $(WEAVER_EXE) @@ -106,7 +108,7 @@ $(WEAVE_EXPORT): $(IMAGES_UPTODATE) $(DOCKER_DISTRIB): curl -o $(DOCKER_DISTRIB) $(DOCKER_DISTRIB_URL) -tests: +tests: $(COVER_EXE) @test/units.sh $(PUBLISH): publish_%: diff --git a/build/Dockerfile b/build/Dockerfile index 23861bdf..08df1d9d 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -3,7 +3,7 @@ FROM ubuntu RUN apt-get -y update && apt-get -y install --no-install-recommends ca-certificates apt-transport-https RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9 RUN echo deb https://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list -RUN apt-get -y update && apt-get -y install --no-install-recommends build-essential git lxc-docker-1.3.1 mercurial libpcap-dev curl make pkg-config gcc bison flex +RUN apt-get -y update && apt-get -y install --no-install-recommends build-essential git lxc-docker-1.3.1 mercurial libpcap-dev curl make pkg-config gcc bison flex python-requests # When doing a build in a container, "apt-get update" happens twice, # which can be a very significant overhead for incremental builds. diff --git a/circle.yml b/circle.yml index 0d1298f8..7b23b9f1 100644 --- a/circle.yml +++ b/circle.yml @@ -35,7 +35,7 @@ dependencies: test: override: - - test "$CIRCLE_NODE_INDEX" != "0" || (docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go -e "COVERDIR=test/coverage" weaveworks/weave-build tests): + - docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go -e COVERDIR=test/coverage -e SLOW=true -e CIRCLECI -e CIRCLE_BUILD_NUM -e CIRCLE_NODE_TOTAL -e CIRCLE_NODE_INDEX weaveworks/weave-build tests: parallel: true - docker run -v /var/run/docker.sock:/run/docker.sock -v /home/ubuntu:/home/go -e COVERAGE=true weaveworks/weave-build: parallel: true @@ -54,6 +54,7 @@ teardown: pre: - test "$CIRCLE_NODE_INDEX" != "0" || (cd $SRCDIR/test; ./gen_coverage_reports.sh): parallel: true - - test "$CIRCLE_NODE_INDEX" != "0" || (go get github.com/mattn/goveralls && goveralls -repotoken $COVERALLS_REPO_TOKEN -coverprofile=$SRCDIR/test/profile.cov -service=circleci || true) + - test "$CIRCLE_NODE_INDEX" != "0" || (go get github.com/mattn/goveralls && goveralls -repotoken $COVERALLS_REPO_TOKEN -coverprofile=$SRCDIR/test/profile.cov -service=circleci || true): + parallel: true - test "$CIRCLE_NODE_INDEX" != "0" || (cd $SRCDIR/test; cp coverage.* $CIRCLE_ARTIFACTS): parallel: true diff --git a/test/gen_coverage_reports.sh b/test/gen_coverage_reports.sh index 523d09d1..567cb0f3 100755 --- a/test/gen_coverage_reports.sh +++ b/test/gen_coverage_reports.sh @@ -1,6 +1,7 @@ #!/bin/bash set -ex +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" if [ -n "$CIRCLECI" ]; then for i in $(seq 1 $(($CIRCLE_NODE_TOTAL - 1))); do @@ -8,7 +9,7 @@ if [ -n "$CIRCLECI" ]; then done fi -go get github.com/weaveworks/weave/testing/cover +$DIR/../testing/cover/cover cover ./coverage/* >profile.cov go tool cover -html=profile.cov -o coverage.html go tool cover -func=profile.cov -o coverage.txt diff --git a/test/run_all.sh b/test/run_all.sh index 4afd13d5..ac1d1143 100755 --- a/test/run_all.sh +++ b/test/run_all.sh @@ -29,7 +29,7 @@ TESTS="${@:-*_test.sh}" # If running on circle, use the scheduler to work out what tests to run if [ -n "$CIRCLECI" -a -z "$NO_SCHEDULER" ]; then - TESTS=$(echo $TESTS | "$DIR/sched" sched $CIRCLE_BUILD_NUM $CIRCLE_NODE_TOTAL $CIRCLE_NODE_INDEX) + TESTS=$(echo $TESTS | "$DIR/sched" sched integration-$CIRCLE_BUILD_NUM $CIRCLE_NODE_TOTAL $CIRCLE_NODE_INDEX) fi echo Running $TESTS diff --git a/test/sched b/test/sched index 4a7c7021..e94e8af8 100755 --- a/test/sched +++ b/test/sched @@ -1,17 +1,17 @@ #!/usr/bin/python -import sys, string, json +import sys, string, json, urllib import requests BASE_URL="http://positive-cocoa-90213.appspot.com" def test_time(test_name, runtime): - r = requests.post(BASE_URL + "/record/%s/%f" % (test_name, runtime)) + r = requests.post(BASE_URL + "/record/%s/%f" % (urllib.quote(test_name, safe=""), runtime)) print r.text assert r.status_code == 204 def test_sched(test_run, shard_count, shard_id): tests = json.dumps({'tests': string.split(sys.stdin.read())}) - r = requests.post(BASE_URL + "/schedule/%d/%d/%d" % (test_run, shard_count, shard_id), data=tests) + r = requests.post(BASE_URL + "/schedule/%s/%d/%d" % (test_run, shard_count, shard_id), data=tests) assert r.status_code == 200 result = r.json() for test in sorted(result['tests']): @@ -30,7 +30,7 @@ def main(): if sys.argv[1] == "time": test_time(sys.argv[2], float(sys.argv[3])) elif sys.argv[1] == "sched": - test_sched(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])) + test_sched(sys.argv[2], int(sys.argv[3]), int(sys.argv[4])) else: usage() diff --git a/test/scheduler/.gitignore b/test/scheduler/.gitignore new file mode 100644 index 00000000..8531a10c --- /dev/null +++ b/test/scheduler/.gitignore @@ -0,0 +1,7 @@ +*.egg-info +*.dist-info +flask +jinja2 +markupsafe +werkzeug +itsdangerous.* diff --git a/test/scheduler/README.md b/test/scheduler/README.md new file mode 100644 index 00000000..df2b4726 --- /dev/null +++ b/test/scheduler/README.md @@ -0,0 +1,6 @@ +To upload newer version: + +``` +pip install -r requirements.txt -t . +appcfg.py update . +``` diff --git a/test/scheduler/main.py b/test/scheduler/main.py index a2cf113b..35d824ab 100644 --- a/test/scheduler/main.py +++ b/test/scheduler/main.py @@ -19,7 +19,7 @@ class Test(ndb.Model): class Schedule(ndb.Model): shards = ndb.JsonProperty() -@app.route('/record//', methods=['POST']) +@app.route('/record//', methods=['POST']) @ndb.transactional def record(test_name, runtime): test = Test.get_by_id(test_name) @@ -30,13 +30,13 @@ def record(test_name, runtime): test.put() return ('', 204) -@app.route('/schedule///', methods=['POST']) +@app.route('/schedule///', methods=['POST']) def schedule(test_run, shard_count, shard): # read tests from body test_names = flask.request.get_json(force=True)['tests'] # first see if we have a scedule already - schedule_id = "%d-%d" % (test_run, shard_count) + schedule_id = "%s-%d" % (test_run, shard_count) schedule = Schedule.get_by_id(schedule_id) if schedule is not None: return flask.json.jsonify(tests=schedule.shards[str(shard)]) diff --git a/test/scheduler/requirements.txt b/test/scheduler/requirements.txt new file mode 100644 index 00000000..7e106024 --- /dev/null +++ b/test/scheduler/requirements.txt @@ -0,0 +1 @@ +flask diff --git a/test/units.sh b/test/units.sh index 2a383c7a..d388b23e 100755 --- a/test/units.sh +++ b/test/units.sh @@ -1,28 +1,58 @@ #!/bin/bash -go get github.com/weaveworks/weave/testing/cover +set -e -if [ -n "$COVERDIR" ] ; then - coverdir="$COVERDIR" -else - coverdir=$(mktemp -d coverage.XXXXXXXXXX) +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SLOW=${SLOW-} +GO_TEST_ARGS="-tags netgo -cpu 4" +if [ -n "$SLOW" -o "$1" = "-slow" ]; then + GO_TEST_ARGS="$GO_TEST_ARGS -race -covermode=atomic" + + if [ -n "$COVERDIR" ] ; then + coverdir="$COVERDIR" + else + coverdir=$(mktemp -d coverage.XXXXXXXXXX) + fi + + mkdir -p $coverdir fi -mkdir -p $coverdir fail=0 -for dir in $(find . -type f -name '*_test.go' | xargs -n1 dirname | grep -v prog | sort -u); do - go get -t -tags netgo $dir - output=$(mktemp $coverdir/unit.XXXXXXXXXX) - if ! go test -cpu 4 -tags netgo -covermode=count -coverprofile=$output $dir ; then - fail=1 - fi +TESTDIRS=$(find . -type f -name '*_test.go' | xargs -n1 dirname | grep -v prog | sort -u) + +# If running on circle, use the scheduler to work out what tests to run on what shard +if [ -n "$CIRCLECI" -a -z "$NO_SCHEDULER" ]; then + TESTDIRS=$(echo $TESTDIRS | "$DIR/sched" sched units-$CIRCLE_BUILD_NUM $CIRCLE_NODE_TOTAL $CIRCLE_NODE_INDEX) + echo $TESTDIRS +fi + +for dir in $TESTDIRS; do + + GO_TEST_ARGS_RUN="$GO_TEST_ARGS" + if [ -n "$SLOW" ]; then + go get -t -tags netgo $dir + output=$(mktemp $coverdir/unit.XXXXXXXXXX) + GO_TEST_ARGS_RUN="$GO_TEST_ARGS -coverprofile=$output" + fi + + START=$(date +%s) + if ! go test $GO_TEST_ARGS_RUN $dir ; then + fail=1 + fi + RUNTIME=$(( $(date +%s) - $START )) + + # Report test runtime when running on circle, to help scheduler + if [ -n "$CIRCLECI" -a -z "$NO_SCHEDULER" ]; then + "$DIR/sched" time $dir $RUNTIME + fi done -if [ -z "$COVERDIR" ] ; then - cover $coverdir/* >profile.cov - rm -rf $coverdir - go tool cover -html=profile.cov -o=coverage.html +if [ -n "$SLOW" -a -z "$COVERDIR" ] ; then + $DIR/../testing/cover/cover $coverdir/* >profile.cov + rm -rf $coverdir + go tool cover -html=profile.cov -o=coverage.html + go tool cover -func=profile.cov | tail -n1 fi exit $fail From 80e56d67dbf0b79b987b87d42dcef15b320fae07 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Mon, 13 Jul 2015 13:23:49 +0100 Subject: [PATCH 080/180] Remove Docker dangling images after copying new ones --- test/setup.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/setup.sh b/test/setup.sh index e5e9edad..71df8c29 100755 --- a/test/setup.sh +++ b/test/setup.sh @@ -12,6 +12,8 @@ echo "Copying weave images, scripts, and certificates to hosts, and" echo " prefetch test images" for HOST in $HOSTS; do docker_on $HOST load -i ../weave.tar + DANGLING_IMAGES="$(docker_on $HOST images -q -f dangling=true)" + [ -n "$DANGLING_IMAGES" ] && docker_on $HOST rmi $DANGLING_IMAGES run_on $HOST mkdir -p bin upload_executable $HOST ../bin/docker-ns upload_executable $HOST ../weave From b67c102fe5df93b502b788a0ad8c3013607ead4d Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Thu, 2 Jul 2015 11:58:26 +0100 Subject: [PATCH 081/180] Remove simple sleep from router accept --- router/router.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/router/router.go b/router/router.go index 141dfc38..1c7dcbb2 100644 --- a/router/router.go +++ b/router/router.go @@ -16,17 +16,12 @@ import ( ) const ( - macMaxAge = 10 * time.Minute // [1] - tcpAcceptDelay = 1 * time.Millisecond // [2] + macMaxAge = 10 * time.Minute // [1] ) // [1] should be greater than typical ARP cache expiries, i.e. > 3/2 * // /proc/sys/net/ipv4_neigh/*/base_reachable_time_ms on Linux -// [2] time to wait between accepting tcp connections. This guards -// against brute-force attacks on the password when encryption is in -// use. It is also a basic DoS defence. - type LogFrameFunc func(string, []byte, *layers.Ethernet) type Config struct { @@ -212,7 +207,6 @@ func (router *Router) listenTCP(localPort int) { continue } router.acceptTCP(tcpConn) - time.Sleep(tcpAcceptDelay) } }() } From 9634526a67b0aa553b5a1275987a8ae1ba8751b2 Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Thu, 2 Jul 2015 11:58:40 +0100 Subject: [PATCH 082/180] Add token bucket implementation --- router/token_bucket.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 router/token_bucket.go diff --git a/router/token_bucket.go b/router/token_bucket.go new file mode 100644 index 00000000..254de6eb --- /dev/null +++ b/router/token_bucket.go @@ -0,0 +1,42 @@ +package router + +import ( + "time" +) + +type TokenBucket struct { + capacity int64 // Maximum capacity of bucket + tokenInterval time.Duration // Token replenishment rate + refillDuration time.Duration // Time to refill from empty + earliestUnspentToken time.Time +} + +func NewTokenBucket(capacity int64, tokenInterval time.Duration) *TokenBucket { + tb := TokenBucket{ + capacity: capacity, + tokenInterval: tokenInterval, + refillDuration: tokenInterval * time.Duration(capacity)} + + tb.earliestUnspentToken = tb.capacityToken() + + return &tb +} + +func (tb *TokenBucket) Wait() { + // If earliest unspent token is in the future, sleep until then + time.Sleep(tb.earliestUnspentToken.Sub(time.Now())) + + // Alternatively, enforce bucket capacity if necessary + capacityToken := tb.capacityToken() + if tb.earliestUnspentToken.Before(capacityToken) { + tb.earliestUnspentToken = capacityToken + } + + // 'Remove' a token from the bucket + tb.earliestUnspentToken = tb.earliestUnspentToken.Add(tb.tokenInterval) +} + +// Determine the historic token timestamp representing a full bucket +func (tb *TokenBucket) capacityToken() time.Time { + return time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval) +} From f3c4a9fc6d723c57eb1273c194d11d319b8eb9d0 Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Thu, 2 Jul 2015 12:03:08 +0100 Subject: [PATCH 083/180] Limit router accept rate with token bucket --- router/router.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/router/router.go b/router/router.go index 1c7dcbb2..b498690b 100644 --- a/router/router.go +++ b/router/router.go @@ -16,12 +16,18 @@ import ( ) const ( - macMaxAge = 10 * time.Minute // [1] + macMaxAge = 10 * time.Minute // [1] + acceptMaxTokens = 100 // [2] + acceptTokenDelay = 100 * time.Millisecond // [3] ) // [1] should be greater than typical ARP cache expiries, i.e. > 3/2 * // /proc/sys/net/ipv4_neigh/*/base_reachable_time_ms on Linux +// [2] capacity of token bucket for rate limiting accepts + +// [3] control rate at which new tokens are added to the bucket + type LogFrameFunc func(string, []byte, *layers.Ethernet) type Config struct { @@ -45,6 +51,7 @@ type Router struct { gossipChannels GossipChannels TopologyGossip Gossip UDPListener *net.UDPConn + acceptLimiter *TokenBucket } type PacketSource interface { @@ -76,6 +83,7 @@ func NewRouter(config Config, name PeerName, nickName string) *Router { router.Routes = NewRoutes(router.Ourself, router.Peers) router.ConnectionMaker = NewConnectionMaker(router.Ourself, router.Peers, router.Port, router.PeerDiscovery) router.TopologyGossip = router.NewGossip("topology", router) + router.acceptLimiter = NewTokenBucket(acceptMaxTokens, acceptTokenDelay) return router } @@ -207,6 +215,7 @@ func (router *Router) listenTCP(localPort int) { continue } router.acceptTCP(tcpConn) + router.acceptLimiter.Wait() } }() } From e2f8b6f9fdc8e770f68b8f46b43c92b1245b3246 Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Thu, 9 Jul 2015 16:45:37 +0100 Subject: [PATCH 084/180] Document /dev/random blocking issue --- site/how-it-works.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/site/how-it-works.md b/site/how-it-works.md index 4e570c7c..70b97ff1 100644 --- a/site/how-it-works.md +++ b/site/how-it-works.md @@ -278,7 +278,7 @@ password, and the result is hashed through SHA256, to form the final ephemeral session key. Thus the supplied password is never exchanged directly, and is thoroughly mixed into the shared secret. Furthermore, the rate at which TCP connections are accepted is limited by weave to -1kHz, which twarts online dictionary attacks on reasonably strong +10Hz, which twarts online dictionary attacks on reasonably strong passwords. The shared key formed by Diffie-Hellman is 256 bits long, appending @@ -293,6 +293,39 @@ not be able to form valid ephemeral session keys. The same ephemeral session key is used for both TCP and UDP traffic between two peers. + Generating fresh keys for every connection +provides forward secrecy at the cost of placing a demand on the Linux +CSPRNG (accessed by `GenerateKey` via `/dev/urandom`) proportional to +the number of inbound connection attempts. Weave has accept throttling +to mitigate against denial of service attacks that seek to deplete the +CSPRNG entropy pool, however even at the lower bound of ten requests +per second there may not be enough entropy gathered on a headless +system to keep pace. + +Under such conditions, the consequences will be limited to slowing +down processes reading from the blocking `/dev/random` device as the +kernel waits for enough new entropy to be harvested. It is important +to note that contrary to intuition this low entropy state does not +compromise the ongoing use of `/dev/urandom` - [expert +opinion](http://blog.cr.yp.to/20140205-entropy.html) +asserts that as long as the CSPRNG is seeded with enough entropy (e.g. +256 bits) before random number generation commences then the output is +entirely safe for use as key material. + +By way of comparison, this is exactly how OpenSSL works - it reads 256 +bits of entropy at startup, and uses that to seed an internal CSPRNG +which is used thenceforth to generate keys. Whilst we could have taken +the same approach and built our own CSPRNG to work around the +potential `/dev/random` blocking issue, we thought it was much more +prudent to rely on the [heavily +scrutinised](http://eprint.iacr.org/2012/251.pdf) Linux random number +generator as [advised +here](http://cr.yp.to/highspeed/coolnacl-20120725.pdf) (page 10, +'Centralizing randomness'). The aforementioned notwithstanding, if +weave's demand on `/dev/urandom` is causing you problems with blocking +`/dev/random` reads, please get in touch with us - we'd love to hear +about your use case. + #### TCP TCP connection are only used to exchange topology information between From db8016112e74208024ac64d2a9240fda51390ed1 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Mon, 13 Jul 2015 18:28:11 +0100 Subject: [PATCH 085/180] Upgrade to Ubuntu 15.04 --- test/Vagrantfile | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/Vagrantfile b/test/Vagrantfile index 1a888f40..070110d0 100644 --- a/test/Vagrantfile +++ b/test/Vagrantfile @@ -14,10 +14,10 @@ require '../vagrant-common.rb' def configure_docker(host, hostname, ip) pkgs = %w(lxc-docker ethtool) - host.vm.box = "ubuntu/ubuntu-14.10-amd64" - host.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/utopic/current/utopic-server-cloudimg-amd64-vagrant-disk1.box" + host.vm.box = "ubuntu/ubuntu-15.04-amd64" + host.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/vivid/current/vivid-server-cloudimg-amd64-vagrant-disk1.box" - host.vm.hostname = hostname + host.vm.provision :shell, :inline => "hostnamectl set-hostname "+hostname host.vm.network "private_network", ip: ip host.vm.synced_folder ".", "/vagrant", disabled: true @@ -29,8 +29,11 @@ def configure_docker(host, hostname, ip) host.vm.provision :shell, :inline => "usermod -a -G docker vagrant; " # Listen on the remote API - host.vm.provision :shell, :inline => "echo 'DOCKER_OPTS=\"-H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375\"' >> /etc/default/docker" - host.vm.provision :shell, :inline => "service docker restart" + host.vm.provision :shell, :inline => "sed -i -e's%-H fd://%-H fd:// -H tcp://0.0.0.0:2375%' /lib/systemd/system/docker.service" + host.vm.provision :shell, :inline => "systemctl daemon-reload" + + host.vm.provision :shell, :inline => "systemctl start docker" + host.vm.provision :shell, :inline => "systemctl enable docker" cleanup(host.vm) end From 4853a1da05ae7ebc7b6308dffcaa0d2cc802a3f4 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Mon, 13 Jul 2015 18:28:29 +0100 Subject: [PATCH 086/180] Tell Docker to use 'overlay' storage driver --- test/Vagrantfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Vagrantfile b/test/Vagrantfile index 070110d0..c150129c 100644 --- a/test/Vagrantfile +++ b/test/Vagrantfile @@ -28,8 +28,8 @@ def configure_docker(host, hostname, ip) install_packages host.vm, pkgs host.vm.provision :shell, :inline => "usermod -a -G docker vagrant; " - # Listen on the remote API - host.vm.provision :shell, :inline => "sed -i -e's%-H fd://%-H fd:// -H tcp://0.0.0.0:2375%' /lib/systemd/system/docker.service" + # Listen on the remote API and use overlay storage driver + host.vm.provision :shell, :inline => "sed -i -e's%-H fd://%-H fd:// -H tcp://0.0.0.0:2375 -s overlay%' /lib/systemd/system/docker.service" host.vm.provision :shell, :inline => "systemctl daemon-reload" host.vm.provision :shell, :inline => "systemctl start docker" From efb0ead9adf1d44912b495fd664803332e912d1f Mon Sep 17 00:00:00 2001 From: Alvaro Saurin Date: Tue, 30 Jun 2015 15:16:25 +0200 Subject: [PATCH 087/180] Resolve unqualified names in the local WeaveDNS domain Unit tests --- nameserver/dns.go | 4 +++ nameserver/names.go | 28 ++++++++++++++++ nameserver/names_test.go | 34 ++++++++++++++++++++ nameserver/server.go | 59 +++++++++++++++++++--------------- nameserver/server_test.go | 16 ++++++--- nameserver/zone_lookup.go | 7 ++-- nameserver/zone_lookup_test.go | 30 +++++++++++++++++ 7 files changed, 143 insertions(+), 35 deletions(-) create mode 100644 nameserver/names.go create mode 100644 nameserver/names_test.go diff --git a/nameserver/dns.go b/nameserver/dns.go index c232d45b..e6b4b6a4 100644 --- a/nameserver/dns.go +++ b/nameserver/dns.go @@ -80,6 +80,10 @@ func makeDNSFailResponse(r *dns.Msg) *dns.Msg { return m } +func failHandleFunc(w dns.ResponseWriter, r *dns.Msg) { + w.WriteMsg(makeDNSFailResponse(r)) +} + // get the maximum UDP-reply length func getMaxReplyLen(r *dns.Msg, proto dnsProtocol) int { maxLen := minUDPSize diff --git a/nameserver/names.go b/nameserver/names.go new file mode 100644 index 00000000..edf227ef --- /dev/null +++ b/nameserver/names.go @@ -0,0 +1,28 @@ +package nameserver + +import ( + "strings" + + "github.com/miekg/dns" +) + +// Get the number of components of a name +// For example, "redis" is 1, "redis.weave.local" is 3... +func nameNumComponents(name string) int { + if len(name) == 0 || name == "." { + return 0 + } + return strings.Count(dns.Fqdn(name), ".") +} + +// normalize a name by +// a) adding the local domain when it is a single component name +// b) converting the result to FQDN +func normalizeName(n string, domain string) string { + // we should never add anything to a FQDN like "redis.", but that's the only thing that + // some broken resolvers will do: to convert the name to FQDN... + if nameNumComponents(n) == 1 { + n = dns.Fqdn(n) + domain + } + return dns.Fqdn(n) +} diff --git a/nameserver/names_test.go b/nameserver/names_test.go new file mode 100644 index 00000000..9af2539c --- /dev/null +++ b/nameserver/names_test.go @@ -0,0 +1,34 @@ +package nameserver + +import ( + "testing" + + "github.com/stretchr/testify/require" + . "github.com/weaveworks/weave/common" +) + +func TestNamesNumComponents(t *testing.T) { + EnableDebugLogging(testing.Verbose()) + + assertNumComps := func(n string, e int) { require.Equal(t, e, nameNumComponents(n), "name num components failed") } + + assertNumComps("", 0) + assertNumComps(".", 0) + assertNumComps("something", 1) + assertNumComps("something.", 1) + assertNumComps("something.local", 2) + assertNumComps("something.local.", 2) +} + +func TestNamesNormalization(t *testing.T) { + EnableDebugLogging(testing.Verbose()) + + assertNormalization := func(s, d, e string) { require.Equal(t, e, normalizeName(s, d), "name normalization failed") } + + assertNormalization("", "domain.local.", ".") + assertNormalization(".", "domain.local.", ".") + assertNormalization("something", "domain.local.", "something.domain.local.") + assertNormalization("something.", "domain.local.", "something.domain.local.") + assertNormalization("something.domain.local", "domain.local.", "something.domain.local.") + assertNormalization("something.domain.local.", "domain.local.", "something.domain.local.") +} diff --git a/nameserver/server.go b/nameserver/server.go index 6f36aaf4..4ff42e4a 100644 --- a/nameserver/server.go +++ b/nameserver/server.go @@ -279,9 +279,6 @@ func (s *DNSServer) Stop() error { // We must create two DNS request multiplexers, depending on the protocol used by // clients (as we use the same protocol for asking upstream servers) func (s *DNSServer) createMux(proto dnsProtocol) *dns.ServeMux { - failFallback := func(w dns.ResponseWriter, r *dns.Msg) { - w.WriteMsg(makeDNSFailResponse(r)) - } notUsHandler := s.notUsHandler(proto) notUsFallback := func(w dns.ResponseWriter, r *dns.Msg) { Log.Infof("[dns msgid %d] -> sending to fallback server", r.MsgHdr.Id) @@ -291,7 +288,7 @@ func (s *DNSServer) createMux(proto dnsProtocol) *dns.ServeMux { // create the multiplexer m := dns.NewServeMux() m.HandleFunc(s.Zone.Domain(), s.localHandler(proto, "Query", dns.TypeA, - s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failFallback)) + s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failHandleFunc)) m.HandleFunc(RDNSDomain, s.localHandler(proto, "Reverse query", dns.TypePTR, s.Zone.DomainLookupInaddr, makePTRReply, s.Zone.ObserveInaddr, notUsFallback)) m.HandleFunc(".", s.notUsHandler(proto)) @@ -373,32 +370,42 @@ func (s *DNSServer) localHandler(proto dnsProtocol, kind string, qtype uint16, func (s *DNSServer) notUsHandler(proto dnsProtocol) dns.HandlerFunc { dnsClient := proto.GetNewClient(DefaultUDPBuflen, s.timeout) + localNameResolver := s.localHandler(proto, "Query", dns.TypeA, + s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failHandleFunc) + return func(w dns.ResponseWriter, r *dns.Msg) { q := r.Question[0] - - // announce our max payload size as the max payload our client supports - maxLen := getMaxReplyLen(r, proto) - rcopy := r - rcopy.SetEdns0(uint16(maxLen), false) - - Log.Debugf("[dns msgid %d] Fallback query: %+v [%s, max:%d bytes]", rcopy.MsgHdr.Id, q, proto, maxLen) - for _, server := range s.Upstream.Servers { - reply, _, err := dnsClient.Exchange(rcopy, fmt.Sprintf("%s:%s", server, s.Upstream.Port)) - if err != nil { - Log.Debugf("[dns msgid %d] Network error trying %s (%s)", - r.MsgHdr.Id, server, err) - continue - } - if reply != nil && reply.Rcode != dns.RcodeSuccess { - Log.Debugf("[dns msgid %d] Failure reported by %s for query %s", - r.MsgHdr.Id, server, q.Name) - continue - } - Log.Debugf("[dns msgid %d] Given answer by %s for query %s", - r.MsgHdr.Id, server, q.Name) - w.WriteMsg(reply) + nc := nameNumComponents(q.Name) + if nc == 1 { + Log.Debugf("[dns msgid %d] Unqualified query: '%+v' ", r.MsgHdr.Id, q) + localNameResolver(w, r) // short names (eg, "redis.") will follow a local resolution process return + } else if nc > 1 { + // announce our max payload size as the max payload our client supports + maxLen := getMaxReplyLen(r, proto) + rcopy := r + rcopy.SetEdns0(uint16(maxLen), false) + + Log.Debugf("[dns msgid %d] Fallback query: %+v [%s, max:%d bytes]", rcopy.MsgHdr.Id, q, proto, maxLen) + for _, server := range s.Upstream.Servers { + reply, _, err := dnsClient.Exchange(rcopy, fmt.Sprintf("%s:%s", server, s.Upstream.Port)) + if err != nil { + Log.Debugf("[dns msgid %d] Network error trying %s (%s)", + r.MsgHdr.Id, server, err) + continue + } + if reply != nil && reply.Rcode != dns.RcodeSuccess { + Log.Debugf("[dns msgid %d] Failure reported by %s for query %s", + r.MsgHdr.Id, server, q.Name) + continue + } + Log.Debugf("[dns msgid %d] Given answer by %s for query %s", + r.MsgHdr.Id, server, q.Name) + w.WriteMsg(reply) + return + } } + Log.Warningf("[dns msgid %d] Failed lookup for external name %s", r.MsgHdr.Id, q.Name) w.WriteMsg(makeDNSFailResponse(r)) } diff --git a/nameserver/server_test.go b/nameserver/server_test.go index 9c4a1976..9ec63986 100644 --- a/nameserver/server_test.go +++ b/nameserver/server_test.go @@ -32,11 +32,12 @@ func TestUDPDNSServer(t *testing.T) { setupForTest(t) const ( - successTestName = "test1.weave.local." - failTestName = "fail.weave.local." - nonLocalName = "weave.works." - testAddr1 = "10.2.2.1" - containerID = "somecontainer" + successTestName = "test1.weave.local." + successTestNameShort = "test1." + failTestName = "fail.weave.local." + nonLocalName = "weave.works." + testAddr1 = "10.2.2.1" + containerID = "somecontainer" ) testCIDR1 := testAddr1 + "/24" @@ -105,6 +106,11 @@ func TestUDPDNSServer(t *testing.T) { require.IsType(t, (*dns.A)(nil), r.Answer[0], "DNS record") require.Equal(t, testAddr1, r.Answer[0].(*dns.A).A.String(), "IP address") + // Assert that we can get the same result when asking for the same name but with no domain + _, r = assertExchange(t, successTestNameShort, dns.TypeA, testPort, 1, 1, 0) + require.IsType(t, (*dns.A)(nil), r.Answer[0], "DNS record") + require.Equal(t, testAddr1, r.Answer[0].(*dns.A).A.String(), "IP address") + assertExchange(t, failTestName, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) _, r = assertExchange(t, testRDNSsuccess, dns.TypePTR, testPort, 1, 1, 0) diff --git a/nameserver/zone_lookup.go b/nameserver/zone_lookup.go index 6e515b62..32486131 100644 --- a/nameserver/zone_lookup.go +++ b/nameserver/zone_lookup.go @@ -4,7 +4,6 @@ import ( "net" "time" - "github.com/miekg/dns" . "github.com/weaveworks/weave/common" ) @@ -62,7 +61,7 @@ func (zone *ZoneDb) LookupName(name string) (res []ZoneRecord, err error) { defer zone.mx.RUnlock() // note: LookupName() is usually called from the mDNS server, so we do not touch the name - name = dns.Fqdn(name) + name = normalizeName(name, zone.domain) Log.Debugf("[zonedb] Looking for name '%s' in local database", name) return zone.lookup(name, func(ns *nameSet) []*recordEntry { return ns.getEntriesForName(name) }) } @@ -117,7 +116,7 @@ func (zone *ZoneDb) domainLookup(target string, lfun ZoneLookupFunc) (res []Zone // Perform a lookup for a name in the zone // The name can be resolved locally with the local database or with some other resolution method (eg, a mDNS query) func (zone *ZoneDb) DomainLookupName(name string) (res []ZoneRecord, err error) { - name = dns.Fqdn(name) + name = normalizeName(name, zone.domain) Log.Debugf("[zonedb] Looking for name '%s' in local(&remote) database", name) zone.mx.Lock() @@ -267,7 +266,7 @@ func (zone *ZoneDb) updater(name string) (nextTime time.Time) { } // perform the refresh for this name - fullName := dns.Fqdn(name) + fullName := normalizeName(name, zone.domain) startTime := zone.clock.Now() Log.Debugf("[zonedb] Refreshing name '%s' with mDNS...", fullName) res, _ := zone.mdnsCli.InsistentLookupName(fullName) diff --git a/nameserver/zone_lookup_test.go b/nameserver/zone_lookup_test.go index 31789133..784d2612 100644 --- a/nameserver/zone_lookup_test.go +++ b/nameserver/zone_lookup_test.go @@ -9,6 +9,36 @@ import ( . "github.com/weaveworks/weave/common" ) +func TestZoneLookups(t *testing.T) { + var ( + id = "foobar" + name = "foo.weave.local" + addr1 = "10.2.2.3/24" + addr2 = "10.2.7.8/24" + ) + + EnableDebugLogging(testing.Verbose()) + + zone, err := NewZoneDb(ZoneConfig{}) + require.NoError(t, err) + err = zone.Start() + require.NoError(t, err) + defer zone.Stop() + + for _, addr := range []string{addr1, addr2} { + ip, _, _ := net.ParseCIDR(addr) + err := zone.AddRecord(id, name, ip) + require.NoError(t, err) + } + + // Check we can query for the name in many different ways... + for _, qName := range []string{"foo.weave.local", "foo.weave.local.", "foo", "foo."} { + res, err := zone.LookupName(qName) + require.NoError(t, err) + require.Equal(t, len(res), 2, "Unexpected number of responses") + } +} + // Check that the refreshing mechanism works as expected func TestZoneRefresh(t *testing.T) { const ( From 499d65e7158987a40a5895f3a6dd6afd39e6c03f Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Tue, 14 Jul 2015 10:50:34 +0000 Subject: [PATCH 088/180] Build cover tool by default, and do go get -t for tests, irregardless of $SLOW --- Makefile | 2 +- test/units.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 1a203884..0784ee8e 100644 --- a/Makefile +++ b/Makefile @@ -46,7 +46,7 @@ NETGO_CHECK=@strings $@ | grep cgo_stub\\\.go >/dev/null || { \ false; \ } -all: $(WEAVE_EXPORT) +all: $(WEAVE_EXPORT) $(COVER_EXE) travis: $(EXES) diff --git a/test/units.sh b/test/units.sh index d388b23e..9fa72d85 100755 --- a/test/units.sh +++ b/test/units.sh @@ -28,10 +28,10 @@ if [ -n "$CIRCLECI" -a -z "$NO_SCHEDULER" ]; then fi for dir in $TESTDIRS; do + go get -t -tags netgo $dir GO_TEST_ARGS_RUN="$GO_TEST_ARGS" if [ -n "$SLOW" ]; then - go get -t -tags netgo $dir output=$(mktemp $coverdir/unit.XXXXXXXXXX) GO_TEST_ARGS_RUN="$GO_TEST_ARGS -coverprofile=$output" fi From 6d17fe5df5e663d1cf693a17405eb92da60002f8 Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Tue, 14 Jul 2015 12:12:35 +0100 Subject: [PATCH 089/180] Need to restart docker after systemd reconfigure --- test/Vagrantfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Vagrantfile b/test/Vagrantfile index c150129c..d8b72c45 100644 --- a/test/Vagrantfile +++ b/test/Vagrantfile @@ -32,7 +32,7 @@ def configure_docker(host, hostname, ip) host.vm.provision :shell, :inline => "sed -i -e's%-H fd://%-H fd:// -H tcp://0.0.0.0:2375 -s overlay%' /lib/systemd/system/docker.service" host.vm.provision :shell, :inline => "systemctl daemon-reload" - host.vm.provision :shell, :inline => "systemctl start docker" + host.vm.provision :shell, :inline => "systemctl restart docker" host.vm.provision :shell, :inline => "systemctl enable docker" cleanup(host.vm) end From bbacaa42b8bf40b823fdf9ab4fce479ae51498a5 Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Tue, 14 Jul 2015 13:23:28 +0100 Subject: [PATCH 090/180] cosmetic --- router/protocol.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/router/protocol.go b/router/protocol.go index 878491a2..53342aa6 100644 --- a/router/protocol.go +++ b/router/protocol.go @@ -265,8 +265,7 @@ func (res *ProtocolIntroResults) doIntroV2(params ProtocolIntroParams, pubKey, p return ErrExpectedCrypto } - res.setupNoCrypto(gob.NewEncoder(params.Conn), - gob.NewDecoder(params.Conn)) + res.setupNoCrypto(gob.NewEncoder(params.Conn), gob.NewDecoder(params.Conn)) case 1: if pubKey == nil { @@ -278,8 +277,7 @@ func (res *ProtocolIntroResults) doIntroV2(params ProtocolIntroParams, pubKey, p return err } - res.setupCrypto(params, gob.NewEncoder(params.Conn), - gob.NewDecoder(params.Conn), rbuf, privKey) + res.setupCrypto(params, gob.NewEncoder(params.Conn), gob.NewDecoder(params.Conn), rbuf, privKey) default: return fmt.Errorf("Bad encryption flag %d", rbuf[0]) From 4c519fc76113acd64cb5455f3dd4e3b588ba7a0e Mon Sep 17 00:00:00 2001 From: Alvaro Saurin Date: Thu, 2 Jul 2015 13:01:59 +0200 Subject: [PATCH 091/180] Smoke tests --- test/230_dns_unqualified_test.sh | 14 +++++++------- test/config.sh | 5 +++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/test/230_dns_unqualified_test.sh b/test/230_dns_unqualified_test.sh index 38e30043..1bbffe83 100755 --- a/test/230_dns_unqualified_test.sh +++ b/test/230_dns_unqualified_test.sh @@ -11,19 +11,19 @@ NAME=seeone.$DOMAIN start_suite "Resolve unqualified names" -launch_dns_on $HOST1 10.2.254.1/24 +launch_dns_on $HOST1 10.2.254.1/24 --debug start_container $HOST1 $C1/24 --name=c1 -h $NAME start_container_with_dns $HOST1 $C2/24 --name=c2 -h seetwo.$DOMAIN start_container_with_dns $HOST1 $C3/24 --name=c3 --dns-search=$DOMAIN container=$(start_container_with_dns $HOST1 $C4/24) -check() { - assert "exec_on $HOST1 $1 getent hosts seeone | tr -s ' '" "$C1 $NAME" -} +assert_dns_a_record $HOST1 c2 seeone $C1 $NAME +assert_dns_a_record $HOST1 c3 seeone $C1 $NAME +assert_dns_a_record $HOST1 "$container" seeone $C1 $NAME -check c2 -check c3 -check "$container" +# check that unqualified names are automatically qualified for broken resolvers +weave_on $HOST1 dns-add $C1 c1 -h mysql.weave.local +assert_dns_a_record $HOST1 c1 mysql $C1 end_suite diff --git a/test/config.sh b/test/config.sh index 3d136999..05fd419d 100644 --- a/test/config.sh +++ b/test/config.sh @@ -188,9 +188,10 @@ assert_no_dns_record() { assert_raises "exec_on $host $container getent hosts $name" 2 } -# assert_dns_a_record +# assert_dns_a_record [] assert_dns_a_record() { - assert "exec_on $1 $2 getent hosts $3 | tr -s ' '" "$4 $3" + exp_name=${5:-$3} + assert "exec_on $1 $2 getent hosts $3 | tr -s ' ' | cut -d ' ' -f 1,2" "$4 $exp_name" } # assert_dns_ptr_record From e26e7e29f237e7f9dc8e6f5f1b33dd4cc4763223 Mon Sep 17 00:00:00 2001 From: Adam Harrison Date: Tue, 14 Jul 2015 13:49:51 +0100 Subject: [PATCH 092/180] Improvements to password handling recommendations --- site/features.md | 9 +++++++-- site/systemd.md | 8 +++++--- test/110_encryption_test.sh | 4 ++-- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/site/features.md b/site/features.md index e25d63e1..9ef088a4 100644 --- a/site/features.md +++ b/site/features.md @@ -245,16 +245,21 @@ In order to connect containers across untrusted networks, weave peers can be told to encrypt traffic by supplying a `-password` option or `WEAVE_PASSWORD` environment variable when launching weave, e.g. - host1$ weave launch -password wEaVe + host1$ weave launch -password wfvAwt7sj or - host1$ export WEAVE_PASSWORD=wEaVe + host1$ export WEAVE_PASSWORD=wfvAwt7sj host1$ weave launch _NOTE: The command line option takes precedence over the environment variable._ +> To avoid leaking your password via the kernel process table or your +> shell history, we recommend you store it in a file and capture it +> into a shell variable prior to launching weave: `export +> WEAVE_PASSWORD=$(cat /path/to/password-file)` + The password needs to be reasonably strong to guard against online dictionary attacks. We recommend at least 50 bits of entropy. An easy way to generate a random password which satsifies this requirement is diff --git a/site/systemd.md b/site/systemd.md index 7f4bda07..9f366fc2 100644 --- a/site/systemd.md +++ b/site/systemd.md @@ -38,9 +38,11 @@ the following format: You can also use the [connect][] command to add participating hosts dynamically. -Additionally, if you want to enable [encryption][] you can specify a password with -`WEAVE_PASSWORD="MakeSureThisIsSecure"` in the `/etc/sysconfig/weave` environment -file, and it will get picked up by weave on launch. +Additionally, if you want to enable [encryption][] you can specify a +password with e.g. `WEAVE_PASSWORD="wfvAwt7sj"` in the +`/etc/sysconfig/weave` environment file, and it will get picked up by +weave on launch. Recommendations for choosing a suitably strong +password can be found [here](features.html#security). You now should be able to launch weave with diff --git a/test/110_encryption_test.sh b/test/110_encryption_test.sh index 967e0003..27761823 100755 --- a/test/110_encryption_test.sh +++ b/test/110_encryption_test.sh @@ -7,8 +7,8 @@ C2=10.2.1.7 start_suite "Ping over encrypted cross-host weave network" -weave_on $HOST1 launch -password notverysecure -weave_on $HOST2 launch -password notverysecure $HOST1 +weave_on $HOST1 launch -password wfvAwt7sj +weave_on $HOST2 launch -password wfvAwt7sj $HOST1 start_container $HOST1 $C1/24 --name=c1 start_container $HOST2 $C2/24 --name=c2 From 18032015b9b5d3674b9fe7e71dbc9e9f73ee101b Mon Sep 17 00:00:00 2001 From: Matthias Radestock Date: Tue, 14 Jul 2015 16:06:05 +0100 Subject: [PATCH 093/180] Revert "Resolve unqualified names in the local WeaveDNS domain" --- nameserver/dns.go | 4 --- nameserver/names.go | 28 ---------------- nameserver/names_test.go | 34 ------------------- nameserver/server.go | 57 ++++++++++++++------------------ nameserver/server_test.go | 16 +++------ nameserver/zone_lookup.go | 7 ++-- nameserver/zone_lookup_test.go | 30 ----------------- test/230_dns_unqualified_test.sh | 14 ++++---- test/config.sh | 5 ++- 9 files changed, 43 insertions(+), 152 deletions(-) delete mode 100644 nameserver/names.go delete mode 100644 nameserver/names_test.go diff --git a/nameserver/dns.go b/nameserver/dns.go index e6b4b6a4..c232d45b 100644 --- a/nameserver/dns.go +++ b/nameserver/dns.go @@ -80,10 +80,6 @@ func makeDNSFailResponse(r *dns.Msg) *dns.Msg { return m } -func failHandleFunc(w dns.ResponseWriter, r *dns.Msg) { - w.WriteMsg(makeDNSFailResponse(r)) -} - // get the maximum UDP-reply length func getMaxReplyLen(r *dns.Msg, proto dnsProtocol) int { maxLen := minUDPSize diff --git a/nameserver/names.go b/nameserver/names.go deleted file mode 100644 index edf227ef..00000000 --- a/nameserver/names.go +++ /dev/null @@ -1,28 +0,0 @@ -package nameserver - -import ( - "strings" - - "github.com/miekg/dns" -) - -// Get the number of components of a name -// For example, "redis" is 1, "redis.weave.local" is 3... -func nameNumComponents(name string) int { - if len(name) == 0 || name == "." { - return 0 - } - return strings.Count(dns.Fqdn(name), ".") -} - -// normalize a name by -// a) adding the local domain when it is a single component name -// b) converting the result to FQDN -func normalizeName(n string, domain string) string { - // we should never add anything to a FQDN like "redis.", but that's the only thing that - // some broken resolvers will do: to convert the name to FQDN... - if nameNumComponents(n) == 1 { - n = dns.Fqdn(n) + domain - } - return dns.Fqdn(n) -} diff --git a/nameserver/names_test.go b/nameserver/names_test.go deleted file mode 100644 index 9af2539c..00000000 --- a/nameserver/names_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package nameserver - -import ( - "testing" - - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -func TestNamesNumComponents(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - - assertNumComps := func(n string, e int) { require.Equal(t, e, nameNumComponents(n), "name num components failed") } - - assertNumComps("", 0) - assertNumComps(".", 0) - assertNumComps("something", 1) - assertNumComps("something.", 1) - assertNumComps("something.local", 2) - assertNumComps("something.local.", 2) -} - -func TestNamesNormalization(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - - assertNormalization := func(s, d, e string) { require.Equal(t, e, normalizeName(s, d), "name normalization failed") } - - assertNormalization("", "domain.local.", ".") - assertNormalization(".", "domain.local.", ".") - assertNormalization("something", "domain.local.", "something.domain.local.") - assertNormalization("something.", "domain.local.", "something.domain.local.") - assertNormalization("something.domain.local", "domain.local.", "something.domain.local.") - assertNormalization("something.domain.local.", "domain.local.", "something.domain.local.") -} diff --git a/nameserver/server.go b/nameserver/server.go index 4ff42e4a..6f36aaf4 100644 --- a/nameserver/server.go +++ b/nameserver/server.go @@ -279,6 +279,9 @@ func (s *DNSServer) Stop() error { // We must create two DNS request multiplexers, depending on the protocol used by // clients (as we use the same protocol for asking upstream servers) func (s *DNSServer) createMux(proto dnsProtocol) *dns.ServeMux { + failFallback := func(w dns.ResponseWriter, r *dns.Msg) { + w.WriteMsg(makeDNSFailResponse(r)) + } notUsHandler := s.notUsHandler(proto) notUsFallback := func(w dns.ResponseWriter, r *dns.Msg) { Log.Infof("[dns msgid %d] -> sending to fallback server", r.MsgHdr.Id) @@ -288,7 +291,7 @@ func (s *DNSServer) createMux(proto dnsProtocol) *dns.ServeMux { // create the multiplexer m := dns.NewServeMux() m.HandleFunc(s.Zone.Domain(), s.localHandler(proto, "Query", dns.TypeA, - s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failHandleFunc)) + s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failFallback)) m.HandleFunc(RDNSDomain, s.localHandler(proto, "Reverse query", dns.TypePTR, s.Zone.DomainLookupInaddr, makePTRReply, s.Zone.ObserveInaddr, notUsFallback)) m.HandleFunc(".", s.notUsHandler(proto)) @@ -370,42 +373,32 @@ func (s *DNSServer) localHandler(proto dnsProtocol, kind string, qtype uint16, func (s *DNSServer) notUsHandler(proto dnsProtocol) dns.HandlerFunc { dnsClient := proto.GetNewClient(DefaultUDPBuflen, s.timeout) - localNameResolver := s.localHandler(proto, "Query", dns.TypeA, - s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failHandleFunc) - return func(w dns.ResponseWriter, r *dns.Msg) { q := r.Question[0] - nc := nameNumComponents(q.Name) - if nc == 1 { - Log.Debugf("[dns msgid %d] Unqualified query: '%+v' ", r.MsgHdr.Id, q) - localNameResolver(w, r) // short names (eg, "redis.") will follow a local resolution process - return - } else if nc > 1 { - // announce our max payload size as the max payload our client supports - maxLen := getMaxReplyLen(r, proto) - rcopy := r - rcopy.SetEdns0(uint16(maxLen), false) - Log.Debugf("[dns msgid %d] Fallback query: %+v [%s, max:%d bytes]", rcopy.MsgHdr.Id, q, proto, maxLen) - for _, server := range s.Upstream.Servers { - reply, _, err := dnsClient.Exchange(rcopy, fmt.Sprintf("%s:%s", server, s.Upstream.Port)) - if err != nil { - Log.Debugf("[dns msgid %d] Network error trying %s (%s)", - r.MsgHdr.Id, server, err) - continue - } - if reply != nil && reply.Rcode != dns.RcodeSuccess { - Log.Debugf("[dns msgid %d] Failure reported by %s for query %s", - r.MsgHdr.Id, server, q.Name) - continue - } - Log.Debugf("[dns msgid %d] Given answer by %s for query %s", - r.MsgHdr.Id, server, q.Name) - w.WriteMsg(reply) - return + // announce our max payload size as the max payload our client supports + maxLen := getMaxReplyLen(r, proto) + rcopy := r + rcopy.SetEdns0(uint16(maxLen), false) + + Log.Debugf("[dns msgid %d] Fallback query: %+v [%s, max:%d bytes]", rcopy.MsgHdr.Id, q, proto, maxLen) + for _, server := range s.Upstream.Servers { + reply, _, err := dnsClient.Exchange(rcopy, fmt.Sprintf("%s:%s", server, s.Upstream.Port)) + if err != nil { + Log.Debugf("[dns msgid %d] Network error trying %s (%s)", + r.MsgHdr.Id, server, err) + continue } + if reply != nil && reply.Rcode != dns.RcodeSuccess { + Log.Debugf("[dns msgid %d] Failure reported by %s for query %s", + r.MsgHdr.Id, server, q.Name) + continue + } + Log.Debugf("[dns msgid %d] Given answer by %s for query %s", + r.MsgHdr.Id, server, q.Name) + w.WriteMsg(reply) + return } - Log.Warningf("[dns msgid %d] Failed lookup for external name %s", r.MsgHdr.Id, q.Name) w.WriteMsg(makeDNSFailResponse(r)) } diff --git a/nameserver/server_test.go b/nameserver/server_test.go index 9ec63986..9c4a1976 100644 --- a/nameserver/server_test.go +++ b/nameserver/server_test.go @@ -32,12 +32,11 @@ func TestUDPDNSServer(t *testing.T) { setupForTest(t) const ( - successTestName = "test1.weave.local." - successTestNameShort = "test1." - failTestName = "fail.weave.local." - nonLocalName = "weave.works." - testAddr1 = "10.2.2.1" - containerID = "somecontainer" + successTestName = "test1.weave.local." + failTestName = "fail.weave.local." + nonLocalName = "weave.works." + testAddr1 = "10.2.2.1" + containerID = "somecontainer" ) testCIDR1 := testAddr1 + "/24" @@ -106,11 +105,6 @@ func TestUDPDNSServer(t *testing.T) { require.IsType(t, (*dns.A)(nil), r.Answer[0], "DNS record") require.Equal(t, testAddr1, r.Answer[0].(*dns.A).A.String(), "IP address") - // Assert that we can get the same result when asking for the same name but with no domain - _, r = assertExchange(t, successTestNameShort, dns.TypeA, testPort, 1, 1, 0) - require.IsType(t, (*dns.A)(nil), r.Answer[0], "DNS record") - require.Equal(t, testAddr1, r.Answer[0].(*dns.A).A.String(), "IP address") - assertExchange(t, failTestName, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) _, r = assertExchange(t, testRDNSsuccess, dns.TypePTR, testPort, 1, 1, 0) diff --git a/nameserver/zone_lookup.go b/nameserver/zone_lookup.go index 32486131..6e515b62 100644 --- a/nameserver/zone_lookup.go +++ b/nameserver/zone_lookup.go @@ -4,6 +4,7 @@ import ( "net" "time" + "github.com/miekg/dns" . "github.com/weaveworks/weave/common" ) @@ -61,7 +62,7 @@ func (zone *ZoneDb) LookupName(name string) (res []ZoneRecord, err error) { defer zone.mx.RUnlock() // note: LookupName() is usually called from the mDNS server, so we do not touch the name - name = normalizeName(name, zone.domain) + name = dns.Fqdn(name) Log.Debugf("[zonedb] Looking for name '%s' in local database", name) return zone.lookup(name, func(ns *nameSet) []*recordEntry { return ns.getEntriesForName(name) }) } @@ -116,7 +117,7 @@ func (zone *ZoneDb) domainLookup(target string, lfun ZoneLookupFunc) (res []Zone // Perform a lookup for a name in the zone // The name can be resolved locally with the local database or with some other resolution method (eg, a mDNS query) func (zone *ZoneDb) DomainLookupName(name string) (res []ZoneRecord, err error) { - name = normalizeName(name, zone.domain) + name = dns.Fqdn(name) Log.Debugf("[zonedb] Looking for name '%s' in local(&remote) database", name) zone.mx.Lock() @@ -266,7 +267,7 @@ func (zone *ZoneDb) updater(name string) (nextTime time.Time) { } // perform the refresh for this name - fullName := normalizeName(name, zone.domain) + fullName := dns.Fqdn(name) startTime := zone.clock.Now() Log.Debugf("[zonedb] Refreshing name '%s' with mDNS...", fullName) res, _ := zone.mdnsCli.InsistentLookupName(fullName) diff --git a/nameserver/zone_lookup_test.go b/nameserver/zone_lookup_test.go index 784d2612..31789133 100644 --- a/nameserver/zone_lookup_test.go +++ b/nameserver/zone_lookup_test.go @@ -9,36 +9,6 @@ import ( . "github.com/weaveworks/weave/common" ) -func TestZoneLookups(t *testing.T) { - var ( - id = "foobar" - name = "foo.weave.local" - addr1 = "10.2.2.3/24" - addr2 = "10.2.7.8/24" - ) - - EnableDebugLogging(testing.Verbose()) - - zone, err := NewZoneDb(ZoneConfig{}) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - for _, addr := range []string{addr1, addr2} { - ip, _, _ := net.ParseCIDR(addr) - err := zone.AddRecord(id, name, ip) - require.NoError(t, err) - } - - // Check we can query for the name in many different ways... - for _, qName := range []string{"foo.weave.local", "foo.weave.local.", "foo", "foo."} { - res, err := zone.LookupName(qName) - require.NoError(t, err) - require.Equal(t, len(res), 2, "Unexpected number of responses") - } -} - // Check that the refreshing mechanism works as expected func TestZoneRefresh(t *testing.T) { const ( diff --git a/test/230_dns_unqualified_test.sh b/test/230_dns_unqualified_test.sh index 1bbffe83..38e30043 100755 --- a/test/230_dns_unqualified_test.sh +++ b/test/230_dns_unqualified_test.sh @@ -11,19 +11,19 @@ NAME=seeone.$DOMAIN start_suite "Resolve unqualified names" -launch_dns_on $HOST1 10.2.254.1/24 --debug +launch_dns_on $HOST1 10.2.254.1/24 start_container $HOST1 $C1/24 --name=c1 -h $NAME start_container_with_dns $HOST1 $C2/24 --name=c2 -h seetwo.$DOMAIN start_container_with_dns $HOST1 $C3/24 --name=c3 --dns-search=$DOMAIN container=$(start_container_with_dns $HOST1 $C4/24) -assert_dns_a_record $HOST1 c2 seeone $C1 $NAME -assert_dns_a_record $HOST1 c3 seeone $C1 $NAME -assert_dns_a_record $HOST1 "$container" seeone $C1 $NAME +check() { + assert "exec_on $HOST1 $1 getent hosts seeone | tr -s ' '" "$C1 $NAME" +} -# check that unqualified names are automatically qualified for broken resolvers -weave_on $HOST1 dns-add $C1 c1 -h mysql.weave.local -assert_dns_a_record $HOST1 c1 mysql $C1 +check c2 +check c3 +check "$container" end_suite diff --git a/test/config.sh b/test/config.sh index 05fd419d..3d136999 100644 --- a/test/config.sh +++ b/test/config.sh @@ -188,10 +188,9 @@ assert_no_dns_record() { assert_raises "exec_on $host $container getent hosts $name" 2 } -# assert_dns_a_record [] +# assert_dns_a_record assert_dns_a_record() { - exp_name=${5:-$3} - assert "exec_on $1 $2 getent hosts $3 | tr -s ' ' | cut -d ' ' -f 1,2" "$4 $exp_name" + assert "exec_on $1 $2 getent hosts $3 | tr -s ' '" "$4 $3" } # assert_dns_ptr_record From 4f82dc97fdf6db99816b99a6fed19698a123f464 Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Mon, 13 Jul 2015 16:24:20 +0000 Subject: [PATCH 094/180] [proxy] More flexible container name -> hostname derivation Provides to new two new flags: `--hostname-match ` and `--hostname-replacement `. When launching a container, its name matched against regular expression ``. Then, based on that match, `` will be used to generate a hostname, which will ultimately be handed over to weaveDNS for registration. The substitution is implemented with https://golang.org/pkg/regexp/#Regexp.ReplaceAllString . Thus, references to regexp substitution groups should be prepended with a dollar sign. For instance, if we provide `--hostname-match '^aws-[0-9]+-(.*)$'` and `--hostname-replacement 'my-app-$1'`, running a container named `aws-12798186823-foo` through WeaveProxy will lead to WeaveDNS registering `my-app-foo`. Closes #1018 --- prog/weaveproxy/main.go | 2 ++ proxy/create_container_interceptor.go | 4 ++- proxy/proxy.go | 39 +++++++++++++++++---------- site/proxy.md | 29 ++++++++++++++++++++ test/680_proxy_hostname_derivation.sh | 32 ++++++++++++++++++++++ weave | 1 + 6 files changed, 92 insertions(+), 15 deletions(-) create mode 100755 test/680_proxy_hostname_derivation.sh diff --git a/prog/weaveproxy/main.go b/prog/weaveproxy/main.go index 815b1ef5..36d1db9d 100644 --- a/prog/weaveproxy/main.go +++ b/prog/weaveproxy/main.go @@ -51,6 +51,8 @@ func main() { mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") ListVar(&c.ListenAddrs, []string{"H"}, defaultListenAddrs, "addresses on which to listen") + mflag.StringVar(&c.HostnameMatch, []string{"-hostname-match"}, "(.*)", "Regexp pattern to apply on container names (e.g. '^aws-[0-9]+-(.*)$')") + mflag.StringVar(&c.HostnameReplacement, []string{"-hostname-replacement"}, "$1", "Expression to generate hostnames based on matches from --hostname-match (e.g. 'my-app-$1')") mflag.BoolVar(&c.NoDefaultIPAM, []string{"#-no-default-ipam", "-no-default-ipalloc"}, false, "do not automatically allocate addresses for containers without a WEAVE_CIDR") mflag.BoolVar(&c.NoRewriteHosts, []string{"no-rewrite-hosts"}, false, "do not automatically rewrite /etc/hosts. Use if you need the docker IP to remain in /etc/hosts") mflag.StringVar(&c.TLSConfig.CACert, []string{"#tlscacert", "-tlscacert"}, "", "Trust certs signed only by this CA") diff --git a/proxy/create_container_interceptor.go b/proxy/create_container_interceptor.go index 8e3cca04..75a67b89 100644 --- a/proxy/create_container_interceptor.go +++ b/proxy/create_container_interceptor.go @@ -58,7 +58,9 @@ func (i *createContainerInterceptor) InterceptRequest(r *http.Request) error { if err := i.setWeaveWaitEntrypoint(container.Config); err != nil { return err } - if err := i.setWeaveDNS(&container, r.URL.Query().Get("name")); err != nil { + containerName := r.URL.Query().Get("name") + hostname := i.proxy.hostnameMatchRegexp.ReplaceAllString(containerName, i.proxy.HostnameReplacement) + if err := i.setWeaveDNS(&container, hostname); err != nil { return err } } diff --git a/proxy/proxy.go b/proxy/proxy.go index 0e1969f2..9b5dce04 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -15,11 +15,13 @@ import ( ) const ( - defaultCaFile = "ca.pem" - defaultKeyFile = "key.pem" - defaultCertFile = "cert.pem" - dockerSock = "/var/run/docker.sock" - dockerSockUnix = "unix://" + dockerSock + defaultCaFile = "ca.pem" + defaultKeyFile = "key.pem" + defaultCertFile = "cert.pem" + dockerSock = "/var/run/docker.sock" + dockerSockUnix = "unix://" + dockerSock + substitutionPatternName = "pattern" + substitutionReplacementName = "replacement" ) var ( @@ -29,19 +31,22 @@ var ( ) type Config struct { - ListenAddrs []string - NoDefaultIPAM bool - NoRewriteHosts bool - TLSConfig TLSConfig - Version string - WithDNS bool - WithoutDNS bool + HostnameMatch string + HostnameReplacement string + ListenAddrs []string + NoDefaultIPAM bool + NoRewriteHosts bool + TLSConfig TLSConfig + Version string + WithDNS bool + WithoutDNS bool } type Proxy struct { Config - client *docker.Client - dockerBridgeIP string + client *docker.Client + dockerBridgeIP string + hostnameMatchRegexp *regexp.Regexp } func NewProxy(c Config) (*Proxy, error) { @@ -65,6 +70,12 @@ func NewProxy(c Config) (*Proxy, error) { p.dockerBridgeIP = string(dockerBridgeIP) } + p.hostnameMatchRegexp, err = regexp.Compile(c.HostnameMatch) + if err != nil { + err := fmt.Errorf("Incorrect hostname match '%s': %s", c.HostnameMatch, err.Error()) + return nil, err + } + return p, nil } diff --git a/site/proxy.md b/site/proxy.md index 453c81de..ed031dc5 100644 --- a/site/proxy.md +++ b/site/proxy.md @@ -130,6 +130,35 @@ automatically if it is running at the point when they are started - see the [weaveDNS usage](weavedns.html#usage) section for an in-depth explanation of the behaviour and how to control it. +Typicaly, the proxy will pass on container names as-is to [weaveDNS](weavedns.html) +for registration. However, there are situations in which the final container +name is out of the user's control (e.g. when using Docker orchestrators which +append control/namespacing identifiers to the original container names). + +For those situations, the proxy provides two flags: `--hostname-match ` +and `--hostname-replacement `. When launching a container, its name +matched against regular expression ``. Then, based on that match, +`` will be used to generate a hostname, which will ultimately be +handed over to weaveDNS for registration. + +For instance, if we launch the proxy using +`--hostname-match '^aws-[0-9]+-(.*)$'` and `--hostname-replacement 'my-app-$1'` + + host1$ weave launch-router && weave launch-dns && weave launch-proxy --hostname-match '^aws-[0-9]+-(.*)$' and --hostname-replacement 'my-app-$1' + host1$ eval "$(weave env)" + +then, running a container named `aws-12798186823-foo` will lead to weaveDNS registering +hostname `my-app-foo` and not `aws-12798186823-foo`. + + host1$ docker run -ti --name=aws-12798186823-foo ubuntu ping my-app-foo + PING my-app-foo.weave.local (10.32.0.2) 56(84) bytes of data. + 64 bytes from my-app-foo.weave.local (10.32.0.2): icmp_seq=1 ttl=64 time=0.027 ms + 64 bytes from my-app-foo.weave.local (10.32.0.2): icmp_seq=2 ttl=64 time=0.067 ms + +Note how regexp substitution groups should be prepended with a dollar sign +(e.g. `$1`). For further details on the regular expression syntax please see +[Google's re2 documentation](https://github.com/google/re2/wiki/Syntax). + ## Securing the docker communication with TLS If you are diff --git a/test/680_proxy_hostname_derivation.sh b/test/680_proxy_hostname_derivation.sh new file mode 100755 index 00000000..e4940dae --- /dev/null +++ b/test/680_proxy_hostname_derivation.sh @@ -0,0 +1,32 @@ +#! /bin/bash + +. ./config.sh + +C1=10.2.0.78 +C2=10.2.0.34 +C3=10.2.0.57 +CNAME1=qiuds71y827hdi-seeone-1io9qd9i0wd +NAME1=seeone.weave.local +CNAME2=124DJKSNK812-seetwo-128hbaJ881 +NAME2=seetwo.weave.local +CNAME3=doesnotmatchpattern +NAME3=doesnotmatchpattern.weave.local + +start_container() { + proxy docker_on $HOST1 run "$@" -dt $DNS_IMAGE /bin/sh +} + +start_suite "Hostname derivation through container name substitutions" + +weave_on $HOST1 launch-dns 10.2.254.1/24 +weave_on $HOST1 launch-proxy --hostname-match '^[^-]+-(?P[^-]*)-[^-]+$' --hostname-replacement '$appname' + +start_container -e WEAVE_CIDR=$C1/24 --name=$CNAME1 +start_container -e WEAVE_CIDR=$C2/24 --name=$CNAME2 +start_container -e WEAVE_CIDR=$C3/24 --name=$CNAME3 + +assert_dns_a_record $HOST1 $CNAME1 $NAME2 $C2 +assert_dns_a_record $HOST1 $CNAME2 $NAME3 $C3 +assert_dns_a_record $HOST1 $CNAME3 $NAME1 $C1 + +end_suite diff --git a/weave b/weave index c7983f68..9588d26b 100755 --- a/weave +++ b/weave @@ -37,6 +37,7 @@ weave launch-router [--password ] [--nickname ] weave launch-dns [] weave launch-proxy [-H ] [--with-dns | --without-dns] [--no-default-ipalloc] [--no-rewrite-hosts] + [[--hostname-match ] [--hostname-replacement ]] weave connect [--replace] [ ...] weave forget ... weave run [--with-dns | --without-dns] [ ...] From f7739ef04cf3bc701f7790b4db841805b45124d1 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Tue, 14 Jul 2015 14:50:39 +0000 Subject: [PATCH 095/180] Don't fail if docker rmi fails --- test/setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/setup.sh b/test/setup.sh index 71df8c29..0410af57 100755 --- a/test/setup.sh +++ b/test/setup.sh @@ -13,7 +13,7 @@ echo " prefetch test images" for HOST in $HOSTS; do docker_on $HOST load -i ../weave.tar DANGLING_IMAGES="$(docker_on $HOST images -q -f dangling=true)" - [ -n "$DANGLING_IMAGES" ] && docker_on $HOST rmi $DANGLING_IMAGES + [ -n "$DANGLING_IMAGES" ] && docker_on $HOST rmi $DANGLING_IMAGES 1>/dev/null 2>&1 || true run_on $HOST mkdir -p bin upload_executable $HOST ../bin/docker-ns upload_executable $HOST ../weave From ded3d6b40bdab5871b86731bd28cfdb0c3a67fe5 Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Tue, 14 Jul 2015 15:29:29 +0000 Subject: [PATCH 096/180] Address PR comments --- proxy/proxy.go | 12 +++++------- site/proxy.md | 6 +++--- weave | 2 +- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/proxy/proxy.go b/proxy/proxy.go index 9b5dce04..214bff22 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -15,13 +15,11 @@ import ( ) const ( - defaultCaFile = "ca.pem" - defaultKeyFile = "key.pem" - defaultCertFile = "cert.pem" - dockerSock = "/var/run/docker.sock" - dockerSockUnix = "unix://" + dockerSock - substitutionPatternName = "pattern" - substitutionReplacementName = "replacement" + defaultCaFile = "ca.pem" + defaultKeyFile = "key.pem" + defaultCertFile = "cert.pem" + dockerSock = "/var/run/docker.sock" + dockerSockUnix = "unix://" + dockerSock ) var ( diff --git a/site/proxy.md b/site/proxy.md index ed031dc5..d5a5bdbd 100644 --- a/site/proxy.md +++ b/site/proxy.md @@ -130,21 +130,21 @@ automatically if it is running at the point when they are started - see the [weaveDNS usage](weavedns.html#usage) section for an in-depth explanation of the behaviour and how to control it. -Typicaly, the proxy will pass on container names as-is to [weaveDNS](weavedns.html) +Typically, the proxy will pass on container names as-is to [weaveDNS](weavedns.html) for registration. However, there are situations in which the final container name is out of the user's control (e.g. when using Docker orchestrators which append control/namespacing identifiers to the original container names). For those situations, the proxy provides two flags: `--hostname-match ` and `--hostname-replacement `. When launching a container, its name -matched against regular expression ``. Then, based on that match, +is matched against regular expression ``. Then, based on that match, `` will be used to generate a hostname, which will ultimately be handed over to weaveDNS for registration. For instance, if we launch the proxy using `--hostname-match '^aws-[0-9]+-(.*)$'` and `--hostname-replacement 'my-app-$1'` - host1$ weave launch-router && weave launch-dns && weave launch-proxy --hostname-match '^aws-[0-9]+-(.*)$' and --hostname-replacement 'my-app-$1' + host1$ weave launch-router && weave launch-dns && weave launch-proxy --hostname-match '^aws-[0-9]+-(.*)$' --hostname-replacement 'my-app-$1' host1$ eval "$(weave env)" then, running a container named `aws-12798186823-foo` will lead to weaveDNS registering diff --git a/weave b/weave index 9588d26b..8b4384e8 100755 --- a/weave +++ b/weave @@ -37,7 +37,7 @@ weave launch-router [--password ] [--nickname ] weave launch-dns [] weave launch-proxy [-H ] [--with-dns | --without-dns] [--no-default-ipalloc] [--no-rewrite-hosts] - [[--hostname-match ] [--hostname-replacement ]] + [--hostname-match ] [--hostname-replacement ] weave connect [--replace] [ ...] weave forget ... weave run [--with-dns | --without-dns] [ ...] From acd8bdec21391a4f48569849ebf600323fae3522 Mon Sep 17 00:00:00 2001 From: Paul Bellamy Date: Mon, 13 Jul 2015 15:01:21 +0100 Subject: [PATCH 097/180] [proxy] respect custom DOCKER_BRIDGE --- proxy/common.go | 9 ++++++++- weave | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/proxy/common.go b/proxy/common.go index 45ed79d8..7c7775c4 100644 --- a/proxy/common.go +++ b/proxy/common.go @@ -6,6 +6,7 @@ import ( "fmt" "io/ioutil" "net/http" + "os" "os/exec" "regexp" @@ -22,7 +23,13 @@ func callWeave(args ...string) ([]byte, error) { args = append([]string{"--local"}, args...) Debug.Print("Calling weave", args) cmd := exec.Command("./weave", args...) - cmd.Env = []string{"PROCFS=/hostproc", "PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"} + cmd.Env = []string{ + "PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "PROCFS=/hostproc", + } + if bridge := os.Getenv("DOCKER_BRIDGE"); bridge != "" { + cmd.Env = append(cmd.Env, fmt.Sprintf("DOCKER_BRIDGE=%s", bridge)) + } out, err := cmd.CombinedOutput() return out, err } diff --git a/weave b/weave index 67d69d9f..eee61860 100755 --- a/weave +++ b/weave @@ -1076,6 +1076,7 @@ case "$COMMAND" in -v /proc:/hostproc \ -e PROCFS=/hostproc \ -e WEAVE_CIDR=none \ + -e DOCKER_BRIDGE \ --entrypoint=/home/weave/weaveproxy \ $WEAVEPROXY_DOCKER_ARGS $EXEC_IMAGE $PROXY_ARGS) wait_for_log $PROXY_CONTAINER_NAME "proxy listening" From 01f7201a9e67fc722261f7781017683b0c538975 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Tue, 7 Jul 2015 13:05:10 +0000 Subject: [PATCH 098/180] Remove legacy WeaveDNS code. --- Makefile | 18 +- common/sched_queue.go | 155 ------- common/sched_queue_test.go | 92 ---- nameserver/addrs.go | 130 ------ nameserver/addrs_test.go | 32 -- nameserver/cache.go | 382 ----------------- nameserver/cache_test.go | 230 ---------- nameserver/dns.go | 117 ----- nameserver/dns_test.go | 39 -- nameserver/http.go | 124 ------ nameserver/http_test.go | 131 ------ nameserver/mdns.go | 28 -- nameserver/mdns_client.go | 290 ------------- nameserver/mdns_client_test.go | 199 --------- nameserver/mdns_lookup.go | 71 --- nameserver/mdns_server.go | 148 ------- nameserver/mdns_server_test.go | 124 ------ nameserver/mdns_test.go | 170 -------- nameserver/mocks_test.go | 507 ---------------------- nameserver/server.go | 414 ------------------ nameserver/server_cache_test.go | 351 --------------- nameserver/server_test.go | 258 ----------- nameserver/zone.go | 739 -------------------------------- nameserver/zone_lookup.go | 291 ------------- nameserver/zone_lookup_test.go | 116 ----- nameserver/zone_test.go | 160 ------- prog/weavedns/Dockerfile | 6 - prog/weavedns/main.go | 186 -------- 28 files changed, 5 insertions(+), 5503 deletions(-) delete mode 100644 common/sched_queue.go delete mode 100644 common/sched_queue_test.go delete mode 100644 nameserver/addrs.go delete mode 100644 nameserver/addrs_test.go delete mode 100644 nameserver/cache.go delete mode 100644 nameserver/cache_test.go delete mode 100644 nameserver/dns.go delete mode 100644 nameserver/dns_test.go delete mode 100644 nameserver/http.go delete mode 100644 nameserver/http_test.go delete mode 100644 nameserver/mdns.go delete mode 100644 nameserver/mdns_client.go delete mode 100644 nameserver/mdns_client_test.go delete mode 100644 nameserver/mdns_lookup.go delete mode 100644 nameserver/mdns_server.go delete mode 100644 nameserver/mdns_server_test.go delete mode 100644 nameserver/mdns_test.go delete mode 100644 nameserver/mocks_test.go delete mode 100644 nameserver/server.go delete mode 100644 nameserver/server_cache_test.go delete mode 100644 nameserver/server_test.go delete mode 100644 nameserver/zone.go delete mode 100644 nameserver/zone_lookup.go delete mode 100644 nameserver/zone_lookup_test.go delete mode 100644 nameserver/zone_test.go delete mode 100644 prog/weavedns/Dockerfile delete mode 100644 prog/weavedns/main.go diff --git a/Makefile b/Makefile index 0784ee8e..dca84405 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -PUBLISH=publish_weave publish_weavedns publish_weaveexec +PUBLISH=publish_weave publish_weaveexec .DEFAULT: all .PHONY: all update tests publish $(PUBLISH) clean prerequisites build travis run-smoketests @@ -10,26 +10,23 @@ DOCKERHUB_USER=weaveworks WEAVE_VERSION=git-$(shell git rev-parse --short=12 HEAD) WEAVER_EXE=prog/weaver/weaver -WEAVEDNS_EXE=prog/weavedns/weavedns WEAVEPROXY_EXE=prog/weaveproxy/weaveproxy SIGPROXY_EXE=prog/sigproxy/sigproxy WEAVEWAIT_EXE=prog/weavewait/weavewait NETCHECK_EXE=prog/netcheck/netcheck COVER_EXE=testing/cover/cover -EXES=$(WEAVER_EXE) $(WEAVEDNS_EXE) $(SIGPROXY_EXE) $(WEAVEPROXY_EXE) $(WEAVEWAIT_EXE) $(NETCHECK_EXE) $(COVER_EXE) +EXES=$(WEAVER_EXE) $(SIGPROXY_EXE) $(WEAVEPROXY_EXE) $(WEAVEWAIT_EXE) $(NETCHECK_EXE) $(COVER_EXE) WEAVER_UPTODATE=.weaver.uptodate -WEAVEDNS_UPTODATE=.weavedns.uptodate WEAVEEXEC_UPTODATE=.weaveexec.uptodate -IMAGES_UPTODATE=$(WEAVER_UPTODATE) $(WEAVEDNS_UPTODATE) $(WEAVEEXEC_UPTODATE) +IMAGES_UPTODATE=$(WEAVER_UPTODATE) $(WEAVEEXEC_UPTODATE) WEAVER_IMAGE=$(DOCKERHUB_USER)/weave -WEAVEDNS_IMAGE=$(DOCKERHUB_USER)/weavedns WEAVEEXEC_IMAGE=$(DOCKERHUB_USER)/weaveexec -IMAGES=$(WEAVER_IMAGE) $(WEAVEDNS_IMAGE) $(WEAVEEXEC_IMAGE) +IMAGES=$(WEAVER_IMAGE) $(WEAVEEXEC_IMAGE) WEAVE_EXPORT=weave.tar @@ -64,13 +61,12 @@ else endif $(NETGO_CHECK) -$(WEAVEDNS_EXE) $(WEAVEPROXY_EXE) $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go +$(WEAVEPROXY_EXE) $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go go get -tags netgo ./$(@D) go build -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" -tags netgo -o $@ ./$(@D) $(NETGO_CHECK) $(WEAVER_EXE): router/*.go ipam/*.go ipam/*/*.go prog/weaver/main.go -$(WEAVEDNS_EXE): nameserver/*.go prog/weavedns/main.go $(WEAVEPROXY_EXE): proxy/*.go prog/weaveproxy/main.go $(NETCHECK_EXE): prog/netcheck/netcheck.go @@ -88,10 +84,6 @@ $(WEAVER_UPTODATE): prog/weaver/Dockerfile $(WEAVER_EXE) $(SUDO) docker build -t $(WEAVER_IMAGE) prog/weaver touch $@ -$(WEAVEDNS_UPTODATE): prog/weavedns/Dockerfile $(WEAVEDNS_EXE) - $(SUDO) docker build -t $(WEAVEDNS_IMAGE) prog/weavedns - touch $@ - $(WEAVEEXEC_UPTODATE): prog/weaveexec/Dockerfile $(DOCKER_DISTRIB) weave $(SIGPROXY_EXE) $(WEAVEPROXY_EXE) $(WEAVEWAIT_EXE) $(NETCHECK_EXE) cp weave prog/weaveexec/weave cp $(SIGPROXY_EXE) prog/weaveexec/sigproxy diff --git a/common/sched_queue.go b/common/sched_queue.go deleted file mode 100644 index cbfc9eb3..00000000 --- a/common/sched_queue.go +++ /dev/null @@ -1,155 +0,0 @@ -package common - -import ( - "container/heap" - "math" - "time" - - "sync/atomic" - - "github.com/benbjohnson/clock" -) - -// A callable is a function that is called and return an (optional) next scheduled time -type callable func() time.Time - -type schedCall struct { - t time.Time - c callable -} - -func (sc *schedCall) FromNow(now time.Time) time.Duration { - if sc.t.After(now) { - return time.Duration(sc.t.Sub(now).Nanoseconds()) - } - return time.Duration(0) -} - -//////////////////////////////////////////////////////////////////////////////// - -// A min-heap of scheduled callables -type schedCallsHeap []*schedCall - -func (ch *schedCallsHeap) Len() int { return len(*ch) } -func (ch *schedCallsHeap) Less(i, j int) bool { return (*ch)[i].t.Before((*ch)[j].t) } -func (ch *schedCallsHeap) Swap(i, j int) { - (*ch)[i], (*ch)[j] = (*ch)[j], (*ch)[i] -} - -func (ch *schedCallsHeap) Push(x interface{}) { - // Push and Pop use pointer receivers because they modify the slice's length, - // not just its contents. - entry := x.(*schedCall) - *ch = append(*ch, entry) -} - -func (ch *schedCallsHeap) Pop() interface{} { - old := *ch - n := len(old) - item := old[n-1] - *ch = old[0 : n-1] - return item -} - -//////////////////////////////////////////////////////////////////////////////// - -// SchedQueue is queue of scheduled callables -type SchedQueue struct { - clock clock.Clock - callablesH schedCallsHeap - schedChan chan *schedCall - closeChan chan bool - counter uint64 // number of calls invoked so far (used for stats). Note: it will wrap. -} - -// NewSchedQueue creates a new scheduled queue -func NewSchedQueue(clock clock.Clock) *SchedQueue { - cq := SchedQueue{ - clock: clock, - schedChan: make(chan *schedCall), - closeChan: make(chan bool), - } - heap.Init(&cq.callablesH) - return &cq -} - -// Start starts the scheduled queue -func (cq *SchedQueue) Start() { - go func() { - defer func() { Log.Debugf("[sched-q] Quitting (%d calls pending)", len(cq.callablesH)) }() - - var now time.Time - timer := cq.clock.Timer(time.Duration(math.MaxInt64)) - - for { - // Wait until an insertion, until the next callable or until we are Stop()ed - select { - case ce := <-cq.schedChan: - heap.Push(&cq.callablesH, ce) - now = cq.clock.Now() - case <-cq.closeChan: - return - case now = <-timer.C: - } - - timer.Stop() - durationUntilNext := cq.durationUntilNext(now) - for durationUntilNext == 0 { - sched := heap.Pop(&cq.callablesH).(*schedCall) - - atomic.AddUint64(&cq.counter, 1) - schedNextTime := sched.c() - - if !schedNextTime.IsZero() { - sched.t = schedNextTime - heap.Push(&cq.callablesH, sched) // TODO: use a Fix() instead of Pop()&Push() - } - - now = cq.clock.Now() - durationUntilNext = cq.durationUntilNext(now) - } - - timer = cq.clock.Timer(durationUntilNext) - } - }() -} - -// Stop stops the scheduled queue -func (cq *SchedQueue) Stop() { - Log.Debugf("[sched-q] Stopping...") - cq.closeChan <- true -} - -// Add schedules a call. -// The callable should not modify the scheduled queue in any way. -func (cq *SchedQueue) Add(c callable, t time.Time) { - Log.Debugf("[sched-q] Adding call at %s", t) - ce := schedCall{c: c, t: t} - cq.schedChan <- &ce -} - -// Counter returns the number of calls invoked in the queued -// Note: the result will wrap over time. -func (cq *SchedQueue) Count() uint64 { - return atomic.LoadUint64(&cq.counter) -} - -func (cq *SchedQueue) durationUntilNext(now time.Time) time.Duration { - if len(cq.callablesH) > 0 { - firstSched := cq.callablesH[0] - return firstSched.FromNow(now) - } - return time.Duration(math.MaxInt64) -} - -// ensure that the background goroutine has executed any pending callbacks -func (cq *SchedQueue) Flush() { - ch := make(chan struct{}) - flushFunc := func() time.Time { - atomic.AddUint64(&cq.counter, ^uint64(0)) // decrement so nobody sees this - close(ch) - return time.Time{} - } - cq.schedChan <- &schedCall{c: flushFunc, t: time.Time{}} - <-ch -} diff --git a/common/sched_queue_test.go b/common/sched_queue_test.go deleted file mode 100644 index d9eb6830..00000000 --- a/common/sched_queue_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package common - -import ( - "testing" - "time" - - "github.com/benbjohnson/clock" - "github.com/stretchr/testify/require" -) - -// Ensure we can add new calls while forwarding the clock -func TestSchedCallsBasic(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestSchedCallsBasic starting") - - const testSecs = 1000 - clk := clock.NewMock() - schedQueue := NewSchedQueue(clk) - schedQueue.Start() - defer schedQueue.Stop() - - c := func() time.Time { - return clk.Now().Add(time.Second) - } - - schedQueue.Add(c, clk.Now().Add(time.Second)) - schedQueue.Flush() - for i := 0; i < testSecs; i++ { - clk.Add(time.Second) - schedQueue.Flush() - } - - t.Logf("Now: %s - calls: %d", clk.Now(), schedQueue.Count()) - require.Equal(t, testSecs, (int)(schedQueue.Count()), "Number of calls") -} - -// Ensure we can create a 100 seconds gap in the middle of the time travel -func TestSchedCallsGap(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestSchedCallsGap starting") - - const testSecs = 1000 - clk := clock.NewMock() - schedQueue := NewSchedQueue(clk) - schedQueue.Start() - defer schedQueue.Stop() - - c2 := func() time.Time { - if schedQueue.Count() == testSecs/2 { - return clk.Now().Add(time.Duration(100) * time.Second) - } - return clk.Now().Add(time.Second) - } - - schedQueue.Add(c2, clk.Now().Add(time.Second)) - schedQueue.Flush() - for i := 0; i < testSecs; i++ { - clk.Add(time.Second) - schedQueue.Flush() - } - - t.Logf("Now: %s - calls: %d", clk.Now(), schedQueue.Count()) - require.Equal(t, testSecs-100+1, (int)(schedQueue.Count()), "Number of calls") -} - -func TestSchedCallsStop(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestSchedCallsStop starting") - - const testSecs = 1000 - clk := clock.NewMock() - schedQueue := NewSchedQueue(clk) - schedQueue.Start() - defer schedQueue.Stop() - - c2 := func() time.Time { - if schedQueue.Count() == testSecs/2 { - return time.Time{} - } - return clk.Now().Add(time.Second) - } - - schedQueue.Add(c2, clk.Now().Add(time.Second)) - schedQueue.Flush() - for i := 0; i < testSecs; i++ { - clk.Add(time.Second) - schedQueue.Flush() - } - - t.Logf("Now: %s - calls: %d", clk.Now(), schedQueue.Count()) - require.Equal(t, testSecs/2, (int)(schedQueue.Count()), "Number of calls") -} diff --git a/nameserver/addrs.go b/nameserver/addrs.go deleted file mode 100644 index fb3deb66..00000000 --- a/nameserver/addrs.go +++ /dev/null @@ -1,130 +0,0 @@ -package nameserver - -import ( - "bytes" - "fmt" - "net" -) - -// A zone record -// -// Note: all the zone records information is concentrated here. Maybe -// not all queries will use things like priorities or weights, but we -// do not want to create a hierarchy for dealing with all possible -// queries... -type ZoneRecord interface { - Name() string // The name for this IP - IP() net.IP // The IP (v4) address - Priority() int // The priority - Weight() int // The weight - TTL() int // TTL -} - -type ZoneLookup interface { - // Lookup for a name - LookupName(name string) ([]ZoneRecord, error) - // Lookup for an address - LookupInaddr(inaddr string) ([]ZoneRecord, error) -} - -type ZoneLookupFunc func(target string) ([]ZoneRecord, error) - -type ZoneObservable interface { - // Observe anything that affects a particular name in the zone - ObserveName(name string, observer ZoneRecordObserver) error - // Observe anything that affects a particular IP in the zone - ObserveInaddr(inaddr string, observer ZoneRecordObserver) error -} - -type ZoneObserverFunc func(string, ZoneRecordObserver) error -type ZoneRecordObserver func() - -///////////////////////////////////////////////////////////// - -// A basic record struct (satisfying the ZoneRecord interface) -type Record struct { - name string - ip net.IP - priority int - weight int - ttl int -} - -func (r Record) Name() string { return r.name } -func (r Record) IP() net.IP { return r.ip } -func (r Record) Priority() int { return r.priority } -func (r Record) Weight() int { return r.weight } -func (r Record) TTL() int { return r.ttl } - -func (r Record) String() string { - var buf bytes.Buffer - if len(r.Name()) > 0 { - fmt.Fprintf(&buf, "%s", r.Name()) - } - if !r.IP().IsUnspecified() { - fmt.Fprintf(&buf, "[%s]", r.IP()) - } - if r.Priority() > 0 { - fmt.Fprintf(&buf, "/P:%d", r.Priority()) - } - if r.Weight() > 0 { - fmt.Fprintf(&buf, "/W:%d", r.Weight()) - } - if r.TTL() > 0 { - fmt.Fprintf(&buf, "/TTL:%d", r.TTL()) - } - - return buf.String() -} - -///////////////////////////////////////////////////////////// - -func newParseError(reason string, addr string) *net.ParseError { - return &net.ParseError{Type: reason, Text: addr} -} - -// simple IPv4 type that can be used as a key in a map (in contrast with net.IP), used for sets of IPs, etc... -type IPv4 [4]byte - -func (ip IPv4) toNetIP() net.IP { return net.IPv4(ip[0], ip[1], ip[2], ip[3]) } -func (ip IPv4) String() string { return ip.toNetIP().String() } -func ipToIPv4(nip net.IP) IPv4 { ip := nip.To4(); return IPv4([4]byte{ip[0], ip[1], ip[2], ip[3]}) } - -// Parse an address (eg, "10.13.12.11") and return the corresponding IPv4 (eg, "10.13.12.11") -func addrToIPv4(addr string) (IPv4, error) { - ip := net.ParseIP(addr) - if ip == nil { - return IPv4{}, newParseError("IP address", addr) - } - return ipToIPv4(ip), nil -} - -// Parse a reverse address (eg, "11.12.13.10.in-addr.arpa.") and return the corresponding IPv4 (eg, "10.13.12.11") -func raddrToIPv4(addr string) (IPv4, error) { - l := len(addr) - if l < rdnsDomainLen+1 { - return IPv4{}, newParseError("too short reverse IP address", addr) - } - - suffixLen := l - rdnsDomainLen - suffix := addr[suffixLen+1:] - if suffix != RDNSDomain { - return IPv4{}, newParseError("suffix of reverse IP address", addr) - } - ipStr := addr[:suffixLen] - revIP := net.ParseIP(ipStr) - if revIP == nil { - return IPv4{}, newParseError("reverse IP address", addr) - } - - revIP4 := revIP.To4() - return IPv4([4]byte{revIP4[3], revIP4[2], revIP4[1], revIP4[0]}), nil -} - -func raddrToIP(addr string) (net.IP, error) { - r, err := raddrToIPv4(addr) - if err != nil { - return net.IP{}, err - } - return r.toNetIP(), nil -} diff --git a/nameserver/addrs_test.go b/nameserver/addrs_test.go deleted file mode 100644 index 00d1ba7d..00000000 --- a/nameserver/addrs_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package nameserver - -import ( - "net" - "testing" - - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -func TestAddrs(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestAddrs starting") - - ip, err := addrToIPv4("10.13.12.11") - require.NoError(t, err) - require.True(t, net.ParseIP("10.13.12.11").Equal(ip.toNetIP()), "IP") - - ip, err = raddrToIPv4("11.12.13.10.in-addr.arpa.") - require.NoError(t, err) - require.True(t, net.ParseIP("10.13.12.11").Equal(ip.toNetIP()), "IP") - - // some malformed addresses - ip, err = addrToIPv4("10.13.12") - require.True(t, err != nil, "when parsing malformed address") - ip, err = addrToIPv4("10.13.AA.12") - require.True(t, err != nil, "when parsing malformed address") - ip, err = raddrToIPv4("11.12.13.10.in-axxx.arpa.") - require.True(t, err != nil, "when parsing malformed address") - ip, err = raddrToIPv4("11.12.13.10.in-addr") - require.True(t, err != nil, "when parsing malformed address") -} diff --git a/nameserver/cache.go b/nameserver/cache.go deleted file mode 100644 index fd0be604..00000000 --- a/nameserver/cache.go +++ /dev/null @@ -1,382 +0,0 @@ -package nameserver - -import ( - "bytes" - "container/heap" - "errors" - "fmt" - "math" - "sync" - "time" - - "github.com/benbjohnson/clock" - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" -) - -var ( - errInvalidCapacity = errors.New("Invalid cache capacity") - errCouldNotResolve = errors.New("Could not resolve") - errTimeout = errors.New("Timeout while waiting for resolution") - errNoLocalReplies = errors.New("No local replies") -) - -const ( - defPendingTimeout int = 5 // timeout for a resolution -) - -const nullTTL = 0 // a null TTL - -type entryStatus uint8 - -const ( - stPending entryStatus = iota // someone is waiting for the resolution - stResolved entryStatus = iota // resolved -) - -var statusToString = map[entryStatus]string{ - stPending: "pending", - stResolved: "resolved", -} - -const ( - CacheNoLocalReplies uint8 = 1 << iota // not found in local network (stored in the cache so we skip another local lookup or some time) -) - -// a cache entry -type cacheEntry struct { - Status entryStatus // status of the entry - Flags uint8 // some extra flags - ReplyLen int - - question dns.Question - protocol dnsProtocol - reply dns.Msg - - validUntil time.Time // obtained from the reply and stored here for convenience/speed - putTime time.Time - - index int // for fast lookups in the heap -} - -func newCacheEntry(question *dns.Question, now time.Time) *cacheEntry { - e := &cacheEntry{ - Status: stPending, - validUntil: now.Add(time.Second * time.Duration(defPendingTimeout)), - question: *question, - index: -1, - } - - return e -} - -// Get a copy of the reply stored in the entry, but with some values adjusted like the TTL -func (e *cacheEntry) getReply(request *dns.Msg, maxLen int, now time.Time) (*dns.Msg, error) { - if e.Status != stResolved { - return nil, nil - } - - // if the reply has expired or is invalid, force the caller to start a new resolution - if e.hasExpired(now) { - return nil, nil - } - - if e.Flags&CacheNoLocalReplies != 0 { - return nil, errNoLocalReplies - } - - if e.ReplyLen >= maxLen { - Log.Debugf("[cache msgid %d] returning truncated reponse: %d > %d", request.MsgHdr.Id, e.ReplyLen, maxLen) - return makeTruncatedReply(request), nil - } - - // create a copy of the reply, with values for this particular query - reply := e.reply.Copy() - reply.SetReply(request) - - // adjust the TTLs - passedSecs := uint32(now.Sub(e.putTime).Seconds()) - for _, rr := range reply.Answer { - hdr := rr.Header() - ttl := hdr.Ttl - if passedSecs < ttl { - hdr.Ttl = ttl - passedSecs - } else { - return nil, nil // it is expired: do not spend more time and return nil... - } - } - - reply.Rcode = e.reply.Rcode - reply.Authoritative = true - - return reply, nil -} - -func (e cacheEntry) hasExpired(now time.Time) bool { - return e.validUntil.Before(now) || e.validUntil == now -} - -// set the reply for the entry -// returns True if the entry has changed the validUntil time -func (e *cacheEntry) setReply(reply *dns.Msg, ttl int, flags uint8, now time.Time) bool { - var prevValidUntil time.Time - if e.Status == stResolved { - if reply != nil { - Log.Debugf("[cache msgid %d] replacing response in cache", reply.MsgHdr.Id) - } - prevValidUntil = e.validUntil - } - - // make sure we do not overwrite noLocalReplies entries - if flags&CacheNoLocalReplies != 0 { - if e.Flags&CacheNoLocalReplies != 0 { - return false - } - } - - if ttl != nullTTL { - e.validUntil = now.Add(time.Second * time.Duration(ttl)) - } else if reply != nil { - // calculate the validUntil from the reply TTL - var minTTL uint32 = math.MaxUint32 - for _, rr := range reply.Answer { - ttl := rr.Header().Ttl - if ttl < minTTL { - minTTL = ttl // TODO: improve the minTTL calculation (maybe we should skip some RRs) - } - } - e.validUntil = now.Add(time.Second * time.Duration(minTTL)) - } else { - Log.Warningf("[cache] no valid TTL could be calculated") - } - - e.Status = stResolved - e.Flags = flags - e.putTime = now - - if reply != nil { - e.reply = *reply.Copy() - e.ReplyLen = reply.Len() - } - - return (prevValidUntil != e.validUntil) -} - -func (e *cacheEntry) String() string { - var buf bytes.Buffer - q := e.question - fmt.Fprintf(&buf, "'%s'[%s]: ", q.Name, dns.TypeToString[q.Qtype]) - if e.Flags&CacheNoLocalReplies != 0 { - fmt.Fprintf(&buf, "neg-local") - } else { - fmt.Fprintf(&buf, "%s", statusToString[e.Status]) - } - fmt.Fprintf(&buf, "(%d bytes)", e.ReplyLen) - return buf.String() -} - -////////////////////////////////////////////////////////////////////////////////////// - -// An entriesPtrHeap is a min-heap of cache entries. -type entriesPtrsHeap []*cacheEntry - -func (h entriesPtrsHeap) Len() int { return len(h) } -func (h entriesPtrsHeap) Less(i, j int) bool { return h[i].validUntil.Before(h[j].validUntil) } -func (h entriesPtrsHeap) Swap(i, j int) { - h[i], h[j] = h[j], h[i] - h[i].index = i - h[j].index = j -} - -func (h *entriesPtrsHeap) Push(x interface{}) { - // Push and Pop use pointer receivers because they modify the slice's length, - // not just its contents. - n := len(*h) - entry := x.(*cacheEntry) - entry.index = n - *h = append(*h, entry) -} - -func (h *entriesPtrsHeap) Pop() interface{} { - old := *h - n := len(old) - item := old[n-1] - item.index = -1 // for safety - *h = old[0 : n-1] - return item -} - -////////////////////////////////////////////////////////////////////////////////////// - -// The cache interface -type ZoneCache interface { - // Get from the cache - Get(request *dns.Msg, maxLen int) (reply *dns.Msg, err error) - // Put in the cache - Put(request *dns.Msg, reply *dns.Msg, ttl int, flags uint8) int - // Remove from the cache - Remove(question *dns.Question) - // Purge all expired entries from the cache - Purge() - // Remove all entries - Clear() - // Return the cache length - Len() int - // Return the max capacity - Capacity() int -} - -type cacheKey dns.Question -type entries map[cacheKey]*cacheEntry - -// Cache is a thread-safe fixed capacity LRU cache. -type Cache struct { - capacity int - entries entries - entriesH entriesPtrsHeap // len(entriesH) <= len(entries), as pending entries can be in entries but not in entriesH - clock clock.Clock - lock sync.RWMutex -} - -// NewCache creates a cache of the given capacity -func NewCache(capacity int, clk clock.Clock) (*Cache, error) { - if capacity <= 0 { - return nil, errInvalidCapacity - } - c := &Cache{ - capacity: capacity, - entries: make(entries, capacity), - clock: clk, - } - - if c.clock == nil { - c.clock = clock.New() - } - - heap.Init(&c.entriesH) - return c, nil -} - -// Clear removes all the entries in the cache -func (c *Cache) Clear() { - c.lock.Lock() - defer c.lock.Unlock() - - c.entries = make(entries, c.capacity) - heap.Init(&c.entriesH) -} - -// Purge removes the old elements in the cache -func (c *Cache) Purge() { - c.lock.Lock() - defer c.lock.Unlock() - - now := c.clock.Now() - for i, entry := range c.entriesH { - if entry.hasExpired(now) { - heap.Remove(&c.entriesH, i) - delete(c.entries, cacheKey(entry.question)) - } else { - return // all remaining entries must be still valid... - } - } -} - -// Add adds a reply to the cache. -// When `ttl` is equal to `nullTTL`, the cache entry will be valid until the closest TTL in the `reply` -func (c *Cache) Put(request *dns.Msg, reply *dns.Msg, ttl int, flags uint8) int { - c.lock.Lock() - defer c.lock.Unlock() - - now := c.clock.Now() - question := request.Question[0] - key := cacheKey(question) - ent, found := c.entries[key] - if found { - updated := ent.setReply(reply, ttl, flags, now) - if updated { - heap.Fix(&c.entriesH, ent.index) - } - } else { - // If we will add a new item and the capacity has been exceeded, make some room... - if len(c.entriesH) >= c.capacity { - lowestEntry := heap.Pop(&c.entriesH).(*cacheEntry) - delete(c.entries, cacheKey(lowestEntry.question)) - } - ent = newCacheEntry(&question, now) - ent.setReply(reply, ttl, flags, now) - heap.Push(&c.entriesH, ent) - c.entries[key] = ent - } - return ent.ReplyLen -} - -// Look up for a question's reply from the cache. -// If no reply is stored in the cache, it returns a `nil` reply and no error. -func (c *Cache) Get(request *dns.Msg, maxLen int) (reply *dns.Msg, err error) { - c.lock.Lock() - defer c.lock.Unlock() - - now := c.clock.Now() - question := request.Question[0] - key := cacheKey(question) - if ent, found := c.entries[key]; found { - reply, err = ent.getReply(request, maxLen, now) - if ent.hasExpired(now) { - Log.Debugf("[cache msgid %d] expired: removing", request.MsgHdr.Id) - if ent.index > 0 { - heap.Remove(&c.entriesH, ent.index) - } - delete(c.entries, key) - reply = nil - } - } else { - // we are the first asking for this name: create an entry with no reply... the caller must wait - Log.Debugf("[cache msgid %d] addind in pending state", request.MsgHdr.Id) - c.entries[key] = newCacheEntry(&question, now) - } - return -} - -// Remove removes the provided question from the cache. -func (c *Cache) Remove(question *dns.Question) { - c.lock.Lock() - defer c.lock.Unlock() - - key := cacheKey(*question) - if entry, found := c.entries[key]; found { - Log.Debugf("[cache] removing %s-response for '%s'", dns.TypeToString[question.Qtype], question.Name) - if entry.index > 0 { - heap.Remove(&c.entriesH, entry.index) - } - delete(c.entries, key) - } -} - -// Len returns the number of entries in the cache. -func (c *Cache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - - return len(c.entries) -} - -// Return the max capacity -func (c *Cache) Capacity() int { - c.lock.RLock() - defer c.lock.RUnlock() - - return c.capacity -} - -// Return the max capacity -func (c *Cache) String() string { - c.lock.RLock() - defer c.lock.RUnlock() - - var buf bytes.Buffer - for _, entry := range c.entries { - fmt.Fprintf(&buf, "%s\n", entry) - } - return buf.String() -} diff --git a/nameserver/cache_test.go b/nameserver/cache_test.go deleted file mode 100644 index d6e29c25..00000000 --- a/nameserver/cache_test.go +++ /dev/null @@ -1,230 +0,0 @@ -package nameserver - -import ( - "fmt" - "net" - "testing" - "time" - - "github.com/benbjohnson/clock" - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -// Check that the cache keeps its intended capacity constant -func TestCacheLength(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestCacheLength starting") - - const cacheLen = 128 - - l, err := NewCache(cacheLen, nil) - require.NoError(t, err) - - insTime := time.Now() - - t.Logf("Inserting 256 questions in the cache at '%s', with TTL from 0 to 255", insTime) - for i := 0; i < cacheLen*2; i++ { - name := fmt.Sprintf("name%d", i) - questionMsg := new(dns.Msg) - questionMsg.SetQuestion(name, dns.TypeA) - questionMsg.RecursionDesired = true - - question := &questionMsg.Question[0] - - ip := net.ParseIP(fmt.Sprintf("10.0.1.%d", i)) - records := []ZoneRecord{Record{name, ip, 0, 0, 0}} - - reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL) - reply.Answer[0].Header().Ttl = uint32(i) - - l.Put(questionMsg, reply, 0, 0) - } - - require.Equal(t, cacheLen, l.Len(), "cache length") - - minExpectedTime := insTime.Add(time.Duration(cacheLen) * time.Second) - t.Logf("Checking all remaining entries expire after insert_time + %d secs='%s'", cacheLen, minExpectedTime) - for _, entry := range l.entries { - if entry.validUntil.Before(minExpectedTime) { - t.Fatalf("Entry valid until %s", entry.validUntil) - } - } -} - -// Check that the cache entries are ok -func TestCacheEntries(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestCacheEntries starting") - - Log.Infoln("Checking cache consistency") - - const cacheLen = 128 - clk := clock.NewMock() - - l, err := NewCache(cacheLen, clk) - require.NoError(t, err) - - questionMsg := new(dns.Msg) - questionMsg.SetQuestion("some.name", dns.TypeA) - questionMsg.RecursionDesired = true - - question := &questionMsg.Question[0] - - t.Logf("Trying to get a name") - resp, err := l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - if resp != nil { - t.Logf("Got\n%s", resp) - t.Fatalf("ERROR: Did not expect a reponse from Get() yet") - } - t.Logf("Trying to get it again") - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - if resp != nil { - t.Logf("Got\n%s", resp) - t.Fatalf("ERROR: Did not expect a reponse from Get() yet") - } - - t.Logf("Inserting the reply") - records := []ZoneRecord{Record{"some.name", net.ParseIP("10.0.1.1"), 0, 0, 0}} - reply1 := makeAddressReply(questionMsg, question, records, DefaultLocalTTL) - l.Put(questionMsg, reply1, nullTTL, 0) - - t.Logf("Checking we can Get() the reply now") - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - require.True(t, resp != nil, "reponse from Get()") - t.Logf("Received '%s'", resp.Answer[0]) - require.IsType(t, (*dns.A)(nil), resp.Answer[0], "DNS record") - ttlGet1 := resp.Answer[0].Header().Ttl - - clk.Add(time.Duration(1) * time.Second) - t.Logf("Checking that a second Get(), after 1 second, gets the same result, but with reduced TTL") - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - require.True(t, resp != nil, "reponse from a second Get()") - t.Logf("Received '%s'", resp.Answer[0]) - require.IsType(t, (*dns.A)(nil), resp.Answer[0], "DNS record") - ttlGet2 := resp.Answer[0].Header().Ttl - require.Equal(t, 1, int(ttlGet1-ttlGet2), "TTL difference") - - clk.Add(time.Duration(DefaultLocalTTL) * time.Second) - t.Logf("Checking that a third Get(), after %d second, gets no result", DefaultLocalTTL) - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - if resp != nil { - t.Logf("Got\n%s", resp) - t.Fatalf("ERROR: Did NOT expect a reponse from the second Get()") - } - - t.Logf("Checking that an Remove() results in Get() returning nothing") - records = []ZoneRecord{Record{"some.name", net.ParseIP("10.0.9.9"), 0, 0, 0}} - replyTemp := makeAddressReply(questionMsg, question, records, DefaultLocalTTL) - l.Put(questionMsg, replyTemp, nullTTL, 0) - lenBefore := l.Len() - l.Remove(question) - require.Equal(t, lenBefore-1, l.Len(), "cache length") - l.Remove(question) // do it again: should have no effect... - require.Equal(t, lenBefore-1, l.Len(), "cache length") - - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - require.True(t, resp == nil, "reponse from the Get() after a Remove()") - - t.Logf("Inserting a two replies for the same query") - records = []ZoneRecord{Record{"some.name", net.ParseIP("10.0.1.2"), 0, 0, 0}} - reply2 := makeAddressReply(questionMsg, question, records, DefaultLocalTTL) - l.Put(questionMsg, reply2, nullTTL, 0) - clk.Add(time.Duration(1) * time.Second) - records = []ZoneRecord{Record{"some.name", net.ParseIP("10.0.1.3"), 0, 0, 0}} - reply3 := makeAddressReply(questionMsg, question, records, DefaultLocalTTL) - l.Put(questionMsg, reply3, nullTTL, 0) - - t.Logf("Checking we get the last one...") - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - require.True(t, resp != nil, "reponse from the Get()") - t.Logf("Received '%s'", resp.Answer[0]) - require.IsType(t, (*dns.A)(nil), resp.Answer[0], "DNS record") - require.Equal(t, "10.0.1.3", resp.Answer[0].(*dns.A).A.String(), "IP address") - require.Equal(t, int(DefaultLocalTTL), int(resp.Answer[0].Header().Ttl), "TTL") - - clk.Add(time.Duration(DefaultLocalTTL-1) * time.Second) - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - require.True(t, resp != nil, "reponse from the Get()") - t.Logf("Received '%s'", resp.Answer[0]) - require.IsType(t, (*dns.A)(nil), resp.Answer[0], "DNS record") - require.Equal(t, "10.0.1.3", resp.Answer[0].(*dns.A).A.String(), "IP address") - require.Equal(t, 1, int(resp.Answer[0].Header().Ttl), "TTL") - - t.Logf("Checking we get empty replies when they are expired...") - lenBefore = l.Len() - clk.Add(time.Duration(DefaultLocalTTL) * time.Second) - resp, err = l.Get(questionMsg, minUDPSize) - require.NoError(t, err) - if resp != nil { - t.Logf("Got\n%s", resp.Answer[0]) - t.Fatalf("ERROR: Did NOT expect a reponse from the Get()") - } - require.Equal(t, lenBefore-1, l.Len(), "cache length (after getting an expired entry)") - - questionMsg2 := new(dns.Msg) - questionMsg2.SetQuestion("some.other.name", dns.TypeA) - questionMsg2.RecursionDesired = true - question2 := &questionMsg2.Question[0] - - t.Logf("Trying to Get() a name") - resp, err = l.Get(questionMsg2, minUDPSize) - require.NoError(t, err) - require.Nil(t, resp, "reponse from Get() yet") - - t.Logf("Checking that an Remove() between Get() and Put() does not break things") - records = []ZoneRecord{Record{"some.name", net.ParseIP("10.0.9.9"), 0, 0, 0}} - replyTemp2 := makeAddressReply(questionMsg2, question2, records, DefaultLocalTTL) - l.Remove(question2) - l.Put(questionMsg2, replyTemp2, nullTTL, 0) - resp, err = l.Get(questionMsg2, minUDPSize) - require.NoError(t, err) - require.NotNil(t, resp, "reponse from Get()") - - questionMsg3 := new(dns.Msg) - questionMsg3.SetQuestion("some.other.name", dns.TypeA) - questionMsg3.RecursionDesired = true - question3 := &questionMsg3.Question[0] - - t.Logf("Checking that a entry with CacheNoLocalReplies return an error") - l.Put(questionMsg3, nil, DefaultLocalTTL, CacheNoLocalReplies) - resp, err = l.Get(questionMsg3, minUDPSize) - require.Nil(t, resp, "Get() response with CacheNoLocalReplies") - require.True(t, err == errNoLocalReplies, "Get() error with CacheNoLocalReplies") - - t.Logf("Checking that more Put's do not make the negative TTL longer") - clk.Add(time.Duration(DefaultLocalTTL/2) * time.Second) - l.Put(questionMsg3, nil, DefaultLocalTTL, CacheNoLocalReplies) - clk.Add(time.Duration(1) * time.Second) - l.Put(questionMsg3, nil, DefaultLocalTTL, CacheNoLocalReplies) - clk.Add(time.Duration(1) * time.Second) - l.Put(questionMsg3, nil, DefaultLocalTTL, CacheNoLocalReplies) - resp, err = l.Get(questionMsg3, minUDPSize) - require.Nil(t, resp, "Get() response with CacheNoLocalReplies") - require.True(t, err == errNoLocalReplies, "Get() error with CacheNoLocalReplies") - - clk.Add(time.Duration(DefaultLocalTTL/2) * time.Second) - t.Logf("Checking that we get an expired response after %d seconds", DefaultLocalTTL) - clk.Add(time.Second * time.Duration(DefaultLocalTTL+1)) - t.Logf("Checking that we get an expired response after %d seconds", DefaultLocalTTL) - resp, err = l.Get(questionMsg3, minUDPSize) - require.Nil(t, resp, "expired Get() response with CacheNoLocalReplies") - require.Nil(t, err, "expired Get() error with CacheNoLocalReplies") - - l.Remove(question3) - t.Logf("Checking that Put&Get with CacheNoLocalReplies with a Remove in the middle returns nothing") - l.Put(questionMsg3, nil, nullTTL, CacheNoLocalReplies) - l.Remove(question3) - resp, err = l.Get(questionMsg3, minUDPSize) - require.Nil(t, resp, "Get() reponse with CacheNoLocalReplies") - require.Nil(t, err, "Get() error with CacheNoLocalReplies") -} diff --git a/nameserver/dns.go b/nameserver/dns.go deleted file mode 100644 index c232d45b..00000000 --- a/nameserver/dns.go +++ /dev/null @@ -1,117 +0,0 @@ -package nameserver - -import ( - "math/rand" - "time" - - "github.com/miekg/dns" -) - -const ( - minUDPSize = 512 - maxUDPSize = 65535 -) - -func makeHeader(r *dns.Msg, q *dns.Question, ttl int) *dns.RR_Header { - return &dns.RR_Header{ - Name: q.Name, - Rrtype: q.Qtype, - Class: dns.ClassINET, - Ttl: uint32(ttl), - } -} - -func makeReply(r *dns.Msg, as []dns.RR) *dns.Msg { - m := new(dns.Msg) - m.SetReply(r) - m.RecursionAvailable = true - m.Answer = as - return m -} - -func makeTruncatedReply(r *dns.Msg) *dns.Msg { - // for truncated response, we create a minimal reply with the Truncated bit set - reply := new(dns.Msg) - reply.SetReply(r) - reply.Truncated = true - return reply -} - -type DNSResponseBuilder func(r *dns.Msg, q *dns.Question, addrs []ZoneRecord, ttl int) *dns.Msg - -func makeAddressReply(r *dns.Msg, q *dns.Question, addrs []ZoneRecord, ttl int) *dns.Msg { - answers := make([]dns.RR, len(addrs)) - header := makeHeader(r, q, ttl) - count := 0 - for _, addr := range addrs { - ip := addr.IP() - ip4 := ip.To4() - - switch q.Qtype { - case dns.TypeA: - if ip4 != nil { - answers[count] = &dns.A{Hdr: *header, A: ip} - count++ - } - case dns.TypeAAAA: - if ip4 == nil { - answers[count] = &dns.AAAA{Hdr: *header, AAAA: ip} - count++ - } - } - } - return makeReply(r, answers[:count]) -} - -func makePTRReply(r *dns.Msg, q *dns.Question, names []ZoneRecord, ttl int) *dns.Msg { - answers := make([]dns.RR, len(names)) - header := makeHeader(r, q, ttl) - for i, name := range names { - answers[i] = &dns.PTR{Hdr: *header, Ptr: name.Name()} - } - return makeReply(r, answers) -} - -func makeDNSFailResponse(r *dns.Msg) *dns.Msg { - m := new(dns.Msg) - m.SetReply(r) - m.RecursionAvailable = true - m.Rcode = dns.RcodeNameError - return m -} - -// get the maximum UDP-reply length -func getMaxReplyLen(r *dns.Msg, proto dnsProtocol) int { - maxLen := minUDPSize - if proto == protTCP { - maxLen = maxUDPSize - } else if opt := r.IsEdns0(); opt != nil { - maxLen = int(opt.UDPSize()) - } - return maxLen -} - -func init() { - rand.Seed(time.Now().UTC().UnixNano()) -} - -// shuffleAnswers reorders answers for very basic load balancing -func shuffleAnswers(answers []dns.RR) []dns.RR { - if len(answers) > 1 { - for i := range answers { - j := rand.Intn(i + 1) - answers[i], answers[j] = answers[j], answers[i] - } - } - - return answers -} - -// only take the first `num` answers -func pruneAnswers(answers []dns.RR, num int) []dns.RR { - if num > 0 && len(answers) > num { - // TODO: we should have some prefer locally-introduced answers, etc... - return answers[:num] - } - return answers -} diff --git a/nameserver/dns_test.go b/nameserver/dns_test.go deleted file mode 100644 index 3e001e6e..00000000 --- a/nameserver/dns_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package nameserver - -import ( - "net" - "testing" - - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -// Check that we can prune an answer -func TestPrune(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestPrune starting") - - questionMsg := new(dns.Msg) - questionMsg.SetQuestion("name", dns.TypeA) - questionMsg.RecursionDesired = true - question := &questionMsg.Question[0] - records := []ZoneRecord{ - Record{"name", net.ParseIP("10.0.1.1"), 0, 0, 0}, - Record{"name", net.ParseIP("10.0.1.2"), 0, 0, 0}, - Record{"name", net.ParseIP("10.0.1.3"), 0, 0, 0}, - Record{"name", net.ParseIP("10.0.1.4"), 0, 0, 0}, - } - - reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL) - reply.Answer[0].Header().Ttl = DefaultLocalTTL - - pruned := pruneAnswers(reply.Answer, 1) - require.Equal(t, 1, len(pruned), "wrong number of answers") - - pruned = pruneAnswers(reply.Answer, 2) - require.Equal(t, 2, len(pruned), "wrong number of answers") - - pruned = pruneAnswers(reply.Answer, 0) - require.Equal(t, len(records), len(pruned), "wrong number of answers") -} diff --git a/nameserver/http.go b/nameserver/http.go deleted file mode 100644 index 02e1d380..00000000 --- a/nameserver/http.go +++ /dev/null @@ -1,124 +0,0 @@ -package nameserver - -import ( - "fmt" - "net" - "net/http" - - "github.com/gorilla/mux" - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/common/docker" -) - -func httpErrorAndLog(w http.ResponseWriter, msg string, - status int, logmsg string, logargs ...interface{}) { - http.Error(w, msg, status) - Log.Warningf("[http] "+logmsg, logargs...) -} - -func extractFQDN(r *http.Request) (string, string) { - if fqdnStr := r.FormValue("fqdn"); fqdnStr != "" { - return fqdnStr, fqdnStr - } - return "*", "" -} - -func ServeHTTP(listener net.Listener, version string, server *DNSServer, dockerCli *docker.Client) { - - muxRouter := mux.NewRouter() - - muxRouter.Methods("GET").Path("/status").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, "weave DNS", version) - fmt.Fprintln(w, server.Status()) - fmt.Fprintln(w, server.Zone.Status()) - }) - - muxRouter.Methods("GET").Path("/domain").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, server.Zone.Domain()) - }) - - muxRouter.Methods("PUT").Path("/name/{id:.+}/{ip:.+}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reqError := func(msg string, logmsg string, logargs ...interface{}) { - httpErrorAndLog(w, msg, http.StatusBadRequest, logmsg, logargs...) - } - - vars := mux.Vars(r) - idStr := vars["id"] - ipStr := vars["ip"] - name := r.FormValue("fqdn") - - if name == "" { - reqError("Invalid FQDN", "Invalid FQDN in request: %s, %s", r.URL, r.Form) - return - } - - ip := net.ParseIP(ipStr) - if ip == nil { - reqError("Invalid IP", "Invalid IP in request: %s", ipStr) - return - } - - domain := server.Zone.Domain() - if !dns.IsSubDomain(domain, name) { - Log.Infof("[http] Ignoring name %s, not in %s", name, domain) - return - } - Log.Infof("[http] Adding %s -> %s", name, ipStr) - if err := server.Zone.AddRecord(idStr, name, ip); err != nil { - if _, ok := err.(DuplicateError); !ok { - httpErrorAndLog( - w, "Internal error", http.StatusInternalServerError, - "Unexpected error from DB: %s", err) - return - } // oh, I already know this. whatever. - } - - if r.FormValue("check-alive") == "true" && dockerCli != nil && dockerCli.IsContainerNotRunning(idStr) { - Log.Infof("[http] '%s' is not running: removing", idStr) - server.Zone.DeleteRecords(idStr, name, ip) - } - }) - - muxRouter.Methods("DELETE").Path("/name/{id:.+}/{ip:.+}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - idStr := vars["id"] - ipStr := vars["ip"] - - ip := net.ParseIP(ipStr) - if ip == nil { - httpErrorAndLog( - w, "Invalid IP in request", http.StatusBadRequest, - "Invalid IP in request: %s", ipStr) - return - } - - fqdnStr, fqdn := extractFQDN(r) - - Log.Infof("[http] Deleting ID %s, IP %s, FQDN %s", idStr, ipStr, fqdnStr) - server.Zone.DeleteRecords(idStr, fqdn, ip) - }) - - muxRouter.Methods("DELETE").Path("/name/{id:.+}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - idStr := vars["id"] - - fqdnStr, fqdn := extractFQDN(r) - - Log.Infof("[http] Deleting ID %s, IP *, FQDN %s", idStr, fqdnStr) - server.Zone.DeleteRecords(idStr, fqdn, net.IP{}) - }) - - muxRouter.Methods("DELETE").Path("/name").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fqdnStr, fqdn := extractFQDN(r) - - Log.Infof("[http] Deleting ID *, IP *, FQDN %s", fqdnStr) - server.Zone.DeleteRecords("", fqdn, net.IP{}) - }) - - http.Handle("/", muxRouter) - - if err := http.Serve(listener, nil); err != nil { - Log.Fatal("[http] Unable to serve http: ", err) - } -} diff --git a/nameserver/http_test.go b/nameserver/http_test.go deleted file mode 100644 index 18e26b1b..00000000 --- a/nameserver/http_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package nameserver - -import ( - "fmt" - "net" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/stretchr/testify/require" - wt "github.com/weaveworks/weave/testing" -) - -func genForm(method string, url string, data url.Values) (resp *http.Response, err error) { - req, err := http.NewRequest(method, url, strings.NewReader(data.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - return http.DefaultClient.Do(req) -} - -func TestHttp(t *testing.T) { - var ( - containerID = "deadbeef" - testDomain = "weave.local." - successTestName = "test1." + testDomain - testAddr1 = "10.2.2.1/24" - testAddr2 = "10.2.2.2/24" - dockerIP = "9.8.7.6" - ) - - zone, err := NewZoneDb(ZoneConfig{Domain: testDomain}) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - httpListener, err := net.Listen("tcp", ":0") - if err != nil { - t.Fatal("Unable to create http listener: ", err) - } - - // Create a useless server... it will not even be started - srv, _ := NewDNSServer(DNSServerConfig{Zone: zone}) - - port := httpListener.Addr().(*net.TCPAddr).Port - go ServeHTTP(httpListener, "", srv, nil) - - // Ask the http server to add our test address into the database - addrParts := strings.Split(testAddr1, "/") - addrURL := fmt.Sprintf("http://localhost:%d/name/%s/%s", port, containerID, addrParts[0]) - resp, err := genForm("PUT", addrURL, - url.Values{"fqdn": {successTestName}, "local_ip": {dockerIP}, "routing_prefix": {addrParts[1]}}) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http response") - - // Check that the address is now there. - ip, _, _ := net.ParseCIDR(testAddr1) - foundIP, err := zone.LookupName(successTestName) - require.NoError(t, err) - if !foundIP[0].IP().Equal(ip) { - t.Fatalf("Unexpected result for %s: received %s, expected %s", successTestName, foundIP, ip) - } - - // Adding exactly the same address should be OK - resp, err = genForm("PUT", addrURL, - url.Values{"fqdn": {successTestName}, "local_ip": {dockerIP}, "routing_prefix": {addrParts[1]}}) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http success response for duplicate add") - - // Now try adding the same address again with a different ident -- - // again should be fine - otherURL := fmt.Sprintf("http://localhost:%d/name/%s/%s", port, "other", addrParts[0]) - resp, err = genForm("PUT", otherURL, - url.Values{"fqdn": {successTestName}, "local_ip": {dockerIP}, "routing_prefix": {addrParts[1]}}) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http response") - - // Adding a new IP for the same name should be OK - addrParts2 := strings.Split(testAddr2, "/") - addrURL2 := fmt.Sprintf("http://localhost:%d/name/%s/%s", port, containerID, addrParts2[0]) - resp, err = genForm("PUT", addrURL2, - url.Values{"fqdn": {successTestName}, "local_ip": {dockerIP}, "routing_prefix": {addrParts2[1]}}) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http success response for second IP") - - // Check that we can get two IPs for that name - ip2, _, _ := net.ParseCIDR(testAddr2) - foundIP, err = zone.LookupName(successTestName) - require.NoError(t, err) - if len(foundIP) != 2 { - t.Logf("IPs found: %s", foundIP) - t.Fatalf("Unexpected result length: received %d responses", len(foundIP)) - } - if !(foundIP[0].IP().Equal(ip) || foundIP[0].IP().Equal(ip2)) { - t.Logf("IPs found: %s", foundIP) - t.Fatalf("Unexpected result for %s: received %s, expected %s", successTestName, foundIP, ip) - } - if !(foundIP[1].IP().Equal(ip) || foundIP[1].IP().Equal(ip2)) { - t.Logf("IPs found: %s", foundIP) - t.Fatalf("Unexpected result for %s: received %s, expected %s", successTestName, foundIP, ip) - } - - // Delete the address - resp, err = genForm("DELETE", addrURL, nil) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http response") - - // Check that the address is still resolvable. - x, err := zone.LookupName(successTestName) - t.Logf("Got %s", x) - require.NoError(t, err) - - // Delete the address record mentioning the other container - resp, err = genForm("DELETE", otherURL, nil) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http response") - - // Delete the second IP - resp, err = genForm("DELETE", addrURL2, nil) - require.NoError(t, err) - require.Equal(t, http.StatusOK, resp.StatusCode, "http response") - - // Check that the address is gone - x, err = zone.LookupName(successTestName) - t.Logf("Got %s", x) - wt.AssertErrorType(t, (*LookupError)(nil), err, "fully-removed address") - - // Would like to shut down the http server at the end of this test - // but it's complicated. - // See https://groups.google.com/forum/#!topic/golang-nuts/vLHWa5sHnCE -} diff --git a/nameserver/mdns.go b/nameserver/mdns.go deleted file mode 100644 index e476fb4f..00000000 --- a/nameserver/mdns.go +++ /dev/null @@ -1,28 +0,0 @@ -package nameserver - -import "net" - -// A basic mDNS service -type ZoneMDNS interface { - // Start the service - Start(*net.Interface) error - // Stop the service - Stop() error -} - -// A mDNS server -type ZoneMDNSServer interface { - ZoneMDNS - // Return the Zone database used by the server - Zone() Zone -} - -// A mDNS client interface -type ZoneMDNSClient interface { - ZoneMDNS - ZoneLookup - // Perform an insistent lookup for a name - InsistentLookupName(name string) ([]ZoneRecord, error) - // Perform an insistent lookup for a reverse address - InsistentLookupInaddr(inaddr string) ([]ZoneRecord, error) -} diff --git a/nameserver/mdns_client.go b/nameserver/mdns_client.go deleted file mode 100644 index 0be13fbd..00000000 --- a/nameserver/mdns_client.go +++ /dev/null @@ -1,290 +0,0 @@ -package nameserver - -import ( - "bytes" - "fmt" - "math" - "net" - "time" - - "github.com/miekg/dns" -) - -// Portions of this code taken from github.com/armon/mdns - -const ( - ipv4mdns = "224.0.0.251" // link-local multicast address - mdnsPort = 5353 // mDNS assigned port - // We wait this long to hear a response from other mDNS servers on - // the network. - mDNSTimeout = 500 * time.Millisecond - MaxDuration = time.Duration(math.MaxInt64) - MailboxSize = 16 -) - -var ( - ipv4Addr = &net.UDPAddr{ - IP: net.ParseIP(ipv4mdns), - Port: mdnsPort, - } -) - -type Response struct { - name string - addr net.IP - ttl int - err error -} - -func (r Response) Name() string { return r.name } -func (r Response) IP() net.IP { return r.addr } -func (r Response) Priority() int { return 0 } -func (r Response) Weight() int { return 0 } -func (r Response) TTL() int { return r.ttl } - -func (r Response) Equal(r2 *Response) bool { - if r.name != r2.name { - return false - } - if !r.addr.Equal(r2.addr) { - return false - } - if r.err != r2.err { - return false - } - return true -} - -func (r Response) String() string { - var buf bytes.Buffer - if r.err != nil { - fmt.Fprintf(&buf, "%s", r.err) - } else { - if len(r.Name()) > 0 { - fmt.Fprintf(&buf, "%s", r.Name()) - } - if !r.IP().IsUnspecified() { - fmt.Fprintf(&buf, "[%s]", r.IP()) - } - if r.ttl > 0 { - fmt.Fprintf(&buf, "(TTL:%d)", r.TTL()) - } - } - return buf.String() -} - -type responseInfo struct { - timeout time.Time // if no answer by this time, give up - insistent bool // insistent queries are not removed on the first reply - ch chan<- *Response -} - -// Represents one query that we have sent for one name. -// If we, internally, get several requests for the same name while we have -// a query in flight, then we don't want to send more queries out. -// Invariant on responseInfos: they are in ascending order of timeout. -type inflightQuery struct { - name string - id uint16 // the DNS message ID - responseInfos []*responseInfo -} - -type MDNSClient struct { - // note unorthodox use of 'Server' class in client logic - using it to - // listen on a multicast socket and call callback whenever a message comes in. - listener *dns.Server - conn *net.UDPConn - addr *net.UDPAddr - inflight map[string]*inflightQuery - actionChan chan<- MDNSAction -} - -type mDNSQueryInfo struct { - name string - querytype uint16 - responseCh chan<- *Response -} - -func NewMDNSClient() (*MDNSClient, error) { - return &MDNSClient{ - addr: ipv4Addr, - inflight: make(map[string]*inflightQuery)}, nil -} - -func (c *MDNSClient) Start(ifi *net.Interface) (err error) { - if c.conn, err = net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0}); err != nil { - return err - } - - multicast, err := LinkLocalMulticastListener(ifi) - if err != nil { - return err - } - - handleMDNS := func(w dns.ResponseWriter, r *dns.Msg) { - // Don't want to handle queries here, so filter anything out that isn't a response - if len(r.Answer) > 0 { - c.ResponseCallback(r) - } - } - - actionChan := make(chan MDNSAction, MailboxSize) - c.actionChan = actionChan - go c.actorLoop(actionChan) - - c.listener = &dns.Server{Unsafe: true, PacketConn: multicast, Handler: dns.HandlerFunc(handleMDNS)} - go c.listener.ActivateAndServe() - - return nil -} - -func (c *MDNSClient) Stop() error { - c.actionChan <- nil - return nil -} - -func LinkLocalMulticastListener(ifi *net.Interface) (net.PacketConn, error) { - return net.ListenMulticastUDP("udp", ifi, ipv4Addr) -} - -// ACTOR client API - -type MDNSAction func() - -// Async -func (c *MDNSClient) SendQuery(name string, querytype uint16, insistent bool, responseCh chan<- *Response) { - c.actionChan <- func() { - query, found := c.inflight[name] - if !found { - m := new(dns.Msg) - m.SetQuestion(name, querytype) - m.RecursionDesired = false - buf, err := m.Pack() - if err != nil { - responseCh <- &Response{err: err} - close(responseCh) - return - } - query = &inflightQuery{ - name: name, - id: m.Id, - } - if _, err = c.conn.WriteTo(buf, c.addr); err != nil { - responseCh <- &Response{err: err} - close(responseCh) - return - } - c.inflight[name] = query - } - info := &responseInfo{ - ch: responseCh, - timeout: time.Now().Add(mDNSTimeout), - insistent: insistent, - } - // Invariant on responseInfos: they are in ascending order of - // timeout. Since we use a fixed interval from Now(), this - // must be after all existing timeouts. - query.responseInfos = append(query.responseInfos, info) - } -} - -// Async - called from dns library multiplexer -func (c *MDNSClient) ResponseCallback(r *dns.Msg) { - c.actionChan <- func() { - for _, answer := range r.Answer { - var name string - var res *Response - - switch rr := answer.(type) { - case *dns.A: - name = rr.Hdr.Name - res = &Response{name: name, addr: rr.A, ttl: int(rr.Hdr.Ttl)} - case *dns.PTR: - name = rr.Hdr.Name - raddr, _ := raddrToIP(name) - res = &Response{name: rr.Ptr, addr: raddr, ttl: int(rr.Hdr.Ttl)} - default: - return - } - - if query, found := c.inflight[name]; found { - var newResponseInfos []*responseInfo - for _, resp := range query.responseInfos { - resp.ch <- res - // insistent queries are not removed on the first reply, but on the timeout - if resp.insistent { - newResponseInfos = append(newResponseInfos, resp) - } else { - close(resp.ch) - } - } - if len(newResponseInfos) == 0 { - delete(c.inflight, name) - } else { - query.responseInfos = newResponseInfos - } - } else { - // We've received a response that didn't match a query - // Do we want to cache it? - } - } - } -} - -// ACTOR server - -// Check all in-flight queries, close all that have already timed out, -// and return the duration until the next timeout -func (c *MDNSClient) checkInFlightQueries() time.Duration { - now := time.Now() - after := MaxDuration - for name, query := range c.inflight { - // Invariant on responseInfos: they are in ascending order of timeout. - numClosed := 0 - for _, item := range query.responseInfos { - duration := item.timeout.Sub(now) - if duration <= 0 { // timed out - close(item.ch) - numClosed++ - } else { - if duration < after { - after = duration - } - break // don't need to look at any more for this query - } - } - // Remove timed-out items from the slice - query.responseInfos = query.responseInfos[numClosed:] - if len(query.responseInfos) == 0 { - delete(c.inflight, name) - } - } - return after -} - -func (c *MDNSClient) actorLoop(actionChan <-chan MDNSAction) { - timer := time.NewTimer(MaxDuration) - run := func() { timer.Reset(c.checkInFlightQueries()) } -loop: - for { - select { - case action := <-actionChan: - if action == nil { - c.listener.Shutdown() - break loop - } else { - action() - run() - } - case <-timer.C: - run() - } - } - - // Close all response channels at termination - for _, query := range c.inflight { - for _, item := range query.responseInfos { - close(item.ch) - } - } -} diff --git a/nameserver/mdns_client_test.go b/nameserver/mdns_client_test.go deleted file mode 100644 index edeb1bf1..00000000 --- a/nameserver/mdns_client_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package nameserver - -import ( - "log" - "net" - "testing" - "time" - - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" - wt "github.com/weaveworks/weave/testing" -) - -var ( - successTestName = "test1.weave." - failTestName = "test2.weave." - testAddr = net.ParseIP("9.8.7.6") - testInAddr = "6.7.8.9.in-addr.arpa." -) - -func minimalServer(w dns.ResponseWriter, req *dns.Msg) { - - sendAnswer := func(m *dns.Msg) { - buf, err := m.Pack() - CheckFatal(err) - if buf == nil { - log.Fatal("Nil buffer") - } - //log.Println("minimalServer sending:", buf) - // This is a bit of a kludge - per the RFC we should send responses from 5353, but that doesn't seem to work - sendconn, err := net.DialUDP("udp", nil, ipv4Addr) - CheckFatal(err) - - _, err = sendconn.Write(buf) - sendconn.Close() - CheckFatal(err) - } - - //log.Println("minimalServer received:", req) - if len(req.Answer) > 0 { - return // Only interested in questions. - } - if len(req.Question) != 1 { - return // We only handle single-question messages - } - - if req.Question[0].Qtype == dns.TypeA && req.Question[0].Name == successTestName { - m := new(dns.Msg) - m.SetReply(req) - hdr := dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeA, - Class: dns.ClassINET, Ttl: 3600} - a := &dns.A{Hdr: hdr, A: testAddr} - m.Answer = append(m.Answer, a) - sendAnswer(m) - } else if req.Question[0].Qtype == dns.TypePTR && req.Question[0].Name == testInAddr { - m := new(dns.Msg) - m.SetReply(req) - hdr := dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypePTR, - Class: dns.ClassINET, Ttl: 3600} - a := &dns.PTR{Hdr: hdr, Ptr: successTestName} - m.Answer = append(m.Answer, a) - sendAnswer(m) - } -} - -func RunLocalMulticastServer() (*dns.Server, error) { - multicast, err := LinkLocalMulticastListener(nil) - if err != nil { - return nil, err - } - server := &dns.Server{ - PacketConn: multicast, - Handler: dns.HandlerFunc(minimalServer), - ReadTimeout: 100 * time.Millisecond} - go server.ActivateAndServe() - return server, nil -} - -func setup(t *testing.T) (*MDNSClient, *dns.Server, error) { - EnableDebugLogging(testing.Verbose()) - - server, err := RunLocalMulticastServer() - if err != nil { - t.Fatalf("Unable to run test server: %s. No default multicast interface?", err) - } - - mdnsClient, err := NewMDNSClient() - require.NoError(t, err) - err = mdnsClient.Start(nil) - require.NoError(t, err) - - return mdnsClient, server, err -} - -func (c *MDNSClient) Shutdown() { - c.actionChan <- nil -} - -type testContext struct { - receivedAddr net.IP - receivedCount int - channel chan *Response -} - -func newTestContext() *testContext { - return &testContext{channel: make(chan *Response, 4)} -} - -func (c *testContext) checkResponse(t *testing.T, channelOk bool, resp *Response) { - if !channelOk { - c.channel = nil - return - } - require.NoError(t, resp.err) - log.Printf("Got address response %s addr %s", resp.Name(), resp.IP()) - c.receivedAddr = resp.IP() - c.receivedCount++ -} - -func TestSimpleQuery(t *testing.T) { - log.Println("TestSimpleQuery starting") - mdnsClient, server, _ := setup(t) - defer mdnsClient.Shutdown() - defer server.Shutdown() - - context := newTestContext() - - // First, a test we expect to succeed - mdnsClient.SendQuery(successTestName, dns.TypeA, false, context.channel) - for resp := range context.channel { - context.checkResponse(t, true, resp) - } - - if !context.receivedAddr.Equal(testAddr) || context.receivedCount != 1 { - t.Fatal("Unexpected result for", successTestName, context.receivedAddr, context.receivedCount) - } - - // Now, a test we expect to time out with no responses - context = newTestContext() - mdnsClient.SendQuery("test2.weave.", dns.TypeA, false, context.channel) - for resp := range context.channel { - context.checkResponse(t, true, resp) - } - - if context.receivedCount > 0 { - t.Fatal("Unexpected result for test2.weave", context.receivedAddr) - } -} - -func TestParallelQuery(t *testing.T) { - log.Println("TestParallelQuery starting") - mdnsClient, server, _ := setup(t) - defer mdnsClient.Shutdown() - defer server.Shutdown() - - context1 := newTestContext() - context2 := newTestContext() - - go mdnsClient.SendQuery(successTestName, dns.TypeA, false, context1.channel) - go mdnsClient.SendQuery(successTestName, dns.TypeA, false, context2.channel) - timeout := time.After(2 * time.Second) -outerloop: - for context1.channel != nil || context2.channel != nil { - select { - case resp, ok := <-context1.channel: - context1.checkResponse(t, ok, resp) - case resp, ok := <-context2.channel: - context2.checkResponse(t, ok, resp) - case <-timeout: - break outerloop - } - } - - if !context1.receivedAddr.Equal(testAddr) || !context2.receivedAddr.Equal(testAddr) || context1.receivedCount != 1 || context2.receivedCount != 1 { - t.Fatal("Unexpected result for", successTestName, context1.receivedAddr, context2.receivedAddr, context1.receivedCount, context2.receivedCount) - } -} - -func TestAsLookup(t *testing.T) { - mdnsClient, server, _ := setup(t) - defer mdnsClient.Shutdown() - defer server.Shutdown() - - ips, err := mdnsClient.LookupName(successTestName) - require.NoError(t, err) - if !testAddr.Equal(ips[0].IP()) { - t.Fatalf("Returned address incorrect %s", ips) - } - - ips, err = mdnsClient.LookupName("foo.example.com.") - wt.AssertErrorType(t, (*LookupError)(nil), err, "unknown hostname") - - names, err := mdnsClient.LookupInaddr(testInAddr) - require.NoError(t, err) - if !(successTestName == names[0].Name()) { - t.Fatalf("Expected name %s, got %s", successTestName, names) - } -} diff --git a/nameserver/mdns_lookup.go b/nameserver/mdns_lookup.go deleted file mode 100644 index db051bb4..00000000 --- a/nameserver/mdns_lookup.go +++ /dev/null @@ -1,71 +0,0 @@ -package nameserver - -import ( - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" -) - -func mdnsLookup(client *MDNSClient, name string, qtype uint16, insistent bool) ([]ZoneRecord, error) { - var responses []*Response - channel := make(chan *Response) - client.SendQuery(name, qtype, insistent, channel) - - for resp := range channel { - if err := resp.err; err != nil { - Log.Debugf("[mdns] Error for query type %s name %s: %s", dns.TypeToString[qtype], name, err) - return nil, err - } - Log.Debugf("[mdns] Got response name for %s-query about name '%s': name '%s', addr '%s'", - dns.TypeToString[qtype], name, resp.name, resp.addr) - - if !insistent { - return []ZoneRecord{resp}, nil // non-background queries return the first response... - } - - // add the response, avoiding duplicates - // TODO: replace this linear search by something better... (not a big deal as we don't expect long responses) - duplicate := false - for _, r := range responses { - if r.Equal(resp) { - duplicate = true - break - } - } - if !duplicate { - responses = append(responses, resp) - } - } - - if len(responses) == 0 { - return nil, LookupError(name) - } - - // convert []Response to []ZoneRecord - res := make([]ZoneRecord, len(responses)) - for i, rr := range responses { - res[i] = ZoneRecord(rr) - } - return res, nil -} - -// Perform a lookup for a name, returning either an IP address or an error -func (client *MDNSClient) LookupName(name string) ([]ZoneRecord, error) { - return mdnsLookup(client, name, dns.TypeA, false) -} - -// Perform a lookup for an IP address, returning either a name or an error -func (client *MDNSClient) LookupInaddr(inaddr string) ([]ZoneRecord, error) { - return mdnsLookup(client, inaddr, dns.TypePTR, false) -} - -// Perform lookup for a name, returning either a list of IP addresses or an error -// Insistent queries will wait up to `mDNSTimeout` milliseconds for responses -func (client *MDNSClient) InsistentLookupName(name string) ([]ZoneRecord, error) { - return mdnsLookup(client, name, dns.TypeA, true) -} - -// Perform an insistent lookup for an IP address, returning either a list of names or an error -// Insistent queries will wait up to `mDNSTimeout` milliseconds for responses -func (client *MDNSClient) InsistentLookupInaddr(inaddr string) ([]ZoneRecord, error) { - return mdnsLookup(client, inaddr, dns.TypePTR, true) -} diff --git a/nameserver/mdns_server.go b/nameserver/mdns_server.go deleted file mode 100644 index df51f6f8..00000000 --- a/nameserver/mdns_server.go +++ /dev/null @@ -1,148 +0,0 @@ -package nameserver - -import ( - "net" - - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" -) - -type MDNSServer struct { - localAddrs []net.Addr - sendconn *net.UDPConn - srv *dns.Server - zone Zone - allowLocal bool - ttl int -} - -// Create a new mDNS server -// Nothing will be done (including port bindings) until you `Start()` the server -func NewMDNSServer(zone Zone, local bool, ttl int) (*MDNSServer, error) { - return &MDNSServer{ - zone: zone, - allowLocal: local, - ttl: ttl, - }, nil -} - -// Return true if testaddr is a UDP address with IP matching my local i/f -func (s *MDNSServer) addrIsLocal(testaddr net.Addr) bool { - if udpaddr, ok := testaddr.(*net.UDPAddr); ok { - for _, localaddr := range s.localAddrs { - if ipnetlocal, ok := localaddr.(*net.IPNet); ok { - if ipnetlocal.IP.Equal(udpaddr.IP) { - return true - } - } - } - } - return false -} - -// Start the mDNS server -func (s *MDNSServer) Start(ifi *net.Interface) (err error) { - // This is a bit of a kludge - per the RFC we should send responses from 5353, but that doesn't seem to work - s.sendconn, err = net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0}) - if err != nil { - return err - } - - conn, err := LinkLocalMulticastListener(ifi) - if err != nil { - return err - } - - if ifi == nil { - s.localAddrs, err = net.InterfaceAddrs() - } else { - s.localAddrs, err = ifi.Addrs() - } - if err != nil { - return err - } - - handleLocal := s.makeHandler(dns.TypeA, - func(zone ZoneLookup, r *dns.Msg, q *dns.Question) *dns.Msg { - if ips, err := zone.LookupName(q.Name); err == nil { - return makeAddressReply(r, q, ips, s.ttl) - } - return nil - }) - - handleReverse := s.makeHandler(dns.TypePTR, - func(zone ZoneLookup, r *dns.Msg, q *dns.Question) *dns.Msg { - if names, err := zone.LookupInaddr(q.Name); err == nil { - return makePTRReply(r, q, names, s.ttl) - } - return nil - }) - - mux := dns.NewServeMux() - mux.HandleFunc(s.zone.Domain(), handleLocal) - mux.HandleFunc(RDNSDomain, handleReverse) - - s.srv = &dns.Server{ - Listener: nil, - PacketConn: conn, - Handler: mux, - } - go s.srv.ActivateAndServe() - return err -} - -// Stop the mDNS server -func (s *MDNSServer) Stop() error { - return s.srv.Shutdown() -} - -func (s *MDNSServer) Zone() Zone { - return s.zone -} - -type LookupFunc func(ZoneLookup, *dns.Msg, *dns.Question) *dns.Msg - -func (s *MDNSServer) makeHandler(qtype uint16, lookup LookupFunc) dns.HandlerFunc { - return func(rw dns.ResponseWriter, r *dns.Msg) { - // Handle only questions, ignore answers. We might also ignore - // questions that arise locally (i.e., that come from an IP we - // think is local), but in the interest of avoiding - // complication, and easier testing, this is elided on the - // assumption that the client wouldn't ask if it already knew - // the answer, and if it does ask, it'll be happy to get an - // answer. - remoteAddr := rw.RemoteAddr() - if s.addrIsLocal(remoteAddr) && !s.allowLocal { - Log.Debugf("[mdns] srv: mDNS query from local host ('%s'): ignored", remoteAddr) - return - } - - // TODO: use any Answer in the query for adding records in the Zone database... - if len(r.Answer) == 0 && len(r.Question) > 0 { - q := &r.Question[0] - if q.Qtype == qtype { - Log.Debugf("[mdns msgid %d] srv: trying to answer to mDNS query '%s'", r.MsgHdr.Id, q.Name) - if m := lookup(s.zone, r, q); m != nil { - Log.Debugf("[mdns msgid %d] srv: found local answer to mDNS query '%s'", r.MsgHdr.Id, q.Name) - if err := s.sendResponse(m); err != nil { - Log.Warningf("[mdns msgid %d] srv: error writing mDNS response to %v", r.MsgHdr.Id, s.sendconn) - } else { - Log.Debugf("[mdns msgid %d] srv: response sent: %d answers", r.MsgHdr.Id, len(m.Answer)) - } - } else { - Log.Debugf("[mdns msgid %d] srv: no local answer for answering mDNS query '%s'", - r.MsgHdr.Id, q.Name) - } - } - } - } -} - -func (s *MDNSServer) sendResponse(m *dns.Msg) error { - buf, err := m.Pack() - if err != nil { - return err - } - _, err = s.sendconn.WriteTo(buf, ipv4Addr) - return err -} diff --git a/nameserver/mdns_server_test.go b/nameserver/mdns_server_test.go deleted file mode 100644 index 5022af21..00000000 --- a/nameserver/mdns_server_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package nameserver - -import ( - "net" - "testing" - "time" - - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -func TestServerSimpleQuery(t *testing.T) { - var ( - testRecord1 = Record{"test.weave.local.", net.ParseIP("10.20.20.10"), 0, 0, 0} - testRecord2 = Record{"test.weave.local.", net.ParseIP("10.20.20.20"), 0, 0, 0} - testInAddr1 = "10.20.20.10.in-addr.arpa." - ) - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestServerSimpleQuery starting") - - mzone := newMockedZoneWithRecords([]ZoneRecord{testRecord1, testRecord2}) - mdnsServer, err := NewMDNSServer(mzone, true, DefaultLocalTTL) - require.NoError(t, err) - err = mdnsServer.Start(nil) - require.NoError(t, err) - defer mdnsServer.Stop() - - var receivedAddrs []net.IP - receivedName := "" - recvChan := make(chan interface{}) - receivedCount := 0 - - // Implement a minimal listener for responses - multicast, err := LinkLocalMulticastListener(nil) - require.NoError(t, err) - - handleMDNS := func(w dns.ResponseWriter, r *dns.Msg) { - // Only handle responses here - if len(r.Answer) > 0 { - t.Logf("Received %d answer(s)", len(r.Answer)) - for _, answer := range r.Answer { - recvChan <- answer - } - recvChan <- "ok" - } - } - - sendQuery := func(name string, querytype uint16) { - receivedAddrs = make([]net.IP, 0) - receivedName = "" - receivedCount = 0 - - m := new(dns.Msg) - m.SetQuestion(name, querytype) - m.RecursionDesired = false - buf, err := m.Pack() - require.NoError(t, err) - conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0}) - require.NoError(t, err) - Log.Debugf("Sending UDP packet to %s", ipv4Addr) - _, err = conn.WriteTo(buf, ipv4Addr) - require.NoError(t, err) - - Log.Debugf("Waiting for response") - for { - select { - case x := <-recvChan: - switch rr := x.(type) { - case *dns.A: - t.Logf("... A:\n%+v", rr) - receivedAddrs = append(receivedAddrs, rr.A) - receivedCount++ - case *dns.PTR: - t.Logf("... PTR:\n%+v", rr) - receivedName = rr.Ptr - receivedCount++ - case string: - return - } - case <-time.After(100 * time.Millisecond): - Log.Debugf("Timeout while waiting for response") - return - } - } - } - - listener := &dns.Server{ - Unsafe: true, - PacketConn: multicast, - Handler: dns.HandlerFunc(handleMDNS), - ReadTimeout: 100 * time.Millisecond} - go listener.ActivateAndServe() - defer listener.Shutdown() - - time.Sleep(100 * time.Millisecond) // Allow for server to get going - - Log.Debugf("Checking that we get 2 IPs fo name '%s' [A]", testRecord1.Name()) - sendQuery(testRecord1.Name(), dns.TypeA) - if receivedCount != 2 { - t.Fatalf("Unexpected result count %d for %s", receivedCount, testRecord1.Name()) - } - if !(receivedAddrs[0].Equal(testRecord1.IP()) || receivedAddrs[0].Equal(testRecord2.IP())) { - t.Fatalf("Unexpected result %s for %s", receivedAddrs, testRecord1.Name()) - } - if !(receivedAddrs[1].Equal(testRecord1.IP()) || receivedAddrs[1].Equal(testRecord2.IP())) { - t.Fatalf("Unexpected result %s for %s", receivedAddrs, testRecord1.Name()) - } - - Log.Debugf("Checking that 'testfail.weave.' [A] gets no answers") - sendQuery("testfail.weave.", dns.TypeA) - if receivedCount != 0 { - t.Fatalf("Unexpected result count %d for testfail.weave", receivedCount) - } - - Log.Debugf("Checking that '%s' [PTR] gets one name", testInAddr1) - sendQuery(testInAddr1, dns.TypePTR) - if receivedCount != 1 { - t.Fatalf("Expected an answer to %s, got %d answers", testInAddr1, receivedCount) - } else if !(testRecord1.Name() == receivedName) { - t.Fatalf("Expected answer %s to query for %s, got %s", testRecord1.Name(), testInAddr1, receivedName) - } -} diff --git a/nameserver/mdns_test.go b/nameserver/mdns_test.go deleted file mode 100644 index 6acf1ac8..00000000 --- a/nameserver/mdns_test.go +++ /dev/null @@ -1,170 +0,0 @@ -package nameserver - -import ( - "net" - "testing" - "time" - - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -// Check that we can use a regular mDNS server with a regular mDNS client -func TestClientServerSimpleQuery(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - - testRecord1 := Record{"test.weave.local.", net.ParseIP("10.2.2.1"), 0, 0, 0} - testInAddr1 := "1.2.2.10.in-addr.arpa." - - mzone := newMockedZoneWithRecords([]ZoneRecord{testRecord1}) - mdnsServer, err := NewMDNSServer(mzone, true, DefaultLocalTTL) - require.NoError(t, err) - err = mdnsServer.Start(nil) - require.NoError(t, err) - defer mdnsServer.Stop() - - var receivedAddr net.IP - var receivedName string - receivedCount := 0 - - mdnsCli, err := NewMDNSClient() - require.NoError(t, err) - err = mdnsCli.Start(nil) - require.NoError(t, err) - - sendQuery := func(name string, querytype uint16) { - receivedAddr = nil - receivedName = "" - receivedCount = 0 - Log.Debugf("Sending query...") - switch querytype { - case dns.TypeA: - r, err := mdnsCli.LookupName(name) - if len(r) > 0 { - receivedAddr = r[0].IP() - if err == nil { - receivedCount++ - } - } - case dns.TypePTR: - r, err := mdnsCli.LookupInaddr(name) - if len(r) > 0 { - receivedName = r[0].Name() - if err == nil { - receivedCount++ - } - } - } - } - - time.Sleep(100 * time.Millisecond) // Allow for server to get going - - Log.Debugf("Query: %s dns.TypeA", testRecord1.Name()) - sendQuery(testRecord1.Name(), dns.TypeA) - if receivedCount != 1 { - t.Fatalf("Unexpected result count %d for %s", receivedCount, testRecord1.Name()) - } - if !receivedAddr.Equal(testRecord1.IP()) { - t.Fatalf("Unexpected result %s for %s", receivedAddr, testRecord1.Name()) - } - - Log.Debugf("Query: testfail.weave. dns.TypeA") - sendQuery("testfail.weave.", dns.TypeA) - if receivedCount != 0 { - t.Fatalf("Unexpected result count %d for testfail.weave", receivedCount) - } - - Log.Debugf("Query: %s dns.TypePTR", testInAddr1) - sendQuery(testInAddr1, dns.TypePTR) - if receivedCount != 1 { - t.Fatalf("Expected an answer to %s, got %d answers", testInAddr1, receivedCount) - } else if !(testRecord1.Name() == receivedName) { - t.Fatalf("Expected answer %s to query for %s, got %s", testRecord1.Name(), testInAddr1, receivedName) - } -} - -// Check that we can use a use "insistent" queries -func TestClientServerInsistentQuery(t *testing.T) { - EnableDebugLogging(testing.Verbose()) - - testRecord1 := Record{"test.weave.local.", net.ParseIP("10.2.2.1"), 0, 0, 0} - testInAddr1 := "1.2.2.10.in-addr.arpa." - testRecord2 := Record{"test.weave.local.", net.ParseIP("10.2.2.2"), 0, 0, 0} - testInAddr2 := "2.2.2.10.in-addr.arpa." - - mzone1 := newMockedZoneWithRecords([]ZoneRecord{testRecord1}) - mdnsServer1, err := NewMDNSServer(mzone1, true, DefaultLocalTTL) - require.NoError(t, err) - err = mdnsServer1.Start(nil) - require.NoError(t, err) - defer mdnsServer1.Stop() - - mzone2 := newMockedZoneWithRecords([]ZoneRecord{testRecord2}) - mdnsServer2, err := NewMDNSServer(mzone2, true, DefaultLocalTTL) - require.NoError(t, err) - err = mdnsServer2.Start(nil) - require.NoError(t, err) - defer mdnsServer2.Stop() - - // create a third server with exactly the same info as the second server (so we can test duplicates removals) - mdnsServer3, err := NewMDNSServer(mzone2, true, DefaultLocalTTL) - require.NoError(t, err) - err = mdnsServer3.Start(nil) - require.NoError(t, err) - defer mdnsServer3.Stop() - - var receivedAddrs []ZoneRecord - var receivedNames []ZoneRecord - receivedCount := 0 - - mdnsCli, err := NewMDNSClient() - require.NoError(t, err) - err = mdnsCli.Start(nil) - require.NoError(t, err) - - sendQuery := func(name string, querytype uint16) { - receivedAddrs = nil - receivedNames = nil - receivedCount = 0 - Log.Debugf("Sending query...") - switch querytype { - case dns.TypeA: - receivedAddrs, err = mdnsCli.InsistentLookupName(name) - if err == nil { - receivedCount = len(receivedAddrs) - } - case dns.TypePTR: - receivedNames, err = mdnsCli.InsistentLookupInaddr(name) - if err == nil { - receivedCount = len(receivedNames) - } - } - } - - time.Sleep(100 * time.Millisecond) // Allow for server to get going - - Log.Debugf("Query: %s dns.TypeA", testRecord1.Name()) - sendQuery(testRecord1.Name(), dns.TypeA) - if receivedCount != 2 { - t.Fatalf("Unexpected result count %d for %s", receivedCount, testRecord1.Name()) - } - - Log.Debugf("Query: testfail.weave. dns.TypeA") - sendQuery("testfail.weave.", dns.TypeA) - if receivedCount != 0 { - t.Fatalf("Unexpected result count %d for testfail.weave", receivedCount) - } - - Log.Debugf("Query: %s dns.TypePTR", testInAddr1) - sendQuery(testInAddr1, dns.TypePTR) - if receivedCount != 1 { - t.Fatalf("Expected an answer to %s, got %d answers", testInAddr1, receivedCount) - } - - Log.Debugf("Query: %s dns.TypePTR", testInAddr2) - sendQuery(testInAddr2, dns.TypePTR) - if receivedCount != 1 { - t.Fatalf("Expected an answer to %s, got %d answers", testInAddr2, receivedCount) - } -} diff --git a/nameserver/mocks_test.go b/nameserver/mocks_test.go deleted file mode 100644 index 58bb5e04..00000000 --- a/nameserver/mocks_test.go +++ /dev/null @@ -1,507 +0,0 @@ -package nameserver - -import ( - "fmt" - "net" - "strconv" - "sync" - "testing" - "time" - - "github.com/benbjohnson/clock" - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -const ( - testSocketTimeout = 100 // in millisecs -) - -// Warn about some methods that some day should be implemented... -func notImplWarn() { Log.Warningf("Mocked method. Not implemented.") } - -// A mocked Zone that always returns the same records -// * it does not send/receive any mDNS query -type mockedZoneWithRecords struct { - sync.RWMutex - - records []ZoneRecord - - // Statistics - NumLookupsName int - NumLookupsInaddr int -} - -func newMockedZoneWithRecords(zr []ZoneRecord) *mockedZoneWithRecords { - return &mockedZoneWithRecords{records: zr} -} -func (mz *mockedZoneWithRecords) Domain() string { return DefaultLocalDomain } -func (mz *mockedZoneWithRecords) LookupName(name string) ([]ZoneRecord, error) { - Log.Debugf("[mocked zone]: LookupName: returning records %s", mz.records) - mz.Lock() - defer mz.Unlock() - - mz.NumLookupsName++ - var res []ZoneRecord - for _, r := range mz.records { - if r.Name() == name { - res = append(res, r) - } - } - return res, nil -} - -func (mz *mockedZoneWithRecords) LookupInaddr(inaddr string) ([]ZoneRecord, error) { - Log.Debugf("[mocked zone]: LookupInaddr: returning records %s", mz.records) - mz.Lock() - defer mz.Unlock() - - mz.NumLookupsInaddr++ - var res []ZoneRecord - for _, r := range mz.records { - revIP, err := raddrToIP(inaddr) - if err != nil { - return nil, newParseError("lookup address", inaddr) - } - if r.IP().Equal(revIP) { - res = append(res, r) - } - } - return res, nil -} - -func (mz *mockedZoneWithRecords) DomainLookupName(name string) ([]ZoneRecord, error) { - return mz.LookupName(name) -} -func (mz *mockedZoneWithRecords) DomainLookupInaddr(inaddr string) ([]ZoneRecord, error) { - return mz.LookupInaddr(inaddr) -} - -// the following methods are not currently needed... -func (mz *mockedZoneWithRecords) AddRecord(ident string, name string, ip net.IP) error { - notImplWarn() - return nil -} -func (mz *mockedZoneWithRecords) DeleteRecords(ident string, name string, ip net.IP) int { - notImplWarn() - return 0 -} -func (mz *mockedZoneWithRecords) Status() string { notImplWarn(); return "nothing" } -func (mz *mockedZoneWithRecords) ObserveName(name string, observer ZoneRecordObserver) error { - notImplWarn() - return nil -} -func (mz *mockedZoneWithRecords) ObserveInaddr(inaddr string, observer ZoneRecordObserver) error { - notImplWarn() - return nil -} - -////////////////////////////////////////////////////////////////// - -// A mocked mDNS server -type mockedMDNSServer struct { - zone Zone -} - -func newMockedMDNSServer(z Zone) *mockedMDNSServer { return &mockedMDNSServer{zone: z} } -func (ms *mockedMDNSServer) Start(_ *net.Interface) error { return nil } -func (ms *mockedMDNSServer) Stop() error { return nil } -func (ms *mockedMDNSServer) Zone() Zone { return ms.zone } - -// a useful mix of NewMockedZone and NewMockedMDNSServer -func newMockedMDNSServerWithRecord(zr ZoneRecord) *mockedMDNSServer { - return newMockedMDNSServer(newMockedZoneWithRecords([]ZoneRecord{zr})) -} -func newMockedMDNSServerWithRecords(zrs []ZoneRecord) *mockedMDNSServer { - return newMockedMDNSServer(newMockedZoneWithRecords(zrs)) -} - -////////////////////////////////////////////////////////////////// - -// A mocked mDNS client. -// This mock asks a group of (potentially mocked) mDNS servers -type mockedMDNSClient struct { - sync.RWMutex - - servers map[ZoneMDNSServer]ZoneMDNSServer - - // Statistics - NumLookupsName int - NumLookupsInaddr int - NumInsLookupsName int - NumInsLookupsInaddr int -} - -func newMockedMDNSClient(srvrs []*mockedMDNSServer) *mockedMDNSClient { - r := mockedMDNSClient{ - servers: make(map[ZoneMDNSServer]ZoneMDNSServer), - } - if srvrs != nil { - for _, server := range srvrs { - r.servers[server] = server - } - } - return &r -} - -func (mc *mockedMDNSClient) Start(ifi *net.Interface) error { return nil } -func (mc *mockedMDNSClient) Stop() error { return nil } -func (mc *mockedMDNSClient) Domain() string { return DefaultLocalDomain } -func (mc *mockedMDNSClient) LookupName(name string) ([]ZoneRecord, error) { - mc.Lock() - defer mc.Unlock() - - // get a random result - mc.NumLookupsName++ - for _, server := range mc.servers { - r, err := server.Zone().LookupName(name) - if err == nil { - return r, nil // return the first answer - } - } - return nil, LookupError(name) -} - -func (mc *mockedMDNSClient) LookupInaddr(inaddr string) ([]ZoneRecord, error) { - mc.Lock() - defer mc.Unlock() - - // get a random result - mc.NumLookupsInaddr++ - for _, server := range mc.servers { - r, err := server.Zone().LookupInaddr(inaddr) - if err == nil { - return r, nil // return the first answer - } - } - return nil, LookupError(inaddr) -} - -func (mc *mockedMDNSClient) InsistentLookupName(name string) ([]ZoneRecord, error) { - mc.Lock() - defer mc.Unlock() - - var res []ZoneRecord - mc.NumInsLookupsName++ - for _, server := range mc.servers { - r, err := server.Zone().LookupName(name) - if err == nil { - res = append(res, r...) - } - } - if len(res) == 0 { - return nil, LookupError(name) - } - return res, nil -} - -func (mc *mockedMDNSClient) InsistentLookupInaddr(inaddr string) ([]ZoneRecord, error) { - mc.Lock() - defer mc.Unlock() - - var res []ZoneRecord - mc.NumInsLookupsInaddr++ - for _, server := range mc.servers { - r, err := server.Zone().LookupInaddr(inaddr) - if err == nil { - res = append(res, r...) - } - } - if len(res) == 0 { - return nil, LookupError(inaddr) - } - return res, nil -} - -func (mc *mockedMDNSClient) AddServer(srv ZoneMDNSServer) { - mc.Lock() - defer mc.Unlock() - mc.servers[srv] = srv -} - -func (mc *mockedMDNSClient) RemoveServer(srv ZoneMDNSServer) { - mc.Lock() - defer mc.Unlock() - delete(mc.servers, srv) -} - -////////////////////////////////////////////////////////////////// - -type zbmEntry struct { - Server *mockedMDNSServer - Client *mockedMDNSClient - Zone *ZoneDb -} -type zoneDbsWithMockedMDns []*zbmEntry - -// Creates a group of (real) zone databases linked through mocked mDNS servers and clients -// This effectively creates a cluster of WeaveDNS peers -func newZoneDbsWithMockedMDns(num int, config ZoneConfig) zoneDbsWithMockedMDns { - res := make(zoneDbsWithMockedMDns, num) - - for i := 0; i < num; i++ { - res[i] = new(zbmEntry) - - Log.Debugf("[test] Creating mocked mDNS server #%d", i) - res[i].Server = newMockedMDNSServer(nil) - - Log.Debugf("[test] Creating mocked mDNS client #%d", i) - res[i].Client = newMockedMDNSClient([]*mockedMDNSServer{}) - - cfg := config - cfg.MDNSClient = res[i].Client - cfg.MDNSServer = res[i].Server - - Log.Debugf("[test] Creating ZoneDb #%d", i) - res[i].Zone, _ = NewZoneDb(cfg) - - // link the mDNS server to its zone - // ZoneDbs are connected to mDNS in two directions: they use their mDNS - // clients for asking other peers about names/IPs, and export their records - // through a mDNS server. - res[i].Server.zone = res[i].Zone - } - - // link all the clients to all the servers - for i := 0; i < num; i++ { - for j := 0; j < num; j++ { - // with this check, the local client will not ask to the local server - // this is not what we currently do, but can be convenient in some cases - // for finding some bugs... - if i != j { - Log.Debugf("[test] Linking mocked mDNS client #%d to server #%d", i, j) - res[i].Client.AddServer(res[j].Server) - } - } - } - - return res -} - -func (zbs zoneDbsWithMockedMDns) Start() { - for _, entry := range zbs { - entry.Zone.Start() - } -} - -func (zbs zoneDbsWithMockedMDns) Stop() { - for _, entry := range zbs { - entry.Zone.Stop() - } -} - -func (zbs zoneDbsWithMockedMDns) Flush() { - for _, entry := range zbs { - entry.Zone.refreshScheds.Flush() - } -} - -////////////////////////////////////////////////////////////////// - -// A mocked cache where we never find a single thing... ;) -type mockedCache struct { - NumGets int - NumPuts int - NumRemovals int -} - -func newMockedCache() *mockedCache { return &mockedCache{} } - -func (c *mockedCache) Get(request *dns.Msg, maxLen int) (reply *dns.Msg, err error) { - c.NumGets++ - return nil, nil -} -func (c *mockedCache) Put(request *dns.Msg, reply *dns.Msg, ttl int, flags uint8) int { - c.NumPuts++ - return 0 -} -func (c *mockedCache) Remove(question *dns.Question) { c.NumRemovals++ } -func (c *mockedCache) Purge() {} -func (c *mockedCache) Clear() {} -func (c *mockedCache) Len() int { return 0 } -func (c *mockedCache) Capacity() int { return DefaultCacheLen } - -////////////////////////////////////////////////////////////////// - -// A mocked fallback server -type mockedFallback struct { - CliConfig *dns.ClientConfig - Addr string - Port int - - udpSrv *dns.Server - tcpSrv *dns.Server -} - -// Create a mocked fallback server -// You can use the server's `CliConfig` as the `UpstreamCfg` of a `DNSServer`... -func newMockedFallback(udpH dns.HandlerFunc, tcpH dns.HandlerFunc) (*mockedFallback, error) { - udpSrv, fallbackAddr, err := runLocalUDPServer("127.0.0.1:0", udpH) - if err != nil { - return nil, err - } - _, fallbackPort, err := net.SplitHostPort(fallbackAddr) - if err != nil { - return nil, err - } - - fallbackPortI, _ := strconv.Atoi(fallbackPort) - - res := mockedFallback{ - udpSrv: udpSrv, - Addr: fallbackAddr, - Port: fallbackPortI, - CliConfig: &dns.ClientConfig{ - Servers: []string{"127.0.0.1"}, - Port: fallbackPort, - }, - } - - if tcpH != nil { - fallbackTCPAddr := fmt.Sprintf("127.0.0.1:%s", fallbackPort) - res.tcpSrv, _, err = runLocalTCPServer(fallbackTCPAddr, tcpH) - if err != nil { - return nil, err - } - } - - return &res, nil -} - -// Start the fallback server -func (mf *mockedFallback) Start() error { - return nil -} - -// Stop the fallback server -func (mf *mockedFallback) Stop() error { - if mf.tcpSrv != nil { - mf.udpSrv.Shutdown() - mf.udpSrv = nil - } - if mf.tcpSrv != nil { - mf.tcpSrv.Shutdown() - mf.udpSrv = nil - } - return nil -} - -// Run a UDP fallback server -func runLocalUDPServer(laddr string, handler dns.HandlerFunc) (*dns.Server, string, error) { - Log.Debugf("[mocked fallback] Starting fallback UDP server at %s", laddr) - pc, err := net.ListenPacket("udp", laddr) - if err != nil { - return nil, "", err - } - server := &dns.Server{PacketConn: pc, Handler: handler, ReadTimeout: testSocketTimeout * time.Millisecond} - - go func() { - server.ActivateAndServe() - pc.Close() - }() - - Log.Debugf("[mocked fallback] Fallback UDP server listening at %s", pc.LocalAddr()) - return server, pc.LocalAddr().String(), nil -} - -// Run a TCP fallback server -func runLocalTCPServer(laddr string, handler dns.HandlerFunc) (*dns.Server, string, error) { - Log.Debugf("[mocked fallback] Starting fallback TCP server at %s", laddr) - laddrTCP, err := net.ResolveTCPAddr("tcp", laddr) - if err != nil { - return nil, "", err - } - - l, err := net.ListenTCP("tcp", laddrTCP) - if err != nil { - return nil, "", err - } - server := &dns.Server{Listener: l, Handler: handler, ReadTimeout: testSocketTimeout * time.Millisecond} - - go func() { - server.ActivateAndServe() - l.Close() - }() - - Log.Debugf("[mocked fallback] Fallback TCP server listening at %s", l.Addr().String()) - return server, l.Addr().String(), nil -} - -////////////////////////////////////////////////////////////////// - -type mockedClock struct { - *clock.Mock -} - -func newMockedClock() *mockedClock { - return &mockedClock{clock.NewMock()} -} - -// Note: moving the clock forward does not take into account the data that could -// be waiting in channels. So your code should not depend on the channels -// for creating new timers. Otherwise, time travelling will not be reliable... -func (clk *mockedClock) Forward(secs int) { - Log.Debugf(">>>>>>> Moving clock forward %d seconds - Time traveling >>>>>>>", secs) - clk.Add(time.Duration(secs) * time.Second) - Log.Debugf("<<<<<<< Time travel finished! We are at %s <<<<<<<", clk.Now()) -} - -////////////////////////////////////////////////////////////////// - -// Perform a DNS query and assert the reply code, number or answers, etc -func assertExchange(t *testing.T, z string, ty uint16, port int, minAnswers int, maxAnswers int, expErr int) (*dns.Msg, *dns.Msg) { - require.NotEqual(t, 0, port, "invalid DNS server port") - - c := &dns.Client{ - UDPSize: testUDPBufSize, - } - - m := new(dns.Msg) - m.RecursionDesired = true - m.SetQuestion(z, ty) - m.SetEdns0(testUDPBufSize, false) // we don't want to play with truncation here... - - lstAddr := fmt.Sprintf("127.0.0.1:%d", port) - r, _, err := c.Exchange(m, lstAddr) - t.Logf("Response from '%s':\n%+v\n", lstAddr, r) - if err != nil { - t.Errorf("Error when querying DNS server at %s: %s", lstAddr, err) - } - require.NoError(t, err) - if minAnswers == 0 && maxAnswers == 0 { - require.Equal(t, expErr, r.Rcode, "DNS response code") - } else { - require.Equal(t, dns.RcodeSuccess, r.Rcode, "DNS response code") - } - answers := len(r.Answer) - if minAnswers >= 0 && answers < minAnswers { - require.FailNow(t, fmt.Sprintf("Number of answers >= %d", minAnswers)) - } - if maxAnswers >= 0 && answers > maxAnswers { - require.FailNow(t, fmt.Sprintf("Number of answers <= %d", maxAnswers)) - } - return m, r -} - -// Assert that we have a response in the cache for a query `q` -func assertInCache(t *testing.T, cache ZoneCache, q *dns.Msg, desc string) { - r, err := cache.Get(q, maxUDPSize) - require.NoError(t, err) - require.NotNil(t, r, fmt.Sprintf("value in the cache: %s", desc)) -} - -// Assert that we have a response in the cache for a query `q` -func assertNotLocalInCache(t *testing.T, cache ZoneCache, q *dns.Msg, desc string) { - r, err := cache.Get(q, maxUDPSize) - if !(r == nil && err == errNoLocalReplies) { - t.Fatalf("Cache does not return a noLocalReplies error for query %s", q) - } -} - -// Assert that we do not have a response in the cache for a query `q` -func assertNotInCache(t *testing.T, cache ZoneCache, q *dns.Msg, desc string) { - r, err := cache.Get(q, maxUDPSize) - require.NoError(t, err) - require.Nil(t, r, fmt.Sprintf("value in the cache: %s\n%s", desc, r)) -} diff --git a/nameserver/server.go b/nameserver/server.go deleted file mode 100644 index 6f36aaf4..00000000 --- a/nameserver/server.go +++ /dev/null @@ -1,414 +0,0 @@ -package nameserver - -import ( - "bytes" - "fmt" - "net" - "strconv" - "sync" - "time" - - "github.com/benbjohnson/clock" - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" -) - -const ( - DefaultServerPort = 53 // The default server port - DefaultHTTPPort = 6785 // The default http port - DefaultCLICfgFile = "/etc/resolv.conf" // default "resolv.conf" file to try to load - DefaultLocalTTL = 30 // default TTL for responses for local domain queries - DefaultUDPBuflen = 4096 // bigger than the default 512 - DefaultCacheLen = 8192 // default cache capacity - DefaultTimeout = 5000 // default timeout for DNS resolutions (millisecs) - DefaultMaxAnswers = 1 // default number of answers provided to users -) - -type DNSServerConfig struct { - // The zone - Zone Zone - // (Optional) client config file for resolving upstream servers - UpstreamCfgFile string - // (Optional) DNS client config for the fallback server(s) - UpstreamCfg *dns.ClientConfig - // (Optional) port number (for TCP and UDP) - Port int - // (Optional) cache size - CacheLen int - // (Optional) disable the cache - CacheDisabled bool - // (Optional) timeout for DNS queries - Timeout int - // (Optional) UDP buffer length - UDPBufLen int - // (Optional) force a specific cache - Cache ZoneCache - // (Optional) TTL for local domain responses - LocalTTL int - // (Optional) TTL for negative results in the local domain (defaults to LocalTTL) - CacheNegLocalTTL int - // (Optional) for a specific clock provider - Clock clock.Clock - // (Optional) Listening socket read timeout (in milliseconds) - ListenReadTimeout int - // Maximum number of answers provided to users - MaxAnswers int -} - -type dnsProtocol uint8 - -const ( - protUDP dnsProtocol = iota // UDP protocol - protTCP dnsProtocol = iota // TCP protocol -) - -func (proto dnsProtocol) String() string { - switch proto { - case protUDP: - return "UDP" - case protTCP: - return "TCP" - } - return "unknown" -} - -// get a new dns.Client for a protocol -func (proto dnsProtocol) GetNewClient(bufsize int, timeout time.Duration) *dns.Client { - Log.Debugf("[dns] Creating %s DNS client with %s timeout", proto, timeout) - switch proto { - case protTCP: - return &dns.Client{Net: "tcp", ReadTimeout: timeout} - case protUDP: - return &dns.Client{Net: "udp", ReadTimeout: timeout, UDPSize: uint16(bufsize)} - } - return nil -} - -// a DNS server -type DNSServer struct { - Zone Zone - Upstream *dns.ClientConfig - Domain string // the local domain - ListenAddr string // the address the server is listening at - - udpSrv *dns.Server - tcpSrv *dns.Server - pc net.PacketConn - lst net.Listener - cache ZoneCache - cacheDisabled bool - maxAnswers int - localTTL int - negLocalTTL int - timeout time.Duration - readTimeout time.Duration - udpBuf int - listenersWg *sync.WaitGroup - clock clock.Clock -} - -// Creates a new DNS server -func NewDNSServer(config DNSServerConfig) (s *DNSServer, err error) { - s = &DNSServer{ - Zone: config.Zone, - Domain: DefaultLocalDomain, - ListenAddr: fmt.Sprintf(":%d", config.Port), - - listenersWg: new(sync.WaitGroup), - timeout: DefaultTimeout * time.Millisecond, - readTimeout: DefaultTimeout * time.Millisecond, - cacheDisabled: false, - maxAnswers: DefaultMaxAnswers, - localTTL: DefaultLocalTTL, - clock: config.Clock, - } - - // check some basic parameters are valid - if s.Zone == nil { - return nil, fmt.Errorf("No valid Zone provided in server initialization") - } - if len(s.Domain) == 0 { - return nil, fmt.Errorf("No valid Domain provided in server initialization") - } - if s.clock == nil { - s.clock = clock.New() - } - - // fill empty parameters with defaults... - if config.UpstreamCfg != nil { - s.Upstream = config.UpstreamCfg - } else { - cfgFile := DefaultCLICfgFile - if len(config.UpstreamCfgFile) > 0 { - cfgFile = config.UpstreamCfgFile - } - if s.Upstream, err = dns.ClientConfigFromFile(cfgFile); err != nil { - return nil, err - } - } - if config.Timeout > 0 { - s.timeout = time.Duration(config.Timeout) * time.Millisecond - } - if config.ListenReadTimeout > 0 { - s.readTimeout = time.Duration(config.ListenReadTimeout) * time.Millisecond - } - if config.UDPBufLen > 0 { - s.udpBuf = config.UDPBufLen - } - if config.MaxAnswers > 0 { - s.maxAnswers = config.MaxAnswers - } - if config.LocalTTL > 0 { - s.localTTL = config.LocalTTL - } - if config.CacheNegLocalTTL > 0 { - s.negLocalTTL = config.CacheNegLocalTTL - } else { - s.negLocalTTL = s.localTTL - } - if config.CacheDisabled { - s.cacheDisabled = true - } - if !s.cacheDisabled { - if config.Cache != nil { - s.cache = config.Cache - } else { - cacheLen := DefaultCacheLen - if config.CacheLen > 0 { - cacheLen = config.CacheLen - } - if s.cache, err = NewCache(cacheLen, s.clock); err != nil { - return - } - } - } - - return -} - -// Start the DNS server -func (s *DNSServer) Start() error { - Log.Infof("[dns] Upstream server(s): %+v", s.Upstream) - if s.cacheDisabled { - Log.Infof("[dns] Cache: disabled") - } else { - Log.Infof("[dns] Cache: %d entries", s.cache.Capacity()) - } - - pc, err := net.ListenPacket("udp", s.ListenAddr) - if err != nil { - return err - } - s.pc = pc - - _, port, err := net.SplitHostPort(pc.LocalAddr().String()) - if err != nil { - return err - } - s.ListenAddr = fmt.Sprintf(":%s", port) - s.udpSrv = &dns.Server{PacketConn: s.pc, Handler: s.createMux(protUDP), ReadTimeout: s.readTimeout} - - // Bind the TCP socket at the same port, aborting otherwise - l, err := net.Listen("tcp", s.ListenAddr) - if err != nil { - s.Stop() - return err - } - s.lst = l - s.tcpSrv = &dns.Server{Listener: l, Handler: s.createMux(protTCP), ReadTimeout: s.readTimeout} - - s.listenersWg.Add(2) - return nil -} - -func (s *DNSServer) ActivateAndServe() { - go func() { - defer s.listenersWg.Done() - - Log.Infof("[dns] Listening for DNS on %s (UDP)", s.ListenAddr) - err := s.udpSrv.ActivateAndServe() - CheckFatal(err) - Log.Debugf("[dns] DNS UDP server exiting...") - }() - - go func() { - defer s.listenersWg.Done() - - Log.Infof("[dns] Listening for DNS on %s (TCP)", s.ListenAddr) - err := s.tcpSrv.ActivateAndServe() - CheckFatal(err) - Log.Debugf("[dns] DNS TCP server exiting...") - }() - - // Waiting for all goroutines to finish (otherwise they die as main routine dies) - s.listenersWg.Wait() - - Log.Infof("[dns] Server exiting...") -} - -// Return status string -func (s *DNSServer) Status() string { - var buf bytes.Buffer - fmt.Fprintln(&buf, "Listen address", s.ListenAddr) - fmt.Fprintln(&buf, "Fallback DNS config", s.Upstream) - return buf.String() -} - -// Perform a graceful shutdown -func (s *DNSServer) Stop() error { - // Stop the listeners/handlers - if s.tcpSrv != nil { - if err := s.tcpSrv.Shutdown(); err != nil { - return err - } - s.lst.Close() - s.tcpSrv = nil - } - if s.udpSrv != nil { - if err := s.udpSrv.Shutdown(); err != nil { - return err - } - s.pc.Close() - s.udpSrv = nil - } - s.listenersWg.Wait() - return nil -} - -// Create a multiplexer for requests -// We must create two DNS request multiplexers, depending on the protocol used by -// clients (as we use the same protocol for asking upstream servers) -func (s *DNSServer) createMux(proto dnsProtocol) *dns.ServeMux { - failFallback := func(w dns.ResponseWriter, r *dns.Msg) { - w.WriteMsg(makeDNSFailResponse(r)) - } - notUsHandler := s.notUsHandler(proto) - notUsFallback := func(w dns.ResponseWriter, r *dns.Msg) { - Log.Infof("[dns msgid %d] -> sending to fallback server", r.MsgHdr.Id) - notUsHandler(w, r) - } - - // create the multiplexer - m := dns.NewServeMux() - m.HandleFunc(s.Zone.Domain(), s.localHandler(proto, "Query", dns.TypeA, - s.Zone.DomainLookupName, makeAddressReply, s.Zone.ObserveName, failFallback)) - m.HandleFunc(RDNSDomain, s.localHandler(proto, "Reverse query", dns.TypePTR, - s.Zone.DomainLookupInaddr, makePTRReply, s.Zone.ObserveInaddr, notUsFallback)) - m.HandleFunc(".", s.notUsHandler(proto)) - return m -} - -// Process a request for a name/address in the '.weave.local.' zone -func (s *DNSServer) localHandler(proto dnsProtocol, kind string, qtype uint16, - lookup func(inaddr string) ([]ZoneRecord, error), - msgBuilder DNSResponseBuilder, observer ZoneObserverFunc, fallback dns.HandlerFunc) dns.HandlerFunc { - - return func(w dns.ResponseWriter, r *dns.Msg) { - q := r.Question[0] - Log.Debugf("[dns msgid %d] %s: %+v", r.MsgHdr.Id, kind, q) - maxLen := getMaxReplyLen(r, proto) - - // cache a response if the cache is enabled, and observe the name/IP - maybeCache := func(m *dns.Msg, ttl int, flags uint8) { - if !s.cacheDisabled { - s.cache.Put(r, m, ttl, flags) - // any change in the Zone database for this IP/name will lead to this - // cache entry being removed... - // TODO: this closure results in unnecessary `Remove`s and some wasted - // mem... but we can live with that. - observer(q.Name, func() { s.cache.Remove(&q) }) - } - } - - if !s.cacheDisabled { - reply, err := s.cache.Get(r, maxLen) - if err != nil { - if err == errNoLocalReplies { - Log.Debugf("[dns msgid %d] Cached no-local-replies", r.MsgHdr.Id) - fallback(w, r) - } else { - Log.Debugf("[dns msgid %d] Error from cache: %s", r.MsgHdr.Id, err) - w.WriteMsg(makeDNSFailResponse(r)) - } - return - } - if reply != nil { - reply.Answer = pruneAnswers(shuffleAnswers(reply.Answer), s.maxAnswers) - Log.Debugf("[dns msgid %d] Returning reply from cache: %s/%d answers", - r.MsgHdr.Id, dns.RcodeToString[reply.MsgHdr.Rcode], len(reply.Answer)) - w.WriteMsg(reply) - return - } - } - - // catch unsupported queries - if q.Qtype != qtype { - Log.Debugf("[dns msgid %d] Unsupported query type %s", r.MsgHdr.Id, dns.TypeToString[q.Qtype]) - m := makeDNSFailResponse(r) - maybeCache(m, s.negLocalTTL, 0) - w.WriteMsg(m) - return - } - - if answers, err := lookup(q.Name); err != nil { - Log.Infof("[dns msgid %d] No results for type %s query for '%s' [caching no-local]", - r.MsgHdr.Id, dns.TypeToString[q.Qtype], q.Name) - - maybeCache(nil, s.negLocalTTL, CacheNoLocalReplies) - fallback(w, r) - } else { - m := msgBuilder(r, &q, answers, s.localTTL) - m.Authoritative = true - maybeCache(m, nullTTL, 0) - m.Answer = pruneAnswers(shuffleAnswers(m.Answer), s.maxAnswers) - Log.Debugf("[dns msgid %d] Sending response: %s/%d answers [code:%s]", - m.MsgHdr.Id, dns.TypeToString[q.Qtype], len(m.Answer), dns.RcodeToString[m.Rcode]) - w.WriteMsg(m) - } - } -} - -// When we receive a request for a name outside of our '.weave.local.' -// domain, ask the configured DNS server as a fallback. -func (s *DNSServer) notUsHandler(proto dnsProtocol) dns.HandlerFunc { - dnsClient := proto.GetNewClient(DefaultUDPBuflen, s.timeout) - - return func(w dns.ResponseWriter, r *dns.Msg) { - q := r.Question[0] - - // announce our max payload size as the max payload our client supports - maxLen := getMaxReplyLen(r, proto) - rcopy := r - rcopy.SetEdns0(uint16(maxLen), false) - - Log.Debugf("[dns msgid %d] Fallback query: %+v [%s, max:%d bytes]", rcopy.MsgHdr.Id, q, proto, maxLen) - for _, server := range s.Upstream.Servers { - reply, _, err := dnsClient.Exchange(rcopy, fmt.Sprintf("%s:%s", server, s.Upstream.Port)) - if err != nil { - Log.Debugf("[dns msgid %d] Network error trying %s (%s)", - r.MsgHdr.Id, server, err) - continue - } - if reply != nil && reply.Rcode != dns.RcodeSuccess { - Log.Debugf("[dns msgid %d] Failure reported by %s for query %s", - r.MsgHdr.Id, server, q.Name) - continue - } - Log.Debugf("[dns msgid %d] Given answer by %s for query %s", - r.MsgHdr.Id, server, q.Name) - w.WriteMsg(reply) - return - } - Log.Warningf("[dns msgid %d] Failed lookup for external name %s", r.MsgHdr.Id, q.Name) - w.WriteMsg(makeDNSFailResponse(r)) - } -} - -// Get the listen port -func (s *DNSServer) GetPort() (int, error) { - _, portS, err := net.SplitHostPort(s.ListenAddr) - if err != nil { - return 0, err - } - return strconv.Atoi(portS) -} diff --git a/nameserver/server_cache_test.go b/nameserver/server_cache_test.go deleted file mode 100644 index 394710d6..00000000 --- a/nameserver/server_cache_test.go +++ /dev/null @@ -1,351 +0,0 @@ -package nameserver - -import ( - "fmt" - "net" - "testing" - "time" - - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -// Check that AddRecord/DeleteRecord/... in the Zone database lead to cache invalidations -func TestServerDbCacheInvalidation(t *testing.T) { - const ( - containerID = "somecontainer" - testName1 = "first.weave.local." - testName2 = "second.weave.local." - ) - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestServerDbCacheInvalidation starting") - - clk := newMockedClock() - - Log.Debugf("Creating mocked mDNS client and server") - mdnsServer1 := newMockedMDNSServerWithRecord(Record{testName1, net.ParseIP("10.2.2.9"), 0, 0, 0}) - mdnsCli1 := newMockedMDNSClient([]*mockedMDNSServer{mdnsServer1}) - - Log.Debugf("Creating zone database with the mocked mDNS client and server") - zoneConfig := ZoneConfig{ - MDNSServer: mdnsServer1, - MDNSClient: mdnsCli1, - Clock: clk, - } - zone, err := NewZoneDb(zoneConfig) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - Log.Debugf("Creating a cache") - cache, err := NewCache(1024, clk) - require.NoError(t, err) - - fallbackHandler := func(w dns.ResponseWriter, req *dns.Msg) { - m := new(dns.Msg) - m.SetReply(req) - if len(req.Question) == 1 { - m.Rcode = dns.RcodeNameError - } - w.WriteMsg(m) - } - - // Run another DNS server for fallback - fallback, err := newMockedFallback(fallbackHandler, nil) - require.NoError(t, err) - fallback.Start() - defer fallback.Stop() - - Log.Debugf("Creating a real DNS server with a mocked cache") - srv, err := NewDNSServer(DNSServerConfig{ - Zone: zone, - Cache: cache, - Clock: clk, - ListenReadTimeout: testSocketTimeout, - UpstreamCfg: fallback.CliConfig, - MaxAnswers: 4, - }) - require.NoError(t, err) - err = srv.Start() - require.NoError(t, err) - go srv.ActivateAndServe() - defer srv.Stop() - time.Sleep(100 * time.Millisecond) // Allow server goroutine to start - - testPort, err := srv.GetPort() - require.NoError(t, err) - require.NotEqual(t, 0, testPort, "invalid listen port") - - Log.Debugf("Adding two IPs to %s", testName1) - zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.1")) - zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.2")) - q, _ := assertExchange(t, testName1, dns.TypeA, testPort, 2, 2, 0) - assertInCache(t, cache, q, fmt.Sprintf("after asking for %s", testName1)) - - // Zone database at this point: - // first.weave.local = 10.2.2.1 10.2.2.2 - - zone.AddRecord(containerID, testName2, net.ParseIP("10.9.9.1")) - assertInCache(t, cache, q, fmt.Sprintf("after adding a new IP for %s", testName2)) - - // we should have an entry in the cache for this query - // if we add another IP, that cache entry should be removed - Log.Debugf("Adding a new IP to %s: the cache entry should be removed", testName1) - zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.3")) - assertNotInCache(t, cache, q, fmt.Sprintf("after adding a new IP for %s", testName1)) - - // Zone database at this point: - // first.weave.local = 10.2.2.1 10.2.2.2 10.2.2.3 - // second.weave.local = 10.9.9.1 - - Log.Debugf("Querying again (so a cache entry will be created)") - q, _ = assertExchange(t, testName1, dns.TypeA, testPort, 3, 4, 0) - assertInCache(t, cache, q, "after asking about the name") - Log.Debugf("... and removing one of the IP addresses") - zone.DeleteRecords(containerID, "", net.ParseIP("10.2.2.2")) - assertNotInCache(t, cache, q, "after deleting IP for 10.2.2.2") - - // Zone database at this point: - // first.weave.local = 10.2.2.1 10.2.2.3 - // second.weave.local = 10.9.9.1 - - // generate cache responses - Log.Debugf("Querying for a raddr") - qname, _ := assertExchange(t, testName1, dns.TypeA, testPort, 2, 2, 0) - qptr, _ := assertExchange(t, "1.2.2.10.in-addr.arpa.", dns.TypePTR, testPort, 1, 1, 0) - qotherName, _ := assertExchange(t, testName2, dns.TypeA, testPort, 1, 1, 0) - qotherPtr, _ := assertExchange(t, "1.9.9.10.in-addr.arpa.", dns.TypePTR, testPort, 1, 1, 0) - qwrongName, _ := assertExchange(t, "wrong.weave.local.", dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - assertInCache(t, cache, qname, "after asking for name") - assertInCache(t, cache, qptr, "after asking for address") - assertInCache(t, cache, qotherName, "after asking for second name") - assertInCache(t, cache, qotherPtr, "after asking for second address") - assertNotLocalInCache(t, cache, qwrongName, "after asking for a wrong name") - - // now we will check if a removal affects all the responses - Log.Debugf("... and removing an IP should invalidate both the cached responses for name and raddr") - zone.DeleteRecords(containerID, "", net.ParseIP("10.2.2.1")) - assertNotInCache(t, cache, qptr, "after deleting record") - assertNotInCache(t, cache, qname, "after deleting record") - assertInCache(t, cache, qotherName, "after deleting record") - - // Zone database at this point: - // first.weave.local = 10.2.2.3 - // second.weave.local = 10.9.9.1 - - // generate cache responses - Log.Debugf("Querying for a raddr") - qptr, _ = assertExchange(t, "3.2.2.10.in-addr.arpa.", dns.TypePTR, testPort, 1, 1, 0) - qname, _ = assertExchange(t, testName1, dns.TypeA, testPort, 1, 1, 0) - qotherName, _ = assertExchange(t, testName2, dns.TypeA, testPort, 1, 1, 0) - qotherPtr, _ = assertExchange(t, "1.9.9.10.in-addr.arpa.", dns.TypePTR, testPort, 1, 1, 0) - assertInCache(t, cache, qname, "after asking for name") - assertInCache(t, cache, qptr, "after asking for PTR") - assertInCache(t, cache, qotherName, "after asking for second name") - assertInCache(t, cache, qotherPtr, "after asking for second address") - - // let's repeat this, but adding an IP - Log.Debugf("... and adding a new IP should invalidate both the cached responses for the name") - zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.7")) - assertNotInCache(t, cache, qname, "after adding a new IP") - assertInCache(t, cache, qotherName, "after adding a new IP") - assertInCache(t, cache, qotherPtr, "after adding a new IP") - - // check that after some time, the cache entry is expired - clk.Forward(int(DefaultLocalTTL) + 1) - assertNotInCache(t, cache, qotherName, "after passing some time") - assertNotInCache(t, cache, qwrongName, "after passing some time") - - // Zone database at this point: - // first.weave.local = 10.2.2.3 10.2.2.7 - // second.weave.local = 10.9.9.1 - - zone.DeleteRecords(containerID, "", net.IP{}) - assertNotInCache(t, cache, qotherName, "after removing container") - assertNotInCache(t, cache, qotherPtr, "after removing container") -} - -// Check if the entries in the cache expire -func TestServerCacheExpiration(t *testing.T) { - const ( - containerID = "somecontainer" - testName1 = "first.weave.local." - testName2 = "second.weave.local." - negativeLocalTTL = 10 - ) - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestServerCacheExpiration starting") - - clk := newMockedClock() - - Log.Debugf("Creating 2 zone databases") - zoneConfig := ZoneConfig{ - RefreshInterval: 0, // no name updates - Clock: clk, - } - dbs := newZoneDbsWithMockedMDns(2, zoneConfig) - dbs.Start() - defer dbs.Stop() - - Log.Debugf("Creating a cache") - cache, err := NewCache(1024, clk) - require.NoError(t, err) - - Log.Debugf("Creating a real DNS server for the first zone database and with the cache") - srv, err := NewDNSServer(DNSServerConfig{ - Zone: dbs[0].Zone, - Cache: cache, - Clock: clk, - ListenReadTimeout: testSocketTimeout, - CacheNegLocalTTL: negativeLocalTTL, - }) - require.NoError(t, err) - err = srv.Start() - require.NoError(t, err) - go srv.ActivateAndServe() - defer srv.Stop() - time.Sleep(100 * time.Millisecond) // Allow server goroutine to start - - testPort, err := srv.GetPort() - require.NoError(t, err) - require.NotEqual(t, 0, testPort, "invalid listen port") - - // Check that the DNS server knows nothing about testName1 - qName1, _ := assertExchange(t, testName1, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - // there should be a negative reply cached during [0, negativeLocalTTL] - assertNotLocalInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - clk.Forward(negativeLocalTTL - 1) - assertNotLocalInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - // after negativeLocalTTL, there should be absolutely nothing in the cache - clk.Forward(2) - assertNotInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - - // We add the IP in the second peer right after - Log.Debugf("Adding an IPs to %s in database #2", testName1) - dbs[1].Zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.1")) - t.Logf("Zone database #2:\n%s", dbs[1].Zone) - - // Check that the DNS server returns updated information, and it will be - // cached during [0, DefaultLocalTTL] - qName1, _ = assertExchange(t, testName1, dns.TypeA, testPort, 1, 1, 0) - - assertInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - clk.Forward(int(DefaultLocalTTL) - 1) - assertInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - // and it will expire after DefaultLocalTTL - clk.Forward(2) - assertNotInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - - // We delete the IP in the second peer right after - Log.Debugf("Removing the IPs from %s in database #2", testName1) - dbs[1].Zone.DeleteRecords(containerID, "", net.ParseIP("10.2.2.1")) - - // Check that we return to the initial state: a neg-local entry in the cache - qName1, _ = assertExchange(t, testName1, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - assertNotLocalInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - clk.Forward(negativeLocalTTL + 1) - - // Check that all entries should be outdated - cache.Purge() - if cache.Len() != 0 { - t.Fatalf("Some entries still valid in cache:\n%s", cache) - } -} - -// Check if the names updates lead to cache invalidations -func TestServerCacheRefresh(t *testing.T) { - const ( - containerID = "somecontainer" - testName1 = "first.weave.local." - testName2 = "second.weave.local." - refreshInterval = int(DefaultLocalTTL) / 3 - ) - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestServerCacheRefresh starting") - clk := newMockedClock() - - Log.Debugf("Creating 2 zone databases") - zoneConfig := ZoneConfig{ - RefreshInterval: refreshInterval, - Clock: clk, - } - dbs := newZoneDbsWithMockedMDns(2, zoneConfig) - dbs.Start() - defer dbs.Stop() - - Log.Debugf("Creating a cache") - cache, err := NewCache(1024, clk) - require.NoError(t, err) - - Log.Debugf("Creating a real DNS server for the first zone database and with the cache") - srv, err := NewDNSServer(DNSServerConfig{ - Zone: dbs[0].Zone, - Cache: cache, - Clock: clk, - ListenReadTimeout: testSocketTimeout, - MaxAnswers: 4, - }) - require.NoError(t, err) - err = srv.Start() - require.NoError(t, err) - go srv.ActivateAndServe() - defer srv.Stop() - time.Sleep(100 * time.Millisecond) // Allow sever goroutine to start - - testPort, err := srv.GetPort() - require.NoError(t, err) - require.NotEqual(t, 0, testPort, "listen port") - - Log.Debugf("Adding an IPs to %s", testName1) - dbs[1].Zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.1")) - dbs.Flush() // ensure the immediate refresh is done - - // Zone database #2 at this point: - // first.weave.local = 10.2.2.1 - - // testName1 and testName2 should have no IPs yet - qName1, _ := assertExchange(t, testName1, dns.TypeA, testPort, 1, 1, 0) - qName2, _ := assertExchange(t, testName2, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - assertInCache(t, cache, qName1, "after asking for first name") - assertNotLocalInCache(t, cache, qName2, "after asking for second name") - - clk.Forward(refreshInterval / 2) - dbs.Flush() - - Log.Debugf("Adding an IP to %s and to %s", testName1, testName2) - dbs[1].Zone.AddRecord(containerID, testName1, net.ParseIP("10.2.2.2")) - dbs[1].Zone.AddRecord(containerID, testName2, net.ParseIP("10.9.9.2")) - - // Zone database #2 at this point: - // first.weave.local = 10.2.2.1 10.2.2.2 - // second.weave.local = 10.9.9.2 - clk.Forward(refreshInterval/2 + 2) - dbs.Flush() - - // at this point, the testName1 should have been refreshed - // so it should have two IPs, and the cache entry should have been invalidated - assertNotInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - assertNotLocalInCache(t, cache, qName2, fmt.Sprintf("after asking for %s", testName2)) - - qName1, _ = assertExchange(t, testName1, dns.TypeA, testPort, 2, 2, 0) - qName2, _ = assertExchange(t, testName2, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - assertInCache(t, cache, qName1, fmt.Sprintf("after asking for %s", testName1)) - assertNotLocalInCache(t, cache, qName2, "after asking for a unknown name") - - // delete the IPs, and some time passes by so the cache should be purged... - dbs[1].Zone.DeleteRecords(containerID, "", net.ParseIP("10.2.2.1")) - dbs[1].Zone.DeleteRecords(containerID, "", net.ParseIP("10.2.2.2")) - clk.Forward(refreshInterval + 1) - dbs.Flush() - - qName1, _ = assertExchange(t, testName1, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - qName2, _ = assertExchange(t, testName2, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - assertNotLocalInCache(t, cache, qName1, "after asking for a unknown name") - assertNotLocalInCache(t, cache, qName2, "after asking for a unknown name") - -} diff --git a/nameserver/server_test.go b/nameserver/server_test.go deleted file mode 100644 index 9c4a1976..00000000 --- a/nameserver/server_test.go +++ /dev/null @@ -1,258 +0,0 @@ -package nameserver - -import ( - "encoding/binary" - "fmt" - "net" - "testing" - "time" - - "github.com/miekg/dns" - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -const ( - testRDNSsuccess = "1.2.2.10.in-addr.arpa." - testRDNSfail = "4.3.2.1.in-addr.arpa." - testRDNSnonlocal = "8.8.8.8.in-addr.arpa." - testUDPBufSize = 16384 -) - -func setupForTest(t *testing.T) { - // fail early if we cannot find a default multicast interface - multicast, err := LinkLocalMulticastListener(nil) - if err != nil { - t.Fatalf("Unable to create multicast listener: %s. No default multicast interface?", err) - } - multicast.Close() -} - -func TestUDPDNSServer(t *testing.T) { - setupForTest(t) - - const ( - successTestName = "test1.weave.local." - failTestName = "fail.weave.local." - nonLocalName = "weave.works." - testAddr1 = "10.2.2.1" - containerID = "somecontainer" - ) - testCIDR1 := testAddr1 + "/24" - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestUDPDNSServer starting") - - zone, err := NewZoneDb(ZoneConfig{}) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - ip, _, _ := net.ParseCIDR(testCIDR1) - zone.AddRecord(containerID, successTestName, ip) - - fallbackHandler := func(w dns.ResponseWriter, req *dns.Msg) { - if len(req.Question) == 0 { - return // ignore empty queries (sent when shutting down the server) - } - m := new(dns.Msg) - m.SetReply(req) - q := req.Question[0] - if q.Name == nonLocalName && q.Qtype == dns.TypeMX { - m.Answer = make([]dns.RR, 1) - m.Answer[0] = &dns.MX{Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 0}, Mx: "mail." + nonLocalName} - } else if q.Name == nonLocalName && q.Qtype == dns.TypeANY { - m.Answer = make([]dns.RR, 512/len("mailn."+nonLocalName)+1) - for i := range m.Answer { - m.Answer[i] = &dns.MX{Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 0}, Mx: fmt.Sprintf("mail%d.%s", i, nonLocalName)} - } - } else if q.Name == testRDNSnonlocal && q.Qtype == dns.TypePTR { - m.Answer = make([]dns.RR, 1) - m.Answer[0] = &dns.PTR{Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: 0}, Ptr: "ns1.google.com."} - } else if q.Name == testRDNSfail && q.Qtype == dns.TypePTR { - m.Rcode = dns.RcodeNameError - } - w.WriteMsg(m) - } - - // Run another DNS server for fallback - fallback, err := newMockedFallback(fallbackHandler, nil) - require.NoError(t, err) - fallback.Start() - defer fallback.Stop() - - srv, err := NewDNSServer(DNSServerConfig{ - Zone: zone, - UpstreamCfg: fallback.CliConfig, - CacheDisabled: true, - ListenReadTimeout: testSocketTimeout, - }) - require.NoError(t, err) - err = srv.Start() - require.NoError(t, err) - go srv.ActivateAndServe() - defer srv.Stop() - time.Sleep(100 * time.Millisecond) // Allow sever goroutine to start - - var r *dns.Msg - - testPort, err := srv.GetPort() - require.NoError(t, err) - require.NotEqual(t, 0, testPort, "invalid listen port") - - _, r = assertExchange(t, successTestName, dns.TypeA, testPort, 1, 1, 0) - require.IsType(t, (*dns.A)(nil), r.Answer[0], "DNS record") - require.Equal(t, testAddr1, r.Answer[0].(*dns.A).A.String(), "IP address") - - assertExchange(t, failTestName, dns.TypeA, testPort, 0, 0, dns.RcodeNameError) - - _, r = assertExchange(t, testRDNSsuccess, dns.TypePTR, testPort, 1, 1, 0) - require.IsType(t, (*dns.PTR)(nil), r.Answer[0], "DNS record") - require.Equal(t, successTestName, r.Answer[0].(*dns.PTR).Ptr, "IP address") - - assertExchange(t, testRDNSfail, dns.TypePTR, testPort, 0, 0, dns.RcodeNameError) - - // This should fail because we don't handle MX records - assertExchange(t, successTestName, dns.TypeMX, testPort, 0, 0, dns.RcodeNameError) - - // This non-local query for an MX record should succeed by being - // passed on to the fallback server - assertExchange(t, nonLocalName, dns.TypeMX, testPort, 1, -1, 0) - - // Now ask a query that we expect to return a lot of data. - assertExchange(t, nonLocalName, dns.TypeANY, testPort, 5, -1, 0) - - assertExchange(t, testRDNSnonlocal, dns.TypePTR, testPort, 1, -1, 0) - - // Not testing MDNS functionality of server here (yet), since it - // needs two servers, each listening on its own address -} - -func TestTCPDNSServer(t *testing.T) { - setupForTest(t) - - const ( - numAnswers = 512 - nonLocalName = "weave.works." - ) - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestTCPDNSServer starting") - - zone, err := NewZoneDb(ZoneConfig{}) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - // generate a list of `numAnswers` IP addresses - var addrs []ZoneRecord - bs := make([]byte, 4) - for i := 0; i < numAnswers; i++ { - binary.LittleEndian.PutUint32(bs, uint32(i)) - ip := net.IPv4(bs[0], bs[1], bs[2], bs[3]) - addrs = append(addrs, ZoneRecord(Record{"", ip, 0, 0, 0})) - } - - // handler for the fallback server: it will just return a very long response - fallbackUDPHandler := func(w dns.ResponseWriter, req *dns.Msg) { - if len(req.Question) == 0 { - return // ignore empty queries (sent when shutting down the server) - } - maxLen := getMaxReplyLen(req, protUDP) - t.Logf("Fallback UDP server got asked: returning %d answers", numAnswers) - q := req.Question[0] - m := makeAddressReply(req, &q, addrs, DefaultLocalTTL) - mLen := m.Len() - m.SetEdns0(uint16(maxLen), false) - - if mLen > maxLen { - t.Logf("... truncated response (%d > %d)", mLen, maxLen) - m.Truncated = true - } - w.WriteMsg(m) - } - fallbackTCPHandler := func(w dns.ResponseWriter, req *dns.Msg) { - if len(req.Question) == 0 { - return // ignore empty queries (sent when shutting down the server) - } - t.Logf("Fallback TCP server got asked: returning %d answers", numAnswers) - q := req.Question[0] - m := makeAddressReply(req, &q, addrs, DefaultLocalTTL) - w.WriteMsg(m) - } - - t.Logf("Running a DNS fallback server with UDP") - fallback, err := newMockedFallback(fallbackUDPHandler, fallbackTCPHandler) - require.NoError(t, err) - fallback.Start() - defer fallback.Stop() - - t.Logf("Creating a WeaveDNS server instance, falling back to 127.0.0.1:%d", fallback.Port) - srv, err := NewDNSServer(DNSServerConfig{ - Zone: zone, - UpstreamCfg: fallback.CliConfig, - CacheDisabled: true, - ListenReadTimeout: testSocketTimeout, - }) - require.NoError(t, err) - err = srv.Start() - require.NoError(t, err) - go srv.ActivateAndServe() - defer srv.Stop() - time.Sleep(100 * time.Millisecond) // Allow sever goroutine to start - - testPort, err := srv.GetPort() - require.NoError(t, err) - require.NotEqual(t, 0, testPort, "listen port") - dnsAddr := fmt.Sprintf("127.0.0.1:%d", testPort) - - t.Logf("Creating a UDP and a TCP client") - uc := new(dns.Client) - uc.UDPSize = minUDPSize - tc := new(dns.Client) - tc.Net = "tcp" - - t.Logf("Creating DNS query message") - m := new(dns.Msg) - m.RecursionDesired = true - m.SetQuestion(nonLocalName, dns.TypeA) - - t.Logf("Checking the fallback server at %s returns a truncated response with UDP", fallback.Addr) - r, _, err := uc.Exchange(m, fallback.Addr) - t.Logf("Got response from fallback server (UDP) with %d answers", len(r.Answer)) - t.Logf("Response:\n%+v\n", r) - require.NoError(t, err) - require.True(t, r.MsgHdr.Truncated, "DNS truncated reponse flag") - require.NotEqual(t, numAnswers, len(r.Answer), "number of answers (UDP)") - - t.Logf("Checking the WeaveDNS server at %s returns a truncated reponse with UDP", dnsAddr) - r, _, err = uc.Exchange(m, dnsAddr) - t.Logf("UDP Response:\n%+v\n", r) - require.NoError(t, err) - require.NotNil(t, r, "response") - t.Logf("%d answers", len(r.Answer)) - require.True(t, r.MsgHdr.Truncated, "DNS truncated reponse flag") - require.NotEqual(t, numAnswers, len(r.Answer), "number of answers (UDP)") - - t.Logf("Checking the WeaveDNS server at %s does not return a truncated reponse with TCP", dnsAddr) - r, _, err = tc.Exchange(m, dnsAddr) - t.Logf("TCP Response:\n%+v\n", r) - require.NoError(t, err) - require.NotNil(t, r, "response") - t.Logf("%d answers", len(r.Answer)) - require.False(t, r.MsgHdr.Truncated, "DNS truncated response flag") - require.Equal(t, numAnswers, len(r.Answer), "number of answers (TCP)") - - t.Logf("Checking the WeaveDNS server at %s does not return a truncated reponse with UDP with a bigger buffer", dnsAddr) - m.SetEdns0(testUDPBufSize, false) - r, _, err = uc.Exchange(m, dnsAddr) - t.Logf("UDP-large Response:\n%+v\n", r) - require.NoError(t, err) - require.NotNil(t, r, "response") - t.Logf("%d answers", len(r.Answer)) - require.NoError(t, err) - require.False(t, r.MsgHdr.Truncated, "DNS truncated response flag") - require.Equal(t, numAnswers, len(r.Answer), "number of answers (UDP-long)") -} diff --git a/nameserver/zone.go b/nameserver/zone.go deleted file mode 100644 index e6598932..00000000 --- a/nameserver/zone.go +++ /dev/null @@ -1,739 +0,0 @@ -package nameserver - -import ( - "bytes" - "fmt" - "net" - "sync" - "time" - - "github.com/benbjohnson/clock" - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" -) - -const ( - RDNSDomain = "in-addr.arpa." -) - -const ( - DefaultLocalDomain = "weave.local." // The default name used for the local domain - DefaultRefreshInterval = int(DefaultLocalTTL) // Period for background updates with mDNS - DefaultRelevantTime = 60 // When to forget info about remote info if nobody asks... - - defaultRemoteIdent = "weave:remote" // Ident used for info obtained from mDNS -) - -// +1 to also exclude a dot -var rdnsDomainLen = len(RDNSDomain) + 1 - -type LookupError string - -func (ops LookupError) Error() string { - return "Unable to find " + string(ops) -} - -type DuplicateError struct { -} - -func (dup DuplicateError) Error() string { - return "Tried to add a duplicate entry" -} - -type Zone interface { - ZoneObservable - ZoneLookup - // The domain where we operate (eg, "weave.local.") - Domain() string - // Add a record in the local database - AddRecord(ident string, name string, ip net.IP) error - // Delete matching records (uninitialised values act as wildcards) - DeleteRecords(ident string, name string, ip net.IP) (count int) - // Lookup for a name in the whole domain - DomainLookupName(name string) ([]ZoneRecord, error) - // Lookup for an address in the whole domain - DomainLookupInaddr(inaddr string) ([]ZoneRecord, error) - // Return a status string - Status() string -} - -/////////////////////////////////////////////////////////////////// -// -// Zone database overview: -// -// idents names entry -// *-------* *------* *------* -// zone -> | ident | --*--> | name | --*-> | IPv4 | -// *-------* | *------* | *------* -// | ident | *--> | name | *-> | IPv4 | -// *-------* *------* *------* -// ... ... -// -// The zone database keeps an ident per container, but also a special -// ident for names/IPs obtained from remote peers. -// -// Each name can have multiple IPs (so far, we only consider IPv4s), and -// each IP is stored in a `recordEntry` in the database. Entries store -// some additional information like priority and weight of the IP (for -// example, for future use with SRV records) -// - -// An entry in the zone database -type recordEntry struct { - Record - - observers []ZoneRecordObserver // the observers for this record - insTime time.Time // time when this record was inserted -} - -func newRecordEntry(zr ZoneRecord, now time.Time) *recordEntry { - return &recordEntry{ - Record: Record{ - name: zr.Name(), - ip: zr.IP(), - priority: zr.Priority(), - weight: zr.Weight(), - ttl: zr.TTL(), - }, - insTime: now, - observers: make([]ZoneRecordObserver, 0), - } -} - -func (re *recordEntry) addIPObserver(zro ZoneRecordObserver) { - re.observers = append(re.observers, zro) -} - -// Notify all the IP observers and then remove them all -// IP address observers are notified when -// - the IP is removed -// - the name is removed -func (re *recordEntry) notifyIPObservers() { - numObservers := len(re.observers) - if numObservers > 0 { - Log.Debugf("[zonedb] Notifying %d observers of '%s'", numObservers, re.ip) - for _, observer := range re.observers { - observer() - } - re.observers = make([]ZoneRecordObserver, 0) - } -} - -func (re *recordEntry) TTL() int { - // if we never set the TTL (eg, when using AddRecord()), return the standard value... - if re.ttl == 0 { - return int(DefaultLocalTTL) - } - return re.ttl -} - -// Check if the info in this record is still valid according to the TTL -func (re *recordEntry) hasExpired(now time.Time) bool { - return re.ttl > 0 && now.Sub(re.insTime).Seconds() > float64(re.ttl) -} - -func (re *recordEntry) String() string { - var buf bytes.Buffer - fmt.Fprintf(&buf, "%s", re.Record) - lobs := len(re.observers) - if lobs > 0 { - fmt.Fprintf(&buf, "/OBS:%d", lobs) - } - return buf.String() -} - -/////////////////////////////////////////////////////////////////// - -// a name, with group of records by IPv4 -type name struct { - name string - ipv4 map[IPv4]*recordEntry // all the IPv4 records for this name - observers []ZoneRecordObserver // the observers for this name - lastRefreshTime time.Time // last time this name was updated by broadcasting a query - lastAccessTime time.Time // last time a Lookup* used info from this name -} - -func newName(n string) *name { - return &name{ - name: n, - ipv4: make(map[IPv4]*recordEntry), - observers: make([]ZoneRecordObserver, 0), - } -} -func (n *name) len() int { return len(n.ipv4) } -func (n *name) empty() bool { return n.len() == 0 } -func (n *name) hasIP(ip net.IP) bool { return n.hasIPv4(ipToIPv4(ip)) } -func (n *name) hasIPv4(ip IPv4) bool { _, found := n.ipv4[ip]; return found } - -// Get all the entries for this name -func (n *name) getAllEntries() (res []*recordEntry) { - for _, entry := range n.ipv4 { - res = append(res, entry) - } - return -} - -// Get the entry for an IP in this name -func (n *name) getEntryForIP(ip IPv4) (res *recordEntry) { - if entry, found := n.ipv4[ip]; found { - res = entry - } - return -} - -// Add a new IPv4 to this name -func (n *name) addIP(zr ZoneRecord, now time.Time) (*recordEntry, error) { - ne := newRecordEntry(zr, now) - ipv4 := ipToIPv4(zr.IP()) - n.ipv4[ipv4] = ne - n.notifyNameObservers() - return ne, nil -} - -// Delete by IP. Pass uninitialized value for wildcard -func (n *name) deleteIP(ip net.IP) int { - count := 0 - if !ip.Equal(net.IP{}) { - ipv4 := ipToIPv4(ip) - if ipv4V, found := n.ipv4[ipv4]; found { - ipv4V.notifyIPObservers() - delete(n.ipv4, ipv4) - count++ - } - } else { - for ipv4K, ipv4V := range n.ipv4 { - ipv4V.notifyIPObservers() - delete(n.ipv4, ipv4K) - count++ - } - } - if count > 0 { - n.notifyNameObservers() - } - return count -} - -// Update the list of IPs for this name, adding new ones and removing old IPs... -func (n *name) updateIPs(records []ZoneRecord, now time.Time) (added int, removed int) { - ipsMap := make(map[IPv4]bool) - - // add the new IPs - for _, record := range records { - ipv4 := ipToIPv4(record.IP()) - ipsMap[ipv4] = true - if !n.hasIPv4(ipv4) { - n.addIP(record, now) - added++ - } - } - - // remove the old IPs - for ipv4, ipRecord := range n.ipv4 { - if _, isNew := ipsMap[ipv4]; !isNew { - ipRecord.notifyIPObservers() // we must notify the observers before removing the IP record... - delete(n.ipv4, ipv4) - removed++ - } - } - - // notify observers and update times - if added > 0 || removed > 0 { - n.lastRefreshTime = now - n.notifyNameObservers() - } - return -} - -// Add a observer for this name -func (n *name) addNameObserver(observer ZoneRecordObserver) { - n.observers = append(n.observers, observer) -} - -// Notify and flush all the observers -// Name observers are notified when -// - an IP is added -// - an IP is removed -// - the name is removed -func (n *name) notifyNameObservers() { - numObservers := len(n.observers) - if numObservers > 0 { - Log.Debugf("[zonedb] Notifying %d observers of '%s'", numObservers, n.name) - for _, observer := range n.observers { - observer() - } - n.observers = make([]ZoneRecordObserver, 0) - } -} - -// Convert a set of IP records to a comma-separated string -func (n *name) String() string { - var buf bytes.Buffer - for _, ip := range n.ipv4 { - fmt.Fprintf(&buf, "%s, ", ip) - } - l := buf.Len() - if l > 2 { - buf.Truncate(l - 2) - } - return buf.String() -} - -/////////////////////////////////////////////////////////////////// - -// all the names in a ident -type nameSet struct { - names map[string]*name -} - -func newNameSet() *nameSet { return &nameSet{names: make(map[string]*name)} } -func (ns *nameSet) len() int { return len(ns.names) } -func (ns *nameSet) empty() bool { return ns.len() == 0 } -func (ns *nameSet) hasName(name string) bool { - n, found := ns.names[name] - if !found { - return false - } - // the name must have some valid IPs in order to be considered as "existent" - return len(n.ipv4) > 0 -} - -// Get the zone entries for a name -// If the name does not exist and `create` is true, a new name will be created -func (ns *nameSet) getName(name string, create bool) (n *name) { - n, found := ns.names[name] - if !found && create { - newName := newName(name) - ns.names[name] = newName - return newName - } - return n -} - -// Get all the entries for a name -func (ns *nameSet) getEntriesForName(name string) (res []*recordEntry) { - n := ns.getName(name, false) - if n != nil { - res = n.getAllEntries() - } - return -} - -// Get all the entries for an IP, for all names -func (ns *nameSet) getEntriesForIP(ip IPv4) (res []*recordEntry) { - for _, name := range ns.names { - entry := name.getEntryForIP(ip) - if entry != nil { - res = append(res, entry) - } - } - return -} - -// Add a new IPv4 to a name -func (ns *nameSet) addIPToName(zr ZoneRecord, now time.Time) (*recordEntry, error) { - n := ns.getName(zr.Name(), true) - ipv4 := ipToIPv4(zr.IP()) - if n.hasIPv4(ipv4) { - return n.getEntryForIP(ipv4), DuplicateError{} - } - ns.touchName(zr.Name(), now) - return n.addIP(zr, now) -} - -// Delete by name and IP. Pass uninitialized values for wildcard -func (ns nameSet) deleteNameIP(name string, ip net.IP) int { - count := 0 - if name != "" { - if nameV, found := ns.names[name]; found { - count += nameV.deleteIP(ip) - if nameV.empty() { - delete(ns.names, name) - } - } - } else { - for nameK, nameV := range ns.names { - count += nameV.deleteIP(ip) - if nameV.empty() { - delete(ns.names, nameK) - } - } - } - return count -} - -// Get the name query time -func (ns *nameSet) getNameLastAccess(n string) time.Time { - if name, found := ns.names[n]; found { - return name.lastAccessTime - } - return time.Time{} -} - -// Touch the last access time for a name -// The access time is saved only for locally-introduced records (otherwise it could -// be lost when names are irrelevant...) -func (ns *nameSet) touchName(name string, now time.Time) { - Log.Debugf("[zonedb] Touching name %s", name) - n := ns.getName(name, false) - if n != nil { - n.lastAccessTime = now - } -} - -func (ns *nameSet) String() string { - var buf bytes.Buffer - for _, name := range ns.names { - fmt.Fprintf(&buf, "%s, ", name) - } - l := buf.Len() - if l > 2 { - buf.Truncate(l - 2) - } - return buf.String() -} - -/////////////////////////////////////////////////////////////////// - -// Name sets, by ident name -type identRecordSet map[string]*nameSet - -func (irs identRecordSet) String() string { - var buf bytes.Buffer - for ident, nameset := range irs { - fmt.Fprintf(&buf, "%.12s: %s\n", ident, nameset) - } - return buf.String() -} - -/////////////////////////////////////////////////////////////////// - -// Invariant on updateRequests: they are in ascending order of time. -type refreshRequest struct { - name string - time time.Time -} - -type ZoneConfig struct { - // The local domain - Domain string - // The interface where mDNS operates - Iface *net.Interface - // Refresh interval for local names in the zone database (disabled by default) (in seconds) - RefreshInterval int - // Forget about remote info if nobody asks for it in this time (in seconds) - RelevantTime int - // TTL returnined in local asnwers (with mDNS) - LocalTTL int - // Force a specific mDNS client - MDNSClient ZoneMDNSClient - // Force a specific mDNS server - MDNSServer ZoneMDNSServer - // For a specific clock provider - Clock clock.Clock -} - -// Zone database -// The zone database contains the locally known information about the zone. -// The zone database uses some other mechanisms (eg, mDNS) for finding unknown -// information or for keeping current information up to date. -type ZoneDb struct { - mx sync.RWMutex - idents identRecordSet - - mdnsCli ZoneMDNSClient - mdnsSrv ZoneMDNSServer - iface *net.Interface - domain string // the local domain - relevantLimit time.Duration // if no one asks for something in this time, it is not relevant a anymore... - clock clock.Clock - - refreshScheds *SchedQueue - refreshCloseChan chan bool - refreshInterval time.Duration -} - -// Create a new zone database -func NewZoneDb(config ZoneConfig) (zone *ZoneDb, err error) { - zone = &ZoneDb{ - domain: config.Domain, - idents: make(identRecordSet), - mdnsCli: config.MDNSClient, - mdnsSrv: config.MDNSServer, - iface: config.Iface, - clock: config.Clock, - relevantLimit: time.Duration(DefaultRelevantTime) * time.Second, - refreshCloseChan: make(chan bool), - } - - // fix the default configuration parameters - if zone.clock == nil { - zone.clock = clock.New() - } - if len(zone.domain) == 0 { - zone.domain = DefaultLocalDomain - } - if config.RefreshInterval > 0 { - zone.refreshInterval = time.Duration(config.RefreshInterval) * time.Second - } - if config.RelevantTime > 0 { - zone.relevantLimit = time.Duration(config.RelevantTime) * time.Second - } - - if zone.refreshInterval > 0 { - zone.refreshScheds = NewSchedQueue(zone.clock) - } - - // Create the mDNS client and server - if zone.mdnsCli == nil { - if zone.mdnsCli, err = NewMDNSClient(); err != nil { - return - } - } - if zone.mdnsSrv == nil { - mdnsTTL := DefaultLocalTTL - if config.LocalTTL > 0 { - mdnsTTL = config.LocalTTL - } - - if zone.mdnsSrv, err = NewMDNSServer(zone, false, mdnsTTL); err != nil { - return - } - } - - return -} - -// Start the zone database -func (zone *ZoneDb) Start() (err error) { - if zone.iface != nil { - Log.Infof("[zonedb] Using mDNS on %+v", zone.iface) - } else { - Log.Infof("[zonedb] Using mDNS on all interfaces") - } - - if err = zone.mdnsCli.Start(zone.iface); err != nil { - return - } - if err = zone.mdnsSrv.Start(zone.iface); err != nil { - return - } - if zone.refreshInterval > 0 { - zone.refreshScheds.Start() - } - - return -} - -// Perform a graceful shutdown of the zone database -func (zone *ZoneDb) Stop() error { - if zone.refreshInterval > 0 { - Log.Debugf("[zonedb] Closing background updaters...") - zone.refreshScheds.Stop() - } - - Log.Debugf("[zonedb] Exiting mDNS client and server...") - zone.mdnsCli.Stop() - zone.mdnsSrv.Stop() - return nil -} - -// Obtain the domain where this database keeps information for -func (zone *ZoneDb) Domain() string { - return zone.domain -} - -// Return the status string -func (zone *ZoneDb) Status() string { - var buf bytes.Buffer - fmt.Fprintln(&buf, "Local domain", zone.domain) - fmt.Fprintln(&buf, "Interface", zone.iface) - fmt.Fprintf(&buf, "Zone database:\n%s", zone) - return buf.String() -} - -// Add a record with `name` pointing to `ip` -func (zone *ZoneDb) AddRecord(ident string, name string, ip net.IP) (err error) { - zone.mx.Lock() - defer zone.mx.Unlock() - Log.Debugf("[zonedb] Adding record: '%s'/'%s'[%s]", ident, name, ip) - record := Record{dns.Fqdn(name), ip, 0, 0, 0} - _, err = zone.getNameSet(ident).addIPToName(record, zone.clock.Now()) - return -} - -// Delete matching records (uninitialised values act as wildcards) -func (zone *ZoneDb) DeleteRecords(ident string, name string, ip net.IP) int { - if name != "" { - name = dns.Fqdn(name) - } - - zone.mx.Lock() - defer zone.mx.Unlock() - - return zone.deleteIdentNameIP(ident, name, ip) -} - -// Observe a name. -// The name must have at least one valid IP address. -// Name observers are notified when -// - an IP is added -// - an IP is removed -// - the name is removed -// The observer will be invoked on any change/removal that affects this name. -// Each observer will be invoked at least once (but possibly more). After that, they will be removed. -// The observer should not try to lock the ZoneDB (you will get a deadlock) -func (zone *ZoneDb) ObserveName(name string, observer ZoneRecordObserver) (err error) { - zone.mx.Lock() - defer zone.mx.Unlock() - - cnt := 0 - name = dns.Fqdn(name) - for _, nameset := range zone.idents { - if n := nameset.getName(name, false); n != nil { - n.addNameObserver(observer) - cnt++ - } - } - if cnt == 0 { - err = LookupError(fmt.Sprintf("%s", name)) - } - return -} - -// Observe a IP address. -// The IP address must be exit in the database. -// IP address observers are notified when -// - the IP is removed -// - the name is removed -// The observer will be invoked on any change/removal that affects this IP. -// Each observer will be invoked at least once (but possibly more). After that, they will be removed. -// The observer should not try to lock the ZoneDB (you will get a deadlock) -func (zone *ZoneDb) ObserveInaddr(inaddr string, observer ZoneRecordObserver) (err error) { - zone.mx.Lock() - defer zone.mx.Unlock() - - cnt := 0 - revIP, err := raddrToIPv4(inaddr) - if err != nil { - return newParseError("lookup address", inaddr) - } - for _, nameset := range zone.idents { - for _, entry := range nameset.getEntriesForIP(revIP) { - entry.addIPObserver(observer) - cnt++ - } - } - if cnt == 0 { - err = LookupError(fmt.Sprintf("%+v/%+v", inaddr, revIP)) - } - return -} - -// Get the string representation of a zone -func (zone *ZoneDb) String() string { - zone.mx.RLock() - defer zone.mx.RUnlock() - return zone.idents.String() -} - -// Notify that a container has died -func (zone *ZoneDb) ContainerDied(ident string) error { - Log.Infof("[zonedb] Container %s down. Removing records", ident) - zone.DeleteRecords(ident, "", net.IP{}) - return nil -} - -// Return true if a remote name is still relevant -func (zone *ZoneDb) IsNameRelevant(n string) bool { - zone.mx.Lock() - defer zone.mx.Unlock() - - lastAccess := time.Time{} - for _, nameset := range zone.idents { - t := nameset.getNameLastAccess(n) - if !t.IsZero() && (lastAccess.IsZero() || t.After(lastAccess)) { - lastAccess = t - } - } - - return !lastAccess.IsZero() && zone.clock.Now().Sub(lastAccess) <= zone.relevantLimit -} - -// Returns true if the info we have for a remote name has expired. Local names are never expired -// Returns false if we do not have info for this name from remote peers. -func (zone *ZoneDb) IsNameExpired(n string) bool { - zone.mx.Lock() - defer zone.mx.Unlock() - - now := zone.clock.Now() - remoteNameSet := zone.getNameSet(defaultRemoteIdent) - entries := remoteNameSet.getEntriesForName(n) - if entries != nil { - for _, entry := range entries { - if entry.hasExpired(now) { - return true - } - } - } - return false -} - -func (zone *ZoneDb) HasNameLocalInfo(n string) bool { - zone.mx.Lock() - defer zone.mx.Unlock() - - remoteNameSet := zone.getNameSet(defaultRemoteIdent) - for _, nameset := range zone.idents { - if nameset != remoteNameSet { - if nameset.hasName(n) { - return true - } - } - } - return false -} - -// Return true if the we have obtained some information for a name from remote peers -// We can have both local (eg, introduced through the HTTP API) and remote (eg, mDNS) -// information for a name. This method only checks if there is remote information... -func (zone *ZoneDb) HasNameRemoteInfo(n string) bool { - zone.mx.Lock() - defer zone.mx.Unlock() - - remoteNameSet := zone.getNameSet(defaultRemoteIdent) - if remoteNameSet != nil { - return remoteNameSet.hasName(n) - } - return false -} - -// Get or create a name set -func (zone *ZoneDb) getNameSet(ident string) *nameSet { - ns, found := zone.idents[ident] - if !found { - ns = newNameSet() - zone.idents[ident] = ns - } - return ns -} - -// Delete by ident, name and IP. Pass uninitialized value for wildcard -func (zone *ZoneDb) deleteIdentNameIP(ident string, name string, ip net.IP) int { - count := 0 - if ident != "" { - if identV, found := zone.idents[ident]; found { - count += identV.deleteNameIP(name, ip) - if identV.empty() { - delete(zone.idents, ident) - } - } - } else { - for identK, identV := range zone.idents { - count += identV.deleteNameIP(name, ip) - if identV.empty() { - delete(zone.idents, identK) - } - } - } - return count -} diff --git a/nameserver/zone_lookup.go b/nameserver/zone_lookup.go deleted file mode 100644 index 6e515b62..00000000 --- a/nameserver/zone_lookup.go +++ /dev/null @@ -1,291 +0,0 @@ -package nameserver - -import ( - "net" - "time" - - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" -) - -type uniqZoneRecordKey struct { - name string - ipv4 IPv4 -} - -// A group of ZoneRecords where there are no duplicates (according to the name & IPv4) -type uniqZoneRecords map[uniqZoneRecordKey]ZoneRecord - -func newUniqZoneRecords() uniqZoneRecords { - return make(uniqZoneRecords, 0) -} - -// Add a new ZoneRecord to the group -func (uzr *uniqZoneRecords) add(zr ZoneRecord) { - key := uniqZoneRecordKey{zr.Name(), ipToIPv4(zr.IP())} - (*uzr)[key] = zr -} - -// Return the group as an slice -func (uzr *uniqZoneRecords) toSlice() []ZoneRecord { - res := make([]ZoneRecord, len(*uzr)) - i := 0 - for _, r := range *uzr { - res[i] = r - i++ - } - return res -} - -////////////////////////////////////////////////////////////////////////////// - -// Lookup in the database for locally-introduced information -func (zone *ZoneDb) lookup(target string, lfun func(ns *nameSet) []*recordEntry) (res []ZoneRecord, err error) { - uniq := newUniqZoneRecords() - for identName, nameset := range zone.idents { - if identName != defaultRemoteIdent { - for _, ze := range lfun(nameset) { - uniq.add(ze) - } - } - } - if len(uniq) == 0 { - return nil, LookupError(target) - } - return uniq.toSlice(), nil -} - -// Perform a lookup for a name in the zone -// The name can be resolved locally with the local database -func (zone *ZoneDb) LookupName(name string) (res []ZoneRecord, err error) { - zone.mx.RLock() - defer zone.mx.RUnlock() - - // note: LookupName() is usually called from the mDNS server, so we do not touch the name - name = dns.Fqdn(name) - Log.Debugf("[zonedb] Looking for name '%s' in local database", name) - return zone.lookup(name, func(ns *nameSet) []*recordEntry { return ns.getEntriesForName(name) }) -} - -// Perform a lookup for a IP address in the zone -// The address can be resolved locally with the local database -func (zone *ZoneDb) LookupInaddr(inaddr string) (res []ZoneRecord, err error) { - zone.mx.RLock() - defer zone.mx.RUnlock() - - // note: LookupInaddr() is usually called from the mDNS server, so we do not touch the name - revIPv4, err := raddrToIPv4(inaddr) - if err != nil { - return nil, newParseError("lookup address", inaddr) - } - Log.Debugf("[zonedb] Looking for address in local database: '%s' (%s)", revIPv4, inaddr) - return zone.lookup(inaddr, func(ns *nameSet) []*recordEntry { return ns.getEntriesForIP(revIPv4) }) -} - -// Perform a domain lookup with mDNS -func (zone *ZoneDb) domainLookup(target string, lfun ZoneLookupFunc) (res []ZoneRecord, err error) { - // no local results have been obtained in the local database: try with a mDNS query - Log.Debugf("[zonedb] '%s' not in local database... trying with mDNS", target) - lanswers, err := lfun(target) - if err != nil { - Log.Debugf("[zonedb] mDNS lookup error for '%s': %s", target, err) - return nil, err - } - - // if the request has been successful, save the IP in the local database and return the corresponding ZoneRecord - // (we do not get the remote ident in the mDNS reply, so we save it in a "remote" ident) - Log.Debugf("[zonedb] adding '%s' (obtained with mDNS) to '%s'", lanswers, target) - res = make([]ZoneRecord, len(lanswers)) - zone.mx.Lock() - now := zone.clock.Now() - uniq := newUniqZoneRecords() - remoteIdent := zone.getNameSet(defaultRemoteIdent) - for _, answer := range lanswers { - r, err := remoteIdent.addIPToName(answer, now) - if err != nil { - zone.mx.Unlock() - Log.Warningf("[zonedb] '%s' insertion for %s failed: %s", answer, target, err) - return nil, err - } - uniq.add(r) - } - zone.mx.Unlock() - - return uniq.toSlice(), nil -} - -// Perform a lookup for a name in the zone -// The name can be resolved locally with the local database or with some other resolution method (eg, a mDNS query) -func (zone *ZoneDb) DomainLookupName(name string) (res []ZoneRecord, err error) { - name = dns.Fqdn(name) - Log.Debugf("[zonedb] Looking for name '%s' in local(&remote) database", name) - - zone.mx.Lock() - now := zone.clock.Now() - uniq := newUniqZoneRecords() - for identName, nameset := range zone.idents { - for _, ze := range nameset.getEntriesForName(name) { - // filter the entries with expired TTL - // locally introduced entries are never expired: they always have TTL=0 - if ze.hasExpired(now) { - Log.Debugf("[zonedb] '%s': expired entry '%s' ignored: removing", name, ze) - nameset.deleteNameIP(name, net.IP{}) - } else { - uniq.add(ze) - } - } - if identName != defaultRemoteIdent { - nameset.touchName(name, now) - } - } - zone.mx.Unlock() - - if len(uniq) > 0 { - Log.Debugf("[zonedb] '%s' resolved in local database", name) - res = uniq.toSlice() - } else { - res, err = zone.domainLookup(name, zone.mdnsCli.LookupName) - } - - if len(res) > 0 { - zone.startUpdatingName(name) - return res, nil - } - return nil, LookupError(name) -} - -// Perform a lookup for a IP address in the zone -// The address can be resolved either with the local database or -// with some other resolution method (eg, a mDNS query) -func (zone *ZoneDb) DomainLookupInaddr(inaddr string) (res []ZoneRecord, err error) { - revIPv4, err := raddrToIPv4(inaddr) - if err != nil { - return nil, newParseError("lookup address", inaddr) - } - - Log.Debugf("[zonedb] Looking for address in local(&remote) database: '%s' (%s)", revIPv4, inaddr) - - zone.mx.Lock() - now := zone.clock.Now() - uniq := newUniqZoneRecords() - for identName, nameset := range zone.idents { - for _, ze := range nameset.getEntriesForIP(revIPv4) { - // filter the entries with expired TTL - // locally introduced entries are never expired: they always have TTL=0 - if ze.hasExpired(now) { - Log.Debugf("[zonedb] '%s': expired entry '%s' ignored: removing", revIPv4, ze) - nameset.deleteNameIP("", revIPv4.toNetIP()) - } else { - uniq.add(ze) - if identName != defaultRemoteIdent { - nameset.touchName(ze.Name(), now) - } - } - } - } - zone.mx.Unlock() - - if len(uniq) > 0 { - Log.Debugf("[zonedb] '%s' resolved in local database", inaddr) - res = uniq.toSlice() - } else { - res, err = zone.domainLookup(inaddr, zone.mdnsCli.LookupInaddr) - } - - if len(res) > 0 { - // note: even for reverse addresses, we perform the background updates in the name, not in the IP - // this simplifies the process and produces basically the same results... - // note: we do not spend time trying to update names that did not return an initial response... - for _, r := range res { - zone.startUpdatingName(r.Name()) - } - - return res, nil - } - return nil, LookupError(inaddr) -} - -////////////////////////////////////////////////////////////////////////////// - -// Names updates try to find all the IPs for a given name with a mDNS query -// -// There are two types of names updates: -// -// - immediate updates. -// After a `DomainLookup*()` for a name not in the database we will return the -// first IP we can get with mDNS from other peers. Waiting for more responses would -// mean more latency in the response to the client, so we send only one answer BUT -// we also trigger an immediate update request for that name in order to get all -// the other IPs we didn't wait for... -// -// - periodic updates -// once we have obtained the first group of IPs for a name, we schedule a periodic -// refresh for that name, so we keep the list of IPs for that name up to date. -// -// These names updates are repeated until either -// -// a) there is no interest in the name, determined by a global 'relevant time' -// and the last time some local client asked about the name, -// or -// b) no peers answer one of our refresh requests (because the name has probably -// disappeared from the network) -// - -// Check if we must start updating a name and, in that case, trigger a immediate update -func (zone *ZoneDb) startUpdatingName(name string) { - if zone.refreshInterval > 0 { - zone.mx.Lock() - - // check if we should enqueue a refresh request for this name - n := zone.getNameSet(defaultRemoteIdent).getName(name, true) - if n.lastRefreshTime.IsZero() { - now := zone.clock.Now() - n.lastRefreshTime = now - zone.mx.Unlock() - - Log.Debugf("[zonedb] Creating new immediate refresh request for '%s'", name) - zone.refreshScheds.Add(func() time.Time { return zone.updater(name) }, now) - } else { - zone.mx.Unlock() - } - } -} - -// Update the IPs we have for a name -func (zone *ZoneDb) updater(name string) (nextTime time.Time) { - deleteRemoteInfo := func() { - zone.mx.Lock() - zone.getNameSet(defaultRemoteIdent).deleteNameIP(name, net.IP{}) - zone.mx.Unlock() - } - - // if nobody has asked for this name for long time, just forget about it... - if !zone.IsNameRelevant(name) || zone.IsNameExpired(name) { - Log.Debugf("[zonedb] '%s' seem to be irrelevant now: removing any remote information", name) - deleteRemoteInfo() - return - } - - // perform the refresh for this name - fullName := dns.Fqdn(name) - startTime := zone.clock.Now() - Log.Debugf("[zonedb] Refreshing name '%s' with mDNS...", fullName) - res, _ := zone.mdnsCli.InsistentLookupName(fullName) - if res != nil && len(res) > 0 { - numIps := len(res) - zone.mx.Lock() - now := zone.clock.Now() - added, removed := zone.getNameSet(defaultRemoteIdent).getName(name, true).updateIPs(res, now) - zone.mx.Unlock() - Log.Debugf("[zonedb] Obtained %d IPs for name '%s' with mDNS: %d added, %d removed", - numIps, name, added, removed) - - // once the name has been updated, we re-schedule the update - nextTime = startTime.Add(zone.refreshInterval) - Log.Debugf("[zonedb] Rescheduling update for '%s' in %s", name, nextTime.Sub(zone.clock.Now())) - } else { - Log.Debugf("[zonedb] nobody knows about '%s'... removing", name) - deleteRemoteInfo() - } - return -} diff --git a/nameserver/zone_lookup_test.go b/nameserver/zone_lookup_test.go deleted file mode 100644 index 31789133..00000000 --- a/nameserver/zone_lookup_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package nameserver - -import ( - "net" - "testing" - "time" - - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" -) - -// Check that the refreshing mechanism works as expected -func TestZoneRefresh(t *testing.T) { - const ( - refreshInterval = 5 - relevantTime = 30 - ) - var ( - name = "mysql.weave.local." - addr1 = "10.2.8.4" - addr2 = "10.2.8.5" - addr3 = "10.2.8.6" - addr4 = "10.2.8.7" - ) - - EnableDebugLogging(testing.Verbose()) - Log.Infoln("TestZoneRefresh starting") - - clk := newMockedClock() - - // Create multiple zone databases, linked through mocked mDNS connections - zc := ZoneConfig{ - RefreshInterval: refreshInterval, - RelevantTime: relevantTime, - Clock: clk, - } - dbs := newZoneDbsWithMockedMDns(2, zc) - dbs.Start() - defer dbs.Stop() - - time.Sleep(100 * time.Millisecond) // allow for server to get going - - Log.Debugf("Adding '%s' to Db #1", name) - dbs[0].Zone.AddRecord("someident", name, net.ParseIP(addr1)) - - Log.Debugf("Checking that the name %s is relevant (as it has been locally inserted) and not remote", name) - require.True(t, dbs[0].Zone.IsNameRelevant(name), "name relevant") - require.True(t, dbs[0].Zone.HasNameLocalInfo(name), "local name info") - require.False(t, dbs[0].Zone.HasNameRemoteInfo(name), "remote name info") - - Log.Debugf("Asking for '%s' to Db #1: should get 1 IP from the local database...", name) - res, err := dbs[0].Zone.DomainLookupName(name) - require.NoError(t, err) - Log.Debugf("Got: %s", res) - t.Logf("Db #1 after the lookup:\n%s", dbs[0].Zone) - require.Equal(t, 1, len(res), "lookup result") - - clk.Forward(refreshInterval / 2) - dbs.Flush() - Log.Debugf("A couple of seconds later, we should still have one IP for that name") - res, err = dbs[0].Zone.DomainLookupName(name) - require.NoError(t, err) - require.Equal(t, 1, len(res), "lookup result") - - Log.Debugf("And then we add 2 IPs for that name at ZoneDb 2") - clk.Forward(1) - dbs.Flush() - Log.Debugf("Adding 2 IPs to '%s' in Db #2", name) - dbs[1].Zone.AddRecord("someident", name, net.ParseIP(addr2)) - dbs[1].Zone.AddRecord("someident", name, net.ParseIP(addr3)) - - Log.Debugf("Perform a lookup, to ensure the name will be updated in the background...") - dbs[0].Zone.DomainLookupName(name) - - Log.Debugf("Wait for a while, until a refresh is performed...") - clk.Forward(refreshInterval + 1) - dbs.Flush() - Log.Debugf("A refresh should have been scheduled now: we should have 3 IPs:") - Log.Debugf("the first (local) IP and the others obtained from zone2 with a mDNS query") - Log.Debugf("Asking for '%s' again... we should have 3 IPs now", name) - res, err = dbs[0].Zone.DomainLookupName(name) - Log.Debugf("Got: %s", res) - t.Logf("Db #1 after the second lookup:\n%s", dbs[0].Zone) - require.Equal(t, 3, len(res), "lookup result length") - - Log.Debugf("We will not ask for `name` for a while, so it will become irrelevant and will be removed...") - clk.Forward(refreshInterval + relevantTime + 1) - dbs.Flush() - - // the name should be irrelevant now, and all remote info should have been - // removed from the zone database - Log.Debugf("Name '%s' should not be in the remote database in ZoneDb 1", name) - require.False(t, dbs[0].Zone.IsNameRelevant(name), "name still relevant after some inactivity time") - require.True(t, dbs[0].Zone.HasNameLocalInfo(name), "local name info") - require.False(t, dbs[0].Zone.HasNameRemoteInfo(name), "remote name info") - - Log.Debugf("There is no remote info about this name at zone 1: a new IP appears remotely meanwhile...") - clk.Forward(1) - dbs.Flush() - - Log.Debugf("Adding '%s' to Db #2", name) - dbs[1].Zone.AddRecord("someident", name, net.ParseIP(addr4)) - - Log.Debugf("When we ask about this name again, we get 4 IPs (1 local, 3 remote)") - Log.Debugf("Asking for '%s' again... the first lookup will return only the local results", name) - res, err = dbs[0].Zone.DomainLookupName(name) - require.Equal(t, 1, len(res), "lookup result length") - Log.Debugf("... but a second lookup should return all the results in the network") - - clk.Forward(refreshInterval + 1) - dbs.Flush() - - res, err = dbs[0].Zone.DomainLookupName(name) - Log.Debugf("Got: %s", res) - require.Equal(t, 4, len(res), "lookup result length") -} diff --git a/nameserver/zone_test.go b/nameserver/zone_test.go deleted file mode 100644 index 2a3a1467..00000000 --- a/nameserver/zone_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package nameserver - -import ( - "fmt" - "net" - "testing" - - "github.com/stretchr/testify/require" - . "github.com/weaveworks/weave/common" - wt "github.com/weaveworks/weave/testing" -) - -func TestZone(t *testing.T) { - var ( - container1 = "deadbeef" - container2 = "cowjuice" - name1 = "test1.weave." - name1Addr1 = "10.9.2.1/24" - name1Addr2 = "10.9.2.2/24" - revName1Addr1 = "1.2.9.10.in-addr.arpa." - ) - - EnableDebugLogging(testing.Verbose()) - - zone, err := NewZoneDb(ZoneConfig{}) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - ip1, _, _ := net.ParseCIDR(name1Addr1) - t.Logf("Adding '%s'/%s to '%s'", name1, ip1, container1) - err = zone.AddRecord(container1, name1, ip1) - require.NoError(t, err) - - // Add a few more records to make the job harder - t.Logf("Adding 'adummy.weave.' to 'abcdef0123'") - err = zone.AddRecord("abcdef0123", "adummy.weave.", net.ParseIP("10.9.0.1")) - require.NoError(t, err) - t.Logf("Adding 'zdummy.weave.' to '0123abcdef'") - err = zone.AddRecord("0123abcdef", "zdummy.weave.", net.ParseIP("10.9.0.2")) - require.NoError(t, err) - t.Logf("Zone database:\n%s", zone) - - t.Logf("Checking if we can find the name '%s'", name1) - foundIPs, err := zone.LookupName(name1) - require.NoError(t, err) - - if !foundIPs[0].IP().Equal(ip1) { - t.Fatal("Unexpected result for", name1, foundIPs) - } - - t.Logf("Checking if we cannot find some silly name like 'something.wrong'") - foundIPs, err = zone.LookupName("something.wrong") - wt.AssertErrorType(t, (*LookupError)(nil), err, fmt.Sprintf("unknown name: %+v", foundIPs)) - - ip2, _, _ := net.ParseCIDR(name1Addr2) - t.Logf("Adding a second IP for '%s'/%s to '%s'", name1, ip2, container1) - err = zone.AddRecord(container1, name1, ip2) - require.NoError(t, err) - - t.Logf("Checking if we can find both the old IP and the new IP for '%s'", name1) - foundIPs, err = zone.LookupName(name1) - require.NoError(t, err) - if !(foundIPs[0].IP().Equal(ip1) || foundIPs[1].IP().Equal(ip1)) { - t.Fatal("Unexpected result for", name1, foundIPs) - } - if !(foundIPs[0].IP().Equal(ip2) || foundIPs[1].IP().Equal(ip2)) { - t.Fatal("Unexpected result for", name1, foundIPs) - } - - t.Logf("Checking if we can find the address by IP '1.2.9.10.in-addr.arpa.'") - foundNames, err := zone.LookupInaddr("1.2.9.10.in-addr.arpa.") - require.NoError(t, err) - - if foundNames[0].Name() != name1 { - t.Fatal("Unexpected result for", ip1, foundNames) - } - - t.Logf("Checking we can not find an unknown address '30.20.10.1.in-addr.arpa.'") - foundNames, err = zone.LookupInaddr("30.20.10.1.in-addr.arpa.") - wt.AssertErrorType(t, (*LookupError)(nil), err, fmt.Sprintf("unknown IP: %+v", foundNames)) - - t.Logf("Checking if adding again '%s'/%s in %s results in an error", name1, ip1, container1) - err = zone.AddRecord(container1, name1, ip1) - wt.AssertErrorType(t, (*DuplicateError)(nil), err, "duplicate add") - - t.Logf("Adding '%s'/%s in %s too", name1, ip1, container2) - err = zone.AddRecord(container2, name1, ip1) - require.NoError(t, err) - - name1Removed := 0 - err = zone.ObserveName(name1, func() { t.Logf("Observer #1 for '%s' notified.", name1); name1Removed++ }) - require.NoError(t, err) - err = zone.ObserveName(name1, func() { t.Logf("Observer #2 for '%s' notified.", name1); name1Removed++ }) - require.NoError(t, err) - err = zone.ObserveInaddr(revName1Addr1, func() { t.Logf("Observer #1 for '%s' notified.", revName1Addr1); name1Removed++ }) - require.NoError(t, err) - - t.Logf("Zone database:\n%s", zone) - t.Logf("Deleting the %s in %s", ip1, container1) - count := zone.DeleteRecords(container1, "", ip1) - require.Equal(t, 1, count, "delete failed") - t.Logf("Zone database:\n%s", zone) - - t.Logf("Checking %s's observers have been notified on removal", name1) - if name1Removed < 3 { - t.Logf("Zone database:\n%s", zone) - t.Fatalf("Unexpected number (%d) of calls to observers", name1Removed) - } - - t.Logf("Checking %s can be found", name1) - _, err = zone.LookupName(name1) - require.NoError(t, err) - - t.Logf("Checking %s is not found after removing %s it in %s and %s in %s", - name1, ip1, container2, ip2, container1) - count = zone.DeleteRecords(container1, "", ip2) - require.Equal(t, 1, count, "delete failed") - count = zone.DeleteRecords(container2, "", ip1) - require.Equal(t, 1, count, "delete failed") - t.Logf("Zone database:\n%s", zone) - _, err = zone.LookupName(name1) - wt.AssertErrorType(t, (*LookupError)(nil), err, "after deleting record") - - t.Logf("Checking if removing an unknown record results in an error") - count = zone.DeleteRecords(container1, "", net.ParseIP("0.0.0.0")) - require.Equal(t, 0, count, "delete failed") -} - -func TestDeleteRecords(t *testing.T) { - var ( - id = "foobar" - name = "foo.weave." - addr1 = "10.2.2.3/24" - addr2 = "10.2.7.8/24" - ) - - EnableDebugLogging(testing.Verbose()) - - zone, err := NewZoneDb(ZoneConfig{}) - require.NoError(t, err) - err = zone.Start() - require.NoError(t, err) - defer zone.Stop() - - for _, addr := range []string{addr1, addr2} { - ip, _, _ := net.ParseCIDR(addr) - err := zone.AddRecord(id, name, ip) - require.NoError(t, err) - } - - _, err = zone.LookupName(name) - require.NoError(t, err) - - count := zone.DeleteRecords(id, "", net.IP{}) - require.Equal(t, 2, count, "wildcard delete failed") - _, err = zone.LookupName(name) - wt.AssertErrorType(t, (*LookupError)(nil), err, "after deleting records for ident") -} diff --git a/prog/weavedns/Dockerfile b/prog/weavedns/Dockerfile deleted file mode 100644 index 883b34b8..00000000 --- a/prog/weavedns/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM scratch -MAINTAINER Weaveworks Inc -WORKDIR /home/weave -ADD ./weavedns /home/weave/ -EXPOSE 53/udp -ENTRYPOINT ["/home/weave/weavedns"] diff --git a/prog/weavedns/main.go b/prog/weavedns/main.go deleted file mode 100644 index c8217656..00000000 --- a/prog/weavedns/main.go +++ /dev/null @@ -1,186 +0,0 @@ -package main - -import ( - "fmt" - "net" - "os" - "strconv" - - "github.com/docker/docker/pkg/mflag" - "github.com/miekg/dns" - . "github.com/weaveworks/weave/common" - "github.com/weaveworks/weave/common/docker" - weavedns "github.com/weaveworks/weave/nameserver" - weavenet "github.com/weaveworks/weave/net" -) - -var version = "(unreleased version)" - -func main() { - var ( - justVersion bool - dockerCli *docker.Client - ifaceName string - apiPath string - domain string - dnsPort int - httpIfaceName string - httpPort int - wait int - ttl int - negTTL int - timeout int - udpbuf int - fallback string - refreshInterval int - relevantTime int - maxAnswers int - cacheLen int - cacheDisabled bool - watch bool - logLevel string - err error - ) - - mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") - mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to use for multicast") - mflag.StringVar(&apiPath, []string{"#api", "-api"}, "unix:///var/run/docker.sock", "path to Docker API socket") - mflag.StringVar(&domain, []string{"#domain", "-domain"}, weavedns.DefaultLocalDomain, "local domain (ie, 'weave.local.')") - mflag.IntVar(&wait, []string{"#wait", "-wait"}, -1, "number of seconds to wait for interfaces to come up (0=don't wait, -1=wait forever)") - mflag.IntVar(&dnsPort, []string{"#dnsport", "#-dnsport", "-dns-port"}, weavedns.DefaultServerPort, "port to listen to DNS requests") - mflag.StringVar(&httpIfaceName, []string{"#httpiface", "#-httpiface", "-http-iface"}, "", "interface on which to listen for HTTP requests (empty string means listen on all interfaces)") - mflag.IntVar(&httpPort, []string{"#httpport", "#-httpport", "-http-port"}, weavedns.DefaultHTTPPort, "port to listen to HTTP requests") - mflag.IntVar(&cacheLen, []string{"#cache", "-cache"}, weavedns.DefaultCacheLen, "cache length") - mflag.IntVar(&ttl, []string{"#ttl", "-ttl"}, weavedns.DefaultLocalTTL, "TTL (in secs) for responses for local names") - mflag.BoolVar(&watch, []string{"#watch", "-watch"}, true, "watch the docker socket for container events") - mflag.StringVar(&logLevel, []string{"-log-level"}, "info", "logging level (debug, info, warning, error)") - // advanced options - mflag.IntVar(&negTTL, []string{"#neg-ttl", "-neg-ttl"}, 0, "negative TTL (in secs) for unanswered queries for local names (0=same value as --ttl") - mflag.IntVar(&refreshInterval, []string{"#refresh", "-refresh"}, weavedns.DefaultRefreshInterval, "refresh interval (in secs) for local names (0=disable)") - mflag.IntVar(&maxAnswers, []string{"#max-answers", "#-max-answers", "-dns-max-answers"}, weavedns.DefaultMaxAnswers, "maximum number of answers returned to clients (0=unlimited)") - mflag.IntVar(&relevantTime, []string{"#relevant", "-relevant"}, weavedns.DefaultRelevantTime, "life time for info in the absence of queries (in secs)") - mflag.IntVar(&udpbuf, []string{"#udpbuf", "#-udpbuf", "-dns-udpbuf"}, weavedns.DefaultUDPBuflen, "UDP buffer length for DNS") - mflag.IntVar(&timeout, []string{"#timeout", "#-timeout", "-dns-timeout"}, weavedns.DefaultTimeout, "timeout for resolutions (in millisecs)") - mflag.BoolVar(&cacheDisabled, []string{"#no-cache", "-no-cache"}, false, "disable the cache") - mflag.StringVar(&fallback, []string{"#fallback", "#-fallback", "-dns-fallback"}, "", "force a fallback server (ie, '8.8.8.8:53') (instead of /etc/resolv.conf values)") - mflag.Parse() - - if justVersion { - fmt.Printf("weave DNS %s\n", version) - os.Exit(0) - } - - SetLogLevel(logLevel) - Log.Infof("[main] WeaveDNS version %s", version) // first thing in log: the version - - var iface *net.Interface - if ifaceName != "" { - var err error - Log.Infoln("[main] Waiting for mDNS interface", ifaceName, "to come up") - iface, err = weavenet.EnsureInterface(ifaceName, wait) - if err != nil { - Log.Fatal(err) - } else { - Log.Infoln("[main] Interface", ifaceName, "is up") - } - } - - var httpIP string - if httpIfaceName == "" { - httpIP = "0.0.0.0" - } else { - Log.Infoln("[main] Waiting for HTTP interface", httpIfaceName, "to come up") - httpIface, err := weavenet.EnsureInterface(httpIfaceName, wait) - if err != nil { - Log.Fatal(err) - } - Log.Infoln("[main] Interface", httpIfaceName, "is up") - - addrs, err := httpIface.Addrs() - if err != nil { - Log.Fatal(err) - } - - if len(addrs) == 0 { - Log.Fatal("[main] No addresses on HTTP interface") - } - - ip, _, err := net.ParseCIDR(addrs[0].String()) - if err != nil { - Log.Fatal(err) - } - - httpIP = ip.String() - - } - httpAddr := net.JoinHostPort(httpIP, strconv.Itoa(httpPort)) - - zoneConfig := weavedns.ZoneConfig{ - Domain: domain, - Iface: iface, - LocalTTL: ttl, - RefreshInterval: refreshInterval, - RelevantTime: relevantTime, - } - zone, err := weavedns.NewZoneDb(zoneConfig) - if err != nil { - Log.Fatal("[main] Unable to initialize the Zone database", err) - } - if err := zone.Start(); err != nil { - Log.Fatal("[main] Unable to start the Zone database", err) - } - defer zone.Stop() - - dockerCli, err = docker.NewClient(apiPath) - if err != nil { - Log.Fatal("[main] Unable to start docker client: ", err) - } - - if watch { - err := dockerCli.AddObserver(zone) - if err != nil { - Log.Fatal("[main] Unable to start watcher", err) - } - } - - srvConfig := weavedns.DNSServerConfig{ - Zone: zone, - Port: dnsPort, - CacheLen: cacheLen, - LocalTTL: ttl, - CacheNegLocalTTL: negTTL, - MaxAnswers: maxAnswers, - Timeout: timeout, - UDPBufLen: udpbuf, - CacheDisabled: cacheDisabled, - } - - if len(fallback) > 0 { - fallbackHost, fallbackPort, err := net.SplitHostPort(fallback) - if err != nil { - Log.Fatal("[main] Could not parse fallback host and port", err) - } - srvConfig.UpstreamCfg = &dns.ClientConfig{Servers: []string{fallbackHost}, Port: fallbackPort} - Log.Debugf("[main] DNS fallback at %s:%s", fallbackHost, fallbackPort) - } - - srv, err := weavedns.NewDNSServer(srvConfig) - if err != nil { - Log.Fatal("[main] Failed to initialize the WeaveDNS server", err) - } - - httpListener, err := net.Listen("tcp", httpAddr) - if err != nil { - Log.Fatal("[main] Unable to create http listener: ", err) - } - Log.Infoln("[main] HTTP API listening on", httpAddr) - - go SignalHandlerLoop(srv) - go weavedns.ServeHTTP(httpListener, version, srv, dockerCli) - - err = srv.Start() - if err != nil { - Log.Fatal("[main] Failed to start the WeaveDNS server: ", err) - } - srv.ActivateAndServe() -} From 8b061fd555d3381298b02151da210d82040c827b Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Mon, 29 Jun 2015 15:37:15 +0000 Subject: [PATCH 099/180] Gossip-based DNS embedded in the router. - Nameserver holds a sorted list of (hostname, peer, container id, ip) tuples. - Entries are gossiped using topology gossip / broadcast - only new/updated entries are propogated as expected. - Entries for a given peer are removed when the connection to the peer is lost. - Entries are tombstoned when containers die. Tombstones are kept for 10mins, as they do not need to survive partition, only gossip propagation delay. --- Makefile | 2 +- nameserver/dns.go | 275 ++++++++++++++++++++++ nameserver/dns_test.go | 95 ++++++++ nameserver/entry.go | 184 +++++++++++++++ nameserver/entry_test.go | 113 +++++++++ nameserver/http.go | 85 +++++++ nameserver/nameserver.go | 251 ++++++++++++++++++++ nameserver/nameserver_test.go | 248 +++++++++++++++++++ net/address/address.go | 7 + prog/weaver/main.go | 46 +++- proxy/create_container_interceptor.go | 12 +- site/ipam.md | 2 +- site/proxy.md | 2 +- site/weavedns-design.md | 102 +++----- site/weavedns.md | 145 ++++-------- test/200_dns_test.sh | 2 +- test/210_dns_cross_hosts_test.sh | 35 +++ test/210_dns_multicast_test.sh | 61 ----- test/220_dns_custom_test.sh | 15 +- test/230_dns_unqualified_test.sh | 2 +- test/240_dns_add_name_test.sh | 2 +- test/250_dns_restart_test.sh | 25 ++ test/260_dns_removal_test.sh | 2 +- test/280_with_or_without_dns_test.sh | 11 +- test/290_dns_fallback_test.sh | 2 +- test/295_dns_large_response.sh | 23 ++ test/500_weave_multi_cidr_test.sh | 1 - test/630_proxy_dns_test.sh | 2 +- test/635_proxy_dns_unqualified_test.sh | 3 +- test/640_proxy_restart_reattaches_test.sh | 3 +- test/config.sh | 6 - weave | 93 +++----- 32 files changed, 1528 insertions(+), 329 deletions(-) create mode 100644 nameserver/dns.go create mode 100644 nameserver/dns_test.go create mode 100644 nameserver/entry.go create mode 100644 nameserver/entry_test.go create mode 100644 nameserver/http.go create mode 100644 nameserver/nameserver.go create mode 100644 nameserver/nameserver_test.go create mode 100755 test/210_dns_cross_hosts_test.sh delete mode 100755 test/210_dns_multicast_test.sh create mode 100755 test/250_dns_restart_test.sh create mode 100755 test/295_dns_large_response.sh diff --git a/Makefile b/Makefile index dca84405..3f93170b 100644 --- a/Makefile +++ b/Makefile @@ -66,7 +66,7 @@ $(WEAVEPROXY_EXE) $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go go build -ldflags "-extldflags \"-static\" -X main.version $(WEAVE_VERSION)" -tags netgo -o $@ ./$(@D) $(NETGO_CHECK) -$(WEAVER_EXE): router/*.go ipam/*.go ipam/*/*.go prog/weaver/main.go +$(WEAVER_EXE): router/*.go ipam/*.go ipam/*/*.go nameserver/*.go prog/weaver/main.go $(WEAVEPROXY_EXE): proxy/*.go prog/weaveproxy/main.go $(NETCHECK_EXE): prog/netcheck/netcheck.go diff --git a/nameserver/dns.go b/nameserver/dns.go new file mode 100644 index 00000000..af437897 --- /dev/null +++ b/nameserver/dns.go @@ -0,0 +1,275 @@ +package nameserver + +import ( + "bytes" + "fmt" + "math/rand" + "net" + "sort" + "strings" + "time" + + "github.com/miekg/dns" + + "github.com/weaveworks/weave/net/address" +) + +const ( + topDomain = "." + reverseDNSdomain = "in-addr.arpa." + etcResolvConf = "/etc/resolv.conf" + udpBuffSize = uint16(4096) + minUDPSize = 512 + + DefaultPort = 53 + DefaultTTL = 1 + DefaultClientTimeout = 5 * time.Second +) + +type DNSServer struct { + ns *Nameserver + domain string + ttl uint32 + port int + + servers []*dns.Server + upstream *dns.ClientConfig + tcpClient *dns.Client + udpClient *dns.Client +} + +func NewDNSServer(ns *Nameserver, domain string, port int, ttl uint32, + clientTimeout time.Duration) (*DNSServer, error) { + + s := &DNSServer{ + ns: ns, + domain: dns.Fqdn(domain), + ttl: ttl, + port: port, + tcpClient: &dns.Client{Net: "tcp", ReadTimeout: clientTimeout}, + udpClient: &dns.Client{Net: "udp", ReadTimeout: clientTimeout, UDPSize: udpBuffSize}, + } + var err error + if s.upstream, err = dns.ClientConfigFromFile(etcResolvConf); err != nil { + return nil, err + } + + err = s.listen(port) + return s, err +} + +func (d *DNSServer) String() string { + var buf bytes.Buffer + fmt.Fprintf(&buf, "WeaveDNS (%s)\n", d.ns.ourName) + fmt.Fprintf(&buf, " listening on port %d, for domain %s\n", d.port, d.domain) + fmt.Fprintf(&buf, " response ttl %d\n", d.ttl) + return buf.String() +} + +func (d *DNSServer) listen(port int) error { + udpListener, err := net.ListenPacket("udp", fmt.Sprintf(":%d", port)) + if err != nil { + return err + } + udpServer := &dns.Server{PacketConn: udpListener, Handler: d.createMux(d.udpClient, minUDPSize)} + + tcpListener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + udpServer.Shutdown() + return err + } + tcpServer := &dns.Server{Listener: tcpListener, Handler: d.createMux(d.tcpClient, -1)} + + d.servers = []*dns.Server{udpServer, tcpServer} + return nil +} + +func (d *DNSServer) ActivateAndServe() { + for _, server := range d.servers { + go func(server *dns.Server) { + server.ActivateAndServe() + }(server) + } +} + +func (d *DNSServer) Stop() error { + for _, server := range d.servers { + if err := server.Shutdown(); err != nil { + return err + } + } + return nil +} + +func (d *DNSServer) errorResponse(r *dns.Msg, code int, w dns.ResponseWriter) { + m := dns.Msg{} + m.SetReply(r) + m.RecursionAvailable = true + m.Rcode = code + + d.ns.debugf("error response: %+v", m) + if err := w.WriteMsg(&m); err != nil { + d.ns.infof("error responding: %v", err) + } +} + +func (d *DNSServer) createMux(client *dns.Client, defaultMaxResponseSize int) *dns.ServeMux { + m := dns.NewServeMux() + m.HandleFunc(d.domain, d.handleLocal(defaultMaxResponseSize)) + m.HandleFunc(reverseDNSdomain, d.handleReverse(client, defaultMaxResponseSize)) + m.HandleFunc(topDomain, d.handleRecursive(client, defaultMaxResponseSize)) + return m +} + +func (d *DNSServer) handleLocal(defaultMaxResponseSize int) func(dns.ResponseWriter, *dns.Msg) { + return func(w dns.ResponseWriter, req *dns.Msg) { + d.ns.debugf("local request: %+v", *req) + if len(req.Question) != 1 || req.Question[0].Qtype != dns.TypeA { + d.errorResponse(req, dns.RcodeNameError, w) + return + } + + hostname := req.Question[0].Name + addrs := d.ns.Lookup(hostname) + + response := dns.Msg{} + response.RecursionAvailable = true + response.Authoritative = true + response.SetReply(req) + response.Answer = make([]dns.RR, len(addrs)) + + header := dns.RR_Header{ + Name: hostname, + Rrtype: dns.TypeA, + Class: dns.ClassINET, + Ttl: d.ttl, + } + + for i, addr := range addrs { + ip := addr.IP4() + response.Answer[i] = &dns.A{Hdr: header, A: ip} + } + + shuffleAnswers(&response.Answer) + maxResponseSize := getMaxResponseSize(req, defaultMaxResponseSize) + truncateResponse(&response, maxResponseSize) + + d.ns.debugf("response: %+v", response) + if err := w.WriteMsg(&response); err != nil { + d.ns.infof("error responding: %v", err) + } + } +} + +func (d *DNSServer) handleReverse(client *dns.Client, defaultMaxResponseSize int) func(dns.ResponseWriter, *dns.Msg) { + return func(w dns.ResponseWriter, req *dns.Msg) { + d.ns.debugf("reverse request: %+v", *req) + if len(req.Question) != 1 || req.Question[0].Qtype != dns.TypePTR { + d.errorResponse(req, dns.RcodeNameError, w) + return + } + + ipStr := strings.TrimSuffix(req.Question[0].Name, "."+reverseDNSdomain) + ip, err := address.ParseIP(ipStr) + if err != nil { + d.errorResponse(req, dns.RcodeNameError, w) + return + } + + hostname, err := d.ns.ReverseLookup(ip.Reverse()) + if err != nil { + d.handleRecursive(client, defaultMaxResponseSize)(w, req) + return + } + + response := dns.Msg{} + response.RecursionAvailable = true + response.Authoritative = true + response.SetReply(req) + + header := dns.RR_Header{ + Name: req.Question[0].Name, + Rrtype: dns.TypePTR, + Class: dns.ClassINET, + Ttl: d.ttl, + } + + response.Answer = []dns.RR{&dns.PTR{ + Hdr: header, + Ptr: hostname, + }} + + maxResponseSize := getMaxResponseSize(req, defaultMaxResponseSize) + truncateResponse(&response, maxResponseSize) + + d.ns.debugf("response: %+v", response) + if err := w.WriteMsg(&response); err != nil { + d.ns.infof("error responding: %v", err) + } + } +} + +func (d *DNSServer) handleRecursive(client *dns.Client, defaultMaxResponseSize int) func(dns.ResponseWriter, *dns.Msg) { + return func(w dns.ResponseWriter, req *dns.Msg) { + d.ns.debugf("recursive cdrequest: %+v", *req) + for _, server := range d.upstream.Servers { + response, _, err := client.Exchange(req, fmt.Sprintf("%s:%s", server, d.upstream.Port)) + if err != nil || response == nil { + d.ns.debugf("network error trying %s (%s)", server, err) + continue + } + if response.Rcode != dns.RcodeSuccess && !response.Authoritative { + d.ns.debugf("network error trying %s (%s)", server, err) + continue + } + d.ns.debugf("response: %+v", response) + if err := w.WriteMsg(response); err != nil { + d.ns.infof("error responding: %v", err) + } + return + } + + d.errorResponse(req, dns.RcodeServerFailure, w) + } +} + +func shuffleAnswers(answers *[]dns.RR) { + if len(*answers) <= 1 { + return + } + + for i := range *answers { + j := rand.Intn(i + 1) + (*answers)[i], (*answers)[j] = (*answers)[j], (*answers)[i] + } +} + +func truncateResponse(response *dns.Msg, maxSize int) { + if len(response.Answer) <= 1 || maxSize <= 0 { + return + } + + // take a copy of answers, as we're going to mutate response + answers := response.Answer + + // search for smallest i that is too big + i := sort.Search(len(response.Answer), func(i int) bool { + // return true if too big + response.Answer = answers[:i+1] + return response.Len() > maxSize + }) + if i == len(answers) { + response.Answer = answers + return + } + + response.Answer = answers[:i] + response.Truncated = true +} + +func getMaxResponseSize(req *dns.Msg, defaultMaxResponseSize int) int { + if opt := req.IsEdns0(); opt != nil { + return int(opt.UDPSize()) + } + return defaultMaxResponseSize +} diff --git a/nameserver/dns_test.go b/nameserver/dns_test.go new file mode 100644 index 00000000..b44ce94b --- /dev/null +++ b/nameserver/dns_test.go @@ -0,0 +1,95 @@ +package nameserver + +import ( + "fmt" + "math/rand" + "net" + "testing" + "time" + + "github.com/miekg/dns" + "github.com/stretchr/testify/require" + + "github.com/weaveworks/weave/net/address" + "github.com/weaveworks/weave/router" +) + +func TestTruncation(t *testing.T) { + //common.SetLogLevel("debug") + + peername, err := router.PeerNameFromString("00:00:00:02:00:00") + require.Nil(t, err) + nameserver := New(peername, nil, nil, "") + dnsserver, err := NewDNSServer(nameserver, "weave.local.", 0, 30, 5*time.Second) + require.Nil(t, err) + udpPort := dnsserver.servers[0].PacketConn.LocalAddr().(*net.UDPAddr).Port + tcpPort := dnsserver.servers[1].Listener.Addr().(*net.TCPAddr).Port + go dnsserver.ActivateAndServe() + defer dnsserver.Stop() + + // Add 100 mappings to nameserver + addrs := []address.Address{} + for i := address.Address(0); i < 100; i++ { + addrs = append(addrs, i) + nameserver.AddEntry("foo.weave.local.", "", peername, i) + } + + doRequest := func(client *dns.Client, request *dns.Msg, port int) *dns.Msg { + request.SetQuestion("foo.weave.local.", dns.TypeA) + response, _, err := client.Exchange(request, fmt.Sprintf("127.0.0.1:%d", port)) + require.Nil(t, err) + return response + } + + // do a udp query, ensure we get a truncated response + { + udpClient := dns.Client{Net: "udp", UDPSize: minUDPSize} + response := doRequest(&udpClient, &dns.Msg{}, udpPort) + require.Nil(t, err) + require.True(t, response.MsgHdr.Truncated) + require.True(t, len(response.Answer) < 100) + } + + // do a udp query with big size, ensure we don't get a truncated response + { + udpClient := dns.Client{Net: "udp", UDPSize: 65535} + request := &dns.Msg{} + request.SetEdns0(65535, false) + response := doRequest(&udpClient, request, udpPort) + require.False(t, response.MsgHdr.Truncated) + require.Equal(t, len(response.Answer), 100) + } + + // do a tcp query, ensure we don't get a truncated response + { + tcpClient := dns.Client{Net: "tcp"} + response := doRequest(&tcpClient, &dns.Msg{}, tcpPort) + require.False(t, response.MsgHdr.Truncated) + require.Equal(t, len(response.Answer), 100) + } +} + +func TestTruncateResponse(t *testing.T) { + + header := dns.RR_Header{ + Name: "host.domain.com", + Rrtype: dns.TypePTR, + Class: dns.ClassINET, + Ttl: 30, + } + + for i := 0; i < 10000; i++ { + // generate a random msg + response := &dns.Msg{} + numAnswers := 40 + rand.Intn(200) + response.Answer = make([]dns.RR, numAnswers) + for j := 0; j < numAnswers; j++ { + response.Answer[j] = &dns.A{Hdr: header, A: address.Address(j).IP4()} + } + + // pick a random max size, truncate response to that, check it + maxSize := 512 + rand.Intn(response.Len()-512) + truncateResponse(response, maxSize) + require.True(t, response.Len() <= maxSize) + } +} diff --git a/nameserver/entry.go b/nameserver/entry.go new file mode 100644 index 00000000..0ab22008 --- /dev/null +++ b/nameserver/entry.go @@ -0,0 +1,184 @@ +package nameserver + +import ( + "bytes" + "encoding/gob" + "fmt" + "sort" + "time" + + "github.com/weaveworks/weave/net/address" + "github.com/weaveworks/weave/router" +) + +var now = func() int64 { return time.Now().Unix() } + +type Entry struct { + ContainerID string + Origin router.PeerName + Addr address.Address + Hostname string + Version int + Tombstone int64 // timestamp of when it was deleted +} + +type Entries []Entry + +func (e1 *Entry) equal(e2 *Entry) bool { + return e1.ContainerID == e2.ContainerID && + e1.Origin == e2.Origin && + e1.Addr == e2.Addr && + e1.Hostname == e2.Hostname +} + +func (e1 *Entry) less(e2 *Entry) bool { + // Entries are kept sorted by Hostname, Origin, ContainerID then address + switch { + case e1.Hostname != e2.Hostname: + return e1.Hostname < e2.Hostname + + case e1.Origin != e2.Origin: + return e1.Origin < e2.Origin + + case e1.ContainerID != e2.ContainerID: + return e1.ContainerID < e2.ContainerID + + default: + return e1.Addr < e2.Addr + } +} + +// returns true to indicate a change +func (e1 *Entry) merge(e2 *Entry) bool { + // we know container id, origin, add and hostname are equal + if e2.Version > e1.Version { + e1.Version = e2.Version + e1.Tombstone = e2.Tombstone + } + return e2.Version != e1.Version +} + +func (e1 *Entry) String() string { + return fmt.Sprintf("%s -> %s", e1.Hostname, e1.Addr.String()) +} + +func (es Entries) Len() int { return len(es) } +func (es Entries) Swap(i, j int) { panic("Swap") } +func (es Entries) Less(i, j int) bool { return es[i].less(&es[j]) } + +func (es *Entries) check() error { + if !sort.IsSorted(es) { + return fmt.Errorf("Not sorted!") + } + return nil +} + +func (es *Entries) checkAndPanic() { + if err := es.check(); err != nil { + panic(err) + } +} + +func (es *Entries) add(hostname, containerid string, origin router.PeerName, addr address.Address) Entry { + defer es.checkAndPanic() + + entry := Entry{Hostname: hostname, Origin: origin, ContainerID: containerid, Addr: addr} + i := sort.Search(len(*es), func(i int) bool { + return !(*es)[i].less(&entry) + }) + if i < len(*es) && (*es)[i].equal(&entry) { + (*es)[i].Tombstone = 0 + (*es)[i].Version++ + } else { + *es = append(*es, Entry{}) + copy((*es)[i+1:], (*es)[i:]) + (*es)[i] = entry + } + return (*es)[i] +} + +func (es *Entries) merge(incoming Entries) Entries { + defer es.checkAndPanic() + var ( + newEntries Entries + i = 0 + ) + + for _, entry := range incoming { + for i < len(*es) && (*es)[i].less(&entry) { + i++ + } + if i < len(*es) && (*es)[i].equal(&entry) { + if !(*es)[i].merge(&entry) { + continue + } + } + *es = append(*es, Entry{}) + copy((*es)[i+1:], (*es)[i:]) + (*es)[i] = entry + newEntries = append(newEntries, entry) + } + + return newEntries +} + +func (es *Entries) tombstone(ourname router.PeerName, f func(*Entry) bool) *Entries { + tombstoned := Entries{} + for i, e := range *es { + if f(&e) && e.Origin == ourname { + e.Version++ + e.Tombstone = now() + (*es)[i] = e + tombstoned = append(tombstoned, e) + } + } + return &tombstoned +} + +func (es *Entries) filter(f func(*Entry) bool) { + i := 0 + for _, e := range *es { + if !f(&e) { + continue + } + (*es)[i] = e + i++ + } + *es = (*es)[:i] +} + +func (es Entries) lookup(hostname string) Entries { + i := sort.Search(len(es), func(i int) bool { + return es[i].Hostname >= hostname + }) + if i >= len(es) || es[i].Hostname != hostname { + return Entries{} + } + + j := sort.Search(len(es)-i, func(j int) bool { + return es[i+j].Hostname > hostname + }) + + return es[i : i+j] +} + +func (es *Entries) first(f func(*Entry) bool) (*Entry, error) { + for _, e := range *es { + if f(&e) { + return &e, nil + } + } + return nil, fmt.Errorf("Not found") +} + +func (es *Entries) Merge(other router.GossipData) { + es.merge(*other.(*Entries)) +} + +func (es *Entries) Encode() [][]byte { + buf := &bytes.Buffer{} + if err := gob.NewEncoder(buf).Encode(es); err != nil { + panic(err) + } + return [][]byte{buf.Bytes()} +} diff --git a/nameserver/entry_test.go b/nameserver/entry_test.go new file mode 100644 index 00000000..5e8efa03 --- /dev/null +++ b/nameserver/entry_test.go @@ -0,0 +1,113 @@ +package nameserver + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/weaveworks/weave/net/address" + "github.com/weaveworks/weave/router" +) + +func TestAdd(t *testing.T) { + oldNow := now + defer func() { now = oldNow }() + now = func() int64 { return 1234 } + + entries := Entries{} + entries.add("A", "", router.UnknownPeerName, address.Address(0)) + expected := Entries{ + Entry{Hostname: "A", Origin: router.UnknownPeerName, Addr: address.Address(0)}, + } + require.Equal(t, entries, expected) + + entries.tombstone(router.UnknownPeerName, func(e *Entry) bool { return e.Hostname == "A" }) + expected = Entries{ + Entry{Hostname: "A", Origin: router.UnknownPeerName, Addr: address.Address(0), Version: 1, Tombstone: 1234}, + } + require.Equal(t, entries, expected) + + entries.add("A", "", router.UnknownPeerName, address.Address(0)) + expected = Entries{ + Entry{Hostname: "A", Origin: router.UnknownPeerName, Addr: address.Address(0), Version: 2}, + } + require.Equal(t, entries, expected) +} + +func TestMerge(t *testing.T) { + e1 := Entries{ + Entry{Hostname: "A"}, + Entry{Hostname: "C"}, + Entry{Hostname: "D"}, + Entry{Hostname: "F"}, + } + + e2 := Entries{ + Entry{Hostname: "B"}, + Entry{Hostname: "E"}, + Entry{Hostname: "F"}, + } + + e1.merge(e2) + expected := Entries{ + Entry{Hostname: "A"}, + Entry{Hostname: "B"}, + Entry{Hostname: "C"}, + Entry{Hostname: "D"}, + Entry{Hostname: "E"}, + Entry{Hostname: "F"}, + } + + require.Equal(t, e1, expected) +} + +func TestTombstone(t *testing.T) { + oldNow := now + defer func() { now = oldNow }() + now = func() int64 { return 1234 } + + es := Entries{ + Entry{Hostname: "A"}, + Entry{Hostname: "B"}, + } + + es.tombstone(router.UnknownPeerName, func(e *Entry) bool { + return e.Hostname == "B" + }) + expected := Entries{ + Entry{Hostname: "A"}, + Entry{Hostname: "B", Version: 1, Tombstone: 1234}, + } + require.Equal(t, es, expected) +} + +func TestDelete(t *testing.T) { + es := Entries{ + Entry{Hostname: "A"}, + Entry{Hostname: "B"}, + } + + es.filter(func(e *Entry) bool { + return e.Hostname != "A" + }) + expected := Entries{ + Entry{Hostname: "B"}, + } + require.Equal(t, es, expected) +} + +func TestLookup(t *testing.T) { + es := Entries{ + Entry{Hostname: "A"}, + Entry{Hostname: "B", ContainerID: "foo"}, + Entry{Hostname: "B", ContainerID: "bar"}, + Entry{Hostname: "C"}, + } + + have := es.lookup("B") + want := Entries{ + Entry{Hostname: "B", ContainerID: "foo"}, + Entry{Hostname: "B", ContainerID: "bar"}, + } + require.Equal(t, have, want) +} diff --git a/nameserver/http.go b/nameserver/http.go new file mode 100644 index 00000000..d85b9970 --- /dev/null +++ b/nameserver/http.go @@ -0,0 +1,85 @@ +package nameserver + +import ( + "fmt" + "net/http" + + "github.com/gorilla/mux" + "github.com/miekg/dns" + + "github.com/weaveworks/weave/common" + "github.com/weaveworks/weave/net/address" +) + +func badRequest(w http.ResponseWriter, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + common.Log.Warningf("[gossipdns]: %v", err) +} + +func (n *Nameserver) HandleHTTP(router *mux.Router) { + router.Methods("GET").Path("/domain").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, n.domain) + }) + + router.Methods("PUT").Path("/name/{container}/{ip}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var ( + vars = mux.Vars(r) + container = vars["container"] + ipStr = vars["ip"] + hostname = r.FormValue("fqdn") + ip, err = address.ParseIP(ipStr) + ) + if err != nil { + badRequest(w, err) + return + } + + if err := n.AddEntry(dns.Fqdn(hostname), container, n.ourName, ip); err != nil { + badRequest(w, fmt.Errorf("Unable to add entry: %v", err)) + return + } + + if r.FormValue("check-alive") == "true" && n.docker.IsContainerNotRunning(container) { + common.Log.Infof("[gossipdns] '%s' is not running: removing", container) + if err := n.Delete(hostname, container, ipStr, ip); err != nil { + common.Log.Infof("[gossipdns] failed to remove: %v", err) + } + } + + w.WriteHeader(204) + }) + + deleteHandler := func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + + hostname := r.FormValue("fqdn") + if hostname == "" { + hostname = "*" + } else { + hostname = dns.Fqdn(hostname) + } + + container, ok := vars["container"] + if !ok { + container = "*" + } + + ipStr, ok := vars["ip"] + ip, err := address.ParseIP(ipStr) + if ok && err != nil { + badRequest(w, err) + return + } else if !ok { + ipStr = "*" + } + + if err := n.Delete(hostname, container, ipStr, ip); err != nil { + badRequest(w, fmt.Errorf("Unable to delete entries: %v", err)) + return + } + w.WriteHeader(204) + } + router.Methods("DELETE").Path("/name/{container}/{ip}").HandlerFunc(deleteHandler) + router.Methods("DELETE").Path("/name/{container}").HandlerFunc(deleteHandler) + router.Methods("DELETE").Path("/name").HandlerFunc(deleteHandler) +} diff --git a/nameserver/nameserver.go b/nameserver/nameserver.go new file mode 100644 index 00000000..43562ae5 --- /dev/null +++ b/nameserver/nameserver.go @@ -0,0 +1,251 @@ +package nameserver + +import ( + "bytes" + "encoding/gob" + "fmt" + "sync" + "time" + + "github.com/miekg/dns" + + . "github.com/weaveworks/weave/common" + "github.com/weaveworks/weave/common/docker" + "github.com/weaveworks/weave/net/address" + "github.com/weaveworks/weave/router" +) + +const ( + // Tombstones do not need to survive long periods of peer disconnection, as + // we delete entries for disconnected peers. Therefore they just need to hang + // around to account for propagation delay through gossip. 10 minutes sounds + // long enough. + tombstoneTimeout = time.Minute * 10 + + // Used by prog/weaver/main.go and proxy/create_container_interceptor.go + DefaultDomain = "weave.local." +) + +// Nameserver: gossip-based, in memory nameserver. +// - Holds a sorted list of (hostname, peer, container id, ip) tuples for the whole cluster. +// - This list is gossiped & merged around the cluser. +// - Lookup-by-hostname are O(nlogn), and return a (copy of a) slice of the entries +// - Update is O(n) for now +type Nameserver struct { + sync.RWMutex + ourName router.PeerName + domain string + gossip router.Gossip + docker *docker.Client + entries Entries + peers *router.Peers + quit chan struct{} +} + +func New(ourName router.PeerName, peers *router.Peers, docker *docker.Client, domain string) *Nameserver { + ns := &Nameserver{ + ourName: ourName, + domain: dns.Fqdn(domain), + peers: peers, + docker: docker, + quit: make(chan struct{}), + } + if peers != nil { + peers.OnGC(ns.PeerGone) + } + return ns +} + +func (n *Nameserver) SetGossip(gossip router.Gossip) { + n.gossip = gossip +} + +func (n *Nameserver) Start() { + go func() { + ticker := time.Tick(tombstoneTimeout) + for { + select { + case <-n.quit: + return + case <-ticker: + n.deleteTombstones() + } + } + }() +} + +func (n *Nameserver) Stop() { + n.quit <- struct{}{} +} + +func (n *Nameserver) AddEntry(hostname, containerid string, origin router.PeerName, addr address.Address) error { + n.infof("adding entry %s -> %s", hostname, addr.String()) + n.Lock() + entry := n.entries.add(hostname, containerid, origin, addr) + n.Unlock() + + if n.gossip != nil { + return n.gossip.GossipBroadcast(&Entries{entry}) + } + return nil +} + +func (n *Nameserver) Lookup(hostname string) []address.Address { + n.RLock() + defer n.RUnlock() + + entries := n.entries.lookup(hostname) + result := []address.Address{} + for _, e := range entries { + if e.Tombstone > 0 { + continue + } + result = append(result, e.Addr) + } + n.debugf("lookup %s -> %s", hostname, &result) + return result +} + +func (n *Nameserver) ReverseLookup(ip address.Address) (string, error) { + n.RLock() + defer n.RUnlock() + + match, err := n.entries.first(func(e *Entry) bool { + return e.Addr == ip + }) + if err != nil { + return "", err + } + n.debugf("reverse lookup %s -> %s", ip, match.Hostname) + return match.Hostname, nil +} + +func (n *Nameserver) ContainerDied(ident string) error { + n.Lock() + entries := n.entries.tombstone(n.ourName, func(e *Entry) bool { + if e.ContainerID == ident { + n.infof("container %s died, tombstoning entry %s", ident, e.String()) + return true + } + return false + }) + n.Unlock() + if n.gossip != nil { + return n.gossip.GossipBroadcast(entries) + } + return nil +} + +func (n *Nameserver) PeerGone(peer *router.Peer) { + n.Lock() + defer n.Unlock() + n.entries.filter(func(e *Entry) bool { + return e.Origin != peer.Name + }) +} + +func (n *Nameserver) Delete(hostname, containerid, ipStr string, ip address.Address) error { + n.Lock() + n.infof("tombstoning hostname=%s, containerid=%s, ip=%s", hostname, containerid, ipStr) + entries := n.entries.tombstone(n.ourName, func(e *Entry) bool { + if hostname != "*" && e.Hostname != hostname { + return false + } + + if containerid != "*" && e.ContainerID != containerid { + return false + } + + if ipStr != "*" && e.Addr != ip { + return false + } + return true + }) + n.Unlock() + if n.gossip != nil { + return n.gossip.GossipBroadcast(entries) + } + return nil +} + +func (n *Nameserver) deleteTombstones() { + n.Lock() + defer n.Unlock() + now := time.Now().Unix() + n.entries.filter(func(e *Entry) bool { + return now-e.Tombstone <= int64(tombstoneTimeout/time.Second) + }) +} + +func (n *Nameserver) String() string { + n.RLock() + defer n.RUnlock() + var buf bytes.Buffer + for _, entry := range n.entries { + if entry.Tombstone > 0 { + continue + } + containerid := entry.ContainerID + if len(containerid) > 12 { + containerid = containerid[:12] + } + fmt.Fprintf(&buf, "%s: %s [%s]\n", containerid, entry.Hostname, entry.Addr.String()) + } + return buf.String() +} + +func (n *Nameserver) Gossip() router.GossipData { + n.RLock() + defer n.RUnlock() + result := make(Entries, len(n.entries)) + copy(result, n.entries) + return &result +} + +func (n *Nameserver) OnGossipUnicast(sender router.PeerName, msg []byte) error { + return nil +} + +func (n *Nameserver) receiveGossip(msg []byte) (router.GossipData, router.GossipData, error) { + var entries Entries + if err := gob.NewDecoder(bytes.NewReader(msg)).Decode(&entries); err != nil { + return nil, nil, err + } + + if err := entries.check(); err != nil { + return nil, nil, err + } + + n.Lock() + defer n.Unlock() + + if n.peers != nil { + entries.filter(func(e *Entry) bool { + return n.peers.Fetch(e.Origin) != nil + }) + } + + newEntries := n.entries.merge(entries) + return &newEntries, &entries, nil +} + +// merge received data into state and return "everything new I've +// just learnt", or nil if nothing in the received data was new +func (n *Nameserver) OnGossip(msg []byte) (router.GossipData, error) { + newEntries, _, err := n.receiveGossip(msg) + return newEntries, err +} + +// merge received data into state and return a representation of +// the received data, for further propagation +func (n *Nameserver) OnGossipBroadcast(msg []byte) (router.GossipData, error) { + _, entries, err := n.receiveGossip(msg) + return entries, err +} + +func (n *Nameserver) infof(fmt string, args ...interface{}) { + Log.Infof("[nameserver %s] "+fmt, append([]interface{}{n.ourName}, args...)...) +} +func (n *Nameserver) debugf(fmt string, args ...interface{}) { + Log.Debugf("[nameserver %s] "+fmt, append([]interface{}{n.ourName}, args...)...) +} diff --git a/nameserver/nameserver_test.go b/nameserver/nameserver_test.go new file mode 100644 index 00000000..f1b091fe --- /dev/null +++ b/nameserver/nameserver_test.go @@ -0,0 +1,248 @@ +package nameserver + +import ( + "fmt" + "math/rand" + "reflect" + "sort" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/weaveworks/weave/net/address" + "github.com/weaveworks/weave/router" + "github.com/weaveworks/weave/testing/gossip" +) + +func makeNetwork(size int) ([]*Nameserver, *gossip.TestRouter) { + gossipRouter := gossip.NewTestRouter(0.0) + nameservers := make([]*Nameserver, size) + + for i := 0; i < size; i++ { + name, _ := router.PeerNameFromString(fmt.Sprintf("%02d:00:00:02:00:00", i)) + nameserver := New(name, nil, nil, "") + nameserver.SetGossip(gossipRouter.Connect(nameserver.ourName, nameserver)) + nameserver.Start() + nameservers[i] = nameserver + } + + return nameservers, gossipRouter +} + +func stopNetwork(nameservers []*Nameserver) { + for _, nameserver := range nameservers { + nameserver.Stop() + } +} + +type pair struct { + origin router.PeerName + addr address.Address +} + +type mapping struct { + hostname string + addrs []pair +} + +type addrs []address.Address + +func (a addrs) Len() int { return len(a) } +func (a addrs) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a addrs) Less(i, j int) bool { return a[i] < a[j] } +func (a addrs) String() string { + ss := []string{} + for _, addr := range a { + ss = append(ss, addr.String()) + } + return strings.Join(ss, " ") +} + +func (m mapping) Addrs() []address.Address { + want := addrs{} + for _, p := range m.addrs { + want = append(want, p.addr) + } + sort.Sort(want) + return want +} + +func TestNameservers(t *testing.T) { + //common.SetLogLevel("debug") + + lookupTimeout := 20 // ms + nameservers, grouter := makeNetwork(50) + defer stopNetwork(nameservers) + nameserversByName := map[router.PeerName]*Nameserver{} + for _, n := range nameservers { + nameserversByName[n.ourName] = n + } + mappings := []mapping{} + + check := func(nameserver *Nameserver, expected mapping) { + have := []address.Address{} + for i := 0; i < lookupTimeout; i++ { + have = nameserver.Lookup(expected.hostname) + sort.Sort(addrs(have)) + if reflect.DeepEqual(have, expected.Addrs()) { + return + } + time.Sleep(1 * time.Millisecond) + } + want := expected.Addrs() + require.Equal(t, addrs(want).String(), addrs(have).String()) + } + + addMapping := func() { + nameserver := nameservers[rand.Intn(len(nameservers))] + addr := address.Address(rand.Int31()) + hostname := fmt.Sprintf("hostname%d", rand.Int63()) + mapping := mapping{hostname, []pair{{nameserver.ourName, addr}}} + mappings = append(mappings, mapping) + + require.Nil(t, nameserver.AddEntry(hostname, "", nameserver.ourName, addr)) + check(nameserver, mapping) + } + + addExtraMapping := func() { + if len(mappings) <= 0 { + return + } + nameserver := nameservers[rand.Intn(len(nameservers))] + i := rand.Intn(len(mappings)) + mapping := mappings[i] + addr := address.Address(rand.Int31()) + mapping.addrs = append(mapping.addrs, pair{nameserver.ourName, addr}) + mappings[i] = mapping + + require.Nil(t, nameserver.AddEntry(mapping.hostname, "", nameserver.ourName, addr)) + check(nameserver, mapping) + } + + deleteMapping := func() { + if len(mappings) <= 0 { + return + } + i := rand.Intn(len(mappings)) + mapping := mappings[i] + if len(mapping.addrs) <= 0 { + return + } + j := rand.Intn(len(mapping.addrs)) + pair := mapping.addrs[j] + mapping.addrs = append(mapping.addrs[:j], mapping.addrs[j+1:]...) + mappings[i] = mapping + nameserver := nameserversByName[pair.origin] + + require.Nil(t, nameserver.Delete(mapping.hostname, "*", pair.addr.String(), pair.addr)) + check(nameserver, mapping) + } + + doLookup := func() { + if len(mappings) <= 0 { + return + } + mapping := mappings[rand.Intn(len(mappings))] + nameserver := nameservers[rand.Intn(len(nameservers))] + check(nameserver, mapping) + } + + doReverseLookup := func() { + if len(mappings) <= 0 { + return + } + mapping := mappings[rand.Intn(len(mappings))] + if len(mapping.addrs) <= 0 { + return + } + nameserver := nameservers[rand.Intn(len(nameservers))] + hostname := "" + var err error + for i := 0; i < lookupTimeout; i++ { + hostname, err = nameserver.ReverseLookup(mapping.addrs[0].addr) + if err != nil && mapping.hostname == hostname { + return + } + time.Sleep(1 * time.Millisecond) + } + require.Nil(t, err) + require.Equal(t, mapping.hostname, hostname) + } + + for i := 0; i < 1000; i++ { + if i%10 == 0 { + grouter.Flush() + } + + r := rand.Float32() + switch { + case r < 0.1: + addMapping() + + case 0.1 <= r && r < 0.2: + addExtraMapping() + + case 0.2 <= r && r < 0.3: + deleteMapping() + + case 0.3 <= r && r < 0.9: + doLookup() + + case 0.9 <= r: + doReverseLookup() + } + } +} + +func TestContainerAndPeerDeath(t *testing.T) { + peername, err := router.PeerNameFromString("00:00:00:02:00:00") + require.Nil(t, err) + nameserver := New(peername, nil, nil, "") + + err = nameserver.AddEntry("hostname", "containerid", peername, address.Address(0)) + require.Nil(t, err) + require.Equal(t, []address.Address{0}, nameserver.Lookup("hostname")) + + err = nameserver.ContainerDied("containerid") + require.Nil(t, err) + require.Equal(t, []address.Address{}, nameserver.Lookup("hostname")) + + err = nameserver.AddEntry("hostname", "containerid", peername, address.Address(0)) + require.Nil(t, err) + require.Equal(t, []address.Address{0}, nameserver.Lookup("hostname")) + + nameserver.PeerGone(&router.Peer{Name: peername}) + require.Equal(t, []address.Address{}, nameserver.Lookup("hostname")) +} + +func TestTombstoneDeletion(t *testing.T) { + oldNow := now + defer func() { now = oldNow }() + now = func() int64 { return 1234 } + + peername, err := router.PeerNameFromString("00:00:00:02:00:00") + require.Nil(t, err) + nameserver := New(peername, nil, nil, "") + + err = nameserver.AddEntry("hostname", "containerid", peername, address.Address(0)) + require.Nil(t, err) + require.Equal(t, []address.Address{0}, nameserver.Lookup("hostname")) + + err = nameserver.Delete("hostname", "containerid", "", address.Address(0)) + require.Nil(t, err) + require.Equal(t, []address.Address{}, nameserver.Lookup("hostname")) + require.Equal(t, Entries{{ + ContainerID: "containerid", + Origin: peername, + Addr: address.Address(0), + Hostname: "hostname", + Version: 1, + Tombstone: 1234, + }}, nameserver.entries) + + now = func() int64 { return 1234 + int64(tombstoneTimeout/time.Second) + 1 } + nameserver.deleteTombstones() + require.Equal(t, Entries{}, nameserver.entries) +} diff --git a/net/address/address.go b/net/address/address.go index f97d44c8..f3faf138 100644 --- a/net/address/address.go +++ b/net/address/address.go @@ -98,3 +98,10 @@ func Min(a, b Offset) Offset { } return a } + +func (addr Address) Reverse() Address { + return ((addr >> 24) & 0xff) | // move byte 3 to byte 0 + ((addr << 8) & 0xff0000) | // move byte 1 to byte 2 + ((addr >> 8) & 0xff00) | // move byte 2 to byte 1 + ((addr << 24) & 0xff000000) // byte 0 to byte 3 +} diff --git a/prog/weaver/main.go b/prog/weaver/main.go index 30a17d96..53aa3b20 100644 --- a/prog/weaver/main.go +++ b/prog/weaver/main.go @@ -8,6 +8,7 @@ import ( "os" "runtime" "strings" + "time" "github.com/davecheney/profile" "github.com/docker/docker/pkg/mflag" @@ -16,6 +17,7 @@ import ( . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common/docker" "github.com/weaveworks/weave/ipam" + "github.com/weaveworks/weave/nameserver" weavenet "github.com/weaveworks/weave/net" "github.com/weaveworks/weave/net/address" weave "github.com/weaveworks/weave/router" @@ -52,6 +54,10 @@ func main() { peerCount int apiPath string peers []string + dnsDomain string + dnsPort int + dnsTTL int + dnsClientTimeout time.Duration ) mflag.BoolVar(&justVersion, []string{"#version", "-version"}, false, "print version and exit") @@ -73,6 +79,11 @@ func main() { mflag.StringVar(&ipsubnetCIDR, []string{"#ipsubnet", "#-ipsubnet", "-ipalloc-default-subnet"}, "", "subnet to allocate within by default, in CIDR notation") mflag.IntVar(&peerCount, []string{"#initpeercount", "#-initpeercount", "-init-peer-count"}, 0, "number of peers in network (for IP address allocation)") mflag.StringVar(&apiPath, []string{"#api", "-api"}, "unix:///var/run/docker.sock", "Path to Docker API socket") + mflag.StringVar(&dnsDomain, []string{"-dns-domain"}, nameserver.DefaultDomain, "local domain to server requests for") + mflag.IntVar(&dnsPort, []string{"-dns-port"}, nameserver.DefaultPort, "port to listen on for DNS requests") + mflag.IntVar(&dnsTTL, []string{"-dns-ttl"}, nameserver.DefaultTTL, "TTL for DNS request from our domain") + mflag.DurationVar(&dnsClientTimeout, []string{"-dns-fallback-timeout"}, nameserver.DefaultClientTimeout, "timeout for fallback DNS requests") + mflag.Parse() peers = mflag.Args() @@ -141,15 +152,15 @@ func main() { router := weave.NewRouter(config, name, nickName) Log.Println("Our name is", router.Ourself) + dockerCli, err := docker.NewClient(apiPath) + if err != nil { + Log.Fatal("Unable to start docker client: ", err) + } + var allocator *ipam.Allocator var defaultSubnet address.CIDR - var dockerCli *docker.Client if iprangeCIDR != "" { allocator, defaultSubnet = createAllocator(router, iprangeCIDR, ipsubnetCIDR, determineQuorum(peerCount, peers)) - dockerCli, err = docker.NewClient(apiPath) - if err != nil { - Log.Fatal("Unable to start docker client: ", err) - } if err = dockerCli.AddObserver(allocator); err != nil { Log.Fatal("Unable to start watcher", err) } @@ -157,6 +168,22 @@ func main() { Log.Fatal("--init-peer-count flag specified without --ipalloc-range") } + ns := nameserver.New(router.Ourself.Peer.Name, router.Peers, dockerCli, dnsDomain) + ns.SetGossip(router.NewGossip("nameserver", ns)) + if err = dockerCli.AddObserver(ns); err != nil { + Log.Fatal("Unable to start watcher", err) + } + ns.Start() + defer ns.Stop() + + dnsserver, err := nameserver.NewDNSServer(ns, dnsDomain, dnsPort, + uint32(dnsTTL), dnsClientTimeout) + if err != nil { + Log.Fatal("Unable to start dns server: ", err) + } + dnsserver.ActivateAndServe() + defer dnsserver.Stop() + router.Start() if errors := router.ConnectionMaker.InitiateConnections(peers, false); len(errors) > 0 { Log.Fatal(errorMessages(errors)) @@ -166,7 +193,7 @@ func main() { // so there is no point in doing "weave launch --http-addr ''". // This is here to support stand-alone use of weaver. if httpAddr != "" { - go handleHTTP(router, httpAddr, allocator, defaultSubnet, dockerCli) + go handleHTTP(router, httpAddr, allocator, defaultSubnet, dockerCli, ns, dnsserver) } SignalHandlerLoop(router) @@ -270,13 +297,15 @@ func determineQuorum(initPeerCountFlag int, peers []string) uint { return quorum } -func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator, defaultSubnet address.CIDR, docker *docker.Client) { +func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator, defaultSubnet address.CIDR, docker *docker.Client, ns *nameserver.Nameserver, dnsserver *nameserver.DNSServer) { muxRouter := mux.NewRouter() if allocator != nil { allocator.HandleHTTP(muxRouter, defaultSubnet, docker) } + ns.HandleHTTP(muxRouter) + muxRouter.Methods("GET").Path("/status").Headers("Accept", "application/json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json, _ := router.StatusJSON(version) w.Header().Set("Content-Type", "application/json") @@ -290,6 +319,9 @@ func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator fmt.Fprintln(w, allocator.String()) fmt.Fprintln(w, "Allocator default subnet:", defaultSubnet) } + fmt.Fprintln(w, "") + fmt.Fprintln(w, dnsserver.String()) + fmt.Fprintln(w, ns.String()) }) muxRouter.Methods("POST").Path("/connect").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/proxy/create_container_interceptor.go b/proxy/create_container_interceptor.go index 8e3cca04..f4c3ee06 100644 --- a/proxy/create_container_interceptor.go +++ b/proxy/create_container_interceptor.go @@ -9,8 +9,10 @@ import ( "strings" "github.com/fsouza/go-dockerclient" + . "github.com/weaveworks/weave/common" "github.com/weaveworks/weave/nameserver" + "github.com/weaveworks/weave/router" ) const MaxDockerHostname = 64 @@ -137,15 +139,15 @@ func (i *createContainerInterceptor) setWeaveDNS(container *createContainerReque } func (i *createContainerInterceptor) getDNSDomain() (domain string, running bool) { - domain = nameserver.DefaultLocalDomain - dnsContainer, err := i.proxy.client.InspectContainer("weavedns") + domain = nameserver.DefaultDomain + weaveContainer, err := i.proxy.client.InspectContainer("weave") if err != nil || - dnsContainer.NetworkSettings == nil || - dnsContainer.NetworkSettings.IPAddress == "" { + weaveContainer.NetworkSettings == nil || + weaveContainer.NetworkSettings.IPAddress == "" { return } - url := fmt.Sprintf("http://%s:%d/domain", dnsContainer.NetworkSettings.IPAddress, nameserver.DefaultHTTPPort) + url := fmt.Sprintf("http://%s:%d/domain", weaveContainer.NetworkSettings.IPAddress, router.HTTPPort) resp, err := http.Get(url) if err != nil || resp.StatusCode != http.StatusOK { return diff --git a/site/ipam.md b/site/ipam.md index 1c28978c..f3596f2a 100644 --- a/site/ipam.md +++ b/site/ipam.md @@ -8,7 +8,7 @@ layout: default Weave automatically assigns containers an IP address that is unique across the network, and releases that address when a container exits. This happens for all invocations of the `run`, `start`, -`attach`, `detach`, `expose`, `hide` and `launch-dns` commands, unless +`attach`, `detach`, `expose`, and `hide` commands, unless the user explictly specified an address. Weave can also assign addresses in multiple subnets. diff --git a/site/proxy.md b/site/proxy.md index 453c81de..2cd04a2b 100644 --- a/site/proxy.md +++ b/site/proxy.md @@ -30,7 +30,7 @@ start it simultaneously with the router and weaveDNS via `launch`: or independently via `launch-proxy`: - host1$ weave launch-router && weave launch-dns && weave launch-proxy + host1$ weave launch-router && weave launch-proxy The first form is more convenient, however you can only pass proxy related configuration arguments to `launch-proxy` so if you need to diff --git a/site/weavedns-design.md b/site/weavedns-design.md index fe70df18..9059505c 100644 --- a/site/weavedns-design.md +++ b/site/weavedns-design.md @@ -6,15 +6,36 @@ layout: default # WeaveDNS (service discovery) Design Notes The model is that each host has a service that is notified of -hostnames and weave addresses for containers on the host. It binds to -the host bridge to answer DNS queries from local containers; anything -it can't answer, it asks with mDNS on the weave network. +hostnames and weave addresses for containers on the host. Like IPAM, +this service is embedded within the router. It binds to +the host bridge to answer DNS queries from local containers; for +anything it can't answer, it uses the infomation in the host's +/etc/resolv.conf to query an 'fallback' server. + +The service is comprised of a DNS server, which answers all DNS queries +from containers, and a in-memory database of hostnames and IPs. The +database on each node contains a complete copy of the hostnames and IPs +for every containers in the cluster. + +For hostname queries in the local domain (default weave.local), the DNS +server will consult the in-memory database. For reverse queries, we +first consult the local database, and if not found we query the +upstream server. For all other queries, we consult the upstream +server. + +Updates to the in-memory database are broadcast to other DNS servers +within the cluster. The in-memory database only contains entries from +connected DNS servers; if a DNS server becomes partitioned from the +cluster, entries belonging to that server are removed from each node in +the cluster. When the partitioned DNS server reconnects, the entries +are re-broadcast around the cluster. + +The DNS server also listens to the Docker event stream, and removes +entries for containers when they die. Entries removed in this way are +tombstoned, and the tombstone lazily broadcast around the cluster. +After a short timeout the tombstones are independantly removed from +each host. -The service is divided into two components: the first is the DNS -server, which serves the records it is told about, and otherwise asks -via mDNS on the weave network. The other component is the DNS updater, -specific to Docker, which monitors the running containers so to add -and remove records from the DNS server. ## DNS server API @@ -24,60 +45,21 @@ and methods: `PUT /name//` Put a record for an IP, bound to a host-scoped identifier (e.g., a -container ID), in the DNS database. +container ID), in the DNS database. The request body must contain +a `fqdn=foo.weave.local` key pair. `DELETE /name//` -Remove a specific record for an IP and host-scoped identifier. +Remove a specific record for an IP and host-scoped identifier. The request +body can optionally contain a `fqdn=foo.weave.local` key pair. `DELETE /name/` Remove all records for the host-scoped identifier. -`GET /name/` +`GET /name/` -List all the records in the database. - -`GET /name/` - -List all the records for a host-scoped identifier. - -`GET /status` - -Give the server status. - -### Record structure - -The record structure is *either* form fields (useful for scripting -PUTs), or a JSON object with the same fields. The fields are: - -```js - { - "fqdn": string, - "routing_prefix": number, - "local_ip": string - } -``` - -> Also TTL? - -## DNS server behaviour - -The DNS server listens for the HTTP requests as above, and maintains a -database of host-local names accordingly. - -It also listens on the host-local network for DNS queries (port -53). Anything that is in its database it responds to immediately. For -other requests, it asks using multicast DNS on the weave network. - -Meanwhile, the DNS server is listening for mDNS queries, and responds -if it the queried name is in its database. - -### Caching mDNS answers - -The DNS server will hear the answers to its own and other servers' -mDNS queries sent on the weave network. It can cache these, to respond -to local DNS requests; the cache is consulted before using mDNS. +List of all IPs (in JSON format) for givne FQDN. ## DNS updater @@ -99,17 +81,3 @@ network attachment of the container, and updates the DNS server. > Perhaps it could put containers on a watch list when it's noticed > them. -## Container startup - -> TBD - -## Grouping and load balancing - -> TBD - -## Extensions - - * An updater that checks health more specifically, e.g., by testing - that a particular port is being listened to, or that it can get a - 200 OK. These could be encoded in the container environment - variables, as per registrator. diff --git a/site/weavedns.md b/site/weavedns.md index f41a7639..1166b00e 100644 --- a/site/weavedns.md +++ b/site/weavedns.md @@ -26,25 +26,15 @@ hosts. ## Using weaveDNS -WeaveDNS is deployed as a set of containers that communicate with each -other over the weave network. One such container needs to be started -on every weave host, either simultaneously with the Weave router and -Weave Docker API proxy via `launch`: +WeaveDNS is deployed as an embedded service within the Weave router. +The service is automatically started when the router is launched: ```bash host1$ weave launch host1$ eval $(weave env) ``` -or independently via `launch-dns`: -```bash -host1$ weave launch-router && weave launch-dns && weave launch-proxy -host1$ eval $(weave env) -``` - -The first form is more convenient, however you can only pass weaveDNS -related configuration arguments to `launch-dns` so if you need to -modify the default behaviour you will have to use the latter. +WeaveDNS related configuration arguments can be passed to `launch`. Application containers will use weaveDNS automatically if it is running at the point when they are started. They will use it for name @@ -61,53 +51,40 @@ root@ubuntu:/# ping pingme > **Please note** if both hostname and container name are specified at > the same time the hostname takes precedence; in this circumstance if -> the hostname is not in the weaveDNS domain the container will *not* be -> registered, but will still use weaveDNS for resolution. +> the hostname is not in the weaveDNS domain the container will *not* +> be registered, but will still use weaveDNS for resolution. It is also possible to force or forbid an application container's use of weaveDNS with the `--with-dns` and `--without-dns` options to -`weave run` and `weave launch-proxy`; these override the runtime -detection of the weaveDNS container. - -Each weaveDNS container started with `launch-dns` needs its own unique -IP address in a subnet that is common to all weaveDNS containers. In -the example above we did not specify such an address, so one was -allocated automatically from the default subnet; you can however -specify an address in CIDR format manually. In this case you are -responsible for ensuring that the IP addresses specified are uniquely -allocated and not in use by any other container. - -Finally, weaveDNS can be stopped independently with - - host1$ weave stop-dns - -or in conjunction with the router and proxy via `stop`. +`weave run` and `weave launch-proxy`. ## How it works -The weaveDNS container running on every host acts as the nameserver -for containers on that host. It learns about hostnames for local -containers from the Weave Docker API proxy and from the `weave run` -command. If a hostname is in the `.weave.local` domain then weaveDNS -records the association of that name with the container's weave IP -address(es). +The weaveDNS service running on every host acts as the nameserver for +containers on that host. It learns about hostnames for local containers +from the proxy and from the `weave run` command. If a hostname is in +the `.weave.local` domain then weaveDNS records the association of that +name with the container's weave IP address(es) in its in-memory +database, and broadcasts the association to other weave peers in the +cluster. When weaveDNS is queried for a name in the `.weave.local` domain, it -first checks its own records. If the name is not found there, it asks -the weaveDNS servers on the other hosts in the weave network. +looks up the hostname its in memory database and responds with the IPs +of all containers for that hostname across the entire cluster, in a +random order. When weaveDNS is queried for a name in a domain other than -`.weave.local`, it queries the host's configured nameserver, -which is the standard behaviour for Docker containers. +`.weave.local`, it queries the host's configured nameserver, which is +the standard behaviour for Docker containers. So that containers can connect to a stable and always routable IP -address, weaveDNS publishes its port 53 to the Docker bridge device, -which is assumed to be `docker0`. Some configurations may use a -different Docker bridge device. To supply a different bridge device, -use the environment variable `DOCKER_BRIDGE`, e.g., +address, weaveDNS listens on port 53 to the Docker bridge device, which +is assumed to be `docker0`. Some configurations may use a different +Docker bridge device. To supply a different bridge device, use the +environment variable `DOCKER_BRIDGE`, e.g., ```bash -$ sudo DOCKER_BRIDGE=someother weave launch-dns +$ sudo DOCKER_BRIDGE=someother weave launch ``` In the event that weaveDNS is launched in this way, it's important that @@ -120,8 +97,8 @@ $ sudo DOCKER_BRIDGE=someother weave run --with-dns ... ## Load balancing It is permissible to register multiple containers with the same name: -weaveDNS picks one address at random on each request. This provides a -basic load balancing capability. +weaveDNS returns all addresses, in a random order, for each request. +This provides a basic load balancing capability. Returning to our earlier example, let us start an additional `pingme` container, this time on the 2nd host, and then run some ping tests... @@ -152,8 +129,9 @@ Notice how the ping reaches different addresses. WeaveDNS removes the addresses of any container that dies. This offers a simple way to implement redundancy. E.g. if in our example we stop one of the `pingme` containers and re-run the ping tests, eventually -(within ~30s at most, since that is the weaveDNS [cache expiry time](#ttl)) we -will only be hitting the address of the container that is still alive. +(within ~30s at most, since that is the weaveDNS +[cache expiry time](#ttl)) we will only be hitting the address of the +container that is still alive. ## Adding and removing extra DNS entries @@ -169,14 +147,15 @@ $ weave dns-add 10.2.1.27 $C -h pingme2.weave.local You can also use `dns-add` to add the container's configured hostname and domain, simply by omitting `-h `. -The inverse operation can be carried out using the `dns-remove` command: +The inverse operation can be carried out using the `dns-remove` +command: ```bash $ weave dns-remove 10.2.1.27 $C ``` -When queried about a name with multiple IPs, weaveDNS returns a random -result from the set of IPs available. +When queried about a name with multiple IPs, weaveDNS returns all IPs +available in a random order. ## Hot-swapping service containers @@ -187,33 +166,20 @@ server container and then [remove](#add-remove) the entry for the old server container. Later, when all connections to the old server have terminated, stop the container as normal. -## Retaining DNS entries when containers stop - -By default, weaveDNS watches docker events and removes entries for any -containers that die. You can tell it not to, by adding `--watch=false` -to the container args: - -```bash -$ weave launch-dns --watch=false -``` ## Configuring a custom TTL -By default, weaveDNS specifies a TTL of 30 seconds in any reply sent to -another peer. Peers will honor the TTL received and cache the answer -until it is considered invalid. - -However, you can force a different TTL value by launching weaveDNS with -the `--ttl` argument: +By default, weaveDNS specifies a TTL of 30 seconds in responses to DNS +requests. However, you can force a different TTL value by launching +weave with the `--dns-ttl` argument: ```bash -$ weave launch-dns --ttl=10 +$ weave launch --dns-ttl=10 ``` -This will shorten the lifespan of answers sent to other peers, -so you will be effectively reducing the probability of them having stale -information, but you will also be increasing their resolution times (as -their cache hit rate will be reduced) and the number of request this +This will shorten the lifespan of answers sent to clients, so you will +be effectively reducing the probability of them having stale +information, but you will also be increasing the number of request this weaveDNS instance will receive. ## Configuring the domain search paths @@ -241,12 +207,12 @@ docker run -ti \ ## Using a different local domain By default, weaveDNS uses `weave.local.` as the domain for names on the -Weave network. In general users do not need to change this domain, but you -can force weaveDNS to use a different domain by launching it -with the `--domain` argument. For example, +Weave network. In general users do not need to change this domain, but +you can force weaveDNS to use a different domain by launching it with +the `--dns-domain` argument. For example, ```bash -$ weave launch-dns --domain="mycompany.local." +$ weave launch --dns-domain="mycompany.local." ``` The local domain should end with `local.`, since these names are @@ -265,16 +231,11 @@ DNS: ```` ... -weave DNS 1.0.0 -Listen address :53 -Fallback DNS config &{[10.0.2.3] [] 53 1 5 2} +WeaveDNS (d6:1b:df:42:af:7d) + listening on port 53, for domain weave.local. + response ttl 30 -Local domain weave.local. -Interface &{74 65535 ethwe 82:0c:92:84:0e:88 up|broadcast|multicast} -Zone database: -144b75a9b873: pingme.weave.local.[10.40.0.1]/OBS:1 -74a5510a91ad: ubuntu.weave.local.[10.40.0.2] -weave:remote: pingme.weave.local.[10.32.0.2]/TTL:30 +1d836dea2c56: foo.weave.local. [10.2.2.1] ... ```` @@ -284,17 +245,16 @@ guide](troubleshooting.html#status-report) for more detail. The second section is pertinent to weaveDNS, and includes: +* Port on which the DNS server is listening * The local domain suffix which is being served -* The address on which the DNS server is listening -* The interface being used for multicast DNS -* The fallback DNS which will be used to resolve non local names -* The names known to the local weaveDNS server. Each entry comprises +* The response ttl +* The names known to the weaveDNS server. Each entry comprises the container ID, IP address and its fully qualified domain name Information on the processing of queries, and the general operation of weaveDNS, can be obtained from the container logs with - docker logs weavedns + docker logs weave ## Present limitations @@ -304,6 +264,3 @@ weaveDNS, can be obtained from the container logs with * The server may give unreachable IPs as answers, since it doesn't try to filter by reachability. If you use subnets, align your hostnames with the subnets. - * We use UDP multicast to find out about remote names (from weaveDNS - servers on other hosts); this likely won't scale well beyond a - certain point T.B.D. diff --git a/test/200_dns_test.sh b/test/200_dns_test.sh index 49fa215a..f4d8c998 100755 --- a/test/200_dns_test.sh +++ b/test/200_dns_test.sh @@ -8,7 +8,7 @@ NAME=seetwo.weave.local start_suite "Resolve names on a single host" -launch_dns_on $HOST1 10.2.254.1/24 +weave_on $HOST1 launch start_container $HOST1 $C2/24 --name=c2 -h $NAME start_container_with_dns $HOST1 $C1/24 --name=c1 diff --git a/test/210_dns_cross_hosts_test.sh b/test/210_dns_cross_hosts_test.sh new file mode 100755 index 00000000..b3836bbc --- /dev/null +++ b/test/210_dns_cross_hosts_test.sh @@ -0,0 +1,35 @@ +#! /bin/bash + +. ./config.sh + +C1=10.2.3.78 +C2=10.2.3.34 +C2a=10.2.3.35 +C2b=10.2.3.36 +UNIVERSE=10.2.4.0/24 +NAME2=seetwo.weave.local +NAME4=seefour.weave.local + +start_suite "Resolve names across hosts" + +weave_on $HOST1 launch --ipalloc-range $UNIVERSE +weave_on $HOST2 launch --ipalloc-range $UNIVERSE $HOST1 + +start_container $HOST2 $C2/24 --name=c2 -h $NAME2 +start_container_with_dns $HOST1 $C1/24 --name=c1 + +assert_dns_record $HOST1 c1 $NAME2 $C2 + +# resolution for names mapped to multiple addresses +weave_on $HOST2 dns-add $C2a c2 -h $NAME2 +weave_on $HOST2 dns-add $C2b c2 -h $NAME2 +assert_dns_record $HOST1 c1 $NAME2 $C2 $C2a $C2b + +# resolution when containers addresses come from IPAM +start_container $HOST2 --name=c4 -h $NAME4 +start_container_with_dns $HOST1 --name=c3 +C4=$(container_ip $HOST2 c4) +assert_dns_record $HOST1 c3 $NAME4 $C4 +assert_raises "exec_on $HOST1 c3 getent hosts 8.8.8.8 | grep google" + +end_suite diff --git a/test/210_dns_multicast_test.sh b/test/210_dns_multicast_test.sh deleted file mode 100755 index e8619703..00000000 --- a/test/210_dns_multicast_test.sh +++ /dev/null @@ -1,61 +0,0 @@ -#! /bin/bash - -. ./config.sh - -C1=10.2.3.78 -C2=10.2.3.34 -C2a=10.2.3.35 -C2b=10.2.3.36 -UNIVERSE=10.2.4.0/24 -NAME2=seetwo.weave.local -NAME4=seefour.weave.local - -start() { - launch_dns_on $HOST1 $1 >/dev/null - launch_dns_on $HOST2 $2 >/dev/null -} - -stop() { - weave_on $HOST1 stop-dns - weave_on $HOST2 stop-dns -} - -check() { - start $1 $2 - assert_dns_record $HOST1 c1 $NAME2 $C2 - assert_raises "exec_on $HOST1 c1 getent hosts 8.8.8.8 | grep google" - stop -} - -start_suite "Resolve names across hosts (with and without IPAM), and repopulate on restart" - -weave_on $HOST1 launch-router --ipalloc-range $UNIVERSE -weave_on $HOST2 launch-router --ipalloc-range $UNIVERSE $HOST1 - -start_container $HOST2 $C2/24 --name=c2 -h $NAME2 -start_container_with_dns $HOST1 $C1/24 --name=c1 - -# resolution when DNS is launched with various ways of obtaining an IP -# NB: this also tests re-population on DNS restart -check ip:10.2.254.1/24 ip:10.2.254.2/24 -check net:10.2.4.128/25 net:10.2.4.128/25 -check net:default net:default -check - -start 10.2.254.1/24 10.2.254.2/24 - -# resolution for names mapped to multiple addresses -weave_on $HOST2 dns-add $C2a c2 -h $NAME2 -weave_on $HOST2 dns-add $C2b c2 -h $NAME2 -assert_dns_record $HOST1 c1 $NAME2 $C2 $C2a $C2b - -# resolution when containers addresses come from IPAM -start_container $HOST2 --name=c4 -h $NAME4 -start_container_with_dns $HOST1 --name=c3 -C4=$(container_ip $HOST2 c4) -assert_dns_record $HOST1 c3 $NAME4 $C4 -assert_raises "exec_on $HOST1 c3 getent hosts 8.8.8.8 | grep google" - -stop - -end_suite diff --git a/test/220_dns_custom_test.sh b/test/220_dns_custom_test.sh index ec1b1efe..bb404d32 100755 --- a/test/220_dns_custom_test.sh +++ b/test/220_dns_custom_test.sh @@ -9,7 +9,20 @@ NAME=seetwo.$DOMAIN start_suite "Resolve names in custom domain" -launch_dns_on $HOST1 10.2.254.1/24 --domain $DOMAIN. +# Check with a trailing dot on domain +weave_on $HOST1 launch --dns-domain $DOMAIN. + +start_container $HOST1 $C2/24 --name=c2 -h $NAME +start_container_with_dns $HOST1 $C1/24 --name=c1 + +assert_dns_record $HOST1 c1 $NAME $C2 + +rm_containers $HOST1 c1 +rm_containers $HOST1 c2 +weave_on $HOST1 stop + +# Check without a trailing dot on domain +weave_on $HOST1 launch --dns-domain $DOMAIN start_container $HOST1 $C2/24 --name=c2 -h $NAME start_container_with_dns $HOST1 $C1/24 --name=c1 diff --git a/test/230_dns_unqualified_test.sh b/test/230_dns_unqualified_test.sh index 38e30043..146af9c3 100755 --- a/test/230_dns_unqualified_test.sh +++ b/test/230_dns_unqualified_test.sh @@ -11,7 +11,7 @@ NAME=seeone.$DOMAIN start_suite "Resolve unqualified names" -launch_dns_on $HOST1 10.2.254.1/24 +weave_on $HOST1 launch start_container $HOST1 $C1/24 --name=c1 -h $NAME start_container_with_dns $HOST1 $C2/24 --name=c2 -h seetwo.$DOMAIN diff --git a/test/240_dns_add_name_test.sh b/test/240_dns_add_name_test.sh index ce76e225..87badd50 100755 --- a/test/240_dns_add_name_test.sh +++ b/test/240_dns_add_name_test.sh @@ -10,7 +10,7 @@ NAME3=seethree.weave.local start_suite "Add and remove names on a single host" -launch_dns_on $HOST1 10.2.254.1/24 +weave_on $HOST1 launch start_container $HOST1 --without-dns $C2/24 --name=c2 start_container_with_dns $HOST1 $C1/24 --name=c1 diff --git a/test/250_dns_restart_test.sh b/test/250_dns_restart_test.sh new file mode 100755 index 00000000..9c8a0e54 --- /dev/null +++ b/test/250_dns_restart_test.sh @@ -0,0 +1,25 @@ +#! /bin/bash + +. ./config.sh + +C1=10.2.0.78 +C2=10.2.0.34 +NAME=seetwo.weave.local + +start_suite "Restart Weave, check for repopulation" + +weave_on $HOST1 launch + +start_container $HOST1 $C2/24 --name=c2 -h $NAME +start_container_with_dns $HOST1 $C1/24 --name=c1 + +assert_dns_record $HOST1 c1 $NAME $C2 +assert_raises "exec_on $HOST1 c1 dig MX $NAME | grep -q 'status: NXDOMAIN'" + +weave_on $HOST1 stop +weave_on $HOST1 launch + +assert_dns_record $HOST1 c1 $NAME $C2 +assert_raises "exec_on $HOST1 c1 dig MX $NAME | grep -q 'status: NXDOMAIN'" + +end_suite diff --git a/test/260_dns_removal_test.sh b/test/260_dns_removal_test.sh index 78fa9bd9..bc951d40 100755 --- a/test/260_dns_removal_test.sh +++ b/test/260_dns_removal_test.sh @@ -16,7 +16,7 @@ check() { start_suite "Automatic DNS record removal on container death" -launch_dns_on $HOST1 10.2.254.1/24 +weave_on $HOST1 launch start_container_with_dns $HOST1 $C1/24 --name=c1 start_container $HOST1 $C2/24 $DOPTS diff --git a/test/280_with_or_without_dns_test.sh b/test/280_with_or_without_dns_test.sh index 2a58be95..f38e23e9 100755 --- a/test/280_with_or_without_dns_test.sh +++ b/test/280_with_or_without_dns_test.sh @@ -20,19 +20,12 @@ assert_resolution() { start_suite "With or without DNS test" +# Assert behaviour without weaveDNS running weave_on $HOST1 launch-router +start_container $HOST1 $TARGET_IP/24 --name c2 -h $TARGET DNS_IP=$(weave_on $HOST1 docker-bridge-ip) -# Assert behaviour without weaveDNS running -assert_no_resolution --without-dns -assert_no_resolution -assert_no_resolution --with-dns - -weave_on $HOST1 launch-dns 10.2.254.1/24 $WEAVEDNS_ARGS -start_container $HOST1 $TARGET_IP/24 --name c2 -h $TARGET - -# Assert behaviour with weaveDNS running assert_no_resolution --without-dns assert_resolution assert_resolution --with-dns diff --git a/test/290_dns_fallback_test.sh b/test/290_dns_fallback_test.sh index 9eee0f8f..1d897732 100755 --- a/test/290_dns_fallback_test.sh +++ b/test/290_dns_fallback_test.sh @@ -4,7 +4,7 @@ start_suite "Resolve a non-weave address" -launch_dns_on $HOST1 10.2.254.1/24 +weave_on $HOST1 launch-router start_container_with_dns $HOST1 10.2.1.5/24 --name=c1 diff --git a/test/295_dns_large_response.sh b/test/295_dns_large_response.sh new file mode 100755 index 00000000..daf7e82e --- /dev/null +++ b/test/295_dns_large_response.sh @@ -0,0 +1,23 @@ +#! /bin/bash + +. ./config.sh + +NAME=seetwo.weave.local + +N=50 +start_suite "Add $N dns entries and check we get the right response." + +weave_on $HOST1 launch + +CID=$(start_container_with_dns $HOST1 10.2.1.0/24 --name=c0) +IPS="" +for i in $(seq $N); do + IPS="$IPS 10.2.1.$i" +done +weave_on $HOST1 dns-add $IPS $CID -h $NAME + +assert_dns_record $HOST1 c0 $NAME $IPS + +assert_raises "exec_on $HOST1 c0 dig MX $NAME | grep -q 'status: NXDOMAIN'" + +end_suite diff --git a/test/500_weave_multi_cidr_test.sh b/test/500_weave_multi_cidr_test.sh index 83bc20c8..d3d09661 100755 --- a/test/500_weave_multi_cidr_test.sh +++ b/test/500_weave_multi_cidr_test.sh @@ -74,7 +74,6 @@ start_suite "Weave run/start/attach/detach/expose/hide with multiple cidr argume # lowest available address in the subnet weave_on $HOST1 launch-router --ipalloc-range 10.2.3.0/24 -launch_dns_on $HOST1 10.254.254.254/24 # Run container with three cidrs CID=$(start_container $HOST1 10.2.1.1/24 ip:10.2.2.1/24 net:10.2.3.0/24 --name=multicidr -h $NAME | cut -b 1-12) diff --git a/test/630_proxy_dns_test.sh b/test/630_proxy_dns_test.sh index d3b9ce04..8276be6c 100755 --- a/test/630_proxy_dns_test.sh +++ b/test/630_proxy_dns_test.sh @@ -37,7 +37,7 @@ weave_on $HOST1 launch-proxy assert_no_resolution # Assert behaviour with weaveDNS running -launch_dns_on $HOST1 10.2.254.1/24 +weave_on $HOST1 launch-router boot_containers assert_dns_record $HOST1 c1 $C2_NAME $C2 assert_dns_record $HOST1 c2 $C1_NAME $C1 diff --git a/test/635_proxy_dns_unqualified_test.sh b/test/635_proxy_dns_unqualified_test.sh index b4ffbd18..f81cbb3f 100755 --- a/test/635_proxy_dns_unqualified_test.sh +++ b/test/635_proxy_dns_unqualified_test.sh @@ -15,8 +15,7 @@ start_container() { start_suite "Resolve unqualified names" -weave_on $HOST1 launch-dns 10.2.254.1/24 -weave_on $HOST1 launch-proxy +weave_on $HOST1 launch start_container -e WEAVE_CIDR=$C1/24 --name=c1 -h $NAME start_container -e WEAVE_CIDR=$C2/24 --name=c2 -h seetwo.$DOMAIN diff --git a/test/640_proxy_restart_reattaches_test.sh b/test/640_proxy_restart_reattaches_test.sh index b85e87c4..1e468def 100755 --- a/test/640_proxy_restart_reattaches_test.sh +++ b/test/640_proxy_restart_reattaches_test.sh @@ -8,8 +8,7 @@ NAME=seetwo.weave.local start_suite "Proxy restart reattaches networking to containers" -launch_dns_on $HOST1 10.2.254.1/24 -weave_on $HOST1 launch-proxy --with-dns +weave_on $HOST1 launch proxy docker_on $HOST1 run -e WEAVE_CIDR=$C2/24 -dt --name=c2 -h $NAME $SMALL_IMAGE /bin/sh proxy docker_on $HOST1 run -e WEAVE_CIDR=$C1/24 -dt --name=c1 $DNS_IMAGE /bin/sh diff --git a/test/config.sh b/test/config.sh index 3d136999..e9e4a49b 100644 --- a/test/config.sh +++ b/test/config.sh @@ -133,12 +133,6 @@ exec_on() { docker -H tcp://$host:$DOCKER_PORT exec $container "$@" } -launch_dns_on() { - host=$1 - shift 1 - weave_on $host launch-dns $@ $WEAVEDNS_ARGS -} - start_container() { host=$1 shift 1 diff --git a/weave b/weave index c7983f68..1bedfb61 100755 --- a/weave +++ b/weave @@ -34,7 +34,6 @@ weave launch [--password ] [--nickname ] weave launch-router [--password ] [--nickname ] [--ipalloc-range [--ipalloc-default-subnet ]] [--no-discovery] [--init-peer-count ] ... -weave launch-dns [] weave launch-proxy [-H ] [--with-dns | --without-dns] [--no-default-ipalloc] [--no-rewrite-hosts] weave connect [--replace] [ ...] @@ -55,7 +54,6 @@ weave config weave version weave stop weave stop-router -weave stop-dns weave stop-proxy weave reset weave rmpeer @@ -78,7 +76,6 @@ exec_remote() { -e VERSION \ -e WEAVE_DEBUG \ -e WEAVE_DOCKER_ARGS \ - -e WEAVEDNS_DOCKER_ARGS \ -e WEAVEPROXY_DOCKER_ARGS \ -e WEAVE_PASSWORD \ -e WEAVE_PORT \ @@ -164,21 +161,16 @@ fi shift 1 BASE_IMAGE=$DOCKERHUB_USER/weave -BASE_DNS_IMAGE=$DOCKERHUB_USER/weavedns IMAGE=$BASE_IMAGE:$IMAGE_VERSION -DNS_IMAGE=$BASE_DNS_IMAGE:$IMAGE_VERSION PROCFS=${PROCFS:-/proc} DOCKER_BRIDGE=${DOCKER_BRIDGE:-docker0} CONTAINER_NAME=${WEAVE_CONTAINER_NAME:-weave} -DNS_CONTAINER_NAME=weavedns BRIDGE=weave CONTAINER_IFNAME=ethwe MTU=65535 PORT=${WEAVE_PORT:-6783} HTTP_PORT=6784 -DNS_HTTP_PORT=6785 -DNS_HTTP_IFNAME=eth0 PROXY_PORT=12375 PROXY_CONTAINER_NAME=weaveproxy COVERAGE_ARGS="" @@ -598,10 +590,6 @@ call_weave() { http_call $CONTAINER_NAME $HTTP_PORT "$@" } -call_dns() { - http_call $DNS_CONTAINER_NAME $DNS_HTTP_PORT "$@" -} - death_msg() { echo "The $1 container has died. Consult the logs with 'docker logs $1' for further details." } @@ -672,7 +660,7 @@ peer_args() { # Memoized function to query the weaveDNS server for our dns domain. dns_domain() { - DNS_DOMAIN=${DNS_DOMAIN:-$(call_dns GET /domain 2>/dev/null || true)} + DNS_DOMAIN=${DNS_DOMAIN:-$(call_weave GET /domain 2>/dev/null || true)} DNS_DOMAIN=${DNS_DOMAIN:-weave.local.} echo $DNS_DOMAIN } @@ -719,9 +707,6 @@ dns_args() { shift done [ -n "$WITHOUT_DNS" ] && return 0 - if [ -z "$WITH_DNS" ] ; then - check_running $DNS_CONTAINER_NAME 2>/dev/null || return 0 - fi DNS_ARGS="--dns $DOCKER_BRIDGE_IP" if [ -n "$NAME_ARG" -a -z "$HOSTNAME_SPECIFIED" ] ; then DOMAIN=$(dns_domain) @@ -754,9 +739,9 @@ check_running() { fi } -# Execute $@ only if the weaveDNS container is running -when_dns_running() { - if check_running $DNS_CONTAINER_NAME 2>/dev/null; then +# Execute $@ only if the weave container is running +when_weave_running() { + if check_running $CONTAINER_NAME 2>/dev/null; then "$@" fi } @@ -788,7 +773,7 @@ put_dns_fqdn() { shift 2 for ADDR in "$@" ; do - call_dns PUT /name/$CONTAINER_ID/${ADDR%/*} --data-urlencode fqdn=$FQDN $CHECK_ALIVE || true + call_weave PUT /name/$CONTAINER_ID/${ADDR%/*} --data-urlencode fqdn=$FQDN $CHECK_ALIVE || true done } @@ -798,7 +783,7 @@ delete_dns() { shift 1 for ADDR in "$@" ; do - call_dns DELETE /name/$CONTAINER_ID/${ADDR%/*} || true + call_weave DELETE /name/$CONTAINER_ID/${ADDR%/*} || true done } @@ -809,13 +794,13 @@ delete_dns_fqdn() { shift 2 for ADDR in "$@" ; do - call_dns DELETE /name/$CONTAINER_ID/${ADDR%/*}?fqdn=$FQDN || true + call_weave DELETE /name/$CONTAINER_ID/${ADDR%/*}?fqdn=$FQDN || true done } # Tell the newly-started weaveDNS about existing weave IPs populate_dns() { - if ! wait_for_status $DNS_CONTAINER_NAME $DNS_HTTP_PORT ; then + if ! wait_for_status $CONTAINER_NAME $HTTP_PORT ; then echo "If running, it will not be pre-populated." >&2 return 0 fi @@ -981,6 +966,7 @@ common_launch_args() { launch_router() { create_bridge + docker_bridge_ip # We set the router name to the bridge mac since that is # stable across re-creations of the containers. # @@ -1050,6 +1036,7 @@ launch_router() { # when launching the weave container. CONTAINER=$(docker run --privileged -d --name=$CONTAINER_NAME \ -p $PORT:$CONTAINER_PORT/tcp -p $PORT:$CONTAINER_PORT/udp \ + -p $DOCKER_BRIDGE_IP:53:53/udp -p $DOCKER_BRIDGE_IP:53:53/tcp \ -v /var/run/docker.sock:/var/run/docker.sock \ -e WEAVE_PASSWORD \ -e WEAVE_CIDR=none \ @@ -1060,24 +1047,6 @@ launch_router() { # Tell the newly-started weave IP allocator about existing weave IPs with_container_addresses ipam_claim weave:expose $(docker ps -q --no-trunc) fi -} - -launch_dns() { - collect_cidr_args "$@" - [ $CIDR_ARG_COUNT -lt 2 ] || usage - shift $CIDR_ARG_COUNT - create_bridge - docker_bridge_ip - # Set WEAVEDNS_DOCKER_ARGS in the environment in order to supply - # additional parameters, such as resource limits, to docker - # when launching the weave container. - DNS_CONTAINER=$(docker run --privileged -d --name=$DNS_CONTAINER_NAME \ - -p $DOCKER_BRIDGE_IP:53:53/udp \ - -e WEAVE_CIDR=none \ - -v /var/run/docker.sock:/var/run/docker.sock \ - $WEAVEDNS_DOCKER_ARGS $DNS_IMAGE --iface $CONTAINER_IFNAME --http-iface "$DNS_HTTP_IFNAME" "$@") - ipam_cidrs_or_die $DNS_CONTAINER $CIDR_ARGS - with_container_netns_or_die $DNS_CONTAINER attach $ALL_CIDRS populate_dns } @@ -1200,7 +1169,7 @@ shift 1 case "$COMMAND" in setup) - for img in $IMAGE $DNS_IMAGE $EXEC_IMAGE ; do + for img in $IMAGE $EXEC_IMAGE ; do docker pull $img done ;; @@ -1212,11 +1181,9 @@ case "$COMMAND" in launch) deprecation_warnings "$@" check_not_running $CONTAINER_NAME $BASE_IMAGE - check_not_running $DNS_CONTAINER_NAME $BASE_DNS_IMAGE check_not_running $PROXY_CONTAINER_NAME $EXEC_IMAGE COMMON_ARGS=$(common_launch_args "$@") launch_router "$@" - launch_dns $COMMON_ARGS launch_proxy $COMMON_ARGS ;; launch-router) @@ -1225,11 +1192,6 @@ case "$COMMAND" in launch_router "$@" echo $CONTAINER ;; - launch-dns) - check_not_running $DNS_CONTAINER_NAME $BASE_DNS_IMAGE - launch_dns "$@" - echo $DNS_CONTAINER - ;; launch-proxy) deprecation_warnings "$@" check_not_running $PROXY_CONTAINER_NAME $EXEC_IMAGE @@ -1260,7 +1222,6 @@ case "$COMMAND" in res=0 call_weave GET /status || res=1 echo - call_dns GET /status 2>/dev/null || true if check_running $PROXY_CONTAINER_NAME 2>/dev/null ; then echo echo "weave proxy is running" @@ -1275,7 +1236,6 @@ case "$COMMAND" in [ $# -eq 0 ] || usage echo weave script $SCRIPT_VERSION ask_version $CONTAINER_NAME $IMAGE || true - ask_version $DNS_CONTAINER_NAME $DNS_IMAGE || true if ! EXEC_IMAGE_ID=$(docker inspect --format='{{.Id}}' $EXEC_IMAGE 2>/dev/null) ; then echo "Unable to find $EXEC_IMAGE image." >&2 else @@ -1296,7 +1256,7 @@ case "$COMMAND" in create_bridge ipam_cidrs_or_die $CONTAINER $CIDR_ARGS with_container_netns_or_die $CONTAINER attach $ALL_CIDRS - when_dns_running with_container_fqdn $CONTAINER put_dns_fqdn $ALL_CIDRS + when_weave_running with_container_fqdn $CONTAINER put_dns_fqdn $ALL_CIDRS echo $CONTAINER ;; dns-args) @@ -1316,7 +1276,7 @@ case "$COMMAND" in create_bridge ipam_cidrs_or_die $CONTAINER $CIDR_ARGS with_container_netns_or_die $CONTAINER attach $ALL_CIDRS - when_dns_running with_container_fqdn $CONTAINER put_dns_fqdn $ALL_CIDRS + when_weave_running with_container_fqdn $CONTAINER put_dns_fqdn $ALL_CIDRS echo $RES ;; attach) @@ -1331,7 +1291,7 @@ case "$COMMAND" in create_bridge ipam_cidrs$ATTACH_TYPE $CONTAINER $CIDR_ARGS with_container_netns$ATTACH_TYPE $CONTAINER attach $ALL_CIDRS >/dev/null - when_dns_running with_container_fqdn $CONTAINER put_dns_fqdn $ALL_CIDRS + when_weave_running with_container_fqdn $CONTAINER put_dns_fqdn $ALL_CIDRS show_addrs $ALL_CIDRS ;; detach) @@ -1341,7 +1301,7 @@ case "$COMMAND" in CONTAINER=$(container_id $1) ipam_cidrs $CONTAINER $CIDR_ARGS with_container_netns $CONTAINER detach $ALL_CIDRS >/dev/null - when_dns_running with_container_fqdn $CONTAINER delete_dns_fqdn $ALL_CIDRS + when_weave_running with_container_fqdn $CONTAINER delete_dns_fqdn $ALL_CIDRS for CIDR in $IPAM_CIDRS ; do call_weave DELETE /ip/$CONTAINER/${CIDR%/*} done @@ -1351,7 +1311,7 @@ case "$COMMAND" in collect_ip_args "$@" shift $IP_COUNT [ $IP_COUNT -gt 0 -a \( $# -eq 1 -o \( $# -eq 3 -a "$2" = "-h" \) \) ] || usage - check_running $DNS_CONTAINER_NAME + check_running $CONTAINER_NAME CONTAINER=$(container_id $1) if [ $# -eq 1 ] ; then with_container_fqdn $CONTAINER put_dns_fqdn $IP_ARGS @@ -1363,7 +1323,7 @@ case "$COMMAND" in collect_ip_args "$@" shift $IP_COUNT [ $IP_COUNT -gt 0 -a \( $# -eq 1 -o \( $# -eq 3 -a "$2" = "-h" \) \) ] || usage - check_running $DNS_CONTAINER_NAME + check_running $CONTAINER_NAME CONTAINER=$(container_id $1) if [ $# -eq 1 ] ; then delete_dns $CONTAINER $IP_ARGS @@ -1389,7 +1349,7 @@ case "$COMMAND" in add_iptables_rule nat WEAVE -d $CIDR ! -s $CIDR -j MASQUERADE add_iptables_rule nat WEAVE -s $CIDR ! -d $CIDR -j MASQUERADE if [ -n "$FQDN" ] ; then - when_dns_running put_dns_fqdn --no-check-alive weave:expose $FQDN $CIDR + when_weave_running put_dns_fqdn --no-check-alive weave:expose $FQDN $CIDR fi fi done @@ -1405,7 +1365,7 @@ case "$COMMAND" in ip addr del dev $BRIDGE $CIDR delete_iptables_rule nat WEAVE -d $CIDR ! -s $CIDR -j MASQUERADE delete_iptables_rule nat WEAVE -s $CIDR ! -d $CIDR -j MASQUERADE - when_dns_running delete_dns weave:expose $CIDR + when_weave_running delete_dns weave:expose $CIDR fi done for CIDR in $IPAM_CIDRS ; do @@ -1416,7 +1376,6 @@ case "$COMMAND" in stop) [ $# -eq 0 ] || usage stop $PROXY_CONTAINER_NAME "Proxy" - stop $DNS_CONTAINER_NAME "WeaveDNS" stop $CONTAINER_NAME "Weave" conntrack -D -p udp --dport $PORT >/dev/null 2>&1 || true ;; @@ -1425,10 +1384,6 @@ case "$COMMAND" in stop $CONTAINER_NAME "Weave" conntrack -D -p udp --dport $PORT >/dev/null 2>&1 || true ;; - stop-dns) - [ $# -eq 0 ] || usage - stop $DNS_CONTAINER_NAME "WeaveDNS" - ;; stop-proxy) [ $# -eq 0 ] || usage stop $PROXY_CONTAINER_NAME "Proxy" @@ -1436,7 +1391,7 @@ case "$COMMAND" in reset) [ $# -eq 0 ] || usage call_weave DELETE /peer >/dev/null 2>&1 || true - for NAME in $CONTAINER_NAME $DNS_CONTAINER_NAME $PROXY_CONTAINER_NAME ; do + for NAME in $CONTAINER_NAME $PROXY_CONTAINER_NAME ; do docker stop $NAME >/dev/null 2>&1 || true docker rm -f $NAME >/dev/null 2>&1 || true done @@ -1451,6 +1406,14 @@ case "$COMMAND" in PEER=$1 call_weave DELETE /peer/$PEER ;; + launch-dns) + echo "The 'launch-dns' command has been removed; DNS is launched as part of 'launch' and 'launch-router'." >&2 + exit 0 + ;; + stop-dns) + echo "The 'stop-dns command has been removed; DNS is stopped as part of 'stop' and 'stop-router'." >&2 + exit 0 + ;; *) echo "Unknown weave command '$COMMAND'" >&2 usage From dfcc9678f3de1ada12ee9c0eb8f76cffc23f95e1 Mon Sep 17 00:00:00 2001 From: Alfonso Acosta Date: Tue, 14 Jul 2015 16:02:19 +0000 Subject: [PATCH 100/180] Make weave usage fit into 80 columns --- weave | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/weave b/weave index 8b4384e8..ae26627b 100755 --- a/weave +++ b/weave @@ -37,7 +37,8 @@ weave launch-router [--password ] [--nickname ] weave launch-dns [] weave launch-proxy [-H ] [--with-dns | --without-dns] [--no-default-ipalloc] [--no-rewrite-hosts] - [--hostname-match ] [--hostname-replacement ] + [--hostname-match ] + [--hostname-replacement ] weave connect [--replace] [ ...] weave forget ... weave run [--with-dns | --without-dns] [ ...] From 361ed1b4a6ba5dc3db488b4a22253d1508a7ac77 Mon Sep 17 00:00:00 2001 From: Tom Wilkie Date: Tue, 14 Jul 2015 13:51:29 +0000 Subject: [PATCH 101/180] Resolve unqualified domains in the weave.local domain. --- nameserver/dns.go | 24 +++++++++++++++++++----- test/230_dns_unqualified_test.sh | 12 ++++++------ test/config.sh | 9 +++------ 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/nameserver/dns.go b/nameserver/dns.go index af437897..c2868aa2 100644 --- a/nameserver/dns.go +++ b/nameserver/dns.go @@ -129,7 +129,11 @@ func (d *DNSServer) handleLocal(defaultMaxResponseSize int) func(dns.ResponseWri return } - hostname := req.Question[0].Name + hostname := dns.Fqdn(req.Question[0].Name) + if strings.Count(hostname, ".") == 1 { + hostname = hostname + d.domain + } + addrs := d.ns.Lookup(hostname) response := dns.Msg{} @@ -139,7 +143,7 @@ func (d *DNSServer) handleLocal(defaultMaxResponseSize int) func(dns.ResponseWri response.Answer = make([]dns.RR, len(addrs)) header := dns.RR_Header{ - Name: hostname, + Name: req.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: d.ttl, @@ -211,15 +215,25 @@ func (d *DNSServer) handleReverse(client *dns.Client, defaultMaxResponseSize int func (d *DNSServer) handleRecursive(client *dns.Client, defaultMaxResponseSize int) func(dns.ResponseWriter, *dns.Msg) { return func(w dns.ResponseWriter, req *dns.Msg) { - d.ns.debugf("recursive cdrequest: %+v", *req) + d.ns.debugf("recursive request: %+v", *req) + + // Resolve unqualified names locally + if len(req.Question) == 1 && req.Question[0].Qtype == dns.TypeA { + hostname := dns.Fqdn(req.Question[0].Name) + if strings.Count(hostname, ".") == 1 { + d.handleLocal(defaultMaxResponseSize)(w, req) + return + } + } + for _, server := range d.upstream.Servers { response, _, err := client.Exchange(req, fmt.Sprintf("%s:%s", server, d.upstream.Port)) if err != nil || response == nil { - d.ns.debugf("network error trying %s (%s)", server, err) + d.ns.debugf("error trying %s: %v", server, err) continue } if response.Rcode != dns.RcodeSuccess && !response.Authoritative { - d.ns.debugf("network error trying %s (%s)", server, err) + d.ns.debugf("non-authoritative error trying %s: %v", server, response.Rcode) continue } d.ns.debugf("response: %+v", response) diff --git a/test/230_dns_unqualified_test.sh b/test/230_dns_unqualified_test.sh index 146af9c3..0283d73f 100755 --- a/test/230_dns_unqualified_test.sh +++ b/test/230_dns_unqualified_test.sh @@ -18,12 +18,12 @@ start_container_with_dns $HOST1 $C2/24 --name=c2 -h seetwo.$DOMAIN start_container_with_dns $HOST1 $C3/24 --name=c3 --dns-search=$DOMAIN container=$(start_container_with_dns $HOST1 $C4/24) -check() { - assert "exec_on $HOST1 $1 getent hosts seeone | tr -s ' '" "$C1 $NAME" -} +assert_dns_a_record $HOST1 c2 seeone $C1 $NAME +assert_dns_a_record $HOST1 c3 seeone $C1 $NAME +assert_dns_a_record $HOST1 "$container" seeone $C1 $NAME -check c2 -check c3 -check "$container" +# check that unqualified names are automatically qualified for broken resolvers +weave_on $HOST1 dns-add $C1 c1 -h mysql.weave.local +assert_dns_a_record $HOST1 c1 mysql $C1 end_suite diff --git a/test/config.sh b/test/config.sh index e9e4a49b..ffdfe652 100644 --- a/test/config.sh +++ b/test/config.sh @@ -43,10 +43,6 @@ CHECK_ETHWE_UP="grep ^1$ /sys/class/net/ethwe/carrier" DOCKER_PORT=2375 -WEAVEDNS_ARGS="--no-cache" -[ -n "$DEBUG" ] && WEAVEDNS_ARGS="$WEAVEDNS_ARGS --log-level=debug" - - upload_executable() { host=$1 file=$2 @@ -182,9 +178,10 @@ assert_no_dns_record() { assert_raises "exec_on $host $container getent hosts $name" 2 } -# assert_dns_a_record +# assert_dns_a_record [] assert_dns_a_record() { - assert "exec_on $1 $2 getent hosts $3 | tr -s ' '" "$4 $3" + exp_name=${5:-$3} + assert "exec_on $1 $2 getent hosts $3 | tr -s ' ' | cut -d ' ' -f 1,2" "$4 $exp_name" } # assert_dns_ptr_record From d9c5d2f9403fd506b53deddad98003d57fb2ce7a Mon Sep 17 00:00:00 2001 From: Paul Bellamy Date: Tue, 14 Jul 2015 17:08:26 +0100 Subject: [PATCH 102/180] update default vagrant box to ubuntu 15 --- Vagrantfile | 4 ++-- vagrant-common.rb | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Vagrantfile b/Vagrantfile index 6a76addb..55e3b54d 100644 --- a/Vagrantfile +++ b/Vagrantfile @@ -18,8 +18,8 @@ pkgs = %w( Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| - config.vm.box = "ubuntu/ubuntu-14.10-amd64" - config.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/utopic/current/utopic-server-cloudimg-amd64-vagrant-disk1.box" + config.vm.box = "ubuntu/ubuntu-15.04-amd64" + config.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/vivid/current/vivid-server-cloudimg-amd64-vagrant-disk1.box" config.vm.network "private_network", ip: vm_ip config.vm.provider :virtualbox do |vb| diff --git a/vagrant-common.rb b/vagrant-common.rb index 7cf8540b..5d6053fb 100644 --- a/vagrant-common.rb +++ b/vagrant-common.rb @@ -45,9 +45,10 @@ end def tweak_docker_daemon(vm) vm.provision :shell, :inline => <