routing.go 9.13 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package dht

import (
4
	"bytes"
5
	"encoding/json"
6
	"errors"
7
	"math/rand"
8
	"sync"
9
	"time"
10

11 12
	proto "code.google.com/p/goprotobuf/proto"

13 14
	ma "github.com/jbenet/go-multiaddr"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	peer "github.com/jbenet/go-ipfs/peer"
16
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
	swarm "github.com/jbenet/go-ipfs/swarm"
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
)

21 22 23
// Pool size is the number of nodes used for group find/set RPC calls
var PoolSize = 6

Jeromy's avatar
Jeromy committed
24 25 26 27 28 29
// We put the 'K' in kademlia!
var KValue = 10

// Its in the paper, i swear
var AlphaValue = 3

30
// GenerateMessageID creates and returns a new message ID
31 32
// TODO: determine a way of creating and managing message IDs
func GenerateMessageID() uint64 {
33
	return (uint64(rand.Uint32()) << 32) | uint64(rand.Uint32())
34 35
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36 37 38 39 40
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
41
// This is the top level "Store" operation of the DHT
42
func (dht *IpfsDHT) PutValue(key u.Key, value []byte) {
Jeromy's avatar
Jeromy committed
43
	complete := make(chan struct{})
Jeromy's avatar
Jeromy committed
44
	count := 0
45
	for _, route := range dht.routingTables {
Jeromy's avatar
Jeromy committed
46 47 48
		peers := route.NearestPeers(kb.ConvertKey(key), KValue)
		for _, p := range peers {
			if p == nil {
49
				dht.network.Error(kb.ErrLookupFailure)
Jeromy's avatar
Jeromy committed
50 51 52 53
				continue
			}
			count++
			go func(sp *peer.Peer) {
54
				err := dht.putValueToNetwork(sp, string(key), value)
Jeromy's avatar
Jeromy committed
55
				if err != nil {
56
					dht.network.Error(err)
Jeromy's avatar
Jeromy committed
57
				}
Jeromy's avatar
Jeromy committed
58
				complete <- struct{}{}
Jeromy's avatar
Jeromy committed
59
			}(p)
Jeromy's avatar
Jeromy committed
60 61
		}
	}
Jeromy's avatar
Jeromy committed
62
	for i := 0; i < count; i++ {
Jeromy's avatar
Jeromy committed
63
		<-complete
64
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
}

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
// A counter for incrementing a variable across multiple threads
type counter struct {
	n   int
	mut sync.RWMutex
}

func (c *counter) Increment() {
	c.mut.Lock()
	c.n++
	c.mut.Unlock()
}

func (c *counter) Decrement() {
	c.mut.Lock()
	c.n--
	c.mut.Unlock()
}

func (c *counter) Size() int {
	c.mut.RLock()
	defer c.mut.RUnlock()
	return c.n
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
type peerSet struct {
	ps map[string]bool
	lk sync.RWMutex
}

func newPeerSet() *peerSet {
	ps := new(peerSet)
	ps.ps = make(map[string]bool)
	return ps
}

func (ps *peerSet) Add(p *peer.Peer) {
	ps.lk.Lock()
	ps.ps[string(p.ID)] = true
	ps.lk.Unlock()
}

func (ps *peerSet) Contains(p *peer.Peer) bool {
	ps.lk.RLock()
	_, ok := ps.ps[string(p.ID)]
	ps.lk.RUnlock()
	return ok
}

func (ps *peerSet) Size() int {
	ps.lk.RLock()
	defer ps.lk.RUnlock()
	return len(ps.ps)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
122 123
// If the search does not succeed, a multiaddr string of a closer peer is
// returned along with util.ErrSearchIncomplete
124 125
func (dht *IpfsDHT) GetValue(key u.Key, timeout time.Duration) ([]byte, error) {
	ll := startNewRPC("GET")
Jeromy's avatar
Jeromy committed
126 127 128 129
	defer func() {
		ll.EndLog()
		ll.Print()
	}()
130

Jeromy's avatar
Jeromy committed
131 132
	// If we have it local, dont bother doing an RPC!
	// NOTE: this might not be what we want to do...
133
	val, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
134 135 136
	if err == nil {
		ll.Success = true
		u.DOut("Found local, returning.")
Jeromy's avatar
Jeromy committed
137 138 139
		return val, nil
	}

140 141
	routeLevel := 0
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertKey(key), PoolSize)
142
	if closest == nil || len(closest) == 0 {
143 144 145
		return nil, kb.ErrLookupFailure
	}

146 147 148 149
	valChan := make(chan []byte)
	npeerChan := make(chan *peer.Peer, 30)
	procPeer := make(chan *peer.Peer, 30)
	errChan := make(chan error)
150
	after := time.After(timeout)
151
	pset := newPeerSet()
152

153
	for _, p := range closest {
154
		pset.Add(p)
155
		npeerChan <- p
156
	}
157

158 159 160 161 162 163
	c := counter{}

	count := 0
	go func() {
		for {
			select {
164
			case p := <-npeerChan:
165
				count++
Jeromy's avatar
Jeromy committed
166
				if count >= KValue {
167
					break
Jeromy's avatar
Jeromy committed
168
				}
169
				c.Increment()
170

171
				procPeer <- p
172 173
			default:
				if c.Size() == 0 {
174
					errChan <- u.ErrNotFound
175
				}
176 177 178
			}
		}
	}()
179

180 181 182
	process := func() {
		for {
			select {
183
			case p, ok := <-procPeer:
184 185 186 187
				if !ok || p == nil {
					c.Decrement()
					return
				}
188
				val, peers, err := dht.getValueOrPeers(p, key, timeout/4, routeLevel)
189
				if err != nil {
190
					u.DErr("%v\n", err.Error())
191
					c.Decrement()
Jeromy's avatar
Jeromy committed
192
					continue
193
				}
194
				if val != nil {
195
					valChan <- val
196 197 198 199 200 201
					c.Decrement()
					return
				}

				for _, np := range peers {
					// TODO: filter out peers that arent closer
Jeromy's avatar
Jeromy committed
202
					if !pset.Contains(np) && pset.Size() < KValue {
203
						pset.Add(np) //This is racey... make a single function to do operation
204
						npeerChan <- np
205
					}
206 207
				}
				c.Decrement()
208
			}
209
		}
210
	}
211

Jeromy's avatar
Jeromy committed
212
	for i := 0; i < AlphaValue; i++ {
213 214 215 216
		go process()
	}

	select {
217
	case val := <-valChan:
218
		return val, nil
219
	case err := <-errChan:
220 221 222 223
		return nil, err
	case <-after:
		return nil, u.ErrTimeout
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226 227 228
}

// Value provider layer of indirection.
// This is what DSHTs (Coral and MainlineDHT) do to store large values in a DHT.

229 230 231
// Provide makes this node announce that it can provide a value for the given key
func (dht *IpfsDHT) Provide(key u.Key) error {
	peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), PoolSize)
232
	if len(peers) == 0 {
233
		return kb.ErrLookupFailure
234 235
	}

236
	pmes := Message{
237 238
		Type: PBDHTMessage_ADD_PROVIDER,
		Key:  string(key),
239 240 241
	}
	pbmes := pmes.ToProtobuf()

242
	for _, p := range peers {
243
		mes := swarm.NewMessage(p, pbmes)
244
		dht.network.Send(mes)
245 246
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249
}

// FindProviders searches for peers who can provide the value for given key.
250 251
func (dht *IpfsDHT) FindProviders(key u.Key, timeout time.Duration) ([]*peer.Peer, error) {
	ll := startNewRPC("FindProviders")
Jeromy's avatar
Jeromy committed
252 253 254 255
	defer func() {
		ll.EndLog()
		ll.Print()
	}()
256
	u.DOut("Find providers for: '%s'\n", key)
257
	p := dht.routingTables[0].NearestPeer(kb.ConvertKey(key))
258 259 260
	if p == nil {
		return nil, kb.ErrLookupFailure
	}
261

262 263
	for level := 0; level < len(dht.routingTables); {
		pmes, err := dht.findProvidersSingle(p, key, level, timeout)
264 265 266
		if err != nil {
			return nil, err
		}
Jeromy's avatar
Jeromy committed
267
		if pmes.GetSuccess() {
268
			provs := dht.addPeerList(key, pmes.GetPeers())
Jeromy's avatar
Jeromy committed
269 270
			ll.Success = true
			return provs, nil
271
		}
272

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
		closer := pmes.GetPeers()
		if len(closer) == 0 {
			level++
			continue
		}
		if peer.ID(closer[0].GetId()).Equal(dht.self.ID) {
			u.DOut("Got myself back as a closer peer.")
			return nil, u.ErrNotFound
		}
		maddr, err := ma.NewMultiaddr(closer[0].GetAddr())
		if err != nil {
			// ??? Move up route level???
			panic("not yet implemented")
		}

		np, err := dht.network.GetConnection(peer.ID(closer[0].GetId()), maddr)
		if err != nil {
290
			u.PErr("[%s] Failed to connect to: %s\n", dht.self.ID.Pretty(), closer[0].GetAddr())
291 292
			level++
			continue
Jeromy's avatar
Jeromy committed
293
		}
294
		p = np
295
	}
Jeromy's avatar
Jeromy committed
296
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
297 298 299 300 301
}

// Find specific Peer

// FindPeer searches for a peer with given ID.
302
func (dht *IpfsDHT) FindPeer(id peer.ID, timeout time.Duration) (*peer.Peer, error) {
303
	// Check if were already connected to them
304
	p, _ := dht.Find(id)
305 306 307 308
	if p != nil {
		return p, nil
	}

309 310
	routeLevel := 0
	p = dht.routingTables[routeLevel].NearestPeer(kb.ConvertPeerID(id))
311 312
	if p == nil {
		return nil, kb.ErrLookupFailure
313
	}
314 315 316
	if p.ID.Equal(id) {
		return p, nil
	}
317

318 319
	for routeLevel < len(dht.routingTables) {
		pmes, err := dht.findPeerSingle(p, id, timeout, routeLevel)
320 321
		plist := pmes.GetPeers()
		if len(plist) == 0 {
322
			routeLevel++
323
		}
324 325 326
		found := plist[0]

		addr, err := ma.NewMultiaddr(found.GetAddr())
Jeromy's avatar
Jeromy committed
327
		if err != nil {
328
			return nil, err
Jeromy's avatar
Jeromy committed
329 330
		}

331
		nxtPeer, err := dht.network.GetConnection(peer.ID(found.GetId()), addr)
Jeromy's avatar
Jeromy committed
332
		if err != nil {
333
			return nil, err
Jeromy's avatar
Jeromy committed
334
		}
335
		if pmes.GetSuccess() {
336 337 338
			if !id.Equal(nxtPeer.ID) {
				return nil, errors.New("got back invalid peer from 'successful' response")
			}
339
			return nxtPeer, nil
Jeromy's avatar
Jeromy committed
340
		}
341
		p = nxtPeer
342
	}
343
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
344
}
345 346 347 348 349 350

// Ping a peer, log the time it took
func (dht *IpfsDHT) Ping(p *peer.Peer, timeout time.Duration) error {
	// Thoughts: maybe this should accept an ID and do a peer lookup?
	u.DOut("Enter Ping.")

351
	pmes := Message{ID: GenerateMessageID(), Type: PBDHTMessage_PING}
352 353 354
	mes := swarm.NewMessage(p, pmes.ToProtobuf())

	before := time.Now()
355
	responseChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
356
	dht.network.Send(mes)
357 358 359

	tout := time.After(timeout)
	select {
360
	case <-responseChan:
361
		roundtrip := time.Since(before)
362
		p.SetLatency(roundtrip)
363
		u.DOut("Ping took %s.\n", roundtrip.String())
364 365 366 367
		return nil
	case <-tout:
		// Timed out, think about removing peer from network
		u.DOut("Ping peer timed out.")
368
		dht.listener.Unlisten(pmes.ID)
369 370 371
		return u.ErrTimeout
	}
}
372

373
func (dht *IpfsDHT) getDiagnostic(timeout time.Duration) ([]*diagInfo, error) {
374 375
	u.DOut("Begin Diagnostic")
	//Send to N closest peers
376
	targets := dht.routingTables[0].NearestPeers(kb.ConvertPeerID(dht.self.ID), 10)
377 378

	// TODO: Add timeout to this struct so nodes know when to return
379
	pmes := Message{
380
		Type: PBDHTMessage_DIAGNOSTIC,
381
		ID:   GenerateMessageID(),
382 383
	}

384
	listenChan := dht.listener.Listen(pmes.ID, len(targets), time.Minute*2)
385 386

	pbmes := pmes.ToProtobuf()
387
	for _, p := range targets {
388
		mes := swarm.NewMessage(p, pbmes)
389
		dht.network.Send(mes)
390 391 392 393 394 395 396 397 398
	}

	var out []*diagInfo
	after := time.After(timeout)
	for count := len(targets); count > 0; {
		select {
		case <-after:
			u.DOut("Diagnostic request timed out.")
			return out, u.ErrTimeout
Jeromy's avatar
Jeromy committed
399
		case resp := <-listenChan:
400 401
			pmesOut := new(PBDHTMessage)
			err := proto.Unmarshal(resp.Data, pmesOut)
402 403 404 405 406 407
			if err != nil {
				// NOTE: here and elsewhere, need to audit error handling,
				//		some errors should be continued on from
				return out, err
			}

408
			dec := json.NewDecoder(bytes.NewBuffer(pmesOut.GetValue()))
409 410 411 412 413 414 415 416 417 418 419 420
			for {
				di := new(diagInfo)
				err := dec.Decode(di)
				if err != nil {
					break
				}

				out = append(out, di)
			}
		}
	}

421
	return nil, nil
422
}