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 168
					errChan <- u.ErrNotFound
					return
Jeromy's avatar
Jeromy committed
169
				}
170
				c.Increment()
171

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

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

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

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

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

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

228 229 230
// 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)
231
	if len(peers) == 0 {
232
		return kb.ErrLookupFailure
233 234
	}

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

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

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

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

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
		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 {
289
			u.PErr("[%s] Failed to connect to: %s\n", dht.self.ID.Pretty(), closer[0].GetAddr())
290 291
			level++
			continue
Jeromy's avatar
Jeromy committed
292
		}
293
		p = np
294
	}
Jeromy's avatar
Jeromy committed
295
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296 297 298 299 300
}

// Find specific Peer

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

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

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

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

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

// 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.")

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

	before := time.Now()
354
	responseChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
355
	dht.netChan.Outgoing <- mes
356 357 358

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

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

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

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

	pbmes := pmes.ToProtobuf()
386
	for _, p := range targets {
387
		mes := swarm.NewMessage(p, pbmes)
388
		dht.netChan.Outgoing <- mes
389 390 391 392 393 394 395 396 397
	}

	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
398
		case resp := <-listenChan:
399 400
			pmesOut := new(PBDHTMessage)
			err := proto.Unmarshal(resp.Data, pmesOut)
401 402 403 404 405 406
			if err != nil {
				// NOTE: here and elsewhere, need to audit error handling,
				//		some errors should be continued on from
				return out, err
			}

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

				out = append(out, di)
			}
		}
	}

420
	return nil, nil
421
}