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

import (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
4
	"math"
Jeromy's avatar
Jeromy committed
5
	"sync"
6
	"time"
7

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
9

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	inet "github.com/jbenet/go-ipfs/p2p/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
	peer "github.com/jbenet/go-ipfs/p2p/peer"
12
	"github.com/jbenet/go-ipfs/routing"
13
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
14
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
	errors "github.com/jbenet/go-ipfs/util/debugerror"
Jeromy's avatar
Jeromy committed
17
	pset "github.com/jbenet/go-ipfs/util/peerset"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
)

20 21 22 23 24 25
// asyncQueryBuffer is the size of buffered channels in async queries. This
// buffer allows multiple queries to execute simultaneously, return their
// results and continue querying closer peers. Note that different query
// results will wait for the channel to drain.
var asyncQueryBuffer = 10

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27 28 29 30
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
31
// This is the top level "Store" operation of the DHT
32
func (dht *IpfsDHT) PutValue(ctx context.Context, key u.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
34 35 36 37
	err := dht.putLocal(key, value)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38

Jeromy's avatar
Jeromy committed
39 40 41 42 43 44
	sk, err := dht.getOwnPrivateKey()
	if err != nil {
		return err
	}

	rec, err := MakePutRecord(sk, key, value)
45 46 47 48 49
	if err != nil {
		log.Error("Creation of record failed!")
		return err
	}

50
	pchan, err := dht.getClosestPeers(ctx, key)
51 52 53
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54

55 56 57 58 59
	wg := sync.WaitGroup{}
	for p := range pchan {
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Jeromy's avatar
Jeromy committed
60
			err := dht.putValueToPeer(ctx, p, key, rec)
61 62 63 64 65 66 67
			if err != nil {
				log.Errorf("failed putting value to peer: %s", err)
			}
		}(p)
	}
	wg.Wait()
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69 70
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
71 72
// If the search does not succeed, a multiaddr string of a closer peer is
// returned along with util.ErrSearchIncomplete
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74 75 76
	log := dht.log().Prefix("GetValue(%s)", key)
	log.Debugf("start")
	defer log.Debugf("end")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77

Jeromy's avatar
Jeromy committed
78
	// If we have it local, dont bother doing an RPC!
79
	val, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
80
	if err == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81
		log.Debug("have it locally")
Jeromy's avatar
Jeromy committed
82
		return val, nil
Jeromy's avatar
Jeromy committed
83 84
	} else {
		log.Debug("failed to get value locally: %s", err)
Jeromy's avatar
Jeromy committed
85 86
	}

87
	// get closest peers in the routing table
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88 89 90
	rtp := dht.routingTable.ListPeers()
	log.Debugf("peers in rt: %s", len(rtp), rtp)

91
	closest := dht.routingTable.NearestPeers(kb.ConvertKey(key), PoolSize)
92
	if closest == nil || len(closest) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
		log.Warning("No peers from routing table!")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94
		return nil, errors.Wrap(kb.ErrLookupFailure)
95 96
	}

97
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
99
		val, peers, err := dht.getValueOrPeers(ctx, p, key)
100 101 102
		if err != nil {
			return nil, err
		}
103

104 105 106 107 108 109 110
		res := &dhtQueryResult{value: val, closerPeers: peers}
		if val != nil {
			res.success = true
		}

		return res, nil
	})
111

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
	// run it!
113
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115
	if err != nil {
		return nil, err
116 117
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
	log.Debugf("GetValue %v %v", key, result.value)
119
	if result.value == nil {
120
		return nil, routing.ErrNotFound
121
	}
122 123

	return result.value, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125 126 127 128
}

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

129
// Provide makes this node announce that it can provide a value for the given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
func (dht *IpfsDHT) Provide(ctx context.Context, key u.Key) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
	log := dht.log().Prefix("Provide(%s)", key)
132

Jeromy's avatar
Jeromy committed
133
	defer log.EventBegin(ctx, "provide", &key).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135

	// add self locally
136
	dht.providers.AddProvider(key, dht.self)
137

138
	peers, err := dht.getClosestPeers(ctx, key)
139 140
	if err != nil {
		return err
141 142
	}

Jeromy's avatar
Jeromy committed
143
	wg := sync.WaitGroup{}
144
	for p := range peers {
Jeromy's avatar
Jeromy committed
145 146 147
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
			log.Debugf("putProvider(%s, %s)", key, p)
Jeromy's avatar
Jeromy committed
149 150 151 152 153
			err := dht.putProvider(ctx, p, string(key))
			if err != nil {
				log.Error(err)
			}
		}(p)
154
	}
