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

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

10
	peer "github.com/ipfs/go-ipfs/p2p/peer"
Jeromy's avatar
Jeromy committed
11
	logging "github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log"
12 13
)

Jeromy's avatar
Jeromy committed
14
var log = logging.Logger("table")
15

16 17 18 19 20 21 22 23 24
// 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

25 26 27
	// latency metrics
	metrics peer.Metrics

28 29 30
	// Maximum acceptable latency for peers in this cluster
	maxLatency time.Duration

31
	// kBuckets define all the fingers to other nodes.
Jeromy's avatar
Jeromy committed
32
	Buckets    []*Bucket
33 34 35
	bucketsize int
}

Chas Leichner's avatar
Chas Leichner committed
36
// NewRoutingTable creates a new routing table with a given bucketsize, local ID, and latency tolerance.
37
func NewRoutingTable(bucketsize int, localID ID, latency time.Duration, m peer.Metrics) *RoutingTable {
38
	rt := new(RoutingTable)
39
	rt.Buckets = []*Bucket{newBucket()}
40
	rt.bucketsize = bucketsize
41
	rt.local = localID
42
	rt.maxLatency = latency
43
	rt.metrics = m
44 45 46 47 48
	return rt
}

// Update adds or moves the given peer to the front of its respective bucket
// If a peer gets removed from a bucket, it is returned
49
func (rt *RoutingTable) Update(p peer.ID) {
50 51
	rt.tabLock.Lock()
	defer rt.tabLock.Unlock()
52
	peerID := ConvertPeerID(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53
	cpl := commonPrefixLen(peerID, rt.local)
54

55 56 57
	bucketID := cpl
	if bucketID >= len(rt.Buckets) {
		bucketID = len(rt.Buckets) - 1
58 59
	}

60
	bucket := rt.Buckets[bucketID]
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
	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)
		return
	}

	if rt.metrics.LatencyEWMA(p) > rt.maxLatency {
		// Connection doesnt meet requirements, skip!
		return
	}

	// New peer, add to bucket
	bucket.PushFront(p)

	// Are we past the max bucket size?
	if bucket.Len() > rt.bucketsize {
		// If this bucket is the rightmost bucket, and its full
		// we need to split it and create a new bucket
		if bucketID == len(rt.Buckets)-1 {
			rt.nextBucket()
			return
		} else {
			// If the bucket cant split kick out least active node
			bucket.PopBack()
			return
88 89 90 91
		}
	}
}

92 93 94 95 96 97 98 99 100 101 102 103 104 105
// 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]
106
	bucket.Remove(p)
107 108
}

109
func (rt *RoutingTable) nextBucket() peer.ID {
110 111 112
	bucket := rt.Buckets[len(rt.Buckets)-1]
	newBucket := bucket.Split(len(rt.Buckets)-1, rt.local)
	rt.Buckets = append(rt.Buckets, newBucket)
113
	if newBucket.Len() > rt.bucketsize {
114 115 116 117
		return rt.nextBucket()
	}

	// If all elements were on left side of split...
118 119
	if bucket.Len() > rt.bucketsize {
		return bucket.PopBack()
120
	}
121
	return ""
122 123
}

Jeromy's avatar
Jeromy committed
124
// Find a specific peer by ID or return nil
125
func (rt *RoutingTable) Find(id peer.ID) peer.ID {
Chas Leichner's avatar
Chas Leichner committed
126
	srch := rt.NearestPeers(ConvertPeerID(id), 1)
127 128
	if len(srch) == 0 || srch[0] != id {
		return ""
Jeromy's avatar
Jeromy committed
129 130 131 132
	}
	return srch[0]
}

133
// NearestPeer returns a single peer that is nearest to the given ID
134
func (rt *RoutingTable) NearestPeer(id ID) peer.ID {
135 136 137 138
	peers := rt.NearestPeers(id, 1)
	if len(peers) > 0 {
		return peers[0]
	}
139

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140
	log.Debugf("NearestPeer: Returning nil, table size = %d", rt.Size())
141
	return ""
142 143
}

144
// NearestPeers returns a list of the 'count' closest peers to the given ID
145
func (rt *RoutingTable) NearestPeers(id ID, count int) []peer.ID {
146 147
	rt.tabLock.RLock()
	defer rt.tabLock.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
	cpl := commonPrefixLen(id, rt.local)
149 150 151 152 153 154 155 156 157

	// 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]

	var peerArr peerSorterArr
158
	if bucket.Len() == 0 {
159 160 161
		// In the case of an unusual split, one bucket may be empty.
		// if this happens, search both surrounding buckets for nearest peer
		if cpl > 0 {
162
			plist := rt.Buckets[cpl-1].list
163 164 165
			peerArr = copyPeersFromList(id, peerArr, plist)
		}

Jeromy's avatar
Jeromy committed
166
		if cpl < len(rt.Buckets)-1 {
167
			plist := rt.Buckets[cpl+1].list
168 169 170
			peerArr = copyPeersFromList(id, peerArr, plist)
		}
	} else {
171
		peerArr = copyPeersFromList(id, peerArr, bucket.list)
172 173 174 175 176
	}

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

177
	var out []peer.ID
178 179 180 181 182 183 184
	for i := 0; i < count && i < peerArr.Len(); i++ {
		out = append(out, peerArr[i].p)
	}

	return out
}

185
// Size returns the total number of peers in the routing table
186 187
func (rt *RoutingTable) Size() int {
	var tot int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
	rt.tabLock.RLock()
Jeromy's avatar
Jeromy committed
189
	for _, buck := range rt.Buckets {
190
		tot += buck.Len()
191
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
	rt.tabLock.RUnlock()
193 194 195
	return tot
}

Chas Leichner's avatar
Chas Leichner committed
196
// ListPeers takes a RoutingTable and returns a list of all peers from all buckets in the table.
197
// NOTE: This is potentially unsafe... use at your own risk
198 199
func (rt *RoutingTable) ListPeers() []peer.ID {
	var peers []peer.ID
200
	rt.tabLock.RLock()
Jeromy's avatar
Jeromy committed
201
	for _, buck := range rt.Buckets {
202
		peers = append(peers, buck.Peers()...)
203
	}
204
	rt.tabLock.RUnlock()
205 206
	return peers
}
207

Chas Leichner's avatar
Chas Leichner committed
208 209
// Print prints a descriptive statement about the provided RoutingTable
func (rt *RoutingTable) Print() {
210 211
	fmt.Printf("Routing Table, bs = %d, Max latency = %d\n", rt.bucketsize, rt.maxLatency)
	rt.tabLock.RLock()
212 213 214 215 216 217 218 219 220 221

	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()
222
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
223
	rt.tabLock.RUnlock()
224
}