table.go 6.67 KB
Newer Older
1 2
// package kbucket implements a kademlia 'k-bucket' routing table.
package kbucket
3 4

import (
5
	"errors"
6
	"fmt"
7 8
	"sort"
	"sync"
9
	"time"
10

George Antoniadis's avatar
George Antoniadis committed
11
	logging "github.com/ipfs/go-log"
Jeromy's avatar
Jeromy committed
12 13
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
14 15
)

Jeromy's avatar
Jeromy committed
16
var log = logging.Logger("table")
17

18 19 20
var ErrPeerRejectedHighLatency = errors.New("peer rejected; latency too high")
var ErrPeerRejectedNoCapacity = errors.New("peer rejected; insufficient capacity")

21 22 23 24 25 26 27 28 29
// RoutingTable defines the routing table.
type RoutingTable struct {

	// ID of the local peer
	local ID

	// Blanket lock, refine later for better performance
	tabLock sync.RWMutex

30
	// latency metrics
Jeromy's avatar
Jeromy committed
31
	metrics pstore.Metrics
32

33 34 35
	// Maximum acceptable latency for peers in this cluster
	maxLatency time.Duration

36
	// kBuckets define all the fingers to other nodes.
Jeromy's avatar
Jeromy committed
37
	Buckets    []*Bucket
38
	bucketsize int
Jeromy's avatar
Jeromy committed
39 40 41 42

	// notification functions
	PeerRemoved func(peer.ID)
	PeerAdded   func(peer.ID)
43 44
}

Chas Leichner's avatar
Chas Leichner committed
45
// NewRoutingTable creates a new routing table with a given bucketsize, local ID, and latency tolerance.
Jeromy's avatar
Jeromy committed
46
func NewRoutingTable(bucketsize int, localID ID, latency time.Duration, m pstore.Metrics) *RoutingTable {
Jeromy's avatar
Jeromy committed
47 48 49 50 51 52 53 54 55 56
	rt := &RoutingTable{
		Buckets:     []*Bucket{newBucket()},
		bucketsize:  bucketsize,
		local:       localID,
		maxLatency:  latency,
		metrics:     m,
		PeerRemoved: func(peer.ID) {},
		PeerAdded:   func(peer.ID) {},
	}

57 58 59 60
	return rt
}

// Update adds or moves the given peer to the front of its respective bucket
61
func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
62
	peerID := ConvertPeerID(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
	cpl := commonPrefixLen(peerID, rt.local)
64

65 66
	rt.tabLock.Lock()
	defer rt.tabLock.Unlock()
67 68 69
	bucketID := cpl
	if bucketID >= len(rt.Buckets) {
		bucketID = len(rt.Buckets) - 1
70 71
	}

72
	bucket := rt.Buckets[bucketID]
73 74 75 76 77
	if bucket.Has(p) {
		// If the peer is already in the table, move it to the front.
		// This signifies that it it "more active" and the less active nodes
		// Will as a result tend towards the back of the list
		bucket.MoveToFront(p)
78
		return "", nil
79 80 81 82
	}

	if rt.metrics.LatencyEWMA(p) > rt.maxLatency {
		// Connection doesnt meet requirements, skip!
83 84 85 86 87 88 89 90
		return "", ErrPeerRejectedHighLatency
	}

	// We have enough space in the bucket (whether spawned or grouped).
	if bucket.Len() < rt.bucketsize {
		bucket.PushFront(p)
		rt.PeerAdded(p)
		return "", nil
91 92
	}

93 94 95 96 97 98 99 100 101 102 103 104
	if bucketID == len(rt.Buckets)-1 {
		// if the bucket is too large and this is the last bucket (i.e. wildcard), unfold it.
		rt.nextBucket()
		// the structure of the table has changed, so let's recheck if the peer now has a dedicated bucket.
		bucketID = cpl
		if bucketID >= len(rt.Buckets) {
			bucketID = len(rt.Buckets) - 1
		}
		bucket = rt.Buckets[bucketID]
		if bucket.Len() >= rt.bucketsize {
			// if after all the unfolding, we're unable to find room for this peer, scrap it.
			return "", ErrPeerRejectedNoCapacity
105
		}
106 107 108
		bucket.PushFront(p)
		rt.PeerAdded(p)
		return "", nil
109
	}
110 111

	return "", ErrPeerRejectedNoCapacity
112 113
}

114 115 116 117 118 119 120 121 122 123 124 125 126 127
// Remove deletes a peer from the routing table. This is to be used
// when we are sure a node has disconnected completely.
func (rt *RoutingTable) Remove(p peer.ID) {
	rt.tabLock.Lock()
	defer rt.tabLock.Unlock()
	peerID := ConvertPeerID(p)
	cpl := commonPrefixLen(peerID, rt.local)

	bucketID := cpl
	if bucketID >= len(rt.Buckets) {
		bucketID = len(rt.Buckets) - 1
	}

	bucket := rt.Buckets[bucketID]
128
	bucket.Remove(p)
Jeromy's avatar
Jeromy committed
129
	rt.PeerRemoved(p)
130 131
}

