Merge remote-tracking branch 'origin/create-mesh'

Closes #1659.
This commit is contained in:
Adam Harrison committed 2015-11-09 17:16:35 +00:00
commit f039221ec9
47 files changed
+304 -254

No files matched your search

+1 -1
View File
@@ -70,7 +70,7 @@ $(NETCHECK_EXE): common/*.go common/*/*.go net/*.go
go build $(BUILD_FLAGS) -o $@ ./$(@D) go build $(BUILD_FLAGS) -o $@ ./$(@D)
$(NETGO_CHECK) $(NETGO_CHECK)
$(WEAVER_EXE): router/*.go ipam/*.go ipam/*/*.go nameserver/*.go prog/weaver/*.go $(WEAVER_EXE): router/*.go mesh/*.go ipam/*.go ipam/*/*.go nameserver/*.go prog/weaver/*.go
$(WEAVEPROXY_EXE): proxy/*.go prog/weaveproxy/main.go $(WEAVEPROXY_EXE): proxy/*.go prog/weaveproxy/main.go
$(NETCHECK_EXE): prog/netcheck/netcheck.go $(NETCHECK_EXE): prog/netcheck/netcheck.go
+37 -37
View File
@@ -11,8 +11,8 @@ import (
"github.com/weaveworks/weave/ipam/paxos" "github.com/weaveworks/weave/ipam/paxos"
"github.com/weaveworks/weave/ipam/ring" "github.com/weaveworks/weave/ipam/ring"
"github.com/weaveworks/weave/ipam/space" "github.com/weaveworks/weave/ipam/space"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
// Kinds of message we can unicast to other peers // Kinds of message we can unicast to other peers
@@ -43,31 +43,31 @@ type operation interface {
// are used around data structures. // are used around data structures.
type Allocator struct { type Allocator struct {
actionChan chan<- func() actionChan chan<- func()
ourName router.PeerName ourName mesh.PeerName
universe address.Range // superset of all ranges universe address.Range // superset of all ranges
ring *ring.Ring // information on ranges owned by all peers ring *ring.Ring // information on ranges owned by all peers
space space.Space // more detail on ranges owned by us space space.Space // more detail on ranges owned by us
owned map[string][]address.Address // who owns what addresses, indexed by container-ID owned map[string][]address.Address // who owns what addresses, indexed by container-ID
nicknames map[router.PeerName]string // so we can map nicknames for rmpeer nicknames map[mesh.PeerName]string // so we can map nicknames for rmpeer
pendingAllocates []operation // held until we get some free space pendingAllocates []operation // held until we get some free space
pendingClaims []operation // held until we know who owns the space pendingClaims []operation // held until we know who owns the space
gossip router.Gossip // our link to the outside world for sending messages gossip mesh.Gossip // our link to the outside world for sending messages
paxos *paxos.Node paxos *paxos.Node
paxosTicker *time.Ticker paxosTicker *time.Ticker
shuttingDown bool // to avoid doing any requests while trying to shut down shuttingDown bool // to avoid doing any requests while trying to shut down
isKnownPeer func(router.PeerName) bool isKnownPeer func(mesh.PeerName) bool
now func() time.Time now func() time.Time
} }
// NewAllocator creates and initialises a new Allocator // NewAllocator creates and initialises a new Allocator
func NewAllocator(ourName router.PeerName, ourUID router.PeerUID, ourNickname string, universe address.Range, quorum uint, isKnownPeer func(name router.PeerName) bool) *Allocator { func NewAllocator(ourName mesh.PeerName, ourUID mesh.PeerUID, ourNickname string, universe address.Range, quorum uint, isKnownPeer func(name mesh.PeerName) bool) *Allocator {
return &Allocator{ return &Allocator{
ourName: ourName, ourName: ourName,
universe: universe, universe: universe,
ring: ring.New(universe.Start, universe.End, ourName), ring: ring.New(universe.Start, universe.End, ourName),
owned: make(map[string][]address.Address), owned: make(map[string][]address.Address),
paxos: paxos.NewNode(ourName, ourUID, quorum), paxos: paxos.NewNode(ourName, ourUID, quorum),
nicknames: map[router.PeerName]string{ourName: ourNickname}, nicknames: map[mesh.PeerName]string{ourName: ourNickname},
isKnownPeer: isKnownPeer, isKnownPeer: isKnownPeer,
now: time.Now, now: time.Now,
} }
@@ -75,7 +75,7 @@ func NewAllocator(ourName router.PeerName, ourUID router.PeerUID, ourNickname st
// Start runs the allocator goroutine // Start runs the allocator goroutine
func (alloc *Allocator) Start() { func (alloc *Allocator) Start() {
actionChan := make(chan func(), router.ChannelSize) actionChan := make(chan func(), mesh.ChannelSize)
alloc.actionChan = actionChan alloc.actionChan = actionChan
go alloc.actorLoop(actionChan) go alloc.actorLoop(actionChan)
} }
@@ -165,7 +165,7 @@ func (alloc *Allocator) tryPendingOps() {
} }
} }
func (alloc *Allocator) spaceRequestDenied(sender router.PeerName, r address.Range) { func (alloc *Allocator) spaceRequestDenied(sender mesh.PeerName, r address.Range) {
for i := 0; i < len(alloc.pendingClaims); { for i := 0; i < len(alloc.pendingClaims); {
claim := alloc.pendingClaims[i].(*claim) claim := alloc.pendingClaims[i].(*claim)
if r.Contains(claim.addr) { if r.Contains(claim.addr) {
@@ -276,27 +276,27 @@ func (alloc *Allocator) Free(ident string, addrToFree address.Address) error {
return <-errChan return <-errChan
} }
func (alloc *Allocator) pickPeerFromNicknames(isValid func(router.PeerName) bool) router.PeerName { func (alloc *Allocator) pickPeerFromNicknames(isValid func(mesh.PeerName) bool) mesh.PeerName {
for name := range alloc.nicknames { for name := range alloc.nicknames {
if name != alloc.ourName && isValid(name) { if name != alloc.ourName && isValid(name) {
return name return name
} }
} }
return router.UnknownPeerName return mesh.UnknownPeerName
} }
func (alloc *Allocator) pickPeerForTransfer() router.PeerName { func (alloc *Allocator) pickPeerForTransfer() mesh.PeerName {
// first try alive peers that actively participate in IPAM (i.e. have entries) // first try alive peers that actively participate in IPAM (i.e. have entries)
if heir := alloc.ring.PickPeerForTransfer(alloc.isKnownPeer); heir != router.UnknownPeerName { if heir := alloc.ring.PickPeerForTransfer(alloc.isKnownPeer); heir != mesh.UnknownPeerName {
return heir return heir
} }
// next try alive peers that have IPAM enabled but have no entries // next try alive peers that have IPAM enabled but have no entries
if heir := alloc.pickPeerFromNicknames(alloc.isKnownPeer); heir != router.UnknownPeerName { if heir := alloc.pickPeerFromNicknames(alloc.isKnownPeer); heir != mesh.UnknownPeerName {
return heir return heir
} }
// next try disappeared peers that still have entries // next try disappeared peers that still have entries
t := func(router.PeerName) bool { return true } t := func(mesh.PeerName) bool { return true }
if heir := alloc.ring.PickPeerForTransfer(t); heir != router.UnknownPeerName { if heir := alloc.ring.PickPeerForTransfer(t); heir != mesh.UnknownPeerName {
return heir return heir
} }
// finally, disappeared peers that that passively participated in IPAM // finally, disappeared peers that that passively participated in IPAM
@@ -311,7 +311,7 @@ func (alloc *Allocator) Shutdown() {
alloc.shuttingDown = true alloc.shuttingDown = true
alloc.cancelOps(&alloc.pendingClaims) alloc.cancelOps(&alloc.pendingClaims)
alloc.cancelOps(&alloc.pendingAllocates) alloc.cancelOps(&alloc.pendingAllocates)
if heir := alloc.pickPeerForTransfer(); heir != router.UnknownPeerName { if heir := alloc.pickPeerForTransfer(); heir != mesh.UnknownPeerName {
alloc.ring.Transfer(alloc.ourName, heir) alloc.ring.Transfer(alloc.ourName, heir)
alloc.space.Clear() alloc.space.Clear()
alloc.gossip.GossipBroadcast(alloc.Gossip()) alloc.gossip.GossipBroadcast(alloc.Gossip())
@@ -350,14 +350,14 @@ func (alloc *Allocator) AdminTakeoverRanges(peerNameOrNickname string) error {
// call into the router for this because we are interested in peers // call into the router for this because we are interested in peers
// that have gone away but are still in the ring, which is why we // that have gone away but are still in the ring, which is why we
// maintain our own nicknames map. // maintain our own nicknames map.
func (alloc *Allocator) lookupPeername(name string) (router.PeerName, error) { func (alloc *Allocator) lookupPeername(name string) (mesh.PeerName, error) {
for peername, nickname := range alloc.nicknames { for peername, nickname := range alloc.nicknames {
if nickname == name { if nickname == name {
return peername, nil return peername, nil
} }
} }
return router.PeerNameFromString(name) return mesh.PeerNameFromString(name)
} }
// Restrict the peers in "nicknames" to those in the ring plus peers known to the router // Restrict the peers in "nicknames" to those in the ring plus peers known to the router
@@ -370,7 +370,7 @@ func (alloc *Allocator) pruneNicknames() {
} }
} }
func (alloc *Allocator) annotatePeernames(names []router.PeerName) []string { func (alloc *Allocator) annotatePeernames(names []mesh.PeerName) []string {
var res []string var res []string
for _, name := range names { for _, name := range names {
if nickname, found := alloc.nicknames[name]; found { if nickname, found := alloc.nicknames[name]; found {
@@ -388,7 +388,7 @@ func decodeRange(msg []byte) (r address.Range, err error) {
} }
// OnGossipUnicast (Sync) // OnGossipUnicast (Sync)
func (alloc *Allocator) OnGossipUnicast(sender router.PeerName, msg []byte) error { func (alloc *Allocator) OnGossipUnicast(sender mesh.PeerName, msg []byte) error {
alloc.debugln("OnGossipUnicast from", sender, ": ", len(msg), "bytes") alloc.debugln("OnGossipUnicast from", sender, ": ", len(msg), "bytes")
resultChan := make(chan error) resultChan := make(chan error)
alloc.actionChan <- func() { alloc.actionChan <- func() {
@@ -414,7 +414,7 @@ func (alloc *Allocator) OnGossipUnicast(sender router.PeerName, msg []byte) erro
} }
// OnGossipBroadcast (Sync) // OnGossipBroadcast (Sync)
func (alloc *Allocator) OnGossipBroadcast(sender router.PeerName, msg []byte) (router.GossipData, error) { func (alloc *Allocator) OnGossipBroadcast(sender mesh.PeerName, msg []byte) (mesh.GossipData, error) {
alloc.debugln("OnGossipBroadcast from", sender, ":", len(msg), "bytes") alloc.debugln("OnGossipBroadcast from", sender, ":", len(msg), "bytes")
resultChan := make(chan error) resultChan := make(chan error)
alloc.actionChan <- func() { alloc.actionChan <- func() {
@@ -427,7 +427,7 @@ type gossipState struct {
// We send a timstamp along with the information to be // We send a timstamp along with the information to be
// gossipped in order to detect skewed clocks // gossipped in order to detect skewed clocks
Now int64 Now int64
Nicknames map[router.PeerName]string Nicknames map[mesh.PeerName]string
Paxos paxos.GossipState Paxos paxos.GossipState
Ring *ring.Ring Ring *ring.Ring
@@ -463,11 +463,11 @@ func (alloc *Allocator) Encode() []byte {
} }
// OnGossip (Sync) // OnGossip (Sync)
func (alloc *Allocator) OnGossip(msg []byte) (router.GossipData, error) { func (alloc *Allocator) OnGossip(msg []byte) (mesh.GossipData, error) {
alloc.debugln("Allocator.OnGossip:", len(msg), "bytes") alloc.debugln("Allocator.OnGossip:", len(msg), "bytes")
resultChan := make(chan error) resultChan := make(chan error)
alloc.actionChan <- func() { alloc.actionChan <- func() {
resultChan <- alloc.update(router.UnknownPeerName, msg) resultChan <- alloc.update(mesh.UnknownPeerName, msg)
} }
return nil, <-resultChan // for now, we never propagate updates. TBD return nil, <-resultChan // for now, we never propagate updates. TBD
} }
@@ -478,7 +478,7 @@ type ipamGossipData struct {
alloc *Allocator alloc *Allocator
} }
func (d *ipamGossipData) Merge(other router.GossipData) { func (d *ipamGossipData) Merge(other mesh.GossipData) {
// no-op // no-op
} }
@@ -488,12 +488,12 @@ func (d *ipamGossipData) Encode() [][]byte {
// Gossip returns a GossipData implementation, which in this case always // Gossip returns a GossipData implementation, which in this case always
// returns the latest ring state (and does nothing on merge) // returns the latest ring state (and does nothing on merge)
func (alloc *Allocator) Gossip() router.GossipData { func (alloc *Allocator) Gossip() mesh.GossipData {
return &ipamGossipData{alloc} return &ipamGossipData{alloc}
} }
// SetInterfaces gives the allocator two interfaces for talking to the outside world // SetInterfaces gives the allocator two interfaces for talking to the outside world
func (alloc *Allocator) SetInterfaces(gossip router.Gossip) { func (alloc *Allocator) SetInterfaces(gossip mesh.Gossip) {
alloc.gossip = gossip alloc.gossip = gossip
} }
@@ -540,7 +540,7 @@ func (alloc *Allocator) establishRing() {
} }
} }
func (alloc *Allocator) createRing(peers []router.PeerName) { func (alloc *Allocator) createRing(peers []mesh.PeerName) {
alloc.debugln("Paxos consensus:", peers) alloc.debugln("Paxos consensus:", peers)
alloc.ring.ClaimForPeers(normalizeConsensus(peers)) alloc.ring.ClaimForPeers(normalizeConsensus(peers))
alloc.gossip.GossipBroadcast(alloc.Gossip()) alloc.gossip.GossipBroadcast(alloc.Gossip())
@@ -563,7 +563,7 @@ func (alloc *Allocator) ringUpdated() {
} }
// For compatibility with sort.Interface // For compatibility with sort.Interface
type peerNames []router.PeerName type peerNames []mesh.PeerName
func (a peerNames) Len() int { return len(a) } func (a peerNames) Len() int { return len(a) }
func (a peerNames) Less(i, j int) bool { return a[i] < a[j] } func (a peerNames) Less(i, j int) bool { return a[i] < a[j] }
@@ -572,7 +572,7 @@ func (a peerNames) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// When we get a consensus from Paxos, the peer names are not in a // When we get a consensus from Paxos, the peer names are not in a
// defined order and may contain duplicates. This function sorts them // defined order and may contain duplicates. This function sorts them
// and de-dupes. // and de-dupes.
func normalizeConsensus(consensus []router.PeerName) []router.PeerName { func normalizeConsensus(consensus []mesh.PeerName) []mesh.PeerName {
if len(consensus) == 0 { if len(consensus) == 0 {
return nil return nil
} }
@@ -607,22 +607,22 @@ func encodeRange(r address.Range) []byte {
return buf.Bytes() return buf.Bytes()
} }
func (alloc *Allocator) sendSpaceRequest(dest router.PeerName, r address.Range) error { func (alloc *Allocator) sendSpaceRequest(dest mesh.PeerName, r address.Range) error {
msg := append([]byte{msgSpaceRequest}, encodeRange(r)...) msg := append([]byte{msgSpaceRequest}, encodeRange(r)...)
return alloc.gossip.GossipUnicast(dest, msg) return alloc.gossip.GossipUnicast(dest, msg)
} }
func (alloc *Allocator) sendSpaceRequestDenied(dest router.PeerName, r address.Range) error { func (alloc *Allocator) sendSpaceRequestDenied(dest mesh.PeerName, r address.Range) error {
msg := append([]byte{msgSpaceRequestDenied}, encodeRange(r)...) msg := append([]byte{msgSpaceRequestDenied}, encodeRange(r)...)
return alloc.gossip.GossipUnicast(dest, msg) return alloc.gossip.GossipUnicast(dest, msg)
} }
func (alloc *Allocator) sendRingUpdate(dest router.PeerName) { func (alloc *Allocator) sendRingUpdate(dest mesh.PeerName) {
msg := append([]byte{msgRingUpdate}, alloc.encode()...) msg := append([]byte{msgRingUpdate}, alloc.encode()...)
alloc.gossip.GossipUnicast(dest, msg) alloc.gossip.GossipUnicast(dest, msg)
} }
func (alloc *Allocator) update(sender router.PeerName, msg []byte) error { func (alloc *Allocator) update(sender mesh.PeerName, msg []byte) error {
reader := bytes.NewReader(msg) reader := bytes.NewReader(msg)
decoder := gob.NewDecoder(reader) decoder := gob.NewDecoder(reader)
var data gossipState var data gossipState
@@ -674,7 +674,7 @@ func (alloc *Allocator) update(sender router.PeerName, msg []byte) error {
alloc.createRing(cons.Value) alloc.createRing(cons.Value)
} }
} }
} else if sender != router.UnknownPeerName { } else if sender != mesh.UnknownPeerName {
// Sender is trying to initialize a ring, but we have one // Sender is trying to initialize a ring, but we have one
// already - send it straight back // already - send it straight back
alloc.sendRingUpdate(sender) alloc.sendRingUpdate(sender)
@@ -684,7 +684,7 @@ func (alloc *Allocator) update(sender router.PeerName, msg []byte) error {
return nil return nil
} }
func (alloc *Allocator) donateSpace(r address.Range, to router.PeerName) { func (alloc *Allocator) donateSpace(r address.Range, to mesh.PeerName) {
// No matter what we do, we'll send a unicast gossip // No matter what we do, we'll send a unicast gossip
// of our ring back to tha chap who asked for space. // of our ring back to tha chap who asked for space.
// This serves to both tell him of any space we might // This serves to both tell him of any space we might
+3 -3
View File
@@ -4,8 +4,8 @@ import (
"fmt" "fmt"
"github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
type claim struct { type claim struct {
@@ -43,7 +43,7 @@ func (c *claim) Try(alloc *Allocator) bool {
switch owner := alloc.ring.Owner(c.addr); owner { switch owner := alloc.ring.Owner(c.addr); owner {
case alloc.ourName: case alloc.ourName:
// success // success
case router.UnknownPeerName: case mesh.UnknownPeerName:
// If our ring doesn't know, it must be empty. // If our ring doesn't know, it must be empty.
if c.noErrorOnUnknown { if c.noErrorOnUnknown {
alloc.infof("Claim %s for %s: address allocator still initializing; will try later.", c.addr, c.ident) alloc.infof("Claim %s for %s: address allocator still initializing; will try later.", c.addr, c.ident)
@@ -86,7 +86,7 @@ func (c *claim) Try(alloc *Allocator) bool {
return true return true
} }
func (c *claim) deniedBy(alloc *Allocator, owner router.PeerName) { func (c *claim) deniedBy(alloc *Allocator, owner mesh.PeerName) {
name, found := alloc.nicknames[owner] name, found := alloc.nicknames[owner]
if found { if found {
name = " (" + name + ")" name = " (" + name + ")"
+6 -6
View File
@@ -1,7 +1,7 @@
package paxos package paxos
import ( import (
"github.com/weaveworks/weave/router" "github.com/weaveworks/weave/mesh"
) )
// The node identifier. The use of the UID here is important: Paxos // The node identifier. The use of the UID here is important: Paxos
@@ -9,8 +9,8 @@ import (
// node does not restart and lose its Paxos state but claim to have // node does not restart and lose its Paxos state but claim to have
// the same ID. // the same ID.
type NodeID struct { type NodeID struct {
Name router.PeerName Name mesh.PeerName
UID router.PeerUID UID mesh.PeerUID
} }
// note all fields exported in structs so we can Gob them // note all fields exported in structs so we can Gob them
@@ -39,7 +39,7 @@ func (a ProposalID) valid() bool {
} }
// For seeding IPAM, the value we want consensus on is a set of peer names // For seeding IPAM, the value we want consensus on is a set of peer names
type Value []router.PeerName type Value []mesh.PeerName
// An AcceptedValue is a Value plus the proposal which originated that // An AcceptedValue is a Value plus the proposal which originated that
// Value. The origin is not essential, but makes comparing // Value. The origin is not essential, but makes comparing
@@ -72,7 +72,7 @@ type Node struct {
knows GossipState knows GossipState
} }
func NewNode(name router.PeerName, uid router.PeerUID, quorum uint) *Node { func NewNode(name mesh.PeerName, uid mesh.PeerUID, quorum uint) *Node {
return &Node{ return &Node{
id: NodeID{name, uid}, id: NodeID{name, uid},
quorum: quorum, quorum: quorum,
@@ -223,7 +223,7 @@ func (node *Node) Think() bool {
// about. This is not necessarily all peer names, but it is at least // about. This is not necessarily all peer names, but it is at least
// a quorum, and so good enough for seeding the ring. // a quorum, and so good enough for seeding the ring.
func (node *Node) pickValue() Value { func (node *Node) pickValue() Value {
val := make([]router.PeerName, len(node.knows)) val := make([]mesh.PeerName, len(node.knows))
i := 0 i := 0
for id := range node.knows { for id := range node.knows {
val[i] = id.Name val[i] = id.Name
+5 -5
View File
@@ -6,7 +6,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/weaveworks/weave/router" "github.com/weaveworks/weave/mesh"
) )
type TestNode struct { type TestNode struct {
@@ -97,8 +97,8 @@ func makeRandomModel(params *TestParams, r *rand.Rand, t *testing.T) *Model {
} }
for i := range m.nodes { for i := range m.nodes {
m.nodes[i].Node = NewNode(router.PeerName(i/2+1), m.nodes[i].Node = NewNode(mesh.PeerName(i/2+1),
router.PeerUID(r.Int63()), m.quorum) mesh.PeerUID(r.Int63()), m.quorum)
m.nodes[i].Propose() m.nodes[i].Propose()
} }
@@ -172,8 +172,8 @@ func (m *Model) isolateNode(node *TestNode) {
// Restart a node // Restart a node
func (m *Model) restart(node *TestNode) { func (m *Model) restart(node *TestNode) {
node.Node = NewNode(router.PeerName(m.nextID), node.Node = NewNode(mesh.PeerName(m.nextID),
router.PeerUID(m.r.Int63()), m.quorum) mesh.PeerUID(m.r.Int63()), m.quorum)
m.nextID++ m.nextID++
node.Propose() node.Propose()
+3 -3
View File
@@ -4,14 +4,14 @@ import (
"sort" "sort"
"github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
// Entry represents entries around the ring // Entry represents entries around the ring
type entry struct { type entry struct {
Token address.Address // The start of this range Token address.Address // The start of this range
Peer router.PeerName // Who owns this range Peer mesh.PeerName // Who owns this range
Version uint32 // Version of this range Version uint32 // Version of this range
Free address.Offset // Number of free IPs in this range Free address.Offset // Number of free IPs in this range
} }
@@ -21,7 +21,7 @@ func (e *entry) Equal(e2 *entry) bool {
e.Version == e2.Version e.Version == e2.Version
} }
func (e *entry) update(peername router.PeerName, free address.Offset) { func (e *entry) update(peername mesh.PeerName, free address.Offset) {
e.Peer = peername e.Peer = peername
e.Version++ e.Version++
e.Free = free e.Free = free
+22 -22
View File
@@ -13,16 +13,16 @@ import (
"time" "time"
"github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
// Ring represents the ring itself // Ring represents the ring itself
type Ring struct { type Ring struct {
Start, End address.Address // [min, max) tokens in this ring. Due to wrapping, min == max (effectively) Start, End address.Address // [min, max) tokens in this ring. Due to wrapping, min == max (effectively)
Peer router.PeerName // name of peer owning this ring instance Peer mesh.PeerName // name of peer owning this ring instance
Entries entries // list of entries sorted by token Entries entries // list of entries sorted by token
Seeds []router.PeerName // peers with which the ring was seeded Seeds []mesh.PeerName // peers with which the ring was seeded
} }
func (r *Ring) assertInvariants() { func (r *Ring) assertInvariants() {
@@ -84,7 +84,7 @@ func (r *Ring) checkInvariants() error {
} }
// New creates an empty ring belonging to peer. // New creates an empty ring belonging to peer.
func New(start, end address.Address, peer router.PeerName) *Ring { func New(start, end address.Address, peer mesh.PeerName) *Ring {
common.Assert(start < end) common.Assert(start < end)
ring := &Ring{Start: start, End: end, Peer: peer, Entries: make([]*entry, 0)} ring := &Ring{Start: start, End: end, Peer: peer, Entries: make([]*entry, 0)}
@@ -111,7 +111,7 @@ func (r *Ring) distance(start, end address.Address) address.Offset {
// Preconditions: // Preconditions:
// - start < end // - start < end
// - [start, end) must be owned by the calling peer // - [start, end) must be owned by the calling peer
func (r *Ring) GrantRangeToHost(start, end address.Address, peer router.PeerName) { func (r *Ring) GrantRangeToHost(start, end address.Address, peer mesh.PeerName) {
//fmt.Printf("%s GrantRangeToHost [%v,%v) -> %s\n", r.Peer, start, end, peer) //fmt.Printf("%s GrantRangeToHost [%v,%v) -> %s\n", r.Peer, start, end, peer)
r.assertInvariants() r.assertInvariants()
@@ -210,7 +210,7 @@ func (r *Ring) Merge(gossip Ring) error {
addToResult := func(e entry) { result = append(result, &e) } addToResult := func(e entry) { result = append(result, &e) }
var mine, theirs *entry var mine, theirs *entry
var previousOwner *router.PeerName var previousOwner *mesh.PeerName
// i is index into r.Entries; j is index into gossip.Entries // i is index into r.Entries; j is index into gossip.Entries
var i, j int var i, j int
for i < len(r.Entries) && j < len(gossip.Entries) { for i < len(r.Entries) && j < len(gossip.Entries) {
@@ -318,7 +318,7 @@ func (r *Ring) OwnedRanges() (result []address.Range) {
// ClaimForPeers claims the entire ring for the array of peers passed // ClaimForPeers claims the entire ring for the array of peers passed
// in. Only works for empty rings. // in. Only works for empty rings.
func (r *Ring) ClaimForPeers(peers []router.PeerName) { func (r *Ring) ClaimForPeers(peers []mesh.PeerName) {
common.Assert(r.Empty()) common.Assert(r.Empty())
defer r.assertInvariants() defer r.assertInvariants()
defer r.updateExportedVariables() defer r.updateExportedVariables()
@@ -350,7 +350,7 @@ func (r *Ring) ClaimForPeers(peers []router.PeerName) {
r.Seeds = peers r.Seeds = peers
} }
func (r *Ring) FprintWithNicknames(w io.Writer, m map[router.PeerName]string) { func (r *Ring) FprintWithNicknames(w io.Writer, m map[mesh.PeerName]string) {
for _, entry := range r.Entries { for _, entry := range r.Entries {
nickname, found := m[entry.Peer] nickname, found := m[entry.Peer]
if found { if found {
@@ -365,7 +365,7 @@ func (r *Ring) FprintWithNicknames(w io.Writer, m map[router.PeerName]string) {
func (r *Ring) String() string { func (r *Ring) String() string {
var buffer bytes.Buffer var buffer bytes.Buffer
fmt.Fprintf(&buffer, "Ring [%s, %s)", r.Start, r.End) fmt.Fprintf(&buffer, "Ring [%s, %s)", r.Start, r.End)
r.FprintWithNicknames(&buffer, make(map[router.PeerName]string)) r.FprintWithNicknames(&buffer, make(map[mesh.PeerName]string))
return buffer.String() return buffer.String()
} }
@@ -415,7 +415,7 @@ func (r *Ring) ReportFree(freespace map[address.Address]address.Offset) {
type weightedPeer struct { type weightedPeer struct {
weight float64 weight float64
peername router.PeerName peername mesh.PeerName
} }
type weightedPeers []weightedPeer type weightedPeers []weightedPeer
@@ -426,10 +426,10 @@ func (ws weightedPeers) Swap(i, j int) { ws[i], ws[j] = ws[j], ws[i] }
// ChoosePeersToAskForSpace returns all peers we can ask for space in // ChoosePeersToAskForSpace returns all peers we can ask for space in
// the range [start, end), in weighted-random order. Assumes start<end. // the range [start, end), in weighted-random order. Assumes start<end.
func (r *Ring) ChoosePeersToAskForSpace(start, end address.Address) []router.PeerName { func (r *Ring) ChoosePeersToAskForSpace(start, end address.Address) []mesh.PeerName {
var ( var (
sum address.Offset sum address.Offset
totalSpacePerPeer = make(map[router.PeerName]address.Offset) // Compute total free space per peer totalSpacePerPeer = make(map[mesh.PeerName]address.Offset) // Compute total free space per peer
) )
// iterate through tokens // iterate through tokens
@@ -463,25 +463,25 @@ func (r *Ring) ChoosePeersToAskForSpace(start, end address.Address) []router.Pee
ws = append(ws, weightedPeer{weight: float64(space) * rand.Float64(), peername: peername}) ws = append(ws, weightedPeer{weight: float64(space) * rand.Float64(), peername: peername})
} }
sort.Sort(ws) sort.Sort(ws)
result := make([]router.PeerName, len(ws)) result := make([]mesh.PeerName, len(ws))
for i, wp := range ws { for i, wp := range ws {
result[i] = wp.peername result[i] = wp.peername
} }
return result return result
} }
func (r *Ring) PickPeerForTransfer(isValid func(router.PeerName) bool) router.PeerName { func (r *Ring) PickPeerForTransfer(isValid func(mesh.PeerName) bool) mesh.PeerName {
for _, entry := range r.Entries { for _, entry := range r.Entries {
if entry.Peer != r.Peer && isValid(entry.Peer) { if entry.Peer != r.Peer && isValid(entry.Peer) {
return entry.Peer return entry.Peer
} }
} }
return router.UnknownPeerName return mesh.UnknownPeerName
} }
// Transfer will mark all entries associated with 'from' peer as owned by 'to' peer // Transfer will mark all entries associated with 'from' peer as owned by 'to' peer
// and return ranges indicating the new space we picked up // and return ranges indicating the new space we picked up
func (r *Ring) Transfer(from, to router.PeerName) ([]address.Range, error) { func (r *Ring) Transfer(from, to mesh.PeerName) ([]address.Range, error) {
r.assertInvariants() r.assertInvariants()
defer r.assertInvariants() defer r.assertInvariants()
defer r.updateExportedVariables() defer r.updateExportedVariables()
@@ -511,13 +511,13 @@ func (r *Ring) Contains(addr address.Address) bool {
} }
// Owner returns the peername which owns the range containing addr // Owner returns the peername which owns the range containing addr
func (r *Ring) Owner(token address.Address) router.PeerName { func (r *Ring) Owner(token address.Address) mesh.PeerName {
common.Assert(r.Start <= token && token < r.End) common.Assert(r.Start <= token && token < r.End)
r.assertInvariants() r.assertInvariants()
// There can be no owners on an empty ring // There can be no owners on an empty ring
if r.Empty() { if r.Empty() {
return router.UnknownPeerName return mesh.UnknownPeerName
} }
// Look for the right-most entry, less than or equal to token // Look for the right-most entry, less than or equal to token
@@ -530,8 +530,8 @@ func (r *Ring) Owner(token address.Address) router.PeerName {
} }
// Get the set of PeerNames mentioned in the ring // Get the set of PeerNames mentioned in the ring
func (r *Ring) PeerNames() map[router.PeerName]struct{} { func (r *Ring) PeerNames() map[mesh.PeerName]struct{} {
res := make(map[router.PeerName]struct{}) res := make(map[mesh.PeerName]struct{})
for _, entry := range r.Entries { for _, entry := range r.Entries {
res[entry.Peer] = struct{}{} res[entry.Peer] = struct{}{}
+13 -13
View File
@@ -9,14 +9,14 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
var ( var (
peer1name, _ = router.PeerNameFromString("01:00:00:00:02:00") peer1name, _ = mesh.PeerNameFromString("01:00:00:00:02:00")
peer2name, _ = router.PeerNameFromString("02:00:00:00:02:00") peer2name, _ = mesh.PeerNameFromString("02:00:00:00:02:00")
peer3name, _ = router.PeerNameFromString("03:00:00:00:02:00") peer3name, _ = mesh.PeerNameFromString("03:00:00:00:02:00")
start, end = ParseIP("10.0.0.0"), ParseIP("10.0.0.255") start, end = ParseIP("10.0.0.0"), ParseIP("10.0.0.255")
dot10, dot245 = ParseIP("10.0.0.10"), ParseIP("10.0.0.245") dot10, dot245 = ParseIP("10.0.0.10"), ParseIP("10.0.0.245")
@@ -351,7 +351,7 @@ func TestGossip(t *testing.T) {
assertRing(ring2, []*entry{{Token: start, Peer: peer1name, Free: 255}}) assertRing(ring2, []*entry{{Token: start, Peer: peer1name, Free: 255}})
} }
func assertPeersWithSpace(t *testing.T, ring *Ring, start, end address.Address, expected int) []router.PeerName { func assertPeersWithSpace(t *testing.T, ring *Ring, start, end address.Address, expected int) []mesh.PeerName {
peers := ring.ChoosePeersToAskForSpace(start, end) peers := ring.ChoosePeersToAskForSpace(start, end)
require.Equal(t, expected, len(peers)) require.Equal(t, expected, len(peers))
return peers return peers
@@ -375,7 +375,7 @@ func TestFindFree(t *testing.T) {
ring1.assertInvariants() ring1.assertInvariants()
// We should return others // We should return others
var peers []router.PeerName var peers []mesh.PeerName
ring1.Entries = []*entry{{Token: start, Peer: peer2name, Free: 1}} ring1.Entries = []*entry{{Token: start, Peer: peer2name, Free: 1}}
peers = assertPeersWithSpace(t, ring1, start, end, 1) peers = assertPeersWithSpace(t, ring1, start, end, 1)
@@ -493,7 +493,7 @@ func TestOwner(t *testing.T) {
require.True(t, ring1.Contains(start), "start should be in ring") require.True(t, ring1.Contains(start), "start should be in ring")
require.False(t, ring1.Contains(end), "end should not be in ring") require.False(t, ring1.Contains(end), "end should not be in ring")
require.Equal(t, router.UnknownPeerName, ring1.Owner(start)) require.Equal(t, mesh.UnknownPeerName, ring1.Owner(start))
ring1.ClaimItAll() ring1.ClaimItAll()
ring1.GrantRangeToHost(middle, end, peer2name) ring1.GrantRangeToHost(middle, end, peer2name)
@@ -517,9 +517,9 @@ func TestFuzzRing(t *testing.T) {
iterations = 1000 iterations = 1000
) )
peers := make([]router.PeerName, numPeers) peers := make([]mesh.PeerName, numPeers)
for i := 0; i < numPeers; i++ { for i := 0; i < numPeers; i++ {
peer, _ := router.PeerNameFromString(fmt.Sprintf("%02d:00:00:00:02:00", i)) peer, _ := mesh.PeerNameFromString(fmt.Sprintf("%02d:00:00:00:02:00", i))
peers[i] = peer peers[i] = peer
} }
@@ -601,13 +601,13 @@ func TestFuzzRingHard(t *testing.T) {
var ( var (
numPeers = 100 numPeers = 100
iterations = 3000 iterations = 3000
peers []router.PeerName peers []mesh.PeerName
rings []*Ring rings []*Ring
nextPeerID = 0 nextPeerID = 0
) )
addPeer := func() { addPeer := func() {
peer, _ := router.PeerNameFromString(fmt.Sprintf("%02d:%02d:00:00:00:00", nextPeerID/10, nextPeerID%10)) peer, _ := mesh.PeerNameFromString(fmt.Sprintf("%02d:%02d:00:00:00:00", nextPeerID/10, nextPeerID%10))
common.Log.Debugf("%s: Adding peer", peer) common.Log.Debugf("%s: Adding peer", peer)
nextPeerID++ nextPeerID++
peers = append(peers, peer) peers = append(peers, peer)
@@ -620,7 +620,7 @@ func TestFuzzRingHard(t *testing.T) {
rings[0].ClaimItAll() rings[0].ClaimItAll()
randomPeer := func(exclude int) (int, router.PeerName, *Ring) { randomPeer := func(exclude int) (int, mesh.PeerName, *Ring) {
var peerIndex int var peerIndex int
if exclude >= 0 { if exclude >= 0 {
peerIndex = rand.Intn(len(peers) - 1) peerIndex = rand.Intn(len(peers) - 1)
@@ -729,7 +729,7 @@ func TestFuzzRingHard(t *testing.T) {
} }
func (r *Ring) ClaimItAll() { func (r *Ring) ClaimItAll() {
r.ClaimForPeers([]router.PeerName{r.Peer}) r.ClaimForPeers([]mesh.PeerName{r.Peer})
} }
func (es entries) String() string { func (es entries) String() string {
+12 -12
View File
@@ -8,13 +8,13 @@ import (
"time" "time"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
"github.com/weaveworks/weave/testing/gossip" "github.com/weaveworks/weave/testing/gossip"
) )
type mockMessage struct { type mockMessage struct {
dst router.PeerName dst mesh.PeerName
msgType byte msgType byte
buf []byte buf []byte
} }
@@ -48,13 +48,13 @@ func (m *mockGossipComms) String() string {
// that the contents of messages are never re-ordered. Which, for instance, // that the contents of messages are never re-ordered. Which, for instance,
// requires they are not based off iterating through a map. // requires they are not based off iterating through a map.
func (m *mockGossipComms) GossipBroadcast(update router.GossipData) error { func (m *mockGossipComms) GossipBroadcast(update mesh.GossipData) error {
m.Lock() m.Lock()
defer m.Unlock() defer m.Unlock()
buf := []byte{} buf := []byte{}
if len(m.messages) == 0 { if len(m.messages) == 0 {
require.FailNow(m, fmt.Sprintf("%s: Gossip broadcast message unexpected: \n%x", m.name, buf)) require.FailNow(m, fmt.Sprintf("%s: Gossip broadcast message unexpected: \n%x", m.name, buf))
} else if msg := m.messages[0]; msg.dst != router.UnknownPeerName { } else if msg := m.messages[0]; msg.dst != mesh.UnknownPeerName {
require.FailNow(m, fmt.Sprintf("%s: Expected Gossip message to %s but got broadcast", m.name, msg.dst)) require.FailNow(m, fmt.Sprintf("%s: Expected Gossip message to %s but got broadcast", m.name, msg.dst))
} else if msg.buf != nil && !equalByteBuffer(msg.buf, buf) { } else if msg.buf != nil && !equalByteBuffer(msg.buf, buf) {
require.FailNow(m, fmt.Sprintf("%s: Gossip message not sent as expected: \nwant: %x\ngot : %x", m.name, msg.buf, buf)) require.FailNow(m, fmt.Sprintf("%s: Gossip message not sent as expected: \nwant: %x\ngot : %x", m.name, msg.buf, buf))
@@ -77,12 +77,12 @@ func equalByteBuffer(a, b []byte) bool {
return true return true
} }
func (m *mockGossipComms) GossipUnicast(dstPeerName router.PeerName, buf []byte) error { func (m *mockGossipComms) GossipUnicast(dstPeerName mesh.PeerName, buf []byte) error {
m.Lock() m.Lock()
defer m.Unlock() defer m.Unlock()
if len(m.messages) == 0 { if len(m.messages) == 0 {
require.FailNow(m, fmt.Sprintf("%s: Gossip message to %s unexpected: \n%s", m.name, dstPeerName, buf)) require.FailNow(m, fmt.Sprintf("%s: Gossip message to %s unexpected: \n%s", m.name, dstPeerName, buf))
} else if msg := m.messages[0]; msg.dst == router.UnknownPeerName { } else if msg := m.messages[0]; msg.dst == mesh.UnknownPeerName {
require.FailNow(m, fmt.Sprintf("%s: Expected Gossip broadcast message but got dest %s", m.name, dstPeerName)) require.FailNow(m, fmt.Sprintf("%s: Expected Gossip broadcast message but got dest %s", m.name, dstPeerName))
} else if msg.dst != dstPeerName { } else if msg.dst != dstPeerName {
require.FailNow(m, fmt.Sprintf("%s: Expected Gossip message to %s but got dest %s", m.name, msg.dst, dstPeerName)) require.FailNow(m, fmt.Sprintf("%s: Expected Gossip message to %s but got dest %s", m.name, msg.dst, dstPeerName))
@@ -99,7 +99,7 @@ func (m *mockGossipComms) GossipUnicast(dstPeerName router.PeerName, buf []byte)
func ExpectMessage(alloc *Allocator, dst string, msgType byte, buf []byte) { func ExpectMessage(alloc *Allocator, dst string, msgType byte, buf []byte) {
m := alloc.gossip.(*mockGossipComms) m := alloc.gossip.(*mockGossipComms)
dstPeerName, _ := router.PeerNameFromString(dst) dstPeerName, _ := mesh.PeerNameFromString(dst)
m.Lock() m.Lock()
m.messages = append(m.messages, mockMessage{dstPeerName, msgType, buf}) m.messages = append(m.messages, mockMessage{dstPeerName, msgType, buf})
m.Unlock() m.Unlock()
@@ -108,7 +108,7 @@ func ExpectMessage(alloc *Allocator, dst string, msgType byte, buf []byte) {
func ExpectBroadcastMessage(alloc *Allocator, buf []byte) { func ExpectBroadcastMessage(alloc *Allocator, buf []byte) {
m := alloc.gossip.(*mockGossipComms) m := alloc.gossip.(*mockGossipComms)
m.Lock() m.Lock()
m.messages = append(m.messages, mockMessage{router.UnknownPeerName, 0, buf}) m.messages = append(m.messages, mockMessage{mesh.UnknownPeerName, 0, buf})
m.Unlock() m.Unlock()
} }
@@ -124,7 +124,7 @@ func CheckAllExpectedMessagesSent(allocs ...*Allocator) {
} }
func makeAllocator(name string, cidrStr string, quorum uint) (*Allocator, address.Range) { func makeAllocator(name string, cidrStr string, quorum uint) (*Allocator, address.Range) {
peername, err := router.PeerNameFromString(name) peername, err := mesh.PeerNameFromString(name)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@@ -134,8 +134,8 @@ func makeAllocator(name string, cidrStr string, quorum uint) (*Allocator, addres
panic(err) panic(err)
} }
alloc := NewAllocator(peername, router.PeerUID(rand.Int63()), alloc := NewAllocator(peername, mesh.PeerUID(rand.Int63()),
"nick-"+name, cidr.Range(), quorum, func(router.PeerName) bool { return true }) "nick-"+name, cidr.Range(), quorum, func(mesh.PeerName) bool { return true })
return alloc, cidr.HostRange() return alloc, cidr.HostRange()
} }
@@ -149,7 +149,7 @@ func makeAllocatorWithMockGossip(t *testing.T, name string, universeCIDR string,
} }
func (alloc *Allocator) claimRingForTesting(allocs ...*Allocator) { func (alloc *Allocator) claimRingForTesting(allocs ...*Allocator) {
peers := []router.PeerName{alloc.ourName} peers := []mesh.PeerName{alloc.ourName}
for _, alloc2 := range allocs { for _, alloc2 := range allocs {
peers = append(peers, alloc2.ourName) peers = append(peers, alloc2.ourName)
} }
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"bytes" "bytes"
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
+1 -1
View File
@@ -3,7 +3,7 @@
// It supplies some mock implementations to other unit tests, and is // It supplies some mock implementations to other unit tests, and is
// named "...test.go" so it is only compiled under `go test`. // named "...test.go" so it is only compiled under `go test`.
package router package mesh
import ( import (
"fmt" "fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"net" "net"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"crypto/rand" "crypto/rand"
@@ -3,7 +3,7 @@
// Let peer names be sha256 hashes...of anything (as long as it's // Let peer names be sha256 hashes...of anything (as long as it's
// unique). // unique).
package router package mesh
import ( import (
"crypto/sha256" "crypto/sha256"
@@ -15,7 +15,7 @@
// name. In particular it doesn't actually have to be the MAC of, say, // name. In particular it doesn't actually have to be the MAC of, say,
// the network interface the peer is sniffing on. // the network interface the peer is sniffing on.
package router package mesh
import ( import (
"net" "net"
@@ -56,3 +56,20 @@ func (name PeerName) Bin() []byte {
func (name PeerName) String() string { func (name PeerName) String() string {
return intmac(uint64(name)).String() return intmac(uint64(name)).String()
} }
func macint(mac net.HardwareAddr) (r uint64) {
for _, b := range mac {
r <<= 8
r |= uint64(b)
}
return
}
func intmac(key uint64) (r net.HardwareAddr) {
r = make([]byte, 6)
for i := 5; i >= 0; i-- {
r[i] = byte(key)
key >>= 8
}
return
}
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"bytes" "bytes"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"bytes" "bytes"
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"crypto/rand" "crypto/rand"
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"io" "io"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"math" "math"
+1 -1
View File
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"fmt" "fmt"
@@ -1,4 +1,4 @@
package router package mesh
type SurrogateGossipData struct { type SurrogateGossipData struct {
messages [][]byte messages [][]byte
@@ -1,4 +1,4 @@
package router package mesh
import ( import (
"time" "time"
+4 -4
View File
@@ -11,14 +11,14 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
func startServer(t *testing.T, upstream *dns.ClientConfig) (*DNSServer, *Nameserver, int, int) { func startServer(t *testing.T, upstream *dns.ClientConfig) (*DNSServer, *Nameserver, int, int) {
peername, err := router.PeerNameFromString("00:00:00:02:00:00") peername, err := mesh.PeerNameFromString("00:00:00:02:00:00")
require.Nil(t, err) require.Nil(t, err)
nameserver := New(peername, "", func(router.PeerName) bool { return true }) nameserver := New(peername, "", func(mesh.PeerName) bool { return true })
dnsserver, err := NewDNSServer(nameserver, "weave.local.", "0.0.0.0:0", "", 30, 5*time.Second) dnsserver, err := NewDNSServer(nameserver, "weave.local.", "0.0.0.0:0", "", 30, 5*time.Second)
require.Nil(t, err) require.Nil(t, err)
udpPort := dnsserver.servers[0].PacketConn.LocalAddr().(*net.UDPAddr).Port udpPort := dnsserver.servers[0].PacketConn.LocalAddr().(*net.UDPAddr).Port
@@ -39,7 +39,7 @@ func TestTruncation(t *testing.T) {
addrs := []address.Address{} addrs := []address.Address{}
for i := address.Address(0); i < 100; i++ { for i := address.Address(0); i < 100; i++ {
addrs = append(addrs, i) addrs = append(addrs, i)
nameserver.AddEntry("foo.weave.local.", "", router.UnknownPeerName, i) nameserver.AddEntry("foo.weave.local.", "", mesh.UnknownPeerName, i)
} }
doRequest := func(client *dns.Client, request *dns.Msg, port int, expectedErr error) *dns.Msg { doRequest := func(client *dns.Client, request *dns.Msg, port int, expectedErr error) *dns.Msg {
+5 -5
View File
@@ -8,15 +8,15 @@ import (
"strings" "strings"
"time" "time"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
var now = func() int64 { return time.Now().Unix() } var now = func() int64 { return time.Now().Unix() }
type Entry struct { type Entry struct {
ContainerID string ContainerID string
Origin router.PeerName Origin mesh.PeerName
Addr address.Address Addr address.Address
Hostname string // as supplied Hostname string // as supplied
lHostname string // lowercased (not exported, so not encoded by gob) lHostname string // lowercased (not exported, so not encoded by gob)
@@ -128,7 +128,7 @@ func (es *Entries) checkAndPanic() *Entries {
return es return es
} }
func (es *Entries) add(hostname, containerid string, origin router.PeerName, addr address.Address) Entry { func (es *Entries) add(hostname, containerid string, origin mesh.PeerName, addr address.Address) Entry {
defer es.checkAndPanic().checkAndPanic() defer es.checkAndPanic().checkAndPanic()
entry := Entry{Hostname: hostname, lHostname: strings.ToLower(hostname), entry := Entry{Hostname: hostname, lHostname: strings.ToLower(hostname),
@@ -176,7 +176,7 @@ func (es *Entries) merge(incoming Entries) Entries {
} }
// f returning true means keep the entry. // f returning true means keep the entry.
func (es *Entries) tombstone(ourname router.PeerName, f func(*Entry) bool) Entries { func (es *Entries) tombstone(ourname mesh.PeerName, f func(*Entry) bool) Entries {
defer es.checkAndPanic().checkAndPanic() defer es.checkAndPanic().checkAndPanic()
tombstoned := Entries{} tombstoned := Entries{}
@@ -245,7 +245,7 @@ type GossipData struct {
Entries Entries
} }
func (g *GossipData) Merge(o router.GossipData) { func (g *GossipData) Merge(o mesh.GossipData) {
other := o.(*GossipData) other := o.(*GossipData)
g.Entries.merge(other.Entries) g.Entries.merge(other.Entries)
if g.Timestamp < other.Timestamp { if g.Timestamp < other.Timestamp {
+8 -8
View File
@@ -5,8 +5,8 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
func l(es Entries) Entries { func l(es Entries) Entries {
@@ -28,21 +28,21 @@ func TestAdd(t *testing.T) {
now = func() int64 { return 1234 } now = func() int64 { return 1234 }
entries := Entries{} entries := Entries{}
entries.add("A", "", router.UnknownPeerName, address.Address(0)) entries.add("A", "", mesh.UnknownPeerName, address.Address(0))
expected := l(Entries{ expected := l(Entries{
Entry{Hostname: "A", Origin: router.UnknownPeerName, Addr: address.Address(0)}, Entry{Hostname: "A", Origin: mesh.UnknownPeerName, Addr: address.Address(0)},
}) })
require.Equal(t, entries, expected) require.Equal(t, entries, expected)
entries.tombstone(router.UnknownPeerName, func(e *Entry) bool { return e.Hostname == "A" }) entries.tombstone(mesh.UnknownPeerName, func(e *Entry) bool { return e.Hostname == "A" })
expected = l(Entries{ expected = l(Entries{
Entry{Hostname: "A", Origin: router.UnknownPeerName, Addr: address.Address(0), Version: 1, Tombstone: 1234}, Entry{Hostname: "A", Origin: mesh.UnknownPeerName, Addr: address.Address(0), Version: 1, Tombstone: 1234},
}) })
require.Equal(t, entries, expected) require.Equal(t, entries, expected)
entries.add("A", "", router.UnknownPeerName, address.Address(0)) entries.add("A", "", mesh.UnknownPeerName, address.Address(0))
expected = l(Entries{ expected = l(Entries{
Entry{Hostname: "A", Origin: router.UnknownPeerName, Addr: address.Address(0), Version: 2}, Entry{Hostname: "A", Origin: mesh.UnknownPeerName, Addr: address.Address(0), Version: 2},
}) })
require.Equal(t, entries, expected) require.Equal(t, entries, expected)
} }
@@ -78,7 +78,7 @@ func TestTombstone(t *testing.T) {
es := makeEntries("AB") es := makeEntries("AB")
es.tombstone(router.UnknownPeerName, func(e *Entry) bool { es.tombstone(mesh.UnknownPeerName, func(e *Entry) bool {
return e.Hostname == "B" return e.Hostname == "B"
}) })
expected := l(Entries{ expected := l(Entries{
+13 -13
View File
@@ -8,8 +8,8 @@ import (
"github.com/miekg/dns" "github.com/miekg/dns"
. "github.com/weaveworks/weave/common" . "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
) )
const ( const (
@@ -34,15 +34,15 @@ const (
// - Update is O(n) for now // - Update is O(n) for now
type Nameserver struct { type Nameserver struct {
sync.RWMutex sync.RWMutex
ourName router.PeerName ourName mesh.PeerName
domain string domain string
gossip router.Gossip gossip mesh.Gossip
entries Entries entries Entries
isKnownPeer func(router.PeerName) bool isKnownPeer func(mesh.PeerName) bool
quit chan struct{} quit chan struct{}
} }
func New(ourName router.PeerName, domain string, isKnownPeer func(router.PeerName) bool) *Nameserver { func New(ourName mesh.PeerName, domain string, isKnownPeer func(mesh.PeerName) bool) *Nameserver {
return &Nameserver{ return &Nameserver{
ourName: ourName, ourName: ourName,
domain: dns.Fqdn(domain), domain: dns.Fqdn(domain),
@@ -51,7 +51,7 @@ func New(ourName router.PeerName, domain string, isKnownPeer func(router.PeerNam
} }
} }
func (n *Nameserver) SetGossip(gossip router.Gossip) { func (n *Nameserver) SetGossip(gossip mesh.Gossip) {
n.gossip = gossip n.gossip = gossip
} }
@@ -83,7 +83,7 @@ func (n *Nameserver) broadcastEntries(es ...Entry) error {
return nil return nil
} }
func (n *Nameserver) AddEntry(hostname, containerid string, origin router.PeerName, addr address.Address) error { func (n *Nameserver) AddEntry(hostname, containerid string, origin mesh.PeerName, addr address.Address) error {
n.infof("adding entry %s -> %s", hostname, addr.String()) n.infof("adding entry %s -> %s", hostname, addr.String())
n.Lock() n.Lock()
entry := n.entries.add(hostname, containerid, origin, addr) entry := n.entries.add(hostname, containerid, origin, addr)
@@ -140,7 +140,7 @@ func (n *Nameserver) ContainerDied(ident string) {
} }
} }
func (n *Nameserver) PeerGone(peer router.PeerName) { func (n *Nameserver) PeerGone(peer mesh.PeerName) {
n.infof("peer %s gone", peer.String()) n.infof("peer %s gone", peer.String())
n.Lock() n.Lock()
defer n.Unlock() defer n.Unlock()
@@ -181,7 +181,7 @@ func (n *Nameserver) deleteTombstones() {
}) })
} }
func (n *Nameserver) Gossip() router.GossipData { func (n *Nameserver) Gossip() mesh.GossipData {
n.RLock() n.RLock()
defer n.RUnlock() defer n.RUnlock()
gossip := &GossipData{ gossip := &GossipData{
@@ -192,11 +192,11 @@ func (n *Nameserver) Gossip() router.GossipData {
return gossip return gossip
} }
func (n *Nameserver) OnGossipUnicast(sender router.PeerName, msg []byte) error { func (n *Nameserver) OnGossipUnicast(sender mesh.PeerName, msg []byte) error {
return nil return nil
} }
func (n *Nameserver) receiveGossip(msg []byte) (router.GossipData, router.GossipData, error) { func (n *Nameserver) receiveGossip(msg []byte) (mesh.GossipData, mesh.GossipData, error) {
var gossip GossipData var gossip GossipData
if err := gossip.Decode(msg); err != nil { if err := gossip.Decode(msg); err != nil {
return nil, nil, err return nil, nil, err
@@ -221,14 +221,14 @@ func (n *Nameserver) receiveGossip(msg []byte) (router.GossipData, router.Gossip
// merge received data into state and return "everything new I've // merge received data into state and return "everything new I've
// just learnt", or nil if nothing in the received data was new // just learnt", or nil if nothing in the received data was new
func (n *Nameserver) OnGossip(msg []byte) (router.GossipData, error) { func (n *Nameserver) OnGossip(msg []byte) (mesh.GossipData, error) {
newEntries, _, err := n.receiveGossip(msg) newEntries, _, err := n.receiveGossip(msg)
return newEntries, err return newEntries, err
} }
// merge received data into state and return a representation of // merge received data into state and return a representation of
// the received data, for further propagation // the received data, for further propagation
func (n *Nameserver) OnGossipBroadcast(_ router.PeerName, msg []byte) (router.GossipData, error) { func (n *Nameserver) OnGossipBroadcast(_ mesh.PeerName, msg []byte) (mesh.GossipData, error) {
_, entries, err := n.receiveGossip(msg) _, entries, err := n.receiveGossip(msg)
return entries, err return entries, err
} }
+8 -8
View File
@@ -11,14 +11,14 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
"github.com/weaveworks/weave/router"
wt "github.com/weaveworks/weave/testing" wt "github.com/weaveworks/weave/testing"
"github.com/weaveworks/weave/testing/gossip" "github.com/weaveworks/weave/testing/gossip"
) )
func makeNameserver(name router.PeerName) *Nameserver { func makeNameserver(name mesh.PeerName) *Nameserver {
return New(name, "", func(router.PeerName) bool { return true }) return New(name, "", func(mesh.PeerName) bool { return true })
} }
func makeNetwork(size int) ([]*Nameserver, *gossip.TestRouter) { func makeNetwork(size int) ([]*Nameserver, *gossip.TestRouter) {
@@ -26,7 +26,7 @@ func makeNetwork(size int) ([]*Nameserver, *gossip.TestRouter) {
nameservers := make([]*Nameserver, size) nameservers := make([]*Nameserver, size)
for i := 0; i < size; i++ { for i := 0; i < size; i++ {
name, _ := router.PeerNameFromString(fmt.Sprintf("%02d:00:00:02:00:00", i)) name, _ := mesh.PeerNameFromString(fmt.Sprintf("%02d:00:00:02:00:00", i))
nameserver := makeNameserver(name) nameserver := makeNameserver(name)
nameserver.SetGossip(gossipRouter.Connect(nameserver.ourName, nameserver)) nameserver.SetGossip(gossipRouter.Connect(nameserver.ourName, nameserver))
nameserver.Start() nameserver.Start()
@@ -44,7 +44,7 @@ func stopNetwork(nameservers []*Nameserver, grouter *gossip.TestRouter) {
} }
type pair struct { type pair struct {
origin router.PeerName origin mesh.PeerName
addr address.Address addr address.Address
} }
@@ -91,7 +91,7 @@ func testNameservers(t *testing.T) {
badNameservers := nameservers[25:] badNameservers := nameservers[25:]
// This subset will remain well-connected, and we will deal mainly with them // This subset will remain well-connected, and we will deal mainly with them
nameservers = nameservers[:25] nameservers = nameservers[:25]
nameserversByName := map[router.PeerName]*Nameserver{} nameserversByName := map[mesh.PeerName]*Nameserver{}
for _, n := range nameservers { for _, n := range nameservers {
nameserversByName[n.ourName] = n nameserversByName[n.ourName] = n
} }
@@ -226,7 +226,7 @@ func testNameservers(t *testing.T) {
} }
func TestContainerAndPeerDeath(t *testing.T) { func TestContainerAndPeerDeath(t *testing.T) {
peername, err := router.PeerNameFromString("00:00:00:02:00:00") peername, err := mesh.PeerNameFromString("00:00:00:02:00:00")
require.Nil(t, err) require.Nil(t, err)
nameserver := makeNameserver(peername) nameserver := makeNameserver(peername)
@@ -250,7 +250,7 @@ func TestTombstoneDeletion(t *testing.T) {
defer func() { now = oldNow }() defer func() { now = oldNow }()
now = func() int64 { return 1234 } now = func() int64 { return 1234 }
peername, err := router.PeerNameFromString("00:00:00:02:00:00") peername, err := mesh.PeerNameFromString("00:00:00:02:00:00")
require.Nil(t, err) require.Nil(t, err)
nameserver := makeNameserver(peername) nameserver := makeNameserver(peername)
+3 -2
View File
@@ -6,6 +6,7 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
. "github.com/weaveworks/weave/common" . "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/ipam" "github.com/weaveworks/weave/ipam"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/nameserver" "github.com/weaveworks/weave/nameserver"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
weave "github.com/weaveworks/weave/router" weave "github.com/weaveworks/weave/router"
@@ -24,14 +25,14 @@ var rootTemplate = template.New("root").Funcs(map[string]interface{}{
} }
return count return count
}, },
"printConnectionCounts": func(conns []weave.LocalConnectionStatus) string { "printConnectionCounts": func(conns []mesh.LocalConnectionStatus) string {
counts := make(map[string]int) counts := make(map[string]int)
for _, conn := range conns { for _, conn := range conns {
counts[conn.State]++ counts[conn.State]++
} }
return printCounts(counts, []string{"established", "pending", "retrying", "failed", "connecting"}) return printCounts(counts, []string{"established", "pending", "retrying", "failed", "connecting"})
}, },
"printPeerConnectionCounts": func(peers []weave.PeerStatus) string { "printPeerConnectionCounts": func(peers []mesh.PeerStatus) string {
counts := make(map[string]int) counts := make(map[string]int)
for _, peer := range peers { for _, peer := range peers {
for _, conn := range peer.Connections { for _, conn := range peer.Connections {
+10 -9
View File
@@ -17,6 +17,7 @@ import (
. "github.com/weaveworks/weave/common" . "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/common/docker" "github.com/weaveworks/weave/common/docker"
"github.com/weaveworks/weave/ipam" "github.com/weaveworks/weave/ipam"
"github.com/weaveworks/weave/mesh"
"github.com/weaveworks/weave/nameserver" "github.com/weaveworks/weave/nameserver"
weavenet "github.com/weaveworks/weave/net" weavenet "github.com/weaveworks/weave/net"
"github.com/weaveworks/weave/net/address" "github.com/weaveworks/weave/net/address"
@@ -41,7 +42,7 @@ func main() {
deleteDatapath bool deleteDatapath bool
addDatapathInterface string addDatapathInterface string
config weave.Config config mesh.Config
networkConfig weave.NetworkConfig networkConfig weave.NetworkConfig
protocolMinVersion int protocolMinVersion int
ifaceName string ifaceName string
@@ -74,8 +75,8 @@ func main() {
mflag.BoolVar(&deleteDatapath, []string{"-delete-datapath"}, false, "delete ODP datapath and exit") mflag.BoolVar(&deleteDatapath, []string{"-delete-datapath"}, false, "delete ODP datapath and exit")
mflag.StringVar(&addDatapathInterface, []string{"-add-datapath-iface"}, "", "add a network interface to the ODP datapath and exit") mflag.StringVar(&addDatapathInterface, []string{"-add-datapath-iface"}, "", "add a network interface to the ODP datapath and exit")
mflag.IntVar(&config.Port, []string{"#port", "-port"}, weave.Port, "router port") mflag.IntVar(&config.Port, []string{"#port", "-port"}, mesh.Port, "router port")
mflag.IntVar(&protocolMinVersion, []string{"-min-protocol-version"}, weave.ProtocolMinVersion, "minimum weave protocol version") mflag.IntVar(&protocolMinVersion, []string{"-min-protocol-version"}, mesh.ProtocolMinVersion, "minimum weave protocol version")
mflag.StringVar(&ifaceName, []string{"#iface", "-iface"}, "", "name of interface to capture/inject from (disabled if blank)") 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(&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(&nickName, []string{"#nickname", "-nickname"}, "", "nickname of peer (defaults to hostname)")
@@ -146,8 +147,8 @@ func main() {
Log.Println("Command line options:", options()) Log.Println("Command line options:", options())
Log.Println("Command line peers:", peers) Log.Println("Command line peers:", peers)
if protocolMinVersion < weave.ProtocolMinVersion || protocolMinVersion > weave.ProtocolMaxVersion { if protocolMinVersion < mesh.ProtocolMinVersion || protocolMinVersion > mesh.ProtocolMaxVersion {
Log.Fatalf("--min-protocol-version must be in range [%d,%d]", weave.ProtocolMinVersion, weave.ProtocolMaxVersion) Log.Fatalf("--min-protocol-version must be in range [%d,%d]", mesh.ProtocolMinVersion, mesh.ProtocolMaxVersion)
} }
config.ProtocolMinVersion = byte(protocolMinVersion) config.ProtocolMinVersion = byte(protocolMinVersion)
@@ -212,7 +213,7 @@ func main() {
routerName = iface.HardwareAddr.String() routerName = iface.HardwareAddr.String()
} }
name, err := weave.PeerNameFromUserInput(routerName) name, err := mesh.PeerNameFromUserInput(routerName)
checkFatal(err) checkFatal(err)
if nickName == "" { if nickName == "" {
@@ -253,7 +254,7 @@ func main() {
} }
} }
} }
isKnownPeer := func(name weave.PeerName) bool { isKnownPeer := func(name mesh.PeerName) bool {
return router.Peers.Fetch(name) != nil return router.Peers.Fetch(name) != nil
} }
var allocator *ipam.Allocator var allocator *ipam.Allocator
@@ -271,7 +272,7 @@ func main() {
) )
if !noDNS { if !noDNS {
ns = nameserver.New(router.Ourself.Peer.Name, dnsDomain, isKnownPeer) ns = nameserver.New(router.Ourself.Peer.Name, dnsDomain, isKnownPeer)
router.Peers.OnGC(func(peer *weave.Peer) { ns.PeerGone(peer.Name) }) router.Peers.OnGC(func(peer *mesh.Peer) { ns.PeerGone(peer.Name) })
ns.SetGossip(router.NewGossip("nameserver", ns)) ns.SetGossip(router.NewGossip("nameserver", ns))
observeContainers(ns) observeContainers(ns)
ns.Start() ns.Start()
@@ -366,7 +367,7 @@ func parseAndCheckCIDR(cidrStr string) address.CIDR {
return cidr return cidr
} }
func createAllocator(router *weave.Router, ipRangeStr string, defaultSubnetStr string, quorum uint, isKnownPeer func(weave.PeerName) bool) (*ipam.Allocator, address.CIDR) { func createAllocator(router *mesh.Router, ipRangeStr string, defaultSubnetStr string, quorum uint, isKnownPeer func(mesh.PeerName) bool) (*ipam.Allocator, address.CIDR) {
ipRange := parseAndCheckCIDR(ipRangeStr) ipRange := parseAndCheckCIDR(ipRangeStr)
defaultSubnet := ipRange defaultSubnet := ipRange
if defaultSubnetStr != "" { if defaultSubnetStr != "" {
+14 -13
View File
@@ -9,6 +9,7 @@ import (
"time" "time"
"github.com/weaveworks/go-odp/odp" "github.com/weaveworks/go-odp/odp"
"github.com/weaveworks/weave/mesh"
) )
// The virtual bridge accepts packets from ODP vports and the router // The virtual bridge accepts packets from ODP vports and the router
@@ -40,8 +41,8 @@ type FastDatapath struct {
dp odp.DatapathHandle dp odp.DatapathHandle
deleteFlowsCount uint64 deleteFlowsCount uint64
missHandlers map[odp.VportID]missHandler missHandlers map[odp.VportID]missHandler
localPeer *Peer localPeer *mesh.Peer
peers *Peers peers *mesh.Peers
overlayConsumer OverlayConsumer overlayConsumer OverlayConsumer
// Bridge state: How to send to the given bridge port // Bridge state: How to send to the given bridge port
@@ -62,7 +63,7 @@ type FastDatapath struct {
dec *EthernetDecoder dec *EthernetDecoder
// forwarders by remote peer // forwarders by remote peer
forwarders map[PeerName]*fastDatapathForwarder forwarders map[mesh.PeerName]*fastDatapathForwarder
} }
type FastDatapathConfig struct { type FastDatapathConfig struct {
@@ -105,7 +106,7 @@ func NewFastDatapath(config FastDatapathConfig) (*FastDatapath, error) {
sendToMAC: make(map[MAC]bridgeSender), sendToMAC: make(map[MAC]bridgeSender),
seenMACs: make(map[MAC]struct{}), seenMACs: make(map[MAC]struct{}),
vxlanVportIDs: make(map[int]odp.VportID), vxlanVportIDs: make(map[int]odp.VportID),
forwarders: make(map[PeerName]*fastDatapathForwarder), forwarders: make(map[mesh.PeerName]*fastDatapathForwarder),
} }
if err := fastdp.deleteVxlanVports(); err != nil { if err := fastdp.deleteVxlanVports(); err != nil {
@@ -385,7 +386,7 @@ func (fastdp fastDatapathOverlay) Diagnostics() interface{} {
} }
} }
func (fastdp fastDatapathOverlay) StartConsumingPackets(localPeer *Peer, peers *Peers, consumer OverlayConsumer) error { func (fastdp fastDatapathOverlay) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {
fastdp.lock.Lock() fastdp.lock.Lock()
defer fastdp.lock.Unlock() defer fastdp.lock.Unlock()
@@ -460,17 +461,17 @@ func (fastdp *FastDatapath) getVxlanVportID(udpPort int) (odp.VportID, error) {
return vxlanVportID, nil return vxlanVportID, nil
} }
func (fastdp *FastDatapath) extractPeers(tunnelID [8]byte) (*Peer, *Peer) { func (fastdp *FastDatapath) extractPeers(tunnelID [8]byte) (*mesh.Peer, *mesh.Peer) {
vni := binary.BigEndian.Uint64(tunnelID[:]) vni := binary.BigEndian.Uint64(tunnelID[:])
srcPeer := fastdp.peers.FetchByShortID(PeerShortID(vni & 0xfff)) srcPeer := fastdp.peers.FetchByShortID(mesh.PeerShortID(vni & 0xfff))
dstPeer := fastdp.peers.FetchByShortID(PeerShortID((vni >> 12) & 0xfff)) dstPeer := fastdp.peers.FetchByShortID(mesh.PeerShortID((vni >> 12) & 0xfff))
return srcPeer, dstPeer return srcPeer, dstPeer
} }
type vxlanSpecialPacketFlowOp struct { type vxlanSpecialPacketFlowOp struct {
NonDiscardingFlowOp NonDiscardingFlowOp
fastdp *FastDatapath fastdp *FastDatapath
srcPeer *Peer srcPeer *mesh.Peer
sender *net.UDPAddr sender *net.UDPAddr
} }
@@ -486,7 +487,7 @@ func (op vxlanSpecialPacketFlowOp) Process(frame []byte, dec *EthernetDecoder, b
type fastDatapathForwarder struct { type fastDatapathForwarder struct {
fastdp *FastDatapath fastdp *FastDatapath
remotePeer *Peer remotePeer *mesh.Peer
localIP [4]byte localIP [4]byte
sendControlMsg func(byte, []byte) error sendControlMsg func(byte, []byte) error
connUID uint64 connUID uint64
@@ -506,7 +507,7 @@ type fastDatapathForwarder struct {
errorChan chan error errorChan chan error
} }
func (fastdp fastDatapathOverlay) PrepareConnection(params OverlayConnectionParams) (OverlayConnection, error) { func (fastdp fastDatapathOverlay) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {
if params.SessionKey != nil { if params.SessionKey != nil {
// No encryption suport in fastdp. The weaver main.go // No encryption suport in fastdp. The weaver main.go
// is responsible for ensuring this doesn't happen. // is responsible for ensuring this doesn't happen.
@@ -794,7 +795,7 @@ func (fwd *fastDatapathForwarder) Stop() {
} }
} }
func (fastdp *FastDatapath) addForwarder(peer PeerName, fwd *fastDatapathForwarder) { func (fastdp *FastDatapath) addForwarder(peer mesh.PeerName, fwd *fastDatapathForwarder) {
fastdp.lock.Lock() fastdp.lock.Lock()
defer fastdp.lock.Unlock() defer fastdp.lock.Unlock()
@@ -803,7 +804,7 @@ func (fastdp *FastDatapath) addForwarder(peer PeerName, fwd *fastDatapathForward
fastdp.forwarders[peer] = fwd fastdp.forwarders[peer] = fwd
} }
func (fastdp *FastDatapath) removeForwarder(peer PeerName, fwd *fastDatapathForwarder) { func (fastdp *FastDatapath) removeForwarder(peer mesh.PeerName, fwd *fastDatapathForwarder) {
fastdp.lock.Lock() fastdp.lock.Lock()
defer fastdp.lock.Unlock() defer fastdp.lock.Unlock()
if fastdp.forwarders[peer] == fwd { if fastdp.forwarders[peer] == fwd {
+7 -3
View File
@@ -1,6 +1,10 @@
package router package router
import "net" import (
"net"
"github.com/weaveworks/weave/mesh"
)
// Just enough flow machinery for the weave router // Just enough flow machinery for the weave router
@@ -16,8 +20,8 @@ type PacketKey struct {
} }
type ForwardPacketKey struct { type ForwardPacketKey struct {
SrcPeer *Peer SrcPeer *mesh.Peer
DstPeer *Peer DstPeer *mesh.Peer
PacketKey PacketKey
} }
+3 -2
View File
@@ -2,12 +2,13 @@ package router
import ( import (
"fmt" "fmt"
"net/http"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common"
"net/http"
) )
func (router *Router) HandleHTTP(muxRouter *mux.Router) { func (router *NetworkRouter) HandleHTTP(muxRouter *mux.Router) {
muxRouter.Methods("POST").Path("/connect").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { muxRouter.Methods("POST").Path("/connect").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil { if err := r.ParseForm(); err != nil {
+10 -8
View File
@@ -4,11 +4,13 @@ import (
"net" "net"
"sync" "sync"
"time" "time"
"github.com/weaveworks/weave/mesh"
) )
type MacCacheEntry struct { type MacCacheEntry struct {
lastSeen time.Time lastSeen time.Time
peer *Peer peer *mesh.Peer
} }
type MacCache struct { type MacCache struct {
@@ -16,10 +18,10 @@ type MacCache struct {
table map[uint64]*MacCacheEntry table map[uint64]*MacCacheEntry
maxAge time.Duration maxAge time.Duration
expiryTimer *time.Timer expiryTimer *time.Timer
onExpiry func(net.HardwareAddr, *Peer) onExpiry func(net.HardwareAddr, *mesh.Peer)
} }
func NewMacCache(maxAge time.Duration, onExpiry func(net.HardwareAddr, *Peer)) *MacCache { func NewMacCache(maxAge time.Duration, onExpiry func(net.HardwareAddr, *mesh.Peer)) *MacCache {
cache := &MacCache{ cache := &MacCache{
table: make(map[uint64]*MacCacheEntry), table: make(map[uint64]*MacCacheEntry),
maxAge: maxAge, maxAge: maxAge,
@@ -28,7 +30,7 @@ func NewMacCache(maxAge time.Duration, onExpiry func(net.HardwareAddr, *Peer)) *
return cache return cache
} }
func (cache *MacCache) add(mac net.HardwareAddr, peer *Peer, force bool) (bool, *Peer) { func (cache *MacCache) add(mac net.HardwareAddr, peer *mesh.Peer, force bool) (bool, *mesh.Peer) {
key := macint(mac) key := macint(mac)
now := time.Now() now := time.Now()
@@ -64,15 +66,15 @@ func (cache *MacCache) add(mac net.HardwareAddr, peer *Peer, force bool) (bool,
return false, nil return false, nil
} }
func (cache *MacCache) Add(mac net.HardwareAddr, peer *Peer) (bool, *Peer) { func (cache *MacCache) Add(mac net.HardwareAddr, peer *mesh.Peer) (bool, *mesh.Peer) {
return cache.add(mac, peer, false) return cache.add(mac, peer, false)
} }
func (cache *MacCache) AddForced(mac net.HardwareAddr, peer *Peer) (bool, *Peer) { func (cache *MacCache) AddForced(mac net.HardwareAddr, peer *mesh.Peer) (bool, *mesh.Peer) {
return cache.add(mac, peer, true) return cache.add(mac, peer, true)
} }
func (cache *MacCache) Lookup(mac net.HardwareAddr) *Peer { func (cache *MacCache) Lookup(mac net.HardwareAddr) *mesh.Peer {
key := macint(mac) key := macint(mac)
cache.RLock() cache.RLock()
defer cache.RUnlock() defer cache.RUnlock()
@@ -83,7 +85,7 @@ func (cache *MacCache) Lookup(mac net.HardwareAddr) *Peer {
return entry.peer return entry.peer
} }
func (cache *MacCache) Delete(peer *Peer) bool { func (cache *MacCache) Delete(peer *mesh.Peer) bool {
found := false found := false
cache.Lock() cache.Lock()
defer cache.Unlock() defer cache.Unlock()
+9 -5
View File
@@ -1,8 +1,12 @@
package router package router
import (
"github.com/weaveworks/weave/mesh"
)
// Interface to overlay network packet handling // Interface to overlay network packet handling
type NetworkOverlay interface { type NetworkOverlay interface {
Overlay mesh.Overlay
// The routes have changed, so any cached information should // The routes have changed, so any cached information should
// be discarded. // be discarded.
@@ -12,7 +16,7 @@ type NetworkOverlay interface {
InvalidateShortIDs() InvalidateShortIDs()
// Start consuming forwarded packets. // Start consuming forwarded packets.
StartConsumingPackets(*Peer, *Peers, OverlayConsumer) error StartConsumingPackets(*mesh.Peer, *mesh.Peers, OverlayConsumer) error
} }
// When a consumer is called, the decoder will already have been used // When a consumer is called, the decoder will already have been used
@@ -21,7 +25,7 @@ type OverlayConsumer func(ForwardPacketKey) FlowOp
// All of the machinery to forward packets to a particular peer // All of the machinery to forward packets to a particular peer
type OverlayForwarder interface { type OverlayForwarder interface {
OverlayConnection mesh.OverlayConnection
// Forward a packet across the connection. May be called as soon // Forward a packet across the connection. May be called as soon
// as the overlay connection is created, in particular before // as the overlay connection is created, in particular before
// Confirm(). The return value nil means the key could not be // Confirm(). The return value nil means the key could not be
@@ -29,7 +33,7 @@ type OverlayForwarder interface {
Forward(ForwardPacketKey) FlowOp Forward(ForwardPacketKey) FlowOp
} }
type NullNetworkOverlay struct{ NullOverlay } type NullNetworkOverlay struct{ mesh.NullOverlay }
func (NullNetworkOverlay) InvalidateRoutes() { func (NullNetworkOverlay) InvalidateRoutes() {
} }
@@ -37,7 +41,7 @@ func (NullNetworkOverlay) InvalidateRoutes() {
func (NullNetworkOverlay) InvalidateShortIDs() { func (NullNetworkOverlay) InvalidateShortIDs() {
} }
func (NullNetworkOverlay) StartConsumingPackets(*Peer, *Peers, OverlayConsumer) error { func (NullNetworkOverlay) StartConsumingPackets(*mesh.Peer, *mesh.Peers, OverlayConsumer) error {
return nil return nil
} }
+21 -8
View File
@@ -1,21 +1,34 @@
package router package router
import ( import (
"math"
"net" "net"
"time" "time"
"github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/mesh"
) )
const ( const (
ChannelSize = 16
MaxUDPPacketSize = 65535 MaxUDPPacketSize = 65535
FastHeartbeat = 500 * time.Millisecond FastHeartbeat = 500 * time.Millisecond
SlowHeartbeat = 10 * time.Second SlowHeartbeat = 10 * time.Second
MaxMissedHeartbeats = 6 MaxMissedHeartbeats = 6
HeartbeatTimeout = MaxMissedHeartbeats * SlowHeartbeat HeartbeatTimeout = MaxMissedHeartbeats * SlowHeartbeat
MaxDuration = time.Duration(math.MaxInt64)
NameSize = mesh.NameSize
// should be greater than typical ARP cache expiries, i.e. > 3/2 * // should be greater than typical ARP cache expiries, i.e. > 3/2 *
// /proc/sys/net/ipv4_neigh/*/base_reachable_time_ms on Linux // /proc/sys/net/ipv4_neigh/*/base_reachable_time_ms on Linux
macMaxAge = 10 * time.Minute macMaxAge = 10 * time.Minute
) )
var (
log = common.Log
checkFatal = common.CheckFatal
checkWarn = common.CheckWarn
)
type NetworkConfig struct { type NetworkConfig struct {
BufSz int BufSz int
PacketLogging PacketLogging PacketLogging PacketLogging
@@ -28,12 +41,12 @@ type PacketLogging interface {
} }
type NetworkRouter struct { type NetworkRouter struct {
*Router *mesh.Router
NetworkConfig NetworkConfig
Macs *MacCache Macs *MacCache
} }
func NewNetworkRouter(config Config, networkConfig NetworkConfig, name PeerName, nickName string, overlay NetworkOverlay) *NetworkRouter { func NewNetworkRouter(config mesh.Config, networkConfig NetworkConfig, name mesh.PeerName, nickName string, overlay NetworkOverlay) *NetworkRouter {
if overlay == nil { if overlay == nil {
overlay = NullNetworkOverlay{} overlay = NullNetworkOverlay{}
} }
@@ -41,14 +54,14 @@ func NewNetworkRouter(config Config, networkConfig NetworkConfig, name PeerName,
networkConfig.Bridge = NullBridge{} networkConfig.Bridge = NullBridge{}
} }
router := &NetworkRouter{Router: NewRouter(config, name, nickName, overlay), NetworkConfig: networkConfig} router := &NetworkRouter{Router: mesh.NewRouter(config, name, nickName, overlay), NetworkConfig: networkConfig}
router.Peers.OnInvalidateShortIDs(overlay.InvalidateShortIDs) router.Peers.OnInvalidateShortIDs(overlay.InvalidateShortIDs)
router.Routes.OnChange(overlay.InvalidateRoutes) router.Routes.OnChange(overlay.InvalidateRoutes)
router.Macs = NewMacCache(macMaxAge, router.Macs = NewMacCache(macMaxAge,
func(mac net.HardwareAddr, peer *Peer) { func(mac net.HardwareAddr, peer *mesh.Peer) {
log.Println("Expired MAC", mac, "at", peer) log.Println("Expired MAC", mac, "at", peer)
}) })
router.Peers.OnGC(func(peer *Peer) { router.Macs.Delete(peer) }) router.Peers.OnGC(func(peer *mesh.Peer) { router.Macs.Delete(peer) })
return router return router
} }
@@ -174,10 +187,10 @@ func (router *NetworkRouter) relay(key ForwardPacketKey) FlowOp {
return DiscardingFlowOp{} return DiscardingFlowOp{}
} }
return conn.(*LocalConnection).OverlayConn.(OverlayForwarder).Forward(key) return conn.(*mesh.LocalConnection).OverlayConn.(OverlayForwarder).Forward(key)
} }
func (router *NetworkRouter) relayBroadcast(srcPeer *Peer, key PacketKey) FlowOp { func (router *NetworkRouter) relayBroadcast(srcPeer *mesh.Peer, key PacketKey) FlowOp {
nextHops := router.Routes.Broadcast(srcPeer.Name) nextHops := router.Routes.Broadcast(srcPeer.Name)
if len(nextHops) == 0 { if len(nextHops) == 0 {
return DiscardingFlowOp{} return DiscardingFlowOp{}
@@ -186,7 +199,7 @@ func (router *NetworkRouter) relayBroadcast(srcPeer *Peer, key PacketKey) FlowOp
op := NewMultiFlowOp(true) op := NewMultiFlowOp(true)
for _, conn := range router.Ourself.ConnectionsTo(nextHops) { for _, conn := range router.Ourself.ConnectionsTo(nextHops) {
op.Add(conn.(*LocalConnection).OverlayConn.(OverlayForwarder).Forward(ForwardPacketKey{ op.Add(conn.(*mesh.LocalConnection).OverlayConn.(OverlayForwarder).Forward(ForwardPacketKey{
PacketKey: key, PacketKey: key,
SrcPeer: srcPeer, SrcPeer: srcPeer,
DstPeer: conn.Remote()})) DstPeer: conn.Remote()}))
+4 -2
View File
@@ -2,10 +2,12 @@ package router
import ( import (
"time" "time"
"github.com/weaveworks/weave/mesh"
) )
type NetworkRouterStatus struct { type NetworkRouterStatus struct {
*Status *mesh.Status
Interface string Interface string
CaptureStats map[string]int CaptureStats map[string]int
MACs []MACStatus MACs []MACStatus
@@ -20,7 +22,7 @@ type MACStatus struct {
func NewNetworkRouterStatus(router *NetworkRouter) *NetworkRouterStatus { func NewNetworkRouterStatus(router *NetworkRouter) *NetworkRouterStatus {
return &NetworkRouterStatus{ return &NetworkRouterStatus{
NewStatus(router.Router), mesh.NewStatus(router.Router),
router.Bridge.String(), router.Bridge.String(),
router.Bridge.Stats(), router.Bridge.Stats(),
NewMACStatusSlice(router.Macs)} NewMACStatusSlice(router.Macs)}
+7 -5
View File
@@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"sync" "sync"
"github.com/weaveworks/weave/mesh"
) )
// OverlaySwitch selects which overlay to use, from a set of // OverlaySwitch selects which overlay to use, from a set of
@@ -60,7 +62,7 @@ func (osw *OverlaySwitch) InvalidateShortIDs() {
} }
} }
func (osw *OverlaySwitch) StartConsumingPackets(localPeer *Peer, peers *Peers, consumer OverlayConsumer) error { func (osw *OverlaySwitch) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {
for _, overlay := range osw.overlays { for _, overlay := range osw.overlays {
if err := overlay.StartConsumingPackets(localPeer, peers, consumer); err != nil { if err := overlay.StartConsumingPackets(localPeer, peers, consumer); err != nil {
return err return err
@@ -76,7 +78,7 @@ type namedOverlay struct {
// Find the common set of overlays supported by both sides, with the // Find the common set of overlays supported by both sides, with the
// ordering being the same on both sides too. // ordering being the same on both sides too.
func (osw *OverlaySwitch) commonOverlays(params OverlayConnectionParams) ([]namedOverlay, error) { func (osw *OverlaySwitch) commonOverlays(params mesh.OverlayConnectionParams) ([]namedOverlay, error) {
var peerOverlays []string var peerOverlays []string
if overlaysFeature, present := params.Features["Overlays"]; present { if overlaysFeature, present := params.Features["Overlays"]; present {
peerOverlays = strings.Split(overlaysFeature, " ") peerOverlays = strings.Split(overlaysFeature, " ")
@@ -118,7 +120,7 @@ func (osw *OverlaySwitch) commonOverlays(params OverlayConnectionParams) ([]name
} }
type overlaySwitchForwarder struct { type overlaySwitchForwarder struct {
remotePeer *Peer remotePeer *mesh.Peer
lock sync.Mutex lock sync.Mutex
@@ -160,7 +162,7 @@ type subForwarderEvent struct {
err error err error
} }
func (osw *OverlaySwitch) PrepareConnection(params OverlayConnectionParams) (OverlayConnection, error) { func (osw *OverlaySwitch) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {
if _, present := params.Features["Overlays"]; !present && osw.compatOverlay != nil { if _, present := params.Features["Overlays"]; !present && osw.compatOverlay != nil {
return osw.compatOverlay.PrepareConnection(params) return osw.compatOverlay.PrepareConnection(params)
} }
@@ -197,7 +199,7 @@ func (osw *OverlaySwitch) PrepareConnection(params OverlayConnectionParams) (Ove
xmsg[0] = byte(index) xmsg[0] = byte(index)
xmsg[1] = tag xmsg[1] = tag
copy(xmsg[2:], msg) copy(xmsg[2:], msg)
return origSendControlMessage(ProtocolOverlayControlMsg, xmsg) return origSendControlMessage(mesh.ProtocolOverlayControlMsg, xmsg)
} }
subConn, err := overlay.PrepareConnection(params) subConn, err := overlay.PrepareConnection(params)
+22 -20
View File
@@ -18,6 +18,8 @@ import (
"github.com/google/gopacket" "github.com/google/gopacket"
"github.com/google/gopacket/layers" "github.com/google/gopacket/layers"
"github.com/weaveworks/weave/mesh"
) )
// This diagram explains the various arithmetic and variables related // This diagram explains the various arithmetic and variables related
@@ -61,21 +63,21 @@ type SleeveOverlay struct {
// These fields are set in StartConsumingPackets, and not // These fields are set in StartConsumingPackets, and not
// subsequently modified // subsequently modified
localPeer *Peer localPeer *mesh.Peer
localPeerBin []byte localPeerBin []byte
consumer OverlayConsumer consumer OverlayConsumer
peers *Peers peers *mesh.Peers
conn *net.UDPConn conn *net.UDPConn
lock sync.Mutex lock sync.Mutex
forwarders map[PeerName]*sleeveForwarder forwarders map[mesh.PeerName]*sleeveForwarder
} }
func NewSleeveOverlay(localPort int) NetworkOverlay { func NewSleeveOverlay(localPort int) NetworkOverlay {
return &SleeveOverlay{localPort: localPort} return &SleeveOverlay{localPort: localPort}
} }
func (sleeve *SleeveOverlay) StartConsumingPackets(localPeer *Peer, peers *Peers, consumer OverlayConsumer) error { func (sleeve *SleeveOverlay) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {
localAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprint(":", sleeve.localPort)) localAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprint(":", sleeve.localPort))
if err != nil { if err != nil {
return err return err
@@ -114,7 +116,7 @@ func (sleeve *SleeveOverlay) StartConsumingPackets(localPeer *Peer, peers *Peers
sleeve.consumer = consumer sleeve.consumer = consumer
sleeve.peers = peers sleeve.peers = peers
sleeve.conn = conn sleeve.conn = conn
sleeve.forwarders = make(map[PeerName]*sleeveForwarder) sleeve.forwarders = make(map[mesh.PeerName]*sleeveForwarder)
go sleeve.readUDP() go sleeve.readUDP()
return nil return nil
} }
@@ -135,19 +137,19 @@ func (*SleeveOverlay) Diagnostics() interface{} {
return nil return nil
} }
func (sleeve *SleeveOverlay) lookupForwarder(peer PeerName) *sleeveForwarder { func (sleeve *SleeveOverlay) lookupForwarder(peer mesh.PeerName) *sleeveForwarder {
sleeve.lock.Lock() sleeve.lock.Lock()
defer sleeve.lock.Unlock() defer sleeve.lock.Unlock()
return sleeve.forwarders[peer] return sleeve.forwarders[peer]
} }
func (sleeve *SleeveOverlay) addForwarder(peer PeerName, fwd *sleeveForwarder) { func (sleeve *SleeveOverlay) addForwarder(peer mesh.PeerName, fwd *sleeveForwarder) {
sleeve.lock.Lock() sleeve.lock.Lock()
defer sleeve.lock.Unlock() defer sleeve.lock.Unlock()
sleeve.forwarders[peer] = fwd sleeve.forwarders[peer] = fwd
} }
func (sleeve *SleeveOverlay) removeForwarder(peer PeerName, fwd *sleeveForwarder) { func (sleeve *SleeveOverlay) removeForwarder(peer mesh.PeerName, fwd *sleeveForwarder) {
sleeve.lock.Lock() sleeve.lock.Lock()
defer sleeve.lock.Unlock() defer sleeve.lock.Unlock()
if sleeve.forwarders[peer] == fwd { if sleeve.forwarders[peer] == fwd {
@@ -172,7 +174,7 @@ func (sleeve *SleeveOverlay) readUDP() {
continue continue
} }
fwdName := PeerNameFromBin(buf[:NameSize]) fwdName := mesh.PeerNameFromBin(buf[:NameSize])
fwd := sleeve.lookupForwarder(fwdName) fwd := sleeve.lookupForwarder(fwdName)
if fwd == nil { if fwd == nil {
continue continue
@@ -212,8 +214,8 @@ func (sleeve *SleeveOverlay) handleFrame(sender *net.UDPAddr, fwd *sleeveForward
return return
} }
srcPeer := sleeve.peers.Fetch(PeerNameFromBin(src)) srcPeer := sleeve.peers.Fetch(mesh.PeerNameFromBin(src))
dstPeer := sleeve.peers.Fetch(PeerNameFromBin(dst)) dstPeer := sleeve.peers.Fetch(mesh.PeerNameFromBin(dst))
if srcPeer == nil || dstPeer == nil { if srcPeer == nil || dstPeer == nil {
return return
} }
@@ -240,7 +242,7 @@ func (sleeve *SleeveOverlay) handleFrame(sender *net.UDPAddr, fwd *sleeveForward
sleeve.sendToConsumer(srcPeer, dstPeer, frame, dec) sleeve.sendToConsumer(srcPeer, dstPeer, frame, dec)
} }
func (sleeve *SleeveOverlay) sendToConsumer(srcPeer, dstPeer *Peer, frame []byte, dec *EthernetDecoder) { func (sleeve *SleeveOverlay) sendToConsumer(srcPeer, dstPeer *mesh.Peer, frame []byte, dec *EthernetDecoder) {
if sleeve.consumer == nil { if sleeve.consumer == nil {
return return
} }
@@ -282,7 +284,7 @@ type sleeveCrypto struct {
type sleeveForwarder struct { type sleeveForwarder struct {
// Immutable // Immutable
sleeve *SleeveOverlay sleeve *SleeveOverlay
remotePeer *Peer remotePeer *mesh.Peer
remotePeerBin []byte remotePeerBin []byte
sendControlMsg func(byte, []byte) error sendControlMsg func(byte, []byte) error
connUID uint64 connUID uint64
@@ -349,7 +351,7 @@ type controlMessage struct {
msg []byte msg []byte
} }
func (sleeve *SleeveOverlay) PrepareConnection(params OverlayConnectionParams) (OverlayConnection, error) { func (sleeve *SleeveOverlay) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {
name := sleeve.localPeer.NameByte name := sleeve.localPeer.NameByte
var crypto sleeveCrypto var crypto sleeveCrypto
if params.SessionKey != nil { if params.SessionKey != nil {
@@ -759,13 +761,13 @@ func (fwd *sleeveForwarder) handleSpecialFrame(special specialFrame) error {
func (fwd *sleeveForwarder) handleControlMessage(cm controlMessage) error { func (fwd *sleeveForwarder) handleControlMessage(cm controlMessage) error {
switch cm.tag { switch cm.tag {
case ProtocolConnectionEstablished: case mesh.ProtocolConnectionEstablished:
return fwd.handleHeartbeatAck() return fwd.handleHeartbeatAck()
case ProtocolFragmentationReceived: case mesh.ProtocolFragmentationReceived:
return fwd.handleFragTestAck() return fwd.handleFragTestAck()
case ProtocolPMTUVerified: case mesh.ProtocolPMTUVerified:
return fwd.handleMTUTestAck(cm.msg) return fwd.handleMTUTestAck(cm.msg)
default: default:
@@ -834,7 +836,7 @@ func (fwd *sleeveForwarder) handleHeartbeat(special specialFrame) error {
if !fwd.ackedHeartbeat { if !fwd.ackedHeartbeat {
fwd.ackedHeartbeat = true fwd.ackedHeartbeat = true
if err := fwd.sendControlMsg(ProtocolConnectionEstablished, nil); err != nil { if err := fwd.sendControlMsg(mesh.ProtocolConnectionEstablished, nil); err != nil {
return err return err
} }
} }
@@ -895,7 +897,7 @@ func (fwd *sleeveForwarder) handleFragTest(frame []byte) error {
return nil return nil
} }
return fwd.sendControlMsg(ProtocolFragmentationReceived, nil) return fwd.sendControlMsg(mesh.ProtocolFragmentationReceived, nil)
} }
func (fwd *sleeveForwarder) handleFragTestAck() error { func (fwd *sleeveForwarder) handleFragTestAck() error {
@@ -941,7 +943,7 @@ func (fwd *sleeveForwarder) sendMTUTest() error {
func (fwd *sleeveForwarder) handleMTUTest(frame []byte) error { func (fwd *sleeveForwarder) handleMTUTest(frame []byte) error {
buf := make([]byte, 2) buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, uint16(len(frame)-EthernetOverhead)) binary.BigEndian.PutUint16(buf, uint16(len(frame)-EthernetOverhead))
return fwd.sendControlMsg(ProtocolPMTUVerified, buf) return fwd.sendControlMsg(mesh.ProtocolPMTUVerified, buf)
} }
func (fwd *sleeveForwarder) handleMTUTestAck(msg []byte) error { func (fwd *sleeveForwarder) handleMTUTestAck(msg []byte) error {
+16 -16
View File
@@ -7,21 +7,21 @@ import (
"time" "time"
"github.com/weaveworks/weave/common" "github.com/weaveworks/weave/common"
"github.com/weaveworks/weave/router" "github.com/weaveworks/weave/mesh"
) )
// Router to convey gossip from one gossiper to another, for testing // Router to convey gossip from one gossiper to another, for testing
type unicastMessage struct { type unicastMessage struct {
sender router.PeerName sender mesh.PeerName
buf []byte buf []byte
} }
type broadcastMessage struct { type broadcastMessage struct {
sender router.PeerName sender mesh.PeerName
data router.GossipData data mesh.GossipData
} }
type gossipMessage struct { type gossipMessage struct {
sender router.PeerName sender mesh.PeerName
data router.GossipData data mesh.GossipData
} }
type exitMessage struct { type exitMessage struct {
exitChan chan struct{} exitChan chan struct{}
@@ -31,12 +31,12 @@ type flushMessage struct {
} }
type TestRouter struct { type TestRouter struct {
gossipChans map[router.PeerName]chan interface{} gossipChans map[mesh.PeerName]chan interface{}
loss float32 // 0.0 means no loss loss float32 // 0.0 means no loss
} }
func NewTestRouter(loss float32) *TestRouter { func NewTestRouter(loss float32) *TestRouter {
return &TestRouter{make(map[router.PeerName]chan interface{}, 100), loss} return &TestRouter{make(map[mesh.PeerName]chan interface{}, 100), loss}
} }
func (grouter *TestRouter) Stop() { func (grouter *TestRouter) Stop() {
@@ -45,7 +45,7 @@ func (grouter *TestRouter) Stop() {
} }
} }
func (grouter *TestRouter) gossipBroadcast(sender router.PeerName, update router.GossipData) error { func (grouter *TestRouter) gossipBroadcast(sender mesh.PeerName, update mesh.GossipData) error {
for _, gossipChan := range grouter.gossipChans { for _, gossipChan := range grouter.gossipChans {
select { select {
case gossipChan <- broadcastMessage{sender: sender, data: update}: case gossipChan <- broadcastMessage{sender: sender, data: update}:
@@ -56,7 +56,7 @@ func (grouter *TestRouter) gossipBroadcast(sender router.PeerName, update router
return nil return nil
} }
func (grouter *TestRouter) gossip(sender router.PeerName, update router.GossipData) error { func (grouter *TestRouter) gossip(sender mesh.PeerName, update mesh.GossipData) error {
count := int(math.Log2(float64(len(grouter.gossipChans)))) count := int(math.Log2(float64(len(grouter.gossipChans))))
for dest, gossipChan := range grouter.gossipChans { for dest, gossipChan := range grouter.gossipChans {
if dest == sender { if dest == sender {
@@ -83,7 +83,7 @@ func (grouter *TestRouter) Flush() {
} }
} }
func (grouter *TestRouter) RemovePeer(peer router.PeerName) { func (grouter *TestRouter) RemovePeer(peer mesh.PeerName) {
gossipChan := grouter.gossipChans[peer] gossipChan := grouter.gossipChans[peer]
resultChan := make(chan struct{}) resultChan := make(chan struct{})
gossipChan <- exitMessage{exitChan: resultChan} gossipChan <- exitMessage{exitChan: resultChan}
@@ -93,10 +93,10 @@ func (grouter *TestRouter) RemovePeer(peer router.PeerName) {
type TestRouterClient struct { type TestRouterClient struct {
router *TestRouter router *TestRouter
sender router.PeerName sender mesh.PeerName
} }
func (grouter *TestRouter) run(sender router.PeerName, gossiper router.Gossiper, gossipChan chan interface{}) { func (grouter *TestRouter) run(sender mesh.PeerName, gossiper mesh.Gossiper, gossipChan chan interface{}) {
gossipTimer := time.Tick(2 * time.Second) gossipTimer := time.Tick(2 * time.Second)
for { for {
select { select {
@@ -155,7 +155,7 @@ func (grouter *TestRouter) run(sender router.PeerName, gossiper router.Gossiper,
} }
} }
func (grouter *TestRouter) Connect(sender router.PeerName, gossiper router.Gossiper) router.Gossip { func (grouter *TestRouter) Connect(sender mesh.PeerName, gossiper mesh.Gossiper) mesh.Gossip {
gossipChan := make(chan interface{}, 100) gossipChan := make(chan interface{}, 100)
go grouter.run(sender, gossiper, gossipChan) go grouter.run(sender, gossiper, gossipChan)
@@ -164,7 +164,7 @@ func (grouter *TestRouter) Connect(sender router.PeerName, gossiper router.Gossi
return TestRouterClient{grouter, sender} return TestRouterClient{grouter, sender}
} }
func (client TestRouterClient) GossipUnicast(dstPeerName router.PeerName, buf []byte) error { func (client TestRouterClient) GossipUnicast(dstPeerName mesh.PeerName, buf []byte) error {
select { select {
case client.router.gossipChans[dstPeerName] <- unicastMessage{sender: client.sender, buf: buf}: case client.router.gossipChans[dstPeerName] <- unicastMessage{sender: client.sender, buf: buf}:
default: // drop the message if we cannot send it default: // drop the message if we cannot send it
@@ -173,6 +173,6 @@ func (client TestRouterClient) GossipUnicast(dstPeerName router.PeerName, buf []
return nil return nil
} }
func (client TestRouterClient) GossipBroadcast(update router.GossipData) error { func (client TestRouterClient) GossipBroadcast(update mesh.GossipData) error {
return client.router.gossipBroadcast(client.sender, update) return client.router.gossipBroadcast(client.sender, update)
} }