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

import (
Jeromy's avatar
Jeromy committed
4
	"sync"
5
	"time"
6

7
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
8
	notif "github.com/jbenet/go-ipfs/notifications"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	inet "github.com/jbenet/go-ipfs/p2p/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	peer "github.com/jbenet/go-ipfs/p2p/peer"
11
	"github.com/jbenet/go-ipfs/routing"
12
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
13
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Jeromy's avatar
Jeromy committed
14
	record "github.com/jbenet/go-ipfs/routing/record"
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
	sk, err := dht.getOwnPrivateKey()
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
44
	rec, err := record.MakePutRecord(sk, key, value)
45
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46
		log.Debug("Creation of record failed!")
47 48 49
		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 61 62 63 64
			notif.PublishQueryEvent(ctx, &notif.QueryEvent{
				Type: notif.Value,
				ID:   p,
			})

Jeromy's avatar
Jeromy committed
65
			err := dht.putValueToPeer(ctx, p, key, rec)
66
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
				log.Debugf("failed putting value to peer: %s", err)
68 69 70 71 72
			}
		}(p)
	}
	wg.Wait()
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73 74 75
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
76 77
// 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
78
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
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
	rtp := dht.routingTable.ListPeers()
Jeromy's avatar
Jeromy committed
90
	log.Debugf("peers in rt: %s", len(rtp), rtp)
91
	if len(rtp) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
		log.Warning("No peers from routing table!")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
		return nil, errors.Wrap(kb.ErrLookupFailure)
94 95
	}

96
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
98 99 100 101 102
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type: notif.SendingQuery,
			ID:   p,
		})

103
		val, peers, err := dht.getValueOrPeers(ctx, p, key)
104 105 106
		if err != nil {
			return nil, err
		}
107

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

Jeromy's avatar
Jeromy committed
113 114 115 116 117 118
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:      notif.PeerResponse,
			ID:        p,
			Responses: pointerizePeerInfos(peers),
		})

119 120
		return res, nil
	})
121

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122
	// run it!
123
	result, err := query.Run(ctx, rtp)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125
	if err != nil {
		return nil, err
126 127
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128
	log.Debugf("GetValue %v %v", key, result.value)
129
	if result.value == nil {
130
		return nil, routing.ErrNotFound
131
	}
132 133

	return result.value, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135 136 137 138
}

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

139
// Provide makes this node announce that it can provide a value for the given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140
func (dht *IpfsDHT) Provide(ctx context.Context, key u.Key) error {
Jeromy's avatar
Jeromy committed
141
	defer log.EventBegin(ctx, "provide", &key).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142 143

	// add self locally
144
	dht.providers.AddProvider(ctx, key, dht.self)
145

146
	peers, err := dht.GetClosestPeers(ctx, key)
147 148
	if err != nil {
		return err
149 150
	}

Jeromy's avatar
Jeromy committed
151
	wg := sync.WaitGroup{}
152
	for p := range peers {
Jeromy's avatar
Jeromy committed
153 154 155
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156
			log.Debugf("putProvider(%s, %s)", key, p)
Jeromy's avatar
Jeromy committed
157 158
			err := dht.putProvider(ctx, p, string(key))
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159
				log.Debug(err)
Jeromy's avatar
Jeromy committed
160 161
			}
		}(p)
162
	}
Jeromy's avatar
Jeromy committed
163
	wg.Wait()
164
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165 166
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
167 168 169
// FindProviders searches until the context expires.
func (dht *IpfsDHT) FindProviders(ctx context.Context, key u.Key) ([]peer.PeerInfo, error) {
	var providers []peer.PeerInfo
Jeromy's avatar
Jeromy committed
170
	for p := range dht.FindProvidersAsync(ctx, key, KValue) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
171 172 173 174 175
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176 177 178
// 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.
179
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.PeerInfo {
180
	log.Event(ctx, "findProviders", &key)
181
	peerOut := make(chan peer.PeerInfo, count)
Jeromy's avatar
Jeromy committed
182 183 184 185
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

186
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key u.Key, count int, peerOut chan peer.PeerInfo) {
Jeromy's avatar
Jeromy committed
187
	defer log.EventBegin(ctx, "findProvidersAsync", &key).Done()
Jeromy's avatar
Jeromy committed
188 189
	defer close(peerOut)

Jeromy's avatar
Jeromy committed
190
	ps := pset.NewLimited(count)
Jeromy's avatar
Jeromy committed
191 192 193
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
		// NOTE: assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
194
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
195
			select {
196
			case peerOut <- dht.peerstore.PeerInfo(p):
Jeromy's avatar
Jeromy committed
197 198 199
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
200
		}
Jeromy's avatar
Jeromy committed
201 202 203

		// If we have enough peers locally, dont bother with remote RPC
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
204 205 206 207 208
			return
		}
	}

	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