132
func (rt *RoutingTable) nextBucket() {
133 134 135
	// This is the last bucket, which allegedly is a mixed bag containing peers not belonging in dedicated (unfolded) buckets.
	// _allegedly_ is used here to denote that *all* peers in the last bucket might feasibly belong to another bucket.
	// This could happen if e.g. we've unfolded 4 buckets, and all peers in folded bucket 5 really belong in bucket 8.
136 137 138 139
	bucket := rt.Buckets[len(rt.Buckets)-1]
	newBucket := bucket.Split(len(rt.Buckets)-1, rt.local)
	rt.Buckets = append(rt.Buckets, newBucket)

140 141 142 143
	// The newly formed bucket still contains too many peers. We probably just unfolded a empty bucket.
	if newBucket.Len() >= rt.bucketsize {
		// Keep unfolding the table until the last bucket is not overflowing.
		rt.nextBucket()
144 145 146
	}
}

Jeromy's avatar
Jeromy committed
147
// Find a specific peer by ID or return nil
148
func (rt *RoutingTable) Find(id peer.ID) peer.ID {
Chas Leichner's avatar
Chas Leichner committed
149
	srch := rt.NearestPeers(ConvertPeerID(id), 1)
150 151
	if len(srch) == 0 || srch[0] != id {
		return ""
Jeromy's avatar
Jeromy committed
152 153 154 155
	}
	return srch[0]
}

156
// NearestPeer returns a single peer that is nearest to the given ID
157
func (rt *RoutingTable) NearestPeer(id ID) peer.ID {
158 159 160 161
	peers := rt.NearestPeers(id, 1)
	if len(peers) > 0 {
		return peers[0]
	}
162

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163
	log.Debugf("NearestPeer: Returning nil, table size = %d", rt.Size())
164
	return ""
165 166
}

167
// NearestPeers returns a list of the 'count' closest peers to the given ID
168
func (rt *RoutingTable) NearestPeers(id ID, count int) []peer.ID {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
	cpl := commonPrefixLen(id, rt.local)
170

Jeromy's avatar
Jeromy committed
171 172
	rt.tabLock.RLock()

173 174 175 176 177 178 179
	// Get bucket at cpl index or last bucket
	var bucket *Bucket
	if cpl >= len(rt.Buckets) {
		cpl = len(rt.Buckets) - 1
	}
	bucket = rt.Buckets[cpl]

180
	peerArr := make(peerSorterArr, 0, count)
181 182 183 184
	peerArr = copyPeersFromList(id, peerArr, bucket.list)
	if len(peerArr) < count {
		// In the case of an unusual split, one bucket may be short or empty.
		// if this happens, search both surrounding buckets for nearby peers
185
		if cpl > 0 {
186
			plist := rt.Buckets[cpl-1].list
187 188 189
			peerArr = copyPeersFromList(id, peerArr, plist)
		}

Jeromy's avatar
Jeromy committed
190
		if cpl < len(rt.Buckets)-1 {
191
			plist := rt.Buckets[cpl+1].list
192 193 194
			peerArr = copyPeersFromList(id, peerArr, plist)
		}
	}
Jeromy's avatar
Jeromy committed
195
	rt.tabLock.RUnlock()
196 197 198 199

	// Sort by distance to local peer
	sort.Sort(peerArr)

200 201 202 203 204 205 206
	if count < len(peerArr) {
		peerArr = peerArr[:count]
	}

	out := make([]peer.ID, 0, len(peerArr))
	for _, p := range peerArr {
		out = append(out, p.p)
207 208 209 210 211
	}

	return out
}

212
// Size returns the total number of peers in the routing table
213 214
func (rt *RoutingTable) Size() int {
	var tot int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
215
	rt.tabLock.RLock()
Jeromy's avatar
Jeromy committed
216
	for _, buck := range rt.Buckets {
217
		tot += buck.Len()
218
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
	rt.tabLock.RUnlock()
220 221 222
	return tot
}

Chas Leichner's avatar
Chas Leichner committed
223
// ListPeers takes a RoutingTable and returns a list of all peers from all buckets in the table.
224 225
func (rt *RoutingTable) ListPeers() []peer.ID {
	var peers []peer.ID
226
	rt.tabLock.RLock()
Jeromy's avatar
Jeromy committed
227
	for _, buck := range rt.Buckets {
228
		peers = append(peers, buck.Peers()...)
229
	}
230
	rt.tabLock.RUnlock()
231 232
	return peers
}
233

Chas Leichner's avatar
Chas Leichner committed
234 235
// Print prints a descriptive statement about the provided RoutingTable
func (rt *RoutingTable) Print() {
236 237
	fmt.Printf("Routing Table, bs = %d, Max latency = %d\n", rt.bucketsize, rt.maxLatency)
	rt.tabLock.RLock()
238 239 240 241 242 243 244 245 246 247

	for i, b := range rt.Buckets {
		fmt.Printf("\tbucket: %d\n", i)

		b.lk.RLock()
		for e := b.list.Front(); e != nil; e = e.Next() {
			p := e.Value.(peer.ID)
			fmt.Printf("\t\t- %s %s\n", p.Pretty(), rt.metrics.LatencyEWMA(p).String())
		}
		b.lk.RUnlock()
248
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249
	rt.tabLock.RUnlock()
250
}