diff --git a/.gitignore b/.gitignore
index 609b440f..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
@@ -51,3 +52,5 @@ prog/weaveexec/netcheck
prog/weaveexec/docker*.tgz
Vagrantfile.local
test/tls/*.pem
+test/coverage
+test/coverage.*
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 37c7871c..3f93170b 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,73 +10,80 @@ 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)
+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
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=$(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."; \
+ echo "To fix that, run"; \
+ echo " sudo go clean -i net"; \
+ echo " sudo go install -tags netgo std"; \
+ false; \
+}
-all: $(WEAVE_EXPORT)
+all: $(WEAVE_EXPORT) $(COVER_EXE)
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)
- @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; \
- }
+endif
+ $(NETGO_CHECK)
-$(WEAVER_EXE): router/*.go ipam/*.go ipam/*/*.go prog/weaver/main.go
-$(WEAVEDNS_EXE): nameserver/*.go prog/weavedns/main.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 nameserver/*.go prog/weaver/main.go
$(WEAVEPROXY_EXE): proxy/*.go prog/weaveproxy/main.go
$(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)
$(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
@@ -93,23 +100,8 @@ $(WEAVE_EXPORT): $(IMAGES_UPTODATE)
$(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 | 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
+tests: $(COVER_EXE)
+ @test/units.sh
$(PUBLISH): publish_%:
$(SUDO) docker tag -f $(DOCKERHUB_USER)/$* $(DOCKERHUB_USER)/$*:$(WEAVE_VERSION)
@@ -120,8 +112,9 @@ publish: $(PUBLISH)
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
diff --git a/README.md b/README.md
index e31c8635..ac209fef 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ it locally to control a weave network on a remote host.
## Quick Start Screencast
-
+
@@ -113,7 +113,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
@@ -121,7 +121,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/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/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}"
;;
diff --git a/bin/multiweave b/bin/multiweave
index 1dd5dfd8..ad4441ac 100755
--- a/bin/multiweave
+++ b/bin/multiweave
@@ -23,14 +23,14 @@ 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
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 --no-dns "$@"
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
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/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 2a01b19f..4bc4d29b 100644
--- a/circle.yml
+++ b/circle.yml
@@ -35,15 +35,26 @@ 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 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
- cd $SRCDIR/test; ./gce.sh setup:
parallel: true
- - cd $SRCDIR/test; . ./gce.sh hosts; ./setup.sh:
+ - cd $SRCDIR/test; eval $(./gce.sh hosts); ./setup.sh:
parallel: true
- - cd $SRCDIR/test; . ./gce.sh hosts; ./run_all.sh:
+ - cd $SRCDIR/test; eval $(./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" || (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/common/docker/client.go b/common/docker/client.go
index 71cdf316..1f2ee0df 100644
--- a/common/docker/client.go
+++ b/common/docker/client.go
@@ -1,23 +1,13 @@
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
+ ContainerDied(ident string)
}
type Client struct {
@@ -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/common/errors.go b/common/errors.go
deleted file mode 100644
index ea6fed41..00000000
--- a/common/errors.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package common
-
-func CheckFatal(e error) {
- if e != nil {
- Log.Fatal(e)
- }
-}
-
-func CheckWarn(e error) {
- if e != nil {
- Log.Warningln(e)
- }
-}
-
-// Assert test is true, panic otherwise
-func Assert(test bool) {
- if !test {
- panic("Assertion failure")
- }
-}
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..d6e86c79 100644
--- a/common/logging.go
+++ b/common/logging.go
@@ -41,22 +41,18 @@ 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
- }
- InitLogging(level)
-}
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 5c733355..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) {
- InitDefaultLogging(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) {
- InitDefaultLogging(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) {
- InitDefaultLogging(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/common/signals.go b/common/signals.go
index e750a8ea..48ed747c 100644
--- a/common/signals.go
+++ b/common/signals.go
@@ -15,22 +15,22 @@ 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")
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/common/utils.go b/common/utils.go
index a3c372b2..95d6872b 100644
--- a/common/utils.go
+++ b/common/utils.go
@@ -1,5 +1,12 @@
package common
+// Assert test is true, panic otherwise
+func Assert(test bool) {
+ if !test {
+ panic("Assertion failure")
+ }
+}
+
func OnOff(b bool) string {
if b {
return "on"
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/docs/hello-screencast.png b/docs/hello-screencast.png
index 70ac6ed3..9385d83f 100644
Binary files a/docs/hello-screencast.png and b/docs/hello-screencast.png differ
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..90177d46 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"
)
@@ -19,6 +19,7 @@ import (
const (
msgSpaceRequest = iota
msgRingUpdate
+ msgSpaceRequestDenied
paxosInterval = time.Second * 5
MinSubnetSize = 4 // first and last addresses are excluded, so 2 would be too small
@@ -64,7 +65,7 @@ func NewAllocator(ourName router.PeerName, ourUID router.PeerUID, ourNickname st
return &Allocator{
ourName: ourName,
universe: universe,
- ring: ring.New(universe.Start, address.Add(universe.Start, universe.Size()), ourName),
+ ring: ring.New(universe.Start, universe.End, ourName),
owned: make(map[string][]address.Address),
paxos: paxos.NewNode(ourName, ourUID, quorum),
nicknames: map[router.PeerName]string{ourName: ourNickname},
@@ -163,6 +164,18 @@ func (alloc *Allocator) tryPendingOps() {
}
}
+func (alloc *Allocator) spaceRequestDenied(sender router.PeerName, r address.Range) {
+ for i := 0; i < len(alloc.pendingClaims); {
+ claim := alloc.pendingClaims[i].(*claim)
+ if r.Contains(claim.addr) {
+ claim.DeniedBy(alloc, sender)
+ alloc.pendingClaims = append(alloc.pendingClaims[:i], alloc.pendingClaims[i+1:]...)
+ continue
+ }
+ i++
+ }
+}
+
func hasBeenCancelled(cancelChan <-chan bool) func() bool {
return func() bool {
select {
@@ -202,21 +215,18 @@ 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
}
// ContainerDied is provided to satisfy the updater interface; does a 'Delete' underneath. Sync.
-func (alloc *Allocator) ContainerDied(ident string) error {
- err := alloc.Delete(ident)
- if err == nil {
+func (alloc *Allocator) ContainerDied(ident string) {
+ if err := alloc.Delete(ident); err == nil {
alloc.debugln("Container", ident, "died; released addresses")
}
- return err
}
// Delete (Sync) - release all IP addresses for container with given name
@@ -343,6 +353,11 @@ func (alloc *Allocator) pruneNicknames() {
}
}
+func decodeRange(msg []byte) (r address.Range, err error) {
+ decoder := gob.NewDecoder(bytes.NewReader(msg))
+ return r, decoder.Decode(&r)
+}
+
// OnGossipUnicast (Sync)
func (alloc *Allocator) OnGossipUnicast(sender router.PeerName, msg []byte) error {
alloc.debugln("OnGossipUnicast from", sender, ": ", len(msg), "bytes")
@@ -351,27 +366,30 @@ func (alloc *Allocator) OnGossipUnicast(sender router.PeerName, msg []byte) erro
switch msg[0] {
case msgSpaceRequest:
// some other peer asked us for space
- decoder := gob.NewDecoder(bytes.NewReader(msg[1:]))
- var r address.Range
- if err := decoder.Decode(&r); err != nil {
- resultChan <- err
- return
+ r, err := decodeRange(msg[1:])
+ if err == nil {
+ alloc.donateSpace(r, sender)
}
- alloc.donateSpace(r, sender)
- resultChan <- nil
+ resultChan <- err
+ case msgSpaceRequestDenied:
+ r, err := decodeRange(msg[1:])
+ if err == nil {
+ alloc.spaceRequestDenied(sender, r)
+ }
+ resultChan <- err
case msgRingUpdate:
- resultChan <- alloc.update(msg[1:])
+ resultChan <- alloc.update(sender, msg[1:])
}
}
return <-resultChan
}
// OnGossipBroadcast (Sync)
-func (alloc *Allocator) OnGossipBroadcast(msg []byte) (router.GossipData, error) {
- alloc.debugln("OnGossipBroadcast:", len(msg), "bytes")
+func (alloc *Allocator) OnGossipBroadcast(sender router.PeerName, msg []byte) (router.GossipData, error) {
+ alloc.debugln("OnGossipBroadcast from", sender, ":", len(msg), "bytes")
resultChan := make(chan error)
alloc.actionChan <- func() {
- resultChan <- alloc.update(msg)
+ resultChan <- alloc.update(sender, msg)
}
return alloc.Gossip(), <-resultChan
}
@@ -420,7 +438,7 @@ func (alloc *Allocator) OnGossip(msg []byte) (router.GossipData, error) {
alloc.debugln("Allocator.OnGossip:", len(msg), "bytes")
resultChan := make(chan error)
alloc.actionChan <- func() {
- resultChan <- alloc.update(msg)
+ resultChan <- alloc.update(router.UnknownPeerName, msg)
}
return nil, <-resultChan // for now, we never propagate updates. TBD
}
@@ -575,13 +593,22 @@ func (alloc *Allocator) propose() {
alloc.gossip.GossipBroadcast(alloc.Gossip())
}
-func (alloc *Allocator) sendSpaceRequest(dest router.PeerName, r address.Range) error {
+func encodeRange(r address.Range) []byte {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
if err := enc.Encode(r); err != nil {
panic(err)
}
- msg := router.Concat([]byte{msgSpaceRequest}, buf.Bytes())
+ return buf.Bytes()
+}
+
+func (alloc *Allocator) sendSpaceRequest(dest router.PeerName, r address.Range) error {
+ msg := router.Concat([]byte{msgSpaceRequest}, encodeRange(r))
+ return alloc.gossip.GossipUnicast(dest, msg)
+}
+
+func (alloc *Allocator) sendSpaceRequestDenied(dest router.PeerName, r address.Range) error {
+ msg := router.Concat([]byte{msgSpaceRequestDenied}, encodeRange(r))
return alloc.gossip.GossipUnicast(dest, msg)
}
@@ -590,7 +617,7 @@ func (alloc *Allocator) sendRingUpdate(dest router.PeerName) {
alloc.gossip.GossipUnicast(dest, msg)
}
-func (alloc *Allocator) update(msg []byte) error {
+func (alloc *Allocator) update(sender router.PeerName, msg []byte) error {
reader := bytes.NewReader(msg)
decoder := gob.NewDecoder(reader)
var data gossipState
@@ -614,6 +641,10 @@ func (alloc *Allocator) update(msg []byte) error {
// shouldn't get updates for a empty Ring. But tolerate
// them just in case.
if data.Ring != nil {
+ if data.Ring.Range() != alloc.universe {
+ return fmt.Errorf("Incompatible IP allocation range %s; ours is %s",
+ data.Ring.Range().AsCIDRString(), alloc.universe.AsCIDRString())
+ }
err = alloc.ring.Merge(*data.Ring)
if !alloc.ring.Empty() {
alloc.pruneNicknames()
@@ -622,16 +653,22 @@ func (alloc *Allocator) update(msg []byte) error {
return err
}
- if data.Paxos != nil && alloc.ring.Empty() {
- if alloc.paxos.Update(data.Paxos) {
- if alloc.paxos.Think() {
- // If something important changed, broadcast
- alloc.gossip.GossipBroadcast(alloc.Gossip())
- }
+ if data.Paxos != nil {
+ if alloc.ring.Empty() {
+ if alloc.paxos.Update(data.Paxos) {
+ if alloc.paxos.Think() {
+ // If something important changed, broadcast
+ alloc.gossip.GossipBroadcast(alloc.Gossip())
+ }
- if ok, cons := alloc.paxos.Consensus(); ok {
- alloc.createRing(cons.Value)
+ if ok, cons := alloc.paxos.Consensus(); ok {
+ alloc.createRing(cons.Value)
+ }
}
+ } else if sender != router.UnknownPeerName {
+ // Sender is trying to initialize a ring, but we have one
+ // already - send it straight back
+ alloc.sendRingUpdate(sender)
}
}
@@ -652,10 +689,14 @@ func (alloc *Allocator) donateSpace(r address.Range, to router.PeerName) {
free := alloc.space.NumFreeAddressesInRange(r)
common.Assert(free == 0)
alloc.debugln("No space to give to peer", to)
+ // separate message maintains backwards-compatibility:
+ // down-level peers will ignore this and still get the ring update.
+ alloc.sendSpaceRequestDenied(to, r)
return
}
alloc.debugln("Giving range", chunk, "to", to)
alloc.ring.GrantRangeToHost(chunk.Start, chunk.End, to)
+ alloc.sendRingUpdate(to)
}
func (alloc *Allocator) assertInvariants() {
diff --git a/ipam/allocator_test.go b/ipam/allocator_test.go
index fcd3027a..c00fb21a 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/ipam/address"
- "github.com/weaveworks/weave/router"
+ "github.com/weaveworks/weave/net/address"
+ "github.com/weaveworks/weave/testing/gossip"
)
const (
@@ -71,7 +72,6 @@ func TestAllocFree(t *testing.T) {
}
func TestBootstrap(t *testing.T) {
- common.InitDefaultLogging(false)
const (
donateSize = 5
donateStart = "10.0.1.7"
@@ -86,7 +86,7 @@ func TestBootstrap(t *testing.T) {
alloc2, _ := makeAllocatorWithMockGossip(t, peerNameString, testStart1+"/22", 2)
defer alloc2.Stop()
- alloc1.OnGossipBroadcast(alloc2.Encode())
+ alloc1.OnGossipBroadcast(alloc2.ourName, alloc2.Encode())
alloc1.actionChan <- func() { alloc1.tryPendingOps() }
@@ -108,19 +108,19 @@ func TestBootstrap(t *testing.T) {
// alloc2 receives paxos update and broadcasts its reply
ExpectBroadcastMessage(alloc2, nil)
- alloc2.OnGossipBroadcast(alloc1.Encode())
+ alloc2.OnGossipBroadcast(alloc1.ourName, alloc1.Encode())
ExpectBroadcastMessage(alloc1, nil)
- alloc1.OnGossipBroadcast(alloc2.Encode())
+ alloc1.OnGossipBroadcast(alloc2.ourName, alloc2.Encode())
// both nodes will get consensus now so initialize the ring
ExpectBroadcastMessage(alloc2, nil)
ExpectBroadcastMessage(alloc2, nil)
- alloc2.OnGossipBroadcast(alloc1.Encode())
+ alloc2.OnGossipBroadcast(alloc1.ourName, alloc1.Encode())
CheckAllExpectedMessagesSent(alloc1, alloc2)
- alloc1.OnGossipBroadcast(alloc2.Encode())
+ alloc1.OnGossipBroadcast(alloc2.ourName, alloc2.Encode())
// now alloc1 should have space
AssertSent(t, done)
@@ -131,23 +131,45 @@ func TestBootstrap(t *testing.T) {
func TestAllocatorClaim(t *testing.T) {
const (
container1 = "abcdef"
- container2 = "baddf00d"
container3 = "b01df00d"
- universe = "10.0.3.0/30"
- testAddr1 = "10.0.3.1" // first address allocated should be .1 because .0 is network addr
+ universe = "10.0.3.0/24"
+ testAddr1 = "10.0.3.2"
+ testAddr2 = "10.0.4.2"
)
- alloc, subnet := makeAllocatorWithMockGossip(t, "01:00:00:01:00:00", universe, 1)
+ allocs, _, subnet := makeNetworkOfAllocators(2, universe)
+ alloc := allocs[1]
defer alloc.Stop()
-
- alloc.claimRingForTesting()
addr1, _ := address.ParseIP(testAddr1)
- err := alloc.Claim(container3, addr1, nil)
+ // First claim should trigger "dunno, I'm going to wait"
+ err := alloc.Claim(container3, addr1)
+ require.NoError(t, err)
+
+ // Do one allocate to ensure paxos is all done
+ alloc.Allocate("unused", subnet, nil)
+ // Do an allocate on the other peer, which we will try to claim later
+ addrx, err := allocs[0].Allocate(container1, subnet, nil)
+
+ // Now try the claim again
+ 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)
require.Equal(t, testAddr1, addr3.String(), "address")
+ // one more claim should still work
+ err = alloc.Claim(container3, addr1)
+ require.NoError(t, err)
+ // claim for a different container should fail
+ err = alloc.Claim(container1, addr1)
+ require.Error(t, err)
+ // claiming the address allocated on the other peer should fail
+ err = alloc.Claim(container1, addrx)
+ require.Error(t, err, "claiming address allocated on other peer should fail")
+ // Check an address outside of our universe
+ addr2, _ := address.ParseIP(testAddr2)
+ err = alloc.Claim(container1, addr2)
+ require.NoError(t, err)
}
func (alloc *Allocator) pause() func() {
@@ -163,18 +185,17 @@ func (alloc *Allocator) pause() func() {
}
func TestCancel(t *testing.T) {
- common.InitDefaultLogging(false)
const (
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)
@@ -182,7 +203,7 @@ func TestCancel(t *testing.T) {
alloc2.Start()
// tell peers about each other
- alloc1.OnGossipBroadcast(alloc2.Encode())
+ alloc1.OnGossipBroadcast(alloc2.ourName, alloc2.Encode())
// Get some IPs, so each allocator has some space
res1, _ := alloc1.Allocate("foo", subnet, nil)
@@ -255,18 +276,18 @@ func TestTransfer(t *testing.T) {
_, err = alloc3.Allocate("bar", subnet, nil)
require.True(t, err == nil, "Failed to get address")
- router.GossipBroadcast(alloc2.Gossip())
- router.flush()
- router.GossipBroadcast(alloc3.Gossip())
- router.flush()
- router.removePeer(alloc2.ourName)
- router.removePeer(alloc3.ourName)
+ alloc2.gossip.GossipBroadcast(alloc2.Gossip())
+ router.Flush()
+ alloc2.gossip.GossipBroadcast(alloc3.Gossip())
+ 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))
@@ -276,7 +297,6 @@ func TestTransfer(t *testing.T) {
}
func TestFakeRouterSimple(t *testing.T) {
- common.InitDefaultLogging(false)
const (
cidr = "10.0.1.7/22"
)
@@ -291,10 +311,9 @@ func TestFakeRouterSimple(t *testing.T) {
}
func TestAllocatorFuzz(t *testing.T) {
- common.InitDefaultLogging(false)
const (
firstpass = 1000
- secondpass = 20000
+ secondpass = 10000
nodes = 10
maxAddresses = 1000
concurrency = 30
@@ -329,27 +348,18 @@ func TestAllocatorFuzz(t *testing.T) {
return xs[:ls]
}
- // Do a Allocate and check the address
- // is unique. Needs a unique container
- // name.
- allocate := func(name string) {
+ bumpPending := func() bool {
stateLock.Lock()
if len(addrs)+numPending >= maxAddresses {
stateLock.Unlock()
- return
+ return false
}
numPending++
stateLock.Unlock()
+ return true
+ }
- allocIndex := rand.Int31n(nodes)
- alloc := allocs[allocIndex]
- //common.Log.Infof("Allocate: asking allocator %d", allocIndex)
- addr, err := alloc.Allocate(name, subnet, nil)
-
- if err != nil {
- panic(fmt.Sprintf("Could not allocate addr"))
- }
-
+ noteAllocation := func(allocIndex int32, name string, addr address.Address) {
//common.Log.Infof("Allocate: got address %s for name %s", addr, name)
addrStr := addr.String()
@@ -366,6 +376,26 @@ func TestAllocatorFuzz(t *testing.T) {
numPending--
}
+ // Do a Allocate and check the address
+ // is unique. Needs a unique container
+ // name.
+ allocate := func(name string) {
+ if !bumpPending() {
+ return
+ }
+
+ allocIndex := rand.Int31n(nodes)
+ alloc := allocs[allocIndex]
+ //common.Log.Infof("Allocate: asking allocator %d", allocIndex)
+ addr, err := alloc.Allocate(name, subnet, nil)
+
+ if err != nil {
+ panic(fmt.Sprintf("Could not allocate addr"))
+ }
+
+ noteAllocation(allocIndex, name, addr)
+ }
+
// Free a random address.
free := func() {
stateLock.Lock()
@@ -426,6 +456,21 @@ func TestAllocatorFuzz(t *testing.T) {
stateLock.Unlock()
}
+ // Claim a random address for a unique container name - may not succeed
+ claim := func(name string) {
+ if !bumpPending() {
+ return
+ }
+ allocIndex := rand.Int31n(nodes)
+ addressIndex := rand.Int31n(int32(subnet.Size()))
+ alloc := allocs[allocIndex]
+ addr := address.Add(subnet.Start, address.Offset(addressIndex))
+ err := alloc.Claim(name, addr)
+ if err == nil {
+ noteAllocation(allocIndex, name, addr)
+ }
+ }
+
// Run function _f_ _iterations_ times, in _concurrency_
// number of goroutines
doConcurrentIterations := func(iterations int, f func(int)) {
@@ -465,9 +510,13 @@ func TestAllocatorFuzz(t *testing.T) {
// free a random addr
free()
- case 0.8 <= r && r < 1.0:
+ case 0.8 <= r && r < 0.95:
// ask for an existing name again, check we get same ip
allocateAgain()
+
+ case 0.95 <= r && r < 1.0:
+ name := fmt.Sprintf("second%d", iteration)
+ claim(name)
}
})
}
@@ -479,7 +528,7 @@ func TestGossipSkew(t *testing.T) {
alloc2.now = func() time.Time { return time.Now().Add(time.Hour * 2) }
defer alloc2.Stop()
- if _, err := alloc1.OnGossipBroadcast(alloc2.Encode()); err == nil {
+ if _, err := alloc1.OnGossipBroadcast(alloc2.ourName, alloc2.Encode()); err == nil {
t.Fail()
}
}
diff --git a/ipam/claim.go b/ipam/claim.go
index 8d96e6e2..fa35ef8f 100644
--- a/ipam/claim.go
+++ b/ipam/claim.go
@@ -3,72 +3,86 @@ package ipam
import (
"fmt"
- "github.com/weaveworks/weave/ipam/address"
+ "github.com/weaveworks/weave/common"
+ "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
)
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) {
+ // 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.Log.Errorln("[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)() {
- 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)
- c.resultChan <- nil
+ alloc.infof("Ignored address %s claimed by %s - not in our universe", c.addr, c.ident)
+ c.sendResult(nil)
return true
}
- // 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 {
- alloc.infof("Ring is empty; will try later.\n", c.addr, owner)
+ switch owner := alloc.ring.Owner(c.addr); owner {
+ case alloc.ourName:
+ // success
+ case router.UnknownPeerName:
+ // If our ring doesn't know, it must be empty.
+ alloc.infof("Claim %s for %s: address allocator still initializing; will try later.", c.addr, c.ident)
+ c.sendResult(nil) // don't make the caller wait
+ return false
+ default:
+ alloc.debugf("requesting address %s from other peer %s", c.addr, owner)
+ err := alloc.sendSpaceRequest(owner, address.NewRange(c.addr, 1))
+ if err != nil { // can't speak to owner right now; figure it out later
+ alloc.infof("Claim %s for %s: %s; will try later.", c.addr, c.ident, err)
+ c.sendResult(nil)
+ }
return false
}
- if owner != alloc.ourName {
- name, found := alloc.nicknames[owner]
- if found {
- name = " (" + name + ")"
- }
- c.resultChan <- 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
- return true
- }
- if existingIdent == "" {
- err := alloc.space.Claim(c.addr)
- if err != nil {
- c.resultChan <- err
- return true
+ switch existingIdent := alloc.findOwner(c.addr); existingIdent {
+ case "":
+ 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)
}
- alloc.debugln("Claimed", c.addr, "for", c.ident)
- alloc.addOwned(c.ident, c.addr)
- c.resultChan <- nil
- return true
+ case c.ident:
+ // same identifier is claiming same address; that's OK
+ c.sendResult(nil)
+ default:
+ // Addr already owned by container on this machine
+ c.sendResult(fmt.Errorf("address %s is already owned by %s", c.addr.String(), existingIdent))
}
- // Addr already owned by container on this machine
- c.resultChan <- fmt.Errorf("address %s is already owned by %s", c.addr.String(), existingIdent)
return true
}
+func (c *claim) DeniedBy(alloc *Allocator, owner router.PeerName) {
+ name, found := alloc.nicknames[owner]
+ if found {
+ name = " (" + name + ")"
+ }
+ c.sendResult(fmt.Errorf("address %s is owned by other peer %s%s", c.addr.String(), owner, name))
+}
+
func (c *claim) Cancel() {
- c.resultChan <- fmt.Errorf("Operation cancelled.")
+ c.sendResult(fmt.Errorf("Operation cancelled."))
}
func (c *claim) String() string {
diff --git a/ipam/http.go b/ipam/http.go
index 0b665385..3fcbb332 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) {
@@ -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
}
@@ -78,7 +77,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 +94,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/ipam/http_test.go b/ipam/http_test.go
index f00ea0b2..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"
)
@@ -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/ipam/ring/entry.go b/ipam/ring/entry.go
index 358216ec..d1d832ed 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"
)
@@ -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
diff --git a/ipam/ring/ring.go b/ipam/ring/ring.go
index 1d55219e..6021efcc 100644
--- a/ipam/ring/ring.go
+++ b/ipam/ring/ring.go
@@ -10,9 +10,10 @@ import (
"io"
"math/rand"
"sort"
+ "time"
"github.com/weaveworks/weave/common"
- "github.com/weaveworks/weave/ipam/address"
+ "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
)
@@ -32,16 +33,14 @@ func (r *Ring) assertInvariants() {
// Errors returned by Merge
var (
- ErrNotSorted = errors.New("Ring not sorted")
- ErrTokenRepeated = errors.New("Token appears twice in ring")
- ErrTokenOutOfRange = errors.New("Token is out of range")
- ErrDifferentSubnets = errors.New("IP Allocator with different subnet detected")
- ErrNewerVersion = errors.New("Received new version for entry I own!")
- ErrInvalidEntry = errors.New("Received invalid state update!")
- ErrEntryInMyRange = errors.New("Received new entry in my range!")
- ErrNoFreeSpace = errors.New("No free space found!")
- ErrInvalidTimeout = errors.New("dt must be greater than 0")
- ErrNotFound = errors.New("No entries for peer found")
+ ErrNotSorted = errors.New("Ring not sorted")
+ ErrTokenRepeated = errors.New("Token appears twice in ring")
+ ErrTokenOutOfRange = errors.New("Token is out of range")
+ ErrDifferentRange = errors.New("Received range differs from ours!")
+ ErrNewerVersion = errors.New("Received new version for entry I own!")
+ ErrInvalidEntry = errors.New("Received invalid state update!")
+ ErrEntryInMyRange = errors.New("Received new entry in my range!")
+ ErrNotFound = errors.New("No entries for peer found")
)
func (r *Ring) checkInvariants() error {
@@ -91,6 +90,10 @@ func New(start, end address.Address, peer router.PeerName) *Ring {
return ring
}
+func (r *Ring) Range() address.Range {
+ return address.Range{Start: r.Start, End: r.End}
+}
+
// Returns the distance between two tokens on this ring, dealing
// with ranges which cross the origin
func (r *Ring) distance(start, end address.Address) address.Offset {
@@ -186,7 +189,7 @@ func (r *Ring) Merge(gossip Ring) error {
}
if r.Start != gossip.Start || r.End != gossip.End {
- return ErrDifferentSubnets
+ return ErrDifferentRange
}
// Now merge their ring with yours, in a temporary ring.
@@ -217,7 +220,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)
@@ -518,3 +521,7 @@ func (r *Ring) PeerNames() map[router.PeerName]struct{} {
return res
}
+
+func init() {
+ rand.Seed(time.Now().UTC().UnixNano())
+}
diff --git a/ipam/ring/ring_test.go b/ipam/ring/ring_test.go
index 852f060e..c9ab789b 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"
)
@@ -212,7 +212,7 @@ func TestMergeErrors(t *testing.T) {
// Should Merge two rings for different ranges
ring2 = New(start, middle, peer2name)
ring2.Entries = []*entry{}
- require.True(t, ring1.Merge(*ring2) == ErrDifferentSubnets, "Expected ErrDifferentSubnets")
+ require.True(t, ring1.Merge(*ring2) == ErrDifferentRange, "Expected ErrDifferentRange")
// Cannot Merge newer version of entry I own
ring2 = New(start, end, peer2name)
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..95f6407a 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/ipam/address"
+ "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()
+ allocs[size-1].gossip.GossipBroadcast(allocs[size-1].Gossip())
+ gossipRouter.Flush()
return allocs, gossipRouter, subnet
}
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 2118832b..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) {
- InitDefaultLogging(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 f3a14cb0..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) {
- InitDefaultLogging(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) {
- InitDefaultLogging(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
index c232d45b..118faea4 100644
--- a/nameserver/dns.go
+++ b/nameserver/dns.go
@@ -1,117 +1,292 @@
package nameserver
import (
+ "bytes"
+ "fmt"
"math/rand"
+ "net"
+ "sort"
+ "strings"
"time"
"github.com/miekg/dns"
+
+ "github.com/weaveworks/weave/net/address"
)
const (
- minUDPSize = 512
- maxUDPSize = 65535
+ topDomain = "."
+ reverseDNSdomain = "in-addr.arpa."
+ etcResolvConf = "/etc/resolv.conf"
+ udpBuffSize = uint16(4096)
+ minUDPSize = 512
+
+ DefaultPort = 53
+ DefaultTTL = 1
+ DefaultClientTimeout = 5 * time.Second
)
-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),
+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 makeReply(r *dns.Msg, as []dns.RR) *dns.Msg {
- m := new(dns.Msg)
+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.Answer = as
+ 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 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
-}
+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
+ }
-type DNSResponseBuilder func(r *dns.Msg, q *dns.Question, addrs []ZoneRecord, ttl int) *dns.Msg
+ hostname := dns.Fqdn(req.Question[0].Name)
+ if strings.Count(hostname, ".") == 1 {
+ hostname = hostname + d.domain
+ }
-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()
+ addrs := d.ns.Lookup(hostname)
- 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++
- }
+ response := dns.Msg{}
+ response.RecursionAvailable = true
+ response.Authoritative = true
+ response.SetReply(req)
+ response.Answer = make([]dns.RR, len(addrs))
+
+ header := dns.RR_Header{
+ Name: req.Question[0].Name,
+ 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)
}
}
- 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 (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
+ }
-func makeDNSFailResponse(r *dns.Msg) *dns.Msg {
- m := new(dns.Msg)
- m.SetReply(r)
- m.RecursionAvailable = true
- m.Rcode = dns.RcodeNameError
- return m
-}
+ ipStr := strings.TrimSuffix(req.Question[0].Name, "."+reverseDNSdomain)
+ ip, err := address.ParseIP(ipStr)
+ if err != nil {
+ d.errorResponse(req, dns.RcodeNameError, w)
+ return
+ }
-// 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
-}
+ hostname, err := d.ns.ReverseLookup(ip.Reverse())
+ if err != nil {
+ d.handleRecursive(client, defaultMaxResponseSize)(w, req)
+ return
+ }
-func init() {
- rand.Seed(time.Now().UTC().UnixNano())
-}
+ response := dns.Msg{}
+ response.RecursionAvailable = true
+ response.Authoritative = true
+ response.SetReply(req)
-// 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]
+ 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)
}
}
-
- 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]
+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 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 {
+ reqCopy := req.Copy()
+ reqCopy.Id = dns.Id()
+ response, _, err := client.Exchange(reqCopy, fmt.Sprintf("%s:%s", server, d.upstream.Port))
+ if err != nil || response == nil {
+ d.ns.debugf("error trying %s: %v", server, err)
+ continue
+ }
+ if response.Rcode != dns.RcodeSuccess && !response.Authoritative {
+ d.ns.debugf("non-authoritative error trying %s: %v", server, response.Rcode)
+ continue
+ }
+ d.ns.debugf("response: %+v", response)
+ response.SetReply(req)
+ if err := w.WriteMsg(response); err != nil {
+ d.ns.infof("error responding: %v", err)
+ }
+ return
+ }
+
+ d.errorResponse(req, dns.RcodeServerFailure, w)
}
- return answers
+}
+
+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
index 1ec25147..b44ce94b 100644
--- a/nameserver/dns_test.go
+++ b/nameserver/dns_test.go
@@ -1,39 +1,95 @@
package nameserver
import (
+ "fmt"
+ "math/rand"
"net"
"testing"
+ "time"
"github.com/miekg/dns"
"github.com/stretchr/testify/require"
- . "github.com/weaveworks/weave/common"
+
+ "github.com/weaveworks/weave/net/address"
+ "github.com/weaveworks/weave/router"
)
-// Check that we can prune an answer
-func TestPrune(t *testing.T) {
- InitDefaultLogging(testing.Verbose())
- Log.Infoln("TestPrune starting")
+func TestTruncation(t *testing.T) {
+ //common.SetLogLevel("debug")
- 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},
+ 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)
}
- reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL)
- reply.Answer[0].Header().Ttl = DefaultLocalTTL
+ 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
+ }
- pruned := pruneAnswers(reply.Answer, 1)
- require.Equal(t, 1, len(pruned), "wrong number of answers")
+ // 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)
+ }
- pruned = pruneAnswers(reply.Answer, 2)
- require.Equal(t, 2, len(pruned), "wrong number of answers")
+ // 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)
+ }
- pruned = pruneAnswers(reply.Answer, 0)
- require.Equal(t, len(records), len(pruned), "wrong number of answers")
+ // 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..6a750cd4
--- /dev/null
+++ b/nameserver/entry.go
@@ -0,0 +1,209 @@
+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 true
+ }
+ return false
+}
+
+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!")
+ }
+ for i := 1; i < len(es); i++ {
+ if es[i].equal(&es[i-1]) {
+ return fmt.Errorf("Duplicate entry: %d:%v and %d:%v", i-1, es[i-1], i, es[i])
+ }
+ }
+ 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 {
+ es.checkAndPanic()
+ 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) {
+ if (*es)[i].Tombstone > 0 {
+ (*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 {
+ es.checkAndPanic()
+ defer es.checkAndPanic()
+ 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) {
+ newEntries = append(newEntries, entry)
+ }
+ } else {
+ *es = append(*es, Entry{})
+ copy((*es)[i+1:], (*es)[i:])
+ (*es)[i] = entry
+ newEntries = append(newEntries, entry)
+ }
+ }
+
+ return newEntries
+}
+
+// f returning true means keep the entry.
+func (es *Entries) tombstone(ourname router.PeerName, f func(*Entry) bool) Entries {
+ es.checkAndPanic()
+ defer es.checkAndPanic()
+ 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) {
+ es.checkAndPanic()
+ defer es.checkAndPanic()
+ i := 0
+ for _, e := range *es {
+ if !f(&e) {
+ continue
+ }
+ (*es)[i] = e
+ i++
+ }
+ *es = (*es)[:i]
+}
+
+func (es Entries) lookup(hostname string) Entries {
+ es.checkAndPanic()
+ 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) {
+ es.checkAndPanic()
+ for _, e := range *es {
+ if f(&e) {
+ return &e, nil
+ }
+ }
+ return nil, fmt.Errorf("Not found")
+}
+
+type GossipData struct {
+ Timestamp int64
+ Entries
+}
+
+func (g *GossipData) Merge(o router.GossipData) {
+ other := o.(*GossipData)
+ g.Entries.merge(other.Entries)
+ if g.Timestamp < other.Timestamp {
+ g.Timestamp = other.Timestamp
+ }
+}
+
+func (g *GossipData) Encode() [][]byte {
+ buf := &bytes.Buffer{}
+ if err := gob.NewEncoder(buf).Encode(g); 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..96d2b883
--- /dev/null
+++ b/nameserver/entry_test.go
@@ -0,0 +1,132 @@
+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"},
+ }
+
+ diff := e1.merge(e2)
+ expectedDiff := Entries{
+ Entry{Hostname: "B"},
+ Entry{Hostname: "E"},
+ }
+ require.Equal(t, expectedDiff, diff)
+
+ expected := Entries{
+ Entry{Hostname: "A"},
+ Entry{Hostname: "B"},
+ Entry{Hostname: "C"},
+ Entry{Hostname: "D"},
+ Entry{Hostname: "E"},
+ Entry{Hostname: "F"},
+ }
+ require.Equal(t, expected, e1)
+
+ diff = e1.merge(e1)
+ require.Equal(t, Entries{}, diff)
+}
+
+func TestOldMerge(t *testing.T) {
+ e1 := Entries{Entry{Hostname: "A", Version: 0}}
+ diff := e1.merge(Entries{Entry{Hostname: "A", Version: 1}})
+ require.Equal(t, Entries{Entry{Hostname: "A", Version: 1}}, diff)
+ require.Equal(t, Entries{Entry{Hostname: "A", Version: 1}}, e1)
+
+ diff = e1.merge(Entries{Entry{Hostname: "A", Version: 0}})
+ require.Equal(t, Entries{}, diff)
+ require.Equal(t, Entries{Entry{Hostname: "A", Version: 1}}, e1)
+}
+
+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, expected, es)
+}
+
+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, expected, es)
+}
+
+func TestLookup(t *testing.T) {
+ es := Entries{
+ Entry{Hostname: "A"},
+ Entry{Hostname: "B", ContainerID: "bar"},
+ Entry{Hostname: "B", ContainerID: "foo"},
+ Entry{Hostname: "C"},
+ }
+
+ have := es.lookup("B")
+ want := Entries{
+ Entry{Hostname: "B", ContainerID: "bar"},
+ Entry{Hostname: "B", ContainerID: "foo"},
+ }
+ require.Equal(t, have, want)
+}
diff --git a/nameserver/http.go b/nameserver/http.go
index 42dd3231..7b3eb352 100644
--- a/nameserver/http.go
+++ b/nameserver/http.go
@@ -1,124 +1,94 @@
package nameserver
import (
+ "encoding/json"
"fmt"
- "net"
"net/http"
"github.com/gorilla/mux"
"github.com/miekg/dns"
- . "github.com/weaveworks/weave/common"
- "github.com/weaveworks/weave/common/docker"
+
+ "github.com/weaveworks/weave/common"
+ "github.com/weaveworks/weave/net/address"
)
-func httpErrorAndLog(w http.ResponseWriter, msg string,
- status int, logmsg string, logargs ...interface{}) {
- http.Error(w, msg, status)
- Log.Warningf("[http] "+logmsg, logargs...)
+func badRequest(w http.ResponseWriter, err error) {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ common.Log.Warningf("[gossipdns]: %v", err)
}
-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())
+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)
})
-
- 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)
+ 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
}
- ip := net.ParseIP(ipStr)
- if ip == nil {
- reqError("Invalid IP", "Invalid IP in request: %s", ipStr)
+ if err := n.AddEntry(dns.Fqdn(hostname), container, n.ourName, ip); err != nil {
+ badRequest(w, fmt.Errorf("Unable to add entry: %v", err))
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" && 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)
+ }
}
- if dockerCli != nil && dockerCli.IsContainerNotRunning(idStr) {
- Log.Infof("[http] '%s' is not running: removing", idStr)
- server.Zone.DeleteRecords(idStr, name, ip)
- }
+ w.WriteHeader(204)
})
- muxRouter.Methods("DELETE").Path("/name/{id:.+}/{ip:.+}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ deleteHandler := 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
+ hostname := r.FormValue("fqdn")
+ if hostname == "" {
+ hostname = "*"
+ } else {
+ hostname = dns.Fqdn(hostname)
}
-
- 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{})
- })
+ container, ok := vars["container"]
+ if !ok {
+ container = "*"
+ }
- http.Handle("/", muxRouter)
+ ipStr, ok := vars["ip"]
+ ip, err := address.ParseIP(ipStr)
+ if ok && err != nil {
+ badRequest(w, err)
+ return
+ } else if !ok {
+ ipStr = "*"
+ }
- if err := http.Serve(listener, nil); err != nil {
- Log.Fatal("[http] Unable to serve http: ", err)
+ 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)
+
+ router.Methods("GET").Path("/name").Headers("Accept", "application/json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n.RLock()
+ defer n.RUnlock()
+ if err := json.NewEncoder(w).Encode(n.entries); err != nil {
+ badRequest(w, fmt.Errorf("Error marshalling response: %v", 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 11f0bc2d..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) {
- InitDefaultLogging(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 3fe89fe0..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."
- )
-
- InitDefaultLogging(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 867eedec..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) {
- InitDefaultLogging(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) {
- InitDefaultLogging(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/nameserver.go b/nameserver/nameserver.go
new file mode 100644
index 00000000..b3a0975c
--- /dev/null
+++ b/nameserver/nameserver.go
@@ -0,0 +1,272 @@
+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 * 30
+
+ // Used by prog/weaver/main.go and proxy/create_container_interceptor.go
+ DefaultDomain = "weave.local."
+
+ // Maximum age of acceptable gossip messages (to account for clock skew)
+ gossipWindow = int64(tombstoneTimeout/time.Second) / 2
+)
+
+// 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) broadcastEntries(es ...Entry) error {
+ if n.gossip != nil {
+ return n.gossip.GossipBroadcast(&GossipData{
+ Entries: Entries(es),
+ Timestamp: now(),
+ })
+ }
+ return nil
+}
+
+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()
+ return n.broadcastEntries(entry)
+}
+
+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) {
+ 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 len(entries) > 0 {
+ if err := n.broadcastEntries(entries...); err != nil {
+ n.errorf("Failed to broadcast container '%s' death: %v", ident, err)
+ }
+ }
+}
+
+func (n *Nameserver) PeerGone(peer *router.Peer) {
+ n.infof("peer gone %s", peer.String())
+ 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()
+ return n.broadcastEntries(entries...)
+}
+
+func (n *Nameserver) deleteTombstones() {
+ n.Lock()
+ defer n.Unlock()
+ now := time.Now().Unix()
+ n.entries.filter(func(e *Entry) bool {
+ return e.Tombstone == 0 || 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()
+ gossip := &GossipData{
+ Entries: make(Entries, len(n.entries)),
+ Timestamp: now(),
+ }
+ copy(gossip.Entries, n.entries)
+ return gossip
+}
+
+func (n *Nameserver) OnGossipUnicast(sender router.PeerName, msg []byte) error {
+ return nil
+}
+
+func (n *Nameserver) receiveGossip(msg []byte) (router.GossipData, router.GossipData, error) {
+ var gossip GossipData
+ if err := gob.NewDecoder(bytes.NewReader(msg)).Decode(&gossip); err != nil {
+ return nil, nil, err
+ }
+
+ if delta := gossip.Timestamp - now(); delta > gossipWindow || delta < -gossipWindow {
+ return nil, nil, fmt.Errorf("clock skew of %d detected", delta)
+ }
+
+ if err := gossip.Entries.check(); err != nil {
+ return nil, nil, err
+ }
+
+ n.Lock()
+ defer n.Unlock()
+
+ if n.peers != nil {
+ gossip.Entries.filter(func(e *Entry) bool {
+ return n.peers.Fetch(e.Origin) != nil
+ })
+ }
+
+ newEntries := n.entries.merge(gossip.Entries)
+ if len(newEntries) > 0 {
+ return &GossipData{Entries: newEntries, Timestamp: now()}, &gossip, nil
+ }
+ return nil, &gossip, 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(_ router.PeerName, 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...)...)
+}
+func (n *Nameserver) errorf(fmt string, args ...interface{}) {
+ Log.Errorf("[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..3d5d462c
--- /dev/null
+++ b/nameserver/nameserver_test.go
@@ -0,0 +1,256 @@
+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"
+ wt "github.com/weaveworks/weave/testing"
+ "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, grouter *gossip.TestRouter) {
+ for _, nameserver := range nameservers {
+ nameserver.Stop()
+ }
+ grouter.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) {
+ wt.RunWithTimeout(t, time.Minute, func() {
+ testNameservers(t)
+ })
+}
+
+func testNameservers(t *testing.T) {
+ //common.SetLogLevel("debug")
+
+ lookupTimeout := 10 // ms
+ nameservers, grouter := makeNetwork(50)
+ defer stopNetwork(nameservers, grouter)
+ 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++ {
+ 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()
+ }
+
+ grouter.Flush()
+ }
+}
+
+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"))
+
+ nameserver.ContainerDied("containerid")
+ 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"))
+
+ nameserver.deleteTombstones()
+ 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/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 35f3dc82..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."
- )
-
- InitDefaultLogging(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
- )
-
- InitDefaultLogging(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
- )
-
- InitDefaultLogging(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 ab19362b..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"
-
- InitDefaultLogging(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."
- )
-
- InitDefaultLogging(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 5f86f34c..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"
- )
-
- InitDefaultLogging(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 04a7e9d9..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."
- )
-
- InitDefaultLogging(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"
- )
-
- InitDefaultLogging(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/ipam/address/address.go b/net/address/address.go
similarity index 78%
rename from ipam/address/address.go
rename to net/address/address.go
index f97d44c8..291a3227 100644
--- a/ipam/address/address.go
+++ b/net/address/address.go
@@ -23,6 +23,17 @@ func (r Range) String() string { return fmt.Sprintf("[%s-%s)", r.Sta
func (r Range) Overlaps(or Range) bool { return !(r.Start >= or.End || r.End <= or.Start) }
func (r Range) Contains(addr Address) bool { return addr >= r.Start && addr < r.End }
+func (r Range) AsCIDRString() string {
+ prefixLen := 32
+ for size := r.Size(); size > 1; size = size / 2 {
+ if size%2 != 0 { // Size not a power of two; cannot be expressed as a CIDR.
+ return r.String()
+ }
+ prefixLen--
+ }
+ return CIDR{Start: r.Start, PrefixLen: prefixLen}.String()
+}
+
type CIDR struct {
Start Address
PrefixLen int
@@ -79,6 +90,10 @@ func (addr Address) IP4() (r net.IP) {
return
}
+func (addr Address) MarshalJSON() ([]byte, error) {
+ return []byte(fmt.Sprintf("%q", addr.String())), nil
+}
+
func (addr Address) String() string {
return addr.IP4().String()
}
@@ -98,3 +113,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/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)
}
diff --git a/net/route.go b/net/route.go
index 6d1722ad..463f843b 100644
--- a/net/route.go
+++ b/net/route.go
@@ -9,17 +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) 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) {
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.
@@ -29,14 +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) 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) {
- return fmt.Errorf("Address %s overlaps with existing route %s on host.", addr, route.Dst)
+ if link, err := netlink.LinkByIndex(route.LinkIndex); err == nil {
+ if _, found := ignoreIfaceNames[link.Attrs().Name]; found {
+ continue
+ }
+ }
+ if err := check(route); err != nil {
+ return err
}
}
return nil
diff --git a/prog/netcheck/netcheck.go b/prog/netcheck/netcheck.go
index 96a26ed4..fe822f2e 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"
)
@@ -14,20 +15,37 @@ func fatal(err error) {
os.Exit(1)
}
+type stringList map[string]struct{}
+
+func (ss *stringList) Set(value string) error {
+ (*ss)[value] = struct{}{}
+ return nil
+}
+
+func (ss *stringList) String() string {
+ return fmt.Sprintf("%v", *ss)
+}
+
func main() {
- if len(os.Args) <= 1 {
- os.Exit(0)
+ ignoreIfaceNames := make(stringList)
+
+ mflag.Var(&ignoreIfaceNames, []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, ignoreIfaceNames)
} else {
- err = weavenet.CheckAddressOverlap(addr)
+ err = weavenet.CheckAddressOverlap(addr, ignoreIfaceNames)
}
if err != nil {
fatal(err)
diff --git a/prog/weavedns/Dockerfile b/prog/weavedns/Dockerfile
deleted file mode 100644
index d7af8837..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", "-wait", "20"]
diff --git a/prog/weavedns/main.go b/prog/weavedns/main.go
deleted file mode 100644
index 36763bc8..00000000
--- a/prog/weavedns/main.go
+++ /dev/null
@@ -1,186 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "net"
- "os"
- "strconv"
-
- "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
- debug bool
- 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", 0, "number of seconds to wait for interface to be created and come up")
- 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.BoolVar(&debug, "debug", false, "output debugging info to stderr")
- // 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()
-
- if justVersion {
- fmt.Printf("weave DNS %s\n", version)
- os.Exit(0)
- }
-
- InitDefaultLogging(debug)
- Log.Infof("[main] WeaveDNS version %s\n", 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()
-}
diff --git a/prog/weaveexec/Dockerfile b/prog/weaveexec/Dockerfile
index c4cdb7a3..9d101bd7 100644
--- a/prog/weaveexec/Dockerfile
+++ b/prog/weaveexec/Dockerfile
@@ -2,6 +2,10 @@ FROM gliderlabs/alpine
MAINTAINER Weaveworks Inc
+WORKDIR /home/weave
+VOLUME /w
+ENTRYPOINT ["/home/weave/sigproxy", "/home/weave/weave"]
+
RUN apk add --update \
curl \
ethtool \
@@ -9,17 +13,10 @@ RUN apk add --update \
iproute2 \
util-linux \
conntrack-tools \
+ bind-tools \
&& rm -rf /var/cache/apk/*
-WORKDIR /home/weave
-
-ADD ./weave /home/weave/
-ADD ./sigproxy /home/weave/
-ADD ./weaveproxy /home/weave/
+ADD ./weave ./sigproxy ./weaveproxy /home/weave/
ADD ./netcheck /usr/bin/
ADD ./weavewait /w/w
ADD ./docker.tgz /
-
-VOLUME /w
-
-ENTRYPOINT ["/home/weave/sigproxy", "/home/weave/weave"]
diff --git a/prog/weaveproxy/main.go b/prog/weaveproxy/main.go
index 150b4788..f77f0406 100644
--- a/prog/weaveproxy/main.go
+++ b/prog/weaveproxy/main.go
@@ -5,37 +5,63 @@ import (
"os"
"strings"
- "github.com/pborman/getopt"
+ "github.com/docker/docker/pkg/mflag"
. "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/proxy"
)
var (
- version = "(unreleased version)"
- defaultListenAddrs = []string{"tcp://0.0.0.0:12375", "unix:///var/run/weave.sock"}
+ version = "(unreleased version)"
)
+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 (
- debug bool
justVersion bool
- c = proxy.Config{ListenAddrs: defaultListenAddrs}
+ logLevel = "info"
+ c = proxy.Config{ListenAddrs: []string{}}
)
c.Version = version
- getopt.BoolVarLong(&debug, "debug", 'd', "log debugging information")
- getopt.BoolVarLong(&justVersion, "version", 0, "print version and exit")
- 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"}, nil, "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")
+ 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)
@@ -46,9 +72,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/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 297444f3..f61318cb 100644
--- a/prog/weaver/main.go
+++ b/prog/weaver/main.go
@@ -2,21 +2,25 @@ package main
import (
"crypto/sha256"
- "flag"
"fmt"
"net"
"net/http"
+ _ "net/http/pprof"
"os"
"runtime"
"strings"
+ "time"
"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"
- "github.com/weaveworks/weave/ipam/address"
+ "github.com/weaveworks/weave/nameserver"
weavenet "github.com/weaveworks/weave/net"
+ "github.com/weaveworks/weave/net/address"
weave "github.com/weaveworks/weave/router"
)
@@ -32,48 +36,61 @@ func main() {
runtime.GOMAXPROCS(procs)
var (
- config weave.Config
- justVersion bool
- ifaceName string
- routerName string
- nickName string
- password string
- wait int
- debug bool
- pktdebug bool
- 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
+ noDNS bool
+ dnsDomain string
+ dnsPort int
+ dnsTTL int
+ dnsClientTimeout time.Duration
)
- 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", 0, "number of seconds to wait for interface to be created and come up (0 = don't wait)")
- 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")
- 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.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)")
+ 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.BoolVar(&noDNS, []string{"-no-dns"}, false, "disable DNS server")
+ 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")
- InitDefaultLogging(debug)
+ mflag.Parse()
+ peers = mflag.Args()
+
+ SetLogLevel(logLevel)
if justVersion {
fmt.Printf("weave router %s\n", version)
os.Exit(0)
@@ -82,6 +99,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 != "" {
@@ -93,7 +115,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()
}
@@ -133,20 +155,40 @@ 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)
}
} else if peerCount > 0 {
- Log.Fatal("-initpeercount flag specified without -iprange")
+ Log.Fatal("--init-peer-count flag specified without --ipalloc-range")
+ }
+
+ var (
+ ns *nameserver.Nameserver
+ dnsserver *nameserver.DNSServer
+ )
+ if !noDNS {
+ 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()
@@ -155,10 +197,10 @@ 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)
+ go handleHTTP(router, httpAddr, allocator, defaultSubnet, dockerCli, ns, dnsserver)
}
SignalHandlerLoop(router)
@@ -174,16 +216,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) {}
@@ -252,13 +304,23 @@ 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)
}
+ if ns != nil {
+ 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")
+ 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())
@@ -266,11 +328,13 @@ func handleHTTP(router *weave.Router, httpAddr string, allocator *ipam.Allocator
fmt.Fprintln(w, allocator.String())
fmt.Fprintln(w, "Allocator default subnet:", defaultSubnet)
}
- })
-
- muxRouter.Methods("GET").Path("/status-json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- json, _ := router.StatusJSON(version)
- w.Write(json)
+ fmt.Fprintln(w, "")
+ if dnsserver == nil {
+ fmt.Fprintln(w, "WeaveDNS is disabled")
+ } else {
+ 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/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/prog/weavewait/main.go b/prog/weavewait/main.go
index 3cb78663..24904f2b 100644
--- a/prog/weavewait/main.go
+++ b/prog/weavewait/main.go
@@ -1,14 +1,19 @@
package main
import (
+ "bufio"
+ "bytes"
"fmt"
+ "io/ioutil"
+ "net"
"os"
"os/exec"
"os/signal"
+ "sort"
+ "strings"
"syscall"
- "time"
- "github.com/weaveworks/weave/net"
+ weavenet "github.com/weaveworks/weave/net"
)
func main() {
@@ -16,23 +21,36 @@ func main() {
os.Exit(0)
}
- args := os.Args[1:]
- signalWait := 20
+ var (
+ args = os.Args[1:]
+ notInExec = true
+ rewriteHosts = true
+ )
+
if args[0] == "-s" {
- signalWait = 0
+ notInExec = false
+ rewriteHosts = false
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):
+ if args[0] == "-h" {
+ rewriteHosts = false
+ args = args[1:]
}
- _, err := net.EnsureInterface("ethwe", interfaceWait)
+
+ if notInExec {
+ usr2 := make(chan os.Signal)
+ signal.Notify(usr2, syscall.SIGUSR2)
+ <-usr2
+ }
+
+ iface, err := weavenet.EnsureInterface("ethwe", -1)
checkErr(err)
+ if rewriteHosts {
+ updateHosts(iface)
+ }
+
binary, err := exec.LookPath(args[0])
checkErr(err)
@@ -45,3 +63,92 @@ func checkErr(err error) {
os.Exit(1)
}
}
+
+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]] = append(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{}
+ 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(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
+}
diff --git a/proxy/common.go b/proxy/common.go
index 7231226c..69d337e3 100644
--- a/proxy/common.go
+++ b/proxy/common.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io/ioutil"
"net/http"
+ "os"
"os/exec"
"regexp"
@@ -18,13 +19,22 @@ 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
+ 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))
+ }
+ 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/create_container_interceptor.go b/proxy/create_container_interceptor.go
index 723a3d0b..e6942a5a 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
@@ -23,9 +25,9 @@ type createContainerRequestBody struct {
MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"`
}
-// Replacement for docker.NoSuchImage, which does not contain the
-// image name, which in turn breaks docker clients post 1.7.0 since
-// they expect the image name to be present in errors.
+// ErrNoSuchImage replaces docker.NoSuchImage, which does not contain the image
+// name, which in turn breaks docker clients post 1.7.0 since they expect the
+// image name to be present in errors.
type ErrNoSuchImage struct {
Name string
}
@@ -46,19 +48,23 @@ func (i *createContainerInterceptor) InterceptRequest(r *http.Request) error {
return err
}
- if cidrs, ok := i.proxy.weaveCIDRsFromConfig(container.Config); ok {
+ if cidrs, err := i.proxy.weaveCIDRsFromConfig(container.Config, container.HostConfig); err != nil {
+ Log.Infof("Ignoring container due to %s", err)
+ } else {
Log.Infof("Creating container with WEAVE_CIDR \"%s\"", strings.Join(cidrs, " "))
if container.HostConfig == nil {
container.HostConfig = &docker.HostConfig{}
}
- container.HostConfig.VolumesFrom = append(container.HostConfig.VolumesFrom, "weaveproxy")
+ container.HostConfig.VolumesFrom = append(container.HostConfig.VolumesFrom, "weaveproxy:ro")
if container.Config == nil {
container.Config = &docker.Config{}
}
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
}
}
@@ -92,7 +98,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
@@ -133,15 +143,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/proxy/create_exec_interceptor.go b/proxy/create_exec_interceptor.go
index 5414346e..8b89a53a 100644
--- a/proxy/create_exec_interceptor.go
+++ b/proxy/create_exec_interceptor.go
@@ -29,7 +29,11 @@ func (i *createExecInterceptor) InterceptRequest(r *http.Request) error {
return err
}
- if cidrs, ok := i.proxy.weaveCIDRsFromConfig(container.Config); ok {
+ _, hasWeaveWait := container.Volumes["/w"]
+ cidrs, err := i.proxy.weaveCIDRsFromConfig(container.Config, container.HostConfig)
+ if err != nil {
+ Log.Infof("Ignoring container %s due to %s", container.ID, err)
+ } else if hasWeaveWait {
Log.Infof("Exec in container %s with WEAVE_CIDR \"%s\"", container.ID, strings.Join(cidrs, " "))
cmd := append(weaveWaitEntrypoint, "-s")
options.Cmd = append(cmd, options.Cmd...)
diff --git a/proxy/proxy.go b/proxy/proxy.go
index 0812ab4b..5f1bbb06 100644
--- a/proxy/proxy.go
+++ b/proxy/proxy.go
@@ -2,6 +2,7 @@ package proxy
import (
"crypto/tls"
+ "errors"
"fmt"
"net"
"net/http"
@@ -26,21 +27,29 @@ var (
containerCreateRegexp = regexp.MustCompile("^(/v[0-9\\.]*)?/containers/create$")
containerStartRegexp = regexp.MustCompile("^(/v[0-9\\.]*)?/containers/[^/]*/(re)?start$")
execCreateRegexp = regexp.MustCompile("^(/v[0-9\\.]*)?/containers/[^/]*/exec$")
+
+ ErrInvalidNetworkMode = errors.New("--net option")
+ ErrWeaveCIDRNone = errors.New("WEAVE_CIDR=none")
+ ErrNoDefaultIPAM = errors.New("--no-default-ipam option")
)
type Config struct {
- ListenAddrs []string
- NoDefaultIPAM 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) {
@@ -57,13 +66,19 @@ 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)
}
+ 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
}
@@ -181,14 +196,22 @@ func (proxy *Proxy) listen(protoAndAddr string) (net.Listener, string, error) {
return listener, fmt.Sprintf("%s://%s", proto, addr), nil
}
-func (proxy *Proxy) weaveCIDRsFromConfig(config *docker.Config) ([]string, bool) {
+func (proxy *Proxy) weaveCIDRsFromConfig(config *docker.Config, hostConfig *docker.HostConfig) ([]string, error) {
+ if hostConfig != nil &&
+ hostConfig.NetworkMode != "" &&
+ hostConfig.NetworkMode != "bridge" {
+ return nil, ErrInvalidNetworkMode
+ }
for _, e := range config.Env {
if strings.HasPrefix(e, "WEAVE_CIDR=") {
if e[11:] == "none" {
- return nil, false
+ return nil, ErrWeaveCIDRNone
}
- return strings.Fields(e[11:]), true
+ return strings.Fields(e[11:]), nil
}
}
- return nil, !proxy.NoDefaultIPAM
+ if proxy.NoDefaultIPAM {
+ return nil, ErrNoDefaultIPAM
+ }
+ return nil, nil
}
diff --git a/proxy/proxy_intercept.go b/proxy/proxy_intercept.go
index 1b6ca46c..999ee87a 100644
--- a/proxy/proxy_intercept.go
+++ b/proxy/proxy_intercept.go
@@ -2,18 +2,32 @@ package proxy
import (
"bufio"
+ "bytes"
"errors"
"fmt"
"io"
- "io/ioutil"
"net"
"net/http"
"net/http/httputil"
+ "strconv"
+ "sync"
"github.com/fsouza/go-dockerclient"
. "github.com/weaveworks/weave/common"
)
+const (
+ maxLineLength = 4096 // assumed <= bufio.defaultBufSize
+ maxChunkSize = bufio.MaxScanTokenSize
+)
+
+var (
+ ErrChunkTooLong = errors.New("chunk too long")
+ ErrInvalidChunkLength = errors.New("invalid byte in chunk length")
+ ErrLineTooLong = errors.New("header line too long")
+ ErrMalformedChunkEncoding = errors.New("malformed chunked encoding")
+)
+
func (proxy *Proxy) Intercept(i interceptor, w http.ResponseWriter, r *http.Request) {
if err := i.InterceptRequest(r); err != nil {
switch err.(type) {
@@ -71,7 +85,7 @@ func (proxy *Proxy) Intercept(i interceptor, w http.ResponseWriter, r *http.Requ
}
func doRawStream(w http.ResponseWriter, resp *http.Response, client *httputil.ClientConn) {
- down, downBuf, up, rem, err := hijack(w, client)
+ down, downBuf, up, remaining, err := hijack(w, client)
if err != nil {
http.Error(w, "Unable to hijack connection for raw stream mode", http.StatusInternalServerError)
return
@@ -94,55 +108,108 @@ func doRawStream(w http.ResponseWriter, resp *http.Response, client *httputil.Cl
return
}
- upDone := make(chan struct{})
- downDone := make(chan struct{})
- go copyStream(down, io.MultiReader(rem, up), upDone)
- go copyStream(up, downBuf, downDone)
- <-upDone
- <-downDone
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go copyStream(down, io.MultiReader(remaining, up), &wg)
+ go copyStream(up, downBuf, &wg)
+ wg.Wait()
}
-func copyStream(dst io.Writer, src io.Reader, done chan struct{}) {
- defer close(done)
+type closeWriter interface {
+ CloseWrite() error
+}
+
+func copyStream(dst io.WriteCloser, src io.Reader, wg *sync.WaitGroup) {
+ defer wg.Done()
if _, err := io.Copy(dst, src); err != nil {
Log.Warning(err)
}
- if c, ok := dst.(interface {
- CloseWrite() error
- }); ok {
- if err := c.CloseWrite(); err != nil {
- Log.Warningf("Error closing connection: %s", err)
- }
+ var err error
+ if c, ok := dst.(closeWriter); ok {
+ err = c.CloseWrite()
+ } else {
+ err = dst.Close()
}
+ if err != nil {
+ Log.Warningf("Error closing connection: %s", err)
+ }
+}
+
+type writeFlusher interface {
+ io.Writer
+ http.Flusher
}
func doChunkedResponse(w http.ResponseWriter, resp *http.Response, client *httputil.ClientConn) {
- // Because we can't go back to request/response after we
- // hijack the connection, we need to close it and make the
- // client open another.
- w.Header().Add("Connection", "close")
+ wf, ok := w.(writeFlusher)
+ if !ok {
+ http.Error(w, "Error forwarding chunked response body: flush not available", http.StatusInternalServerError)
+ return
+ }
+
w.WriteHeader(resp.StatusCode)
- down, _, up, rem, err := hijack(w, client)
- if err != nil {
- http.Error(w, "Unable to hijack response stream for chunked response", http.StatusInternalServerError)
- return
- }
+ up, remaining := client.Hijack()
defer up.Close()
- defer down.Close()
- // Copy the chunked response body to downstream,
- // stopping at the end of the chunked section.
- rawResponseBody := io.MultiReader(rem, up)
- if _, err := io.Copy(ioutil.Discard, httputil.NewChunkedReader(io.TeeReader(rawResponseBody, down))); err != nil {
- http.Error(w, "Error copying chunked response body", http.StatusInternalServerError)
- return
+
+ var err error
+ chunks := bufio.NewScanner(io.MultiReader(remaining, up))
+ chunks.Split(splitChunks)
+ for chunks.Scan() && err == nil {
+ _, err = wf.Write(chunks.Bytes())
+ wf.Flush()
+ }
+ if err == nil {
+ err = chunks.Err()
+ }
+ if err != nil {
+ Log.Errorf("Error forwarding chunked response body: %s", err)
}
- resp.Trailer.Write(down)
- // a chunked response ends with a CRLF
- down.Write([]byte("\r\n"))
}
-func hijack(w http.ResponseWriter, client *httputil.ClientConn) (down net.Conn, downBuf *bufio.ReadWriter, up net.Conn, rem io.Reader, err error) {
+// a bufio.SplitFunc for http chunks
+func splitChunks(data []byte, atEOF bool) (advance int, token []byte, err error) {
+ if atEOF && len(data) == 0 {
+ return 0, nil, nil
+ }
+
+ i := bytes.IndexByte(data, '\n')
+ if i < 0 {
+ return 0, nil, nil
+ }
+ if i > maxLineLength {
+ return 0, nil, ErrLineTooLong
+ }
+
+ chunkSize64, err := strconv.ParseInt(
+ string(bytes.TrimRight(data[:i], " \t\r\n")),
+ 16,
+ 64,
+ )
+ switch {
+ case err != nil:
+ return 0, nil, ErrInvalidChunkLength
+ case chunkSize64 > maxChunkSize:
+ return 0, nil, ErrChunkTooLong
+ case chunkSize64 == 0:
+ return 0, nil, io.EOF
+ }
+ chunkSize := int(chunkSize64)
+
+ data = data[i+1:]
+
+ if len(data) < chunkSize+2 {
+ return 0, nil, nil
+ }
+
+ if data[chunkSize] != '\r' || data[chunkSize+1] != '\n' {
+ return 0, nil, ErrMalformedChunkEncoding
+ }
+
+ return i + chunkSize + 3, data[:chunkSize], nil
+}
+
+func hijack(w http.ResponseWriter, client *httputil.ClientConn) (down net.Conn, downBuf *bufio.ReadWriter, up net.Conn, remaining io.Reader, err error) {
hj, ok := w.(http.Hijacker)
if !ok {
err = errors.New("Unable to cast to Hijack")
@@ -152,6 +219,6 @@ func hijack(w http.ResponseWriter, client *httputil.ClientConn) (down net.Conn,
if err != nil {
return
}
- up, rem = client.Hijack()
+ up, remaining = client.Hijack()
return
}
diff --git a/proxy/proxy_intercept_test.go b/proxy/proxy_intercept_test.go
new file mode 100644
index 00000000..15f96230
--- /dev/null
+++ b/proxy/proxy_intercept_test.go
@@ -0,0 +1,136 @@
+// Based on net/http/internal
+package proxy
+
+import (
+ "bufio"
+ "bytes"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestChunk(t *testing.T) {
+ r := bufio.NewScanner(bytes.NewBufferString(
+ "7\r\nhello, \r\n17\r\nworld! 0123456789abcdef\r\n0\r\n",
+ ))
+ r.Split(splitChunks)
+
+ assertNextChunk(t, r, "hello, ")
+ assertNextChunk(t, r, "world! 0123456789abcdef")
+ assertNoMoreChunks(t, r)
+}
+
+func TestMalformedChunks(t *testing.T) {
+ r := bufio.NewScanner(bytes.NewBufferString(
+ "7\r\nhello, GARBAGEBYTES17\r\nworld! 0123456789abcdef\r\n0\r\n",
+ ))
+ r.Split(splitChunks)
+
+ // First chunk fails
+ {
+ if r.Scan() {
+ t.Errorf("Expected failure when reading chunks, but got one")
+ }
+ e := "malformed chunked encoding"
+ if r.Err() == nil || r.Err().Error() != e {
+ t.Errorf("chunk reader errored %q; want %q", r.Err(), e)
+ }
+ data := r.Bytes()
+ if len(data) != 0 {
+ t.Errorf("chunk should have been empty. got %q", data)
+ }
+ }
+
+ if r.Scan() {
+ t.Errorf("Expected no more chunks, but found too many")
+ }
+}
+
+func TestChunkTooLarge(t *testing.T) {
+ data := make([]byte, maxChunkSize+1)
+ r := bufio.NewScanner(bytes.NewBufferString(strings.Join(
+ []string{
+ strconv.FormatInt(maxChunkSize+1, 16), string(data),
+ "0", "",
+ },
+ "\r\n",
+ )))
+ r.Split(splitChunks)
+
+ // First chunk fails
+ {
+ if r.Scan() {
+ t.Errorf("Expected failure when reading chunks, but got one")
+ }
+ e := "chunk too long"
+ if r.Err() == nil || r.Err().Error() != e {
+ t.Errorf("chunk reader errored %q; want %q", r.Err(), e)
+ }
+ data := r.Bytes()
+ if len(data) != 0 {
+ t.Errorf("chunk should have been empty. got %q", data)
+ }
+ }
+
+ if r.Scan() {
+ t.Errorf("Expected no more chunks, but found too many")
+ }
+}
+
+func TestInvalidChunkSize(t *testing.T) {
+ r := bufio.NewScanner(bytes.NewBufferString(
+ "foobar\r\nhello, \r\n0\r\n",
+ ))
+ r.Split(splitChunks)
+
+ // First chunk fails
+ {
+ if r.Scan() {
+ t.Errorf("Expected failure when reading chunks, but got one")
+ }
+ e := "invalid byte in chunk length"
+ if r.Err() == nil || r.Err().Error() != e {
+ t.Errorf("chunk reader errored %q; want %q", r.Err(), e)
+ }
+ data := r.Bytes()
+ if len(data) != 0 {
+ t.Errorf("chunk should have been empty. got %q", data)
+ }
+ }
+
+ if r.Scan() {
+ t.Errorf("Expected no more chunks, but found too many")
+ }
+}
+
+func TestBytesAfterLastChunkAreIgnored(t *testing.T) {
+ r := bufio.NewScanner(bytes.NewBufferString(
+ "7\r\nhello, \r\n0\r\nGARBAGEBYTES",
+ ))
+ r.Split(splitChunks)
+
+ assertNextChunk(t, r, "hello, ")
+ assertNoMoreChunks(t, r)
+}
+
+func assertNextChunk(t *testing.T, r *bufio.Scanner, expected string) {
+ if !r.Scan() {
+ t.Fatalf("Expected chunk, but ran out early: %v", r.Err())
+ }
+ if r.Err() != nil {
+ t.Fatalf("Error reading chunk: %q", r.Err())
+ }
+ data := r.Bytes()
+ if string(data) != expected {
+ t.Errorf("chunk reader read %q; want %q", data, expected)
+ }
+}
+
+func assertNoMoreChunks(t *testing.T, r *bufio.Scanner) {
+ if r.Scan() {
+ t.Errorf("Expected no more chunks, but found too many")
+ }
+ if r.Err() != nil {
+ t.Errorf("Expected no error, but found: %q", r.Err())
+ }
+}
diff --git a/proxy/start_container_interceptor.go b/proxy/start_container_interceptor.go
index b7da0505..7353c07e 100644
--- a/proxy/start_container_interceptor.go
+++ b/proxy/start_container_interceptor.go
@@ -21,18 +21,20 @@ func (i *startContainerInterceptor) InterceptResponse(r *http.Response) error {
return err
}
- cidrs, ok := i.proxy.weaveCIDRsFromConfig(container.Config)
- if !ok {
- Log.Debug("No Weave CIDR, ignoring")
+ cidrs, err := i.proxy.weaveCIDRsFromConfig(container.Config, container.HostConfig)
+ if err != nil {
+ Log.Infof("Ignoring container %s due to %s", container.ID, err)
return nil
}
Log.Infof("Attaching container %s with WEAVE_CIDR \"%s\" to weave network", container.ID, strings.Join(cidrs, " "))
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})
diff --git a/router/connection.go b/router/connection.go
index 03c69a94..7eb7c5b0 100644
--- a/router/connection.go
+++ b/router/connection.go
@@ -2,9 +2,9 @@ package router
import (
"encoding/binary"
- "encoding/gob"
"fmt"
"net"
+ "strconv"
"sync"
"time"
@@ -118,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)
@@ -232,7 +233,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
})
@@ -283,12 +284,38 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch
defer close(finished)
conn.TCPConn.SetLinger(0)
-
- dec, err := conn.handshake(acceptNewPeer)
+ intro, err := ProtocolIntroParams{
+ MinVersion: conn.Router.ProtocolMinVersion,
+ MaxVersion: ProtocolMaxVersion,
+ Features: conn.makeFeatures(),
+ Conn: conn.TCPConn,
+ Password: conn.Router.Password,
+ Outbound: conn.outbound,
+ }.DoIntro()
if err != nil {
return
}
- conn.Log("completed handshake; using protocol version", conn.version)
+
+ conn.SessionKey = intro.SessionKey
+ conn.tcpSender = intro.Sender
+ conn.version = intro.Version
+
+ remote, err := conn.parseFeatures(intro.Features)
+ if err != nil {
+ return
+ }
+
+ if err = conn.registerRemote(remote, acceptNewPeer); err != nil {
+ return
+ }
+
+ 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]
@@ -303,7 +330,8 @@ func (conn *LocalConnection) run(actionChan <-chan ConnectionAction, finished ch
if err = conn.initHeartbeats(); err != nil {
return
}
- go conn.receiveTCP(dec)
+
+ go conn.receiveTCP(intro.Receiver)
err = conn.actorLoop(actionChan)
}
@@ -352,6 +380,83 @@ 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) MustHave(keys []string) error {
+ for _, key := range keys {
+ if _, ok := features[key]; !ok {
+ return fmt.Errorf("Field %s is missing", key)
+ }
+ }
+ return nil
+}
+
+func (features features) Get(key string) string {
+ return features[key]
+}
+
+func (conn *LocalConnection) parseFeatures(features features) (*Peer, error) {
+ 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
+ }
+
+ nickName := features.Get("NickName")
+
+ uid, err := ParsePeerUID(features.Get("UID"))
+ if err != nil {
+ return nil, err
+ }
+
+ remoteConnID, err := strconv.ParseUint(features.Get("ConnID"), 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)
+ } 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)
@@ -383,7 +488,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)
}
@@ -422,23 +527,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/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/consts.go b/router/consts.go
index 1909498c..6591236a 100644
--- a/router/consts.go
+++ b/router/consts.go
@@ -24,8 +24,8 @@ const (
PMTUVerifyTimeout = 10 * time.Millisecond // gets doubled with every attempt
MaxDuration = time.Duration(math.MaxInt64)
MaxMissedHeartbeats = 6
- HeaderTimeout = 10 * time.Second
HeartbeatTimeout = MaxMissedHeartbeats * SlowHeartbeat
+ MaxTCPMsgSize = 10 * 1024 * 1024
)
var (
diff --git a/router/crypto.go b/router/crypto.go
index b66d2b73..939157af 100644
--- a/router/crypto.go
+++ b/router/crypto.go
@@ -6,6 +6,7 @@ import (
"encoding/binary"
"encoding/gob"
"fmt"
+ "io"
"sync"
"github.com/andybalholm/go-bit"
@@ -31,7 +32,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 +72,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
@@ -337,28 +333,48 @@ type TCPSender interface {
Send([]byte) error
}
-type SimpleTCPSender struct {
+type GobTCPSender struct {
encoder *gob.Encoder
}
+type LengthPrefixTCPSender struct {
+ writer io.Writer
+}
+
type EncryptedTCPSender struct {
- SimpleTCPSender
sync.RWMutex
- state *TCPCryptoState
+ sender TCPSender
+ state *TCPCryptoState
}
-func NewSimpleTCPSender(encoder *gob.Encoder) *SimpleTCPSender {
- return &SimpleTCPSender{encoder: encoder}
+func NewGobTCPSender(encoder *gob.Encoder) *GobTCPSender {
+ return &GobTCPSender{encoder: encoder}
}
-func (sender *SimpleTCPSender) Send(msg []byte) error {
+func (sender *GobTCPSender) Send(msg []byte) error {
return sender.encoder.Encode(msg)
}
-func NewEncryptedTCPSender(encoder *gob.Encoder, sessionKey *[32]byte, outbound bool) *EncryptedTCPSender {
- return &EncryptedTCPSender{
- SimpleTCPSender: *NewSimpleTCPSender(encoder),
- state: NewTCPCryptoState(sessionKey, outbound)}
+func NewLengthPrefixTCPSender(writer io.Writer) *LengthPrefixTCPSender {
+ return &LengthPrefixTCPSender{writer: writer}
+}
+
+func (sender *LengthPrefixTCPSender) Send(msg []byte) error {
+ l := len(msg)
+ if l > MaxTCPMsgSize {
+ return fmt.Errorf("outgoing message exceeds maximum size: %d > %d", l, MaxTCPMsgSize)
+ }
+ // We copy the message so we can send it in a single Write
+ // operation, thus making this thread-safe without locking.
+ prefixedMsg := make([]byte, 4+l)
+ binary.BigEndian.PutUint32(prefixedMsg, uint32(l))
+ copy(prefixedMsg[4:], msg)
+ _, err := sender.writer.Write(prefixedMsg)
+ return err
+}
+
+func NewEncryptedTCPSender(sender TCPSender, sessionKey *[32]byte, outbound bool) *EncryptedTCPSender {
+ return &EncryptedTCPSender{sender: sender, state: NewTCPCryptoState(sessionKey, outbound)}
}
func (sender *EncryptedTCPSender) Send(msg []byte) error {
@@ -366,40 +382,69 @@ func (sender *EncryptedTCPSender) Send(msg []byte) error {
defer sender.Unlock()
encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey)
sender.state.advance()
- return sender.SimpleTCPSender.Send(encodedMsg)
+ return sender.sender.Send(encodedMsg)
}
type TCPReceiver interface {
- Decode([]byte) ([]byte, error)
+ Receive() ([]byte, error)
}
-type SimpleTCPReceiver struct {
+type GobTCPReceiver struct {
+ decoder *gob.Decoder
+}
+
+type LengthPrefixTCPReceiver struct {
+ reader io.Reader
}
type EncryptedTCPReceiver struct {
- SimpleTCPReceiver
- state *TCPCryptoState
+ receiver TCPReceiver
+ state *TCPCryptoState
}
-func NewSimpleTCPReceiver() *SimpleTCPReceiver {
- return &SimpleTCPReceiver{}
+func NewGobTCPReceiver(decoder *gob.Decoder) *GobTCPReceiver {
+ return &GobTCPReceiver{decoder: decoder}
}
-func (receiver *SimpleTCPReceiver) Decode(msg []byte) ([]byte, error) {
- return msg, nil
+func (receiver *GobTCPReceiver) Receive() ([]byte, error) {
+ var msg []byte
+ err := receiver.decoder.Decode(&msg)
+ return msg, err
}
-func NewEncryptedTCPReceiver(sessionKey *[32]byte, outbound bool) *EncryptedTCPReceiver {
- return &EncryptedTCPReceiver{
- SimpleTCPReceiver: *NewSimpleTCPReceiver(),
- state: NewTCPCryptoState(sessionKey, !outbound)}
+func NewLengthPrefixTCPReceiver(reader io.Reader) *LengthPrefixTCPReceiver {
+ return &LengthPrefixTCPReceiver{reader: reader}
}
-func (receiver *EncryptedTCPReceiver) Decode(msg []byte) ([]byte, error) {
+func (receiver *LengthPrefixTCPReceiver) Receive() ([]byte, error) {
+ lenPrefix := make([]byte, 4)
+ if _, err := io.ReadFull(receiver.reader, lenPrefix); err != nil {
+ return nil, err
+ }
+ l := binary.BigEndian.Uint32(lenPrefix)
+ if l > MaxTCPMsgSize {
+ return nil, fmt.Errorf("incoming message exceeds maximum size: %d > %d", l, MaxTCPMsgSize)
+ }
+ msg := make([]byte, l)
+ _, err := io.ReadFull(receiver.reader, msg)
+ return msg, err
+}
+
+func NewEncryptedTCPReceiver(receiver TCPReceiver, sessionKey *[32]byte, outbound bool) *EncryptedTCPReceiver {
+ return &EncryptedTCPReceiver{receiver: receiver, state: NewTCPCryptoState(sessionKey, !outbound)}
+}
+
+func (receiver *EncryptedTCPReceiver) Receive() ([]byte, error) {
+ msg, err := receiver.receiver.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/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/gossip.go b/router/gossip.go
index a3af241b..45db0e83 100644
--- a/router/gossip.go
+++ b/router/gossip.go
@@ -21,7 +21,7 @@ type Gossiper interface {
OnGossipUnicast(sender PeerName, msg []byte) error
// merge received data into state and return a representation of
// the received data, for further propagation
- OnGossipBroadcast(update []byte) (GossipData, error)
+ OnGossipBroadcast(sender PeerName, update []byte) (GossipData, error)
// return state of everything we know; gets called periodically
Gossip() GossipData
// merge received data into state and return "everything new I've
diff --git a/router/gossip_channel.go b/router/gossip_channel.go
index 795573f8..bb70bc20 100644
--- a/router/gossip_channel.go
+++ b/router/gossip_channel.go
@@ -79,7 +79,7 @@ func (c *GossipChannel) deliverBroadcast(srcName PeerName, _ []byte, dec *gob.De
if err := dec.Decode(&payload); err != nil {
return err
}
- data, err := c.gossiper.OnGossipBroadcast(payload)
+ data, err := c.gossiper.OnGossipBroadcast(srcName, payload)
if err != nil || data == nil {
return err
}
diff --git a/router/gossip_test.go b/router/gossip_test.go
index c6936a09..fce0391a 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)
@@ -212,7 +212,7 @@ func (g *testGossiper) OnGossipUnicast(sender PeerName, msg []byte) error {
return nil
}
-func (g *testGossiper) OnGossipBroadcast(update []byte) (GossipData, error) {
+func (g *testGossiper) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) {
g.Lock()
defer g.Unlock()
for _, v := range update {
diff --git a/router/handshake.go b/router/handshake.go
deleted file mode 100644
index d90423e7..00000000
--- a/router/handshake.go
+++ /dev/null
@@ -1,167 +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(acceptNewPeer bool) (*gob.Decoder, 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, 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, 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, err
- }
-
- name, err := PeerNameFromString(nameStr)
- if err != nil {
- return nil, err
- }
- if !acceptNewPeer {
- if _, found := conn.Router.Peers.Fetch(name); !found {
- 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
- }
- remoteConnID, err := strconv.ParseUint(remoteConnIDStr, 10, 64)
- if err != nil {
- return nil, err
- }
- conn.uid = localConnID ^ remoteConnID
-
- remotePublicStr, rpErr := fv.Value("PublicKey")
- if usingPassword {
- if rpErr != nil {
- return nil, rpErr
- }
- remotePublicSlice, rpErr := hex.DecodeString(remotePublicStr)
- if rpErr != nil {
- return 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)
- 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)
- conn.Decryptor = NewNonDecryptor()
- }
-
- return dec, 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) {
- 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
-}
-
-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/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/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/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..82b7d3d8 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 {
@@ -39,20 +39,28 @@ type ConnectionSummary struct {
Established bool
}
-func NewPeers(ourself *LocalPeer, onGC func(*Peer)) *Peers {
- return &Peers{
- ourself: ourself,
- table: make(map[PeerName]*Peer),
- onGC: onGC}
+func NewPeers(ourself *LocalPeer) *Peers {
+ return &Peers{ourself: ourself, table: make(map[PeerName]*Peer)}
+}
+
+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 {
peers.Lock()
defer peers.Unlock()
if existingPeer, found := peers.table[peer.Name]; found {
- if existingPeer.UID != peer.UID {
- return nil
- }
existingPeer.localRefCount++
return existingPeer
}
@@ -61,11 +69,20 @@ 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) 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) {
@@ -106,13 +123,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 {
@@ -146,8 +164,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 {
@@ -186,7 +206,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)
}
}
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/protocol.go b/router/protocol.go
index bb2ebfa0..8b5252d1 100644
--- a/router/protocol.go
+++ b/router/protocol.go
@@ -2,58 +2,329 @@ package router
import (
"bytes"
+ "encoding/gob"
+ "encoding/hex"
"fmt"
"io"
+ "time"
)
const (
- Protocol = "weave"
- ProtocolVersion byte = 1
- ProtocolMinVersion byte = ProtocolVersion
+ Protocol = "weave"
+ ProtocolMinVersion = 1
+ ProtocolMaxVersion = 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 {
+ MinVersion byte
+ MaxVersion byte
+ 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) {
+ 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(); 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() (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, params.MinVersion, params.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 params.MinVersion > minVersion {
+ minVersion = params.MinVersion
}
- maxVersion := ProtocolVersion
- if remoteVersion < maxVersion {
- maxVersion = remoteVersion
+
+ theirMaxVersion := header[len(ProtocolBytes)+1]
+ maxVersion := theirMaxVersion
+ if maxVersion > params.MaxVersion {
+ maxVersion = params.MaxVersion
}
+
if minVersion > maxVersion {
- return 0, fmt.Errorf("remote version [%d,%d] is incompatible with our version [%d,%d]",
- remoteMinVersion, remoteVersion, ProtocolMinVersion, ProtocolVersion)
+ return 0, fmt.Errorf("remote version range [%d,%d] is incompatible with ours [%d,%d]",
+ theirMinVersion, theirMaxVersion,
+ params.MinVersion, params.MaxVersion)
}
+
+ if err := <-writeDone; err != nil {
+ return 0, err
+ }
+
return maxVersion, 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
+ }
+
+ res.Sender = NewGobTCPSender(enc)
+ res.Receiver = NewGobTCPReceiver(dec)
+
+ if pubKey == nil {
+ if _, present := res.Features["PublicKey"]; present {
+ return ErrExpectedNoCrypto
+ }
+ } else {
+ remotePubKeyStr, ok := res.Features["PublicKey"]
+ if !ok {
+ return ErrExpectedCrypto
+ }
+
+ remotePubKey, err := hex.DecodeString(remotePubKeyStr)
+ if err != nil {
+ return err
+ }
+
+ res.setupCrypto(params, 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 length-prefixed messages, which are 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.Sender = NewLengthPrefixTCPSender(params.Conn)
+ res.Receiver = NewLengthPrefixTCPReceiver(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.Sender = NewLengthPrefixTCPSender(params.Conn)
+ res.Receiver = NewLengthPrefixTCPReceiver(params.Conn)
+ res.setupCrypto(params, 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) setupCrypto(params ProtocolIntroParams, remotePubKey []byte, privKey *[32]byte) {
+ var remotePubKeyArr [32]byte
+ copy(remotePubKeyArr[:], remotePubKey)
+ res.SessionKey = FormSessionKey(&remotePubKeyArr, privKey, params.Password)
+ res.Sender = NewEncryptedTCPSender(res.Sender, res.SessionKey, params.Outbound)
+ res.Receiver = NewEncryptedTCPReceiver(res.Receiver, res.SessionKey, params.Outbound)
+}
+
type ProtocolTag byte
const (
diff --git a/router/protocol_test.go b/router/protocol_test.go
new file mode 100644
index 00000000..1a56079a
--- /dev/null
+++ b/router/protocol_test.go
@@ -0,0 +1,96 @@
+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, params ProtocolIntroParams) <-chan ProtocolIntroResults {
+ ch := make(chan ProtocolIntroResults, 1)
+ go func() {
+ res, err := params.DoIntro()
+ 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, ProtocolIntroParams{
+ MinVersion: ProtocolMinVersion,
+ MaxVersion: aver,
+ Features: map[string]string{"Name": "A"},
+ Conn: aconn,
+ Outbound: true,
+ 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
+
+ // 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"))))
+}
diff --git a/router/router.go b/router/router.go
index 00f53588..16f05dd6 100644
--- a/router/router.go
+++ b/router/router.go
@@ -14,27 +14,29 @@ import (
)
const (
- macMaxAge = 10 * time.Minute // [1]
- tcpAcceptDelay = 1 * time.Millisecond // [2]
+ 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] 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.
+// [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, *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 {
@@ -48,6 +50,7 @@ type Router struct {
gossipChannels GossipChannels
TopologyGossip Gossip
UDPListener *net.UDPConn
+ acceptLimiter *TokenBucket
}
type PacketSource interface {
@@ -74,11 +77,13 @@ 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)
router.TopologyGossip = router.NewGossip("topology", router)
+ router.acceptLimiter = NewTokenBucket(acceptMaxTokens, acceptTokenDelay)
return router
}
@@ -205,7 +210,7 @@ func (router *Router) listenTCP(localPort int) {
continue
}
router.acceptTCP(tcpConn)
- time.Sleep(tcpAcceptDelay)
+ router.acceptLimiter.Wait()
}
}()
}
@@ -215,7 +220,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)
}
@@ -281,12 +286,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 +337,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)
@@ -387,7 +389,7 @@ func (router *Router) OnGossipUnicast(sender PeerName, msg []byte) error {
return fmt.Errorf("unexpected topology gossip unicast: %v", msg)
}
-func (router *Router) OnGossipBroadcast(update []byte) (GossipData, error) {
+func (router *Router) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) {
origUpdate, _, err := router.applyTopologyUpdate(update)
if err != nil || len(origUpdate) == 0 {
return nil, err
diff --git a/router/surrogate_gossiper.go b/router/surrogate_gossiper.go
index ea7f443d..04059eb7 100644
--- a/router/surrogate_gossiper.go
+++ b/router/surrogate_gossiper.go
@@ -24,7 +24,7 @@ func (*SurrogateGossiper) OnGossipUnicast(sender PeerName, msg []byte) error {
return nil
}
-func (*SurrogateGossiper) OnGossipBroadcast(update []byte) (GossipData, error) {
+func (*SurrogateGossiper) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) {
return NewSurrogateGossipData(update), nil
}
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)
+}
diff --git a/site/_layouts/default.html b/site/_layouts/default.html
index 8d655afa..7b1ebf61 100644
--- a/site/_layouts/default.html
+++ b/site/_layouts/default.html
@@ -19,7 +19,7 @@
-
+
diff --git a/site/assets/custom.css b/site/assets/custom.css
index 34a32cdd..e175ca54 100644
--- a/site/assets/custom.css
+++ b/site/assets/custom.css
@@ -5489,6 +5489,40 @@ p {
pre {
padding: 30px;
}
+/* making this more look like a note, as opposed to a quote */
+blockquote {
+ padding: 15px;
+ margin-bottom: 17pt;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+ color: #8a6d3b;
+ font-size: inherit;
+}
+blockquote h4 {
+ margin-top: 0;
+ color: inherit;
+}
+blockquote .alert-link {
+ font-weight: bold;
+}
+blockquote > p,
+blockquote > ul {
+ margin-bottom: 0;
+}
+blockquote > p + p {
+ margin-top: 5px;
+}
+blockquote hr {
+ border-top-color: #f7e1b5;
+}
+blockquote .alert-link {
+ color: #66512c;
+}
+blockquote p {
+ margin-top: 0;
+}
.navbar {
padding-top: 15px;
}
diff --git a/site/boot2docker.md b/site/boot2docker.md
index 9835cb48..a3819b66 100644
--- a/site/boot2docker.md
+++ b/site/boot2docker.md
@@ -7,23 +7,28 @@ layout: default
If you are running Docker inside the Boot2Docker VM, e.g. because you
are on a Mac, then the following changes are required to the weave
-instructions:
+instructions. First, we need to get Boot2Docker running:
+
+ host1$ boot2docker init
+ host1$ boot2docker start
+ host1$ eval "$(boot2docker shellinit)"
Assuming you have fetched the 'weave' script via curl or similar, and
-it is in the current directory, transfer it to the Boot2Docker VM and
-make it executable like this:
+it is in the current directory, launch weave on the Boot2Docker VM and
+configure our shell. Because Boot2Docker uses TLS, we have to pass a
+few extra options when launching the docker API proxy:
- host1$ boot2docker ssh "cat > weave" < weave
- host1$ boot2docker ssh "chmod a+x weave"
+ host1$ ./weave launch-router
+ host1$ ./weave launch-proxy --tls \
+ --tlscacert /var/lib/boot2docker/tls/ca.pem \
+ --tlscert /var/lib/boot2docker/tls/server.pem \
+ --tlskey /var/lib/boot2docker/tls/serverkey.pem
+ host1$ eval "$(./weave env)"
-Then, if we were trying to create the same containers as in the first
-example above, the 'launch' command would be run like this:
+Now, we can use the docker command to run our containers, as shown in
+the [proxy documentation](proxy.html):
- host1$ boot2docker ssh "sudo ./weave launch"
-
-and the 'run' command like this:
-
- host1$ C=$(boot2docker ssh "sudo ./weave run 10.2.1.1/24 -t -i ubuntu")
+ host1$ docker run -it ubuntu
For more information about how to access services running in
Boot2Docker from the host or other machines (i.e. outside of the weave
diff --git a/site/features.md b/site/features.md
index 56d771d7..cc9d6126 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.
@@ -142,10 +142,10 @@ 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$ eval $(weave proxy-env)
- host2$ weave launch -iprange 10.2.0.0/16 -ipsubnet 10.2.1.0/24 $HOST1
- host2$ eval $(weave proxy-env)
+ 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 --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
it to allocate from 10.2.1.0/24 within that if no specific subnet is
@@ -251,19 +251,24 @@ 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 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
@@ -291,13 +296,9 @@ returned. So now
host2$ ping 10.2.1.132
will work, and, more interestingly, we can ping our `a1` application
-container, which is residing on `$HOST1`, after finding its IP
-address:
+container, which is residing on `$HOST1`:
- host1$ weave ps a1
- a1 1e:88:d7:5b:77:68 10.2.1.2/24
-
- host2$ ping 10.2.1.2
+ host2$ ping $(weave dns-lookup a1)
Multiple subnet addresses can be exposed or hidden with a single
invocation:
@@ -332,11 +333,8 @@ explained [above](#host-network-integration), i.e.
Then we add a NAT rule to route from the outside world to the
destination container service.
- host1$ weave ps a1
- a1 1e:88:d7:5b:77:68 10.2.1.2/24
-
host2$ iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 2211 \
- -j DNAT --to-destination 10.2.1.2:4422
+ -j DNAT --to-destination $(weave dns-lookup a1):4422
Here we are assuming that the "outside world" is connecting to `$HOST2`
via 'eth0'. We want TCP traffic to port 2211 on the external IPs to be
@@ -496,9 +494,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/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
diff --git a/site/ipam.md b/site/ipam.md
index 295bbf93..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.
@@ -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.
@@ -87,13 +87,21 @@ 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
-range. This can be overridden with the `-iprange` option, e.g.
+By default, weave will allocate IP addresses in the 10.32.0.0/12
+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.
+> 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
@@ -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 d133f28c..212d2817 100644
--- a/site/proxy.md
+++ b/site/proxy.md
@@ -30,32 +30,39 @@ 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
modify the default behaviour you will have to use the latter.
-By default, the proxy listens on /var/run/weave.sock and port 12375, on
-all network interfaces. This can be adjusted with the `-H` argument, e.g.
+By default, the proxy decides where to listen based on how the
+launching client connects to docker. If the launching client connected
+over a unix socket, the proxy will listen on /var/run/weave.sock. If
+the launching client connected over TCP, the proxy will listen on port
+12375, on all network interfaces. This can be adjusted with the `-H`
+argument, e.g.
host1$ weave launch-proxy -H tcp://127.0.0.1:9999
-Multiple -H arguments can be specified. If you are working with a remote
-docker daemon, then any firewalls inbetween need to be configured to permit
-access to the proxy port.
+When launching the proxy via TLS, `-H` and/or [TLS options](#tls) are
+required.
+
+Multiple `-H` arguments can be specified. If you are working with a
+remote docker daemon, then any firewalls inbetween need to be
+configured to permit access to the proxy port.
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
@@ -103,7 +110,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.
@@ -130,6 +137,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.
+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
+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-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
+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
@@ -140,8 +176,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 +193,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,
@@ -167,7 +203,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/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/site/troubleshooting.md b/site/troubleshooting.md
index 8c05a828..30da1e07 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
@@ -95,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/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 2efee67e..5e9d261e 100644
--- a/site/weavedns.md
+++ b/site/weavedns.md
@@ -16,6 +16,7 @@ hosts.
* [Load balancing](#load-balancing)
* [Fault resilience](#fault-resilience)
* [Adding and removing extra DNS entries](#add-remove)
+* [Resolve weaveDNS entries from host](#resolve-weavedns-entries-from-host)
* [Hot-swapping service containers](#hot-swapping)
* [Retaining DNS entries when containers stop](#retain-stopped)
* [Configuring a custom TTL](#ttl)
@@ -26,25 +27,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 proxy-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
-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 +52,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,28 +98,28 @@ $ 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...
```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
-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.
...
```
@@ -152,9 +130,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,23 @@ $ 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.
+
+## Resolve weaveDNS entries from host
+
+You can resolve entries from any host running weaveDNS with `weave
+dns-lookup`:
+
+ host1$ weave dns-lookup pingme
+ 10.40.0.1
## Hot-swapping service containers
@@ -187,33 +174,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 +215,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 +239,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.160.0.1]/OBS:1
-74a5510a91ad: ubuntu.weave.local.[10.160.0.2]
-weave:remote: pingme.weave.local.[10.128.0.2]/TTL:30
+1d836dea2c56: foo.weave.local. [10.2.2.1]
...
````
@@ -284,17 +253,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 +272,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/100_cross_hosts_test.sh b/test/100_cross_hosts_test.sh
index 81be0c6a..a2f77068 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
@@ -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
diff --git a/test/110_encryption_test.sh b/test/110_encryption_test.sh
index 967e0003..5f46a463 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
diff --git a/test/120_discovery_test.sh b/test/120_discovery_test.sh
new file mode 100755
index 00000000..447b3721
--- /dev/null
+++ b/test/120_discovery_test.sh
@@ -0,0 +1,41 @@
+#! /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 --ipalloc-range="" $HOST1
+ weave_on $HOST3 launch-router $1 $HOST2
+}
+
+start_suite "Peer discovery, multi-hop routing and gossip forwarding"
+
+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
+
+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
+# 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'"
+
+end_suite
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..aaa3aaf9 100755
--- a/test/140_weave_local_test.sh
+++ b/test/140_weave_local_test.sh
@@ -2,17 +2,23 @@
. ./config.sh
+weave_local_on() {
+ host=$1
+ shift 1
+ run_on $host sudo COVERAGE=$COVERAGE weave --local $@
+}
+
start_suite "Run weave with --local"
-run_on $HOST1 sudo weave --local reset
+weave_local_on $HOST1 reset
-run_on $HOST1 sudo weave --local launch -iprange 10.2.5.0/24
+weave_local_on $HOST1 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
+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 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
diff --git a/test/150_connect_forget_test.sh b/test/150_connect_forget_test.sh
index 984e70e7..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_on $HOST1 stop-router"
+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'"
diff --git a/test/160_claim_test.sh b/test/160_claim_test.sh
new file mode 100755
index 00000000..c550f3b7
--- /dev/null
+++ b/test/160_claim_test.sh
@@ -0,0 +1,40 @@
+#! /bin/bash
+
+. ./config.sh
+
+start_suite "Claiming addresses"
+
+weave_on $HOST1 launch-router
+weave_on $HOST2 launch-router $HOST1
+
+start_container $HOST1 --name=c1
+start_container $HOST2 --name=c2
+C1=$(container_ip $HOST1 c1)
+assert_raises "exec_on $HOST2 c2 $PING $C1"
+
+stop_router_on $HOST1
+stop_router_on $HOST2
+
+# Start hosts in reverse order so c1's address has to be claimed from host2
+weave_on $HOST2 launch-router
+weave_on $HOST1 launch-router $HOST2
+
+# Start another container on host2, so if it hasn't relinquished c1's
+# address it would give that out as the first available.
+start_container $HOST2 --name=c3
+C3=$(container_ip $HOST2 c3)
+assert_raises "[ $C3 != $C1 ]"
+
+assert_raises "exec_on $HOST1 c1 $PING $C3"
+
+stop_router_on $HOST1
+stop_router_on $HOST2
+
+# Now make host1 attempt to claim from host2, when host2 is stopped
+weave_on $HOST2 launch-router
+# Introduce host3 to remember the IPAM CRDT when we stop host2
+weave_on $HOST3 launch-router $HOST2
+stop_router_on $HOST2
+weave_on $HOST1 launch-router --log-level=debug $HOST3
+
+end_suite
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..82e1ac6a
--- /dev/null
+++ b/test/210_dns_cross_hosts_test.sh
@@ -0,0 +1,76 @@
+#! /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"
+
+for host in $HOSTS; do
+ weave_on $host launch --ipalloc-range $UNIVERSE $HOSTS
+done
+
+# Basic test
+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
+
+# # 2 containers on each host, all with the same names
+# FOO_IPS=
+# for host in $HOSTS; do
+# CID=$(proxy docker_on $host run -dti --name=foo $SMALL_IMAGE /bin/sh)
+# FOO_IPS="$FOO_IPS $(container_ip $host foo)"
+
+# CID=$(proxy docker_on $host run -dti --name=bar $SMALL_IMAGE /bin/sh)
+# BAR_IPS="$BAR_IPS $(container_ip $host bar)"
+# done
+
+# start_container_with_dns $HOST1 --name=baz
+# assert_dns_record $HOST1 baz foo.weave.local $FOO_IPS
+# assert_dns_record $HOST1 baz bar.weave.local $BAR_IPS
+
+# # now stop and start the containers a bunch of times; this tests
+# # gossip dns tombstone behaviour
+# for i in $(seq 5); do
+# for host in $HOSTS; do
+# proxy docker_on $host kill foo 1>/dev/null
+# proxy docker_on $host kill bar 1>/dev/null
+# done
+
+# assert_no_dns_record $HOST1 baz foo.weave.local
+# assert_no_dns_record $HOST1 baz bar.weave.local
+
+# FOO_IPS=
+# BAR_IPS=
+# for host in $HOSTS; do
+# proxy docker_on $host start foo 1>/dev/null
+# proxy docker_on $host start bar 1>/dev/null
+
+# FOO_IPS="$FOO_IPS $(container_ip $host foo)"
+# BAR_IPS="$BAR_IPS $(container_ip $host bar)"
+# done
+
+# assert_dns_record $HOST1 baz foo.weave.local $FOO_IPS
+# assert_dns_record $HOST1 baz bar.weave.local $BAR_IPS
+# done
+
+# 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 fb47f334..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 -iprange $UNIVERSE
-weave_on $HOST2 launch-router -iprange $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..0283d73f 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
+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
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/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_lookup_test.sh b/test/250_dns_lookup_test.sh
new file mode 100755
index 00000000..aa7c283b
--- /dev/null
+++ b/test/250_dns_lookup_test.sh
@@ -0,0 +1,16 @@
+#! /bin/bash
+
+. ./config.sh
+
+C1=10.2.0.78
+
+start_suite "Cross host dns-lookup"
+
+weave_on $HOST1 launch
+weave_on $HOST2 launch $HOST1
+
+start_container $HOST1 $C1/24 --name c1
+
+assert "weave_on $HOST2 dns-lookup c1" $C1
+
+end_suite
diff --git a/test/255_dns_restart_test.sh b/test/255_dns_restart_test.sh
new file mode 100755
index 00000000..9c8a0e54
--- /dev/null
+++ b/test/255_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/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/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 0767e8d7..1d897732 100755
--- a/test/290_dns_fallback_test.sh
+++ b/test/290_dns_fallback_test.sh
@@ -2,12 +2,9 @@
. ./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
+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_test.sh b/test/295_dns_large_response_test.sh
new file mode 100755
index 00000000..daf7e82e
--- /dev/null
+++ b/test/295_dns_large_response_test.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 884d7c74..d3d09661 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
@@ -73,8 +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
-launch_dns_on $HOST1 10.254.254.254/24
+weave_on $HOST1 launch-router --ipalloc-range 10.2.3.0/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/610_proxy_wait_for_weave_test.sh b/test/610_proxy_wait_for_weave_test.sh
index acb748d5..b995c040 100755
--- a/test/610_proxy_wait_for_weave_test.sh
+++ b/test/610_proxy_wait_for_weave_test.sh
@@ -19,4 +19,14 @@ 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"
+
+# Check exec works on containers without weavewait
+docker_on $HOST1 run -dit --name c3 $SMALL_IMAGE /bin/sh
+assert_raises "proxy docker_on $HOST1 exec c3 true"
+
+# Check we can't modify weavewait
+assert_raises "proxy docker_on $HOST1 run -e 'WEAVE_CIDR=10.2.1.2/24' $BASE_IMAGE touch /w/w" 1
+
end_suite
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/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/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/test/660_proxy_ipam_test.sh b/test/660_proxy_ipam_test.sh
index 72a4ceed..24c37679 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
@@ -26,13 +26,21 @@ start $HOST1 --name=auto
start $HOST1 --name=none -e WEAVE_CIDR=none
start $HOST2 --name=zero -e WEAVE_CIDR=
start $HOST2 --name=no-default
+start $HOST1 --name=bridge --net=bridge
+start $HOST1 --name=host --net=host
+start $HOST1 --name=other --net=container:auto
AUTO=$(container_ip $HOST1 auto)
ZERO=$(container_ip $HOST2 zero)
+BRIDGE=$(container_ip $HOST1 bridge)
+OTHER=$(container_ip $HOST1 other)
assert_raises "proxy exec_on $HOST1 auto $PING $ZERO"
assert_raises "proxy exec_on $HOST2 zero $PING $AUTO"
+assert_raises "proxy exec_on $HOST2 zero $PING $BRIDGE"
+assert_raises "proxy exec_on $HOST2 zero $PING $OTHER"
assert_no_ethwe $HOST1 none
assert_no_ethwe $HOST2 no-default
+assert_no_ethwe $HOST1 host
end_suite
diff --git a/test/680_proxy_hostname_derivation_test.sh b/test/680_proxy_hostname_derivation_test.sh
new file mode 100755
index 00000000..2b6a7819
--- /dev/null
+++ b/test/680_proxy_hostname_derivation_test.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-router
+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/test/690_proxy_autoconfig_test.sh b/test/690_proxy_autoconfig_test.sh
new file mode 100755
index 00000000..a59d3fc0
--- /dev/null
+++ b/test/690_proxy_autoconfig_test.sh
@@ -0,0 +1,36 @@
+#! /bin/bash
+
+. ./config.sh
+
+start_suite "Boot the proxy should only listen on client's interface"
+
+# Booting it over unix socket listens on unix socket
+run_on $HOST1 sudo weave launch-proxy
+assert_raises "run_on $HOST1 sudo docker -H unix:///var/run/weave.sock ps"
+assert_raises "proxy docker_on $HOST1 ps" 1
+weave_on $HOST1 stop-proxy
+
+# Booting it over tcp listens on tcp
+weave_on $HOST1 launch-proxy
+assert_raises "run_on $HOST1 sudo docker -H unix:///var/run/weave.sock ps" 1
+assert_raises "proxy docker_on $HOST1 ps"
+weave_on $HOST1 stop-proxy
+
+# Booting it over tcp (no prefix) listens on tcp
+DOCKER_CLIENT_ARGS="-H $HOST1:$DOCKER_PORT" $WEAVE launch-proxy
+assert_raises "run_on $HOST1 sudo docker -H unix:///var/run/weave.sock ps" 1
+assert_raises "proxy docker_on $HOST1 ps"
+weave_on $HOST1 stop-proxy
+
+
+# Booting it over tls errors
+assert_raises "DOCKER_CLIENT_ARGS='--tls' weave_on $HOST1 launch-proxy" 1
+assert_raises "DOCKER_CERT_PATH='./tls' DOCKER_TLS_VERIFY=1 weave_on $HOST1 launch-proxy" 1
+
+# Booting it with a specific -H overrides defaults
+weave_on $HOST1 launch-proxy -H unix:///var/run/weave2.sock
+assert_raises "run_on $HOST1 sudo docker -H unix:///var/run/weave2.sock ps"
+assert_raises "proxy docker_on $HOST1 ps" 1
+weave_on $HOST1 stop-proxy
+
+end_suite
diff --git a/test/README.md b/test/README.md
index 9d7cbdc7..4e18f175 100644
--- a/test/README.md
+++ b/test/README.md
@@ -6,13 +6,21 @@ 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 .
## 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
diff --git a/test/Vagrantfile b/test/Vagrantfile
index 57ef1097..750f4c7f 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
@@ -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
@@ -26,12 +26,8 @@ def configure_docker(host, hostname, ip)
host.vm.provision :shell, :inline => "echo deb https://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
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 => "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"
- cleanup(host.vm)
+ tweak_docker_daemon host.vm
+ cleanup host.vm
end
def configure_resolv_conf(host)
@@ -45,6 +41,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
diff --git a/test/config.sh b/test/config.sh
index 71a4afa3..1d5871cb 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"
@@ -42,16 +43,12 @@ CHECK_ETHWE_UP="grep ^1$ /sys/class/net/ethwe/carrier"
DOCKER_PORT=2375
-WEAVEDNS_ARGS="--no-cache"
-[ -n "$DEBUG" ] && WEAVEDNS_ARGS="$WEAVEDNS_ARGS --debug"
-
-
upload_executable() {
host=$1
file=$2
- prefix=${3:-/usr/local/bin/}
- suffix=$(basename "$file")
- target="$prefix$suffix"
+ target=${3:-/usr/local/bin/$(basename "$file")}
+ dir=$(dirname "$target")
+ run_on $host "[ -e '$dir' ] || sudo mkdir -p '$dir'"
[ -z "$DEBUG" ] || greyly echo "Uploading to $host: $file -> $target" >&2
<"$file" remote $host $SSH $host sh -c "cat | sudo tee $target >/dev/null"
run_on $host "sudo chmod a+x $target"
@@ -60,16 +57,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() {
@@ -113,6 +110,18 @@ weave_on() {
DOCKER_HOST=tcp://$host:$DOCKER_PORT $WEAVE "$@"
}
+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
+}
+
exec_on() {
host=$1
container=$2
@@ -120,12 +129,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
@@ -154,7 +157,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'"
@@ -175,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
@@ -186,7 +190,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)
@@ -196,6 +200,18 @@ start_suite() {
end_suite() {
whitely assert_end
+ for host in $HOSTS; do
+ stop_router_on $host
+ done
+}
+
+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
+ mv cover.router.prof $(mktemp -u ./coverage/integration.XXXXXXXX) || true
}
WEAVE=$DIR/../weave
diff --git a/test/gce.sh b/test/gce.sh
index 02738928..dd1cb63b 100755
--- a/test/gce.sh
+++ b/test/gce.sh
@@ -5,7 +5,7 @@
# ./gce.sh destroy - tear down the VMs
# ./gce.sh make_template - make a fresh VM template; update TEMPLATE_NAME first!
-set -ex
+set -e
KEY_FILE=/tmp/gce_private_key.json
SSH_KEY_FILE=$HOME/.ssh/gce_ssh_key
@@ -13,14 +13,14 @@ 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"
fi
# Setup authentication
-gcloud auth activate-service-account --key-file $KEY_FILE
+gcloud auth activate-service-account --key-file $KEY_FILE 1>/dev/null
gcloud config set project $PROJECT
function vm_names {
@@ -120,9 +120,9 @@ function hosts {
hosts="$hostname $hosts"
args="--add-host=$hostname:$(internal_ip $name) $args"
done
- export SSH=ssh
- export HOSTS="$hosts"
- export WEAVE_DOCKER_ARGS="$args"
+ echo export SSH=ssh
+ echo export HOSTS=\"$hosts\"
+ echo export WEAVE_DOCKER_ARGS=\"$args\"
}
case "$1" in
diff --git a/test/gen_coverage_reports.sh b/test/gen_coverage_reports.sh
new file mode 100755
index 00000000..567cb0f3
--- /dev/null
+++ b/test/gen_coverage_reports.sh
@@ -0,0 +1,16 @@
+#!/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
+ scp node$i:/home/ubuntu/src/github.com/weaveworks/weave/test/coverage/* ./coverage/ || true
+ done
+fi
+
+$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
+tar czf coverage.tar.gz ./coverage
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/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
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/setup.sh b/test/setup.sh
index e5e9edad..0410af57 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 1>/dev/null 2>&1 || true
run_on $HOST mkdir -p bin
upload_executable $HOST ../bin/docker-ns
upload_executable $HOST ../weave
diff --git a/test/units.sh b/test/units.sh
new file mode 100755
index 00000000..5b461326
--- /dev/null
+++ b/test/units.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+set -e
+
+DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+SLOW=${SLOW-}
+GO_TEST_ARGS="-tags netgo -cpu 4 -timeout 8m"
+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
+
+fail=0
+
+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 get -t -tags netgo $dir
+
+ GO_TEST_ARGS_RUN="$GO_TEST_ARGS"
+ if [ -n "$SLOW" ]; then
+ COVERPKGS=$(go list -f '{{join .Deps "\n"}}' $dir | grep "weaveworks" | paste -s -d,)
+ output=$(mktemp $coverdir/unit.XXXXXXXXXX)
+ GO_TEST_ARGS_RUN="$GO_TEST_ARGS -coverprofile=$output -coverpkg=$COVERPKGS"
+ 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 [ -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
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/gossip/mocks.go b/testing/gossip/mocks.go
new file mode 100644
index 00000000..95f7d976
--- /dev/null
+++ b/testing/gossip/mocks.go
@@ -0,0 +1,147 @@
+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 {
+ sender router.PeerName
+ 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) Stop() {
+ for peer := range grouter.gossipChans {
+ grouter.RemovePeer(peer)
+ }
+}
+
+func (grouter *TestRouter) gossipBroadcast(sender router.PeerName, update router.GossipData) error {
+ for _, gossipChan := range grouter.gossipChans {
+ select {
+ case gossipChan <- broadcastMessage{sender: sender, 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(sender router.PeerName, 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() {
+ // TODO: this should call OnGossipBroadcast, and we should implement
+ // 'trickle' gossip correctly in this mock. But no one depends on this
+ // difference for testing right now, so we abuse the interface here.
+ diff, err := gossiper.OnGossip(msg)
+ if err != nil {
+ panic(fmt.Sprintf("Error doing gossip broadcast: %s", err))
+ }
+ if diff == nil {
+ continue
+ }
+ // Sanity check - reconsuming the diff should yield nil
+ for _, diffMsg := range diff.Encode() {
+ if nextDiff, err := gossiper.OnGossip(diffMsg); err != nil {
+ panic(fmt.Sprintf("Error doing gossip broadcast: %s", err))
+ } else if nextDiff != nil {
+ panic(fmt.Sprintf("Breach of gossip interface: %v != nil", nextDiff))
+ }
+ }
+ }
+ }
+ case <-gossipTimer:
+ grouter.gossipBroadcast(sender, gossiper.Gossip())
+ }
+ }
+}
+
+func (grouter *TestRouter) Connect(sender router.PeerName, gossiper router.Gossiper) router.Gossip {
+ gossipChan := make(chan interface{}, 100)
+
+ go grouter.run(sender, 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(client.sender, update)
+}
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/vagrant-common.rb b/vagrant-common.rb
index 7cf8540b..8b5557a1 100644
--- a/vagrant-common.rb
+++ b/vagrant-common.rb
@@ -45,9 +45,10 @@ end
def tweak_docker_daemon(vm)
vm.provision :shell, :inline => <