Jeromy's avatar
Jeromy committed
155
	wg.Wait()
156
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157 158
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
159 160 161 162 163 164 165 166 167
// FindProviders searches until the context expires.
func (dht *IpfsDHT) FindProviders(ctx context.Context, key u.Key) ([]peer.PeerInfo, error) {
	var providers []peer.PeerInfo
	for p := range dht.FindProvidersAsync(ctx, key, math.MaxInt32) {
		providers = append(providers, p)
	}
	return providers, nil
}

168 169 170
// Kademlia 'node lookup' operation. Returns a channel of the K closest peers
// to the given key
func (dht *IpfsDHT) getClosestPeers(ctx context.Context, key u.Key) (<-chan peer.ID, error) {
171
	e := log.EventBegin(ctx, "getClosestPeers", &key)
172 173
	tablepeers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
	if len(tablepeers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174
		return nil, errors.Wrap(kb.ErrLookupFailure)
175 176
	}

177 178
	out := make(chan peer.ID, KValue)
	peerset := pset.NewLimited(KValue)
179 180

	for _, p := range tablepeers {
Jeromy's avatar
Jeromy committed
181 182 183 184 185
		select {
		case out <- p:
		case <-ctx.Done():
			return nil, ctx.Err()
		}
186 187 188
		peerset.Add(p)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
		closer, err := dht.closerPeersSingle(ctx, key, p)
		if err != nil {
			log.Errorf("error getting closer peers: %s", err)
			return nil, err
		}

		var filtered []peer.PeerInfo
		for _, p := range closer {
			if kb.Closer(p, dht.self, key) && peerset.TryAdd(p) {
				select {
				case out <- p:
				case <-ctx.Done():
					return nil, ctx.Err()
				}
				filtered = append(filtered, dht.peerstore.PeerInfo(p))
			}
		}

		return &dhtQueryResult{closerPeers: filtered}, nil
	})
210 211

	go func() {
Jeromy's avatar
Jeromy committed
212
		defer close(out)
213
		defer e.Done()
Jeromy's avatar
Jeromy committed
214 215 216 217 218
		// run it!
		_, err := query.Run(ctx, tablepeers)
		if err != nil {
			log.Errorf("closestPeers query run error: %s", err)
		}
219 220 221 222 223 224 225 226 227 228 229 230 231 232
	}()

	return out, nil
}

func (dht *IpfsDHT) closerPeersSingle(ctx context.Context, key u.Key, p peer.ID) ([]peer.ID, error) {
	pmes, err := dht.findPeerSingle(ctx, p, peer.ID(key))
	if err != nil {
		return nil, err
	}

	var out []peer.ID
	for _, pbp := range pmes.GetCloserPeers() {
		pid := peer.ID(pbp.GetId())
233 234 235 236
		if pid != dht.self { // dont add self
			dht.peerstore.AddAddresses(pid, pbp.Addresses())
			out = append(out, pid)
		}
237 238 239 240
	}
	return out, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242 243
// FindProvidersAsync is the same thing as FindProviders, but returns a channel.
// Peers will be returned on the channel as soon as they are found, even before
// the search query completes.
244
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.PeerInfo {
245
	log.Event(ctx, "findProviders", &key)
246
	peerOut := make(chan peer.PeerInfo, count)
Jeromy's avatar
Jeromy committed
247 248 249 250
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

251
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key u.Key, count int, peerOut chan peer.PeerInfo) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253
	log := dht.log().Prefix("FindProviders(%s)", key)

Jeromy's avatar
Jeromy committed
254
	defer log.EventBegin(ctx, "findProvidersAsync", &key).Done()
Jeromy's avatar
Jeromy committed
255 256
	defer close(peerOut)

Jeromy's avatar
Jeromy committed
257
	ps := pset.NewLimited(count)
Jeromy's avatar
Jeromy committed
258 259 260
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
		// NOTE: assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
261
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
262
			select {
263
			case peerOut <- dht.peerstore.PeerInfo(p):
Jeromy's avatar
Jeromy committed
264 265 266
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
267
		}
Jeromy's avatar
Jeromy committed
268 269 270

		// If we have enough peers locally, dont bother with remote RPC
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
271 272 273 274 275
			return
		}
	}

	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277 278 279
		log := log.Prefix("Query(%s)", p)
		log.Debugf("begin")
		defer log.Debugf("end")
280

281
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
282 283 284 285
		if err != nil {
			return nil, err
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
287
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
289 290 291

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292
			log.Debugf("got provider: %s", prov)
293
			if ps.TryAdd(prov.ID) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294
				log.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
295 296 297 298 299 300
				select {
				case peerOut <- prov:
				case <-ctx.Done():
					log.Error("Context timed out sending more providers")
					return nil, ctx.Err()
				}
301
			}
