routing.go 11.9 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"
Jeromy's avatar
Jeromy committed
15
	record "github.com/jbenet/go-ipfs/routing/record"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
	errors "github.com/jbenet/go-ipfs/util/debugerror"
Jeromy's avatar
Jeromy committed
18
	pset "github.com/jbenet/go-ipfs/util/peerset"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
)

21 22 23 24 25 26
// 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
27 28 29 30 31
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

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

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

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

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

56 57 58 59 60
	wg := sync.WaitGroup{}
	for p := range pchan {
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Jeromy's avatar
Jeromy committed
61
			err := dht.putValueToPeer(ctx, p, key, rec)
62 63 64 65 66 67 68
			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
69 70 71
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
72 73
// 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
74
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76 77
	log := dht.log().Prefix("GetValue(%s)", key)
	log.Debugf("start")
	defer log.Debugf("end")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78

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

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

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

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

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

		return res, nil
	})
112

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

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

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

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

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

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

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

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

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
160 161 162 163 164 165 166 167 168
// 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
}

169 170 171
// 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) {
172
	e := log.EventBegin(ctx, "getClosestPeers", &key)
173 174
	tablepeers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
	if len(tablepeers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
		return nil, errors.Wrap(kb.ErrLookupFailure)
176 177
	}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
		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
	})
211 212

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

	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())
234 235 236 237
		if pid != dht.self { // dont add self
			dht.peerstore.AddAddresses(pid, pbp.Addresses())
			out = append(out, pid)
		}
238 239 240 241
	}
	return out, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242 243 244
// 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.
245
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.PeerInfo {
246
	log.Event(ctx, "findProviders", &key)
247
	peerOut := make(chan peer.PeerInfo, count)
Jeromy's avatar
Jeromy committed
248 249 250 251
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

252
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
253 254
	log := dht.log().Prefix("FindProviders(%s)", key)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

380
	return result.peer, nil
381 382
}

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

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

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

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

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

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

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

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

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

		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
}

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

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

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