210 211 212 213
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type: notif.SendingQuery,
			ID:   p,
		})
214
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
215 216 217 218
		if err != nil {
			return nil, err
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
220
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
222 223 224

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225
			log.Debugf("got provider: %s", prov)
226
			if ps.TryAdd(prov.ID) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
				log.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
228 229 230
				select {
				case peerOut <- prov:
				case <-ctx.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
					log.Debug("Context timed out sending more providers")
Jeromy's avatar
Jeromy committed
232 233
					return nil, ctx.Err()
				}
234
			}
Jeromy's avatar
Jeromy committed
235
			if ps.Size() >= count {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
				log.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
237
				return &dhtQueryResult{success: true}, nil
238 239 240
			}
		}

Jeromy's avatar
Jeromy committed
241 242
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
243
		clpeers := pb.PBPeersToPeerInfos(closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
		log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
245 246 247 248 249 250

		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:      notif.PeerResponse,
			ID:        p,
			Responses: pointerizePeerInfos(clpeers),
		})
Jeromy's avatar
Jeromy committed
251 252 253
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

254
	peers := dht.routingTable.ListPeers()
Jeromy's avatar
Jeromy committed
255 256
	_, err := query.Run(ctx, peers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
		log.Debugf("Query error: %s", err)
258 259 260 261
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
262
	}
263 264
}

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

269
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
270
	if pi := dht.FindLocal(id); pi.ID != "" {
271
		return pi, nil
272 273
	}

274 275
	peers := dht.routingTable.ListPeers()
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276
		return peer.PeerInfo{}, errors.Wrap(kb.ErrLookupFailure)
277
	}
278

Jeromy's avatar
Jeromy committed
279
	// Sanity...
280
	for _, p := range peers {
281
		if p == id {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
			log.Debug("Found target peer in list of closest peers...")
283
			return dht.peerstore.PeerInfo(p), nil
284
		}
285
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286

Jeromy's avatar
Jeromy committed
287
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
	query := dht.newQuery(u.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
289 290 291 292
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type: notif.SendingQuery,
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
293

294
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295
		if err != nil {
296
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
297
		}
298

Jeromy's avatar
Jeromy committed
299
		closer := pmes.GetCloserPeers()
300
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
301

302
		// see it we got the peer here
303 304
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
305
				return &dhtQueryResult{
306
					peer:    npi,
Jeromy's avatar
Jeromy committed
307 308 309
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310 311
		}

312 313 314 315 316
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:      notif.PeerResponse,
			Responses: pointerizePeerInfos(clpeerInfos),
		})

317
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
318
	})
319

Jeromy's avatar
Jeromy committed
320
	// run it!
321
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322
	if err != nil {
323
		return peer.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
324 325
	}

326
	log.Debugf("FindPeer %v %v", id, result.success)
327 328
	if result.peer.ID == "" {
		return peer.PeerInfo{}, routing.ErrNotFound
329
	}
Jeromy's avatar
Jeromy committed
330

331
	return result.peer, nil
332 333
}

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

337 338
	peerchan := make(chan peer.PeerInfo, asyncQueryBuffer)
	peersSeen := peer.Set{}
339

340 341
	peers := dht.routingTable.ListPeers()
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
342
		return nil, errors.Wrap(kb.ErrLookupFailure)
343 344 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) {
347

348
		pmes, err := dht.findPeerSingle(ctx, p, id)
349 350 351 352
		if err != nil {
			return nil, err
		}

353
		var clpeers []peer.PeerInfo
354 355
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
356
			pi := pb.PBPeerToPeerInfo(pbp)
357

358 359
			// skip peers already seen
			if _, found := peersSeen[pi.ID]; found {
360 361
				continue
			}
362
			peersSeen[pi.ID] = struct{}{}
363 364 365 366 367 368

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
369
				case peerchan <- pi:
370 371 372 373
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
374
			// TODO maybe query it?
375
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
376
				clpeers = append(clpeers, pi)
377 378 379 380 381 382 383 384 385
			}
		}

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

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
386
		if _, err := query.Run(ctx, peers); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
387
			log.Debug(err)
388 389 390 391 392 393 394 395 396
		}

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

	return peerchan, nil
}

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

403
	pmes := pb.NewMessage(pb.Message_PING, "", 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
404
	_, err := dht.sendRequest(ctx, p, pmes)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
405
	log.Debugf("ping %s end (err = %s)", p, err)
406 407

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