Jeromy's avatar
Jeromy committed
302
			if ps.Size() >= count {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
303
				log.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
304
				return &dhtQueryResult{success: true}, nil
305 306 307
			}
		}

Jeromy's avatar
Jeromy committed
308 309
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
310
		clpeers := pb.PBPeersToPeerInfos(closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
		log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
Jeromy's avatar
Jeromy committed
312 313 314
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

315
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
Jeromy's avatar
Jeromy committed
316 317
	_, err := query.Run(ctx, peers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318
		log.Errorf("Query error: %s", err)
Jeromy's avatar
Jeromy committed
319
	}
320 321
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322
// FindPeer searches for a peer with given ID.
323
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (peer.PeerInfo, error) {
Jeromy's avatar
Jeromy committed
324
	defer log.EventBegin(ctx, "FindPeer", id).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
325

326
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
327
	if pi := dht.FindLocal(id); pi.ID != "" {
328
		return pi, nil
329 330
	}

331
	closest := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
Jeromy's avatar
Jeromy committed
332
	if closest == nil || len(closest) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
333
		return peer.PeerInfo{}, errors.Wrap(kb.ErrLookupFailure)
334
	}
335

Jeromy's avatar
Jeromy committed
336 337
	// Sanity...
	for _, p := range closest {
338
		if p == id {
Jeromy's avatar
Jeromy committed
339
			log.Error("Found target peer in list of closest peers...")
340
			return dht.peerstore.PeerInfo(p), nil
341
		}
342
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343

Jeromy's avatar
Jeromy committed
344
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345
	query := dht.newQuery(u.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
346

347
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
348
		if err != nil {
349
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350
		}
351

Jeromy's avatar
Jeromy committed
352
		closer := pmes.GetCloserPeers()
353
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
354

355
		// see it we got the peer here
356 357
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
358
				return &dhtQueryResult{
359
					peer:    npi,
Jeromy's avatar
Jeromy committed
360 361 362
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
363 364
		}

365
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
366
	})
367

Jeromy's avatar
Jeromy committed
368 369
	// run it!
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
370
	if err != nil {
371
		return peer.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
372 373
	}

374
	log.Debugf("FindPeer %v %v", id, result.success)
375 376
	if result.peer.ID == "" {
		return peer.PeerInfo{}, routing.ErrNotFound
377
	}
Jeromy's avatar
Jeromy committed
378

379
	return result.peer, nil
380 381
}

382
// FindPeersConnectedToPeer searches for peers directly connected to a given peer.
383
func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan peer.PeerInfo, error) {
384

385 386
	peerchan := make(chan peer.PeerInfo, asyncQueryBuffer)
	peersSeen := peer.Set{}
387

388
	closest := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
389
	if closest == nil || len(closest) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
390
		return nil, errors.Wrap(kb.ErrLookupFailure)
391 392 393
	}

	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
394
	query := dht.newQuery(u.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
395

396
		pmes, err := dht.findPeerSingle(ctx, p, id)
397 398 399 400
		if err != nil {
			return nil, err
		}

401
		var clpeers []peer.PeerInfo
402 403
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
404
			pi := pb.PBPeerToPeerInfo(pbp)
405

406 407
			// skip peers already seen
			if _, found := peersSeen[pi.ID]; found {
408 409
				continue
			}
410
			peersSeen[pi.ID] = struct{}{}
411 412 413 414 415 416

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
417
				case peerchan <- pi:
418 419 420 421
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
422
			// TODO maybe query it?
423
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
424
				clpeers = append(clpeers, pi)
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
			}
		}

		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
		if _, err := query.Run(ctx, closest); err != nil {
			log.Error(err)
		}

		// close the peerchan channel when done.
		close(peerchan)
	}()

	return peerchan, nil
}

445
// Ping a peer, log the time it took
446
func (dht *IpfsDHT) Ping(ctx context.Context, p peer.ID) (time.Duration, error) {
447
	// Thoughts: maybe this should accept an ID and do a peer lookup?
Brian Tiger Chow's avatar
Brian Tiger Chow committed
448
	log.Debugf("ping %s start", p)
449
	before := time.Now()
450

451
	pmes := pb.NewMessage(pb.Message_PING, "", 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
452
	_, err := dht.sendRequest(ctx, p, pmes)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
453
	log.Debugf("ping %s end (err = %s)", p, err)
454 455

	return time.Now().Sub(before), err
456
}