go-libp2p-kad-dht/routing.go

395 lines
10 KiB
Go
Raw Normal View History

2014-07-23 04:48:30 -07:00
package dht
import (
"math"
2014-10-11 10:43:54 -07:00
"sync"
"time"
2014-09-17 07:19:40 -07:00
context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
notif "github.com/jbenet/go-ipfs/notifications"
inet "github.com/jbenet/go-ipfs/p2p/net"
peer "github.com/jbenet/go-ipfs/p2p/peer"
"github.com/jbenet/go-ipfs/routing"
pb "github.com/jbenet/go-ipfs/routing/dht/pb"
kb "github.com/jbenet/go-ipfs/routing/kbucket"
2015-01-17 02:50:10 +00:00
record "github.com/jbenet/go-ipfs/routing/record"
2014-07-29 17:55:19 -07:00
u "github.com/jbenet/go-ipfs/util"
2015-01-02 08:36:32 -08:00
errors "github.com/jbenet/go-ipfs/util/debugerror"
2014-12-15 01:33:04 +00:00
pset "github.com/jbenet/go-ipfs/util/peerset"
2014-07-23 04:48:30 -07:00
)
2014-12-08 21:55:51 -08:00
// 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
2014-07-23 04:48:30 -07:00
// This file implements the Routing interface for the IpfsDHT struct.
// Basic Put/Get
// PutValue adds value corresponding to given Key.
// This is the top level "Store" operation of the DHT
func (dht *IpfsDHT) PutValue(ctx context.Context, key u.Key, value []byte) error {
log.Debugf("PutValue %s", key)
2014-09-12 17:34:07 +00:00
err := dht.putLocal(key, value)
if err != nil {
return err
}
2014-09-17 07:19:40 -07:00
sk, err := dht.getOwnPrivateKey()
if err != nil {
return err
}
2015-01-17 02:50:10 +00:00
rec, err := record.MakePutRecord(sk, key, value)
if err != nil {
2015-01-26 19:12:12 -08:00
log.Debug("Creation of record failed!")
return err
}
pchan, err := dht.GetClosestPeers(ctx, key)
if err != nil {
return err
}
2014-09-17 07:19:40 -07:00
wg := sync.WaitGroup{}
for p := range pchan {
wg.Add(1)
go func(p peer.ID) {
defer wg.Done()
2014-12-28 23:46:25 +00:00
err := dht.putValueToPeer(ctx, p, key, rec)
if err != nil {
2015-01-26 19:12:12 -08:00
log.Debugf("failed putting value to peer: %s", err)
}
}(p)
}
wg.Wait()
return nil
2014-07-23 04:48:30 -07:00
}
// GetValue searches for the value corresponding to given Key.
2014-08-06 21:36:56 -07:00
// If the search does not succeed, a multiaddr string of a closer peer is
// returned along with util.ErrSearchIncomplete
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
2014-08-12 22:10:44 -07:00
// If we have it local, dont bother doing an RPC!
2014-08-16 23:03:36 -07:00
val, err := dht.getLocal(key)
2014-08-14 08:32:17 -07:00
if err == nil {
2015-01-05 04:35:54 -08:00
log.Debug("have it locally")
2014-08-12 22:10:44 -07:00
return val, nil
} else {
log.Debug("failed to get value locally: %s", err)
2014-08-12 22:10:44 -07:00
}
// get closest peers in the routing table
2015-01-05 04:35:54 -08:00
rtp := dht.routingTable.ListPeers()
log.Debugf("peers in rt: %s", len(rtp), rtp)
if len(rtp) == 0 {
2015-01-05 04:35:54 -08:00
log.Warning("No peers from routing table!")
2015-01-02 08:36:32 -08:00
return nil, errors.Wrap(kb.ErrLookupFailure)
}
2014-09-18 19:30:04 -07:00
// setup the Query
2015-01-01 12:45:39 -08:00
query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
val, peers, err := dht.getValueOrPeers(ctx, p, key)
2014-09-18 19:30:04 -07:00
if err != nil {
return nil, err
}
2014-09-18 19:30:04 -07:00
res := &dhtQueryResult{value: val, closerPeers: peers}
if val != nil {
res.success = true
}
return res, nil
})
2014-09-17 07:19:40 -07:00
// run it!
result, err := query.Run(ctx, rtp)
2014-09-17 07:19:40 -07:00
if err != nil {
return nil, err
}
log.Debugf("GetValue %v %v", key, result.value)
2014-09-18 19:30:04 -07:00
if result.value == nil {
return nil, routing.ErrNotFound
}
2014-09-18 19:30:04 -07:00
return result.value, nil
2014-07-23 04:48:30 -07:00
}
// Value provider layer of indirection.
// This is what DSHTs (Coral and MainlineDHT) do to store large values in a DHT.
2014-08-16 23:03:36 -07:00
// Provide makes this node announce that it can provide a value for the given key
func (dht *IpfsDHT) Provide(ctx context.Context, key u.Key) error {
2015-01-15 04:45:34 +00:00
defer log.EventBegin(ctx, "provide", &key).Done()
2015-01-05 04:35:54 -08:00
// add self locally
dht.providers.AddProvider(key, dht.self)
peers, err := dht.GetClosestPeers(ctx, key)
if err != nil {
return err
}
2014-12-28 23:46:25 +00:00
wg := sync.WaitGroup{}
for p := range peers {
2014-12-28 23:46:25 +00:00
wg.Add(1)
go func(p peer.ID) {
defer wg.Done()
2015-01-05 04:35:54 -08:00
log.Debugf("putProvider(%s, %s)", key, p)
2014-12-28 23:46:25 +00:00
err := dht.putProvider(ctx, p, string(key))
if err != nil {
2015-01-26 19:12:12 -08:00
log.Debug(err)
2014-12-28 23:46:25 +00:00
}
}(p)
}
2014-12-28 23:46:25 +00:00
wg.Wait()
return nil
2014-07-23 04:48:30 -07:00
}
// 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
}
2014-11-20 10:46:19 -08:00
// 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.
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.PeerInfo {
log.Event(ctx, "findProviders", &key)
peerOut := make(chan peer.PeerInfo, count)
2014-12-11 05:08:39 +00:00
go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
return peerOut
}
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key u.Key, count int, peerOut chan peer.PeerInfo) {
2015-01-15 04:45:34 +00:00
defer log.EventBegin(ctx, "findProvidersAsync", &key).Done()
2014-12-11 05:08:39 +00:00
defer close(peerOut)
2014-12-17 19:27:41 +00:00
ps := pset.NewLimited(count)
2014-12-11 05:08:39 +00:00
provs := dht.providers.GetProviders(ctx, key)
for _, p := range provs {
// NOTE: assuming that this list of peers is unique
2014-12-16 18:33:36 +00:00
if ps.TryAdd(p) {
2014-12-11 05:42:05 +00:00
select {
case peerOut <- dht.peerstore.PeerInfo(p):
2014-12-11 05:42:05 +00:00
case <-ctx.Done():
return
}
2014-12-11 05:08:39 +00:00
}
2014-12-11 05:42:05 +00:00
// If we have enough peers locally, dont bother with remote RPC
if ps.Size() >= count {
2014-12-11 05:08:39 +00:00
return
}
}
// setup the Query
2015-01-01 12:45:39 -08:00
query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
notif.PublishQueryEvent(ctx, &notif.QueryEvent{
Type: notif.SendingQuery,
ID: p,
})
pmes, err := dht.findProvidersSingle(ctx, p, key)
2014-12-11 05:08:39 +00:00
if err != nil {
return nil, err
}
2015-01-05 04:35:54 -08:00
log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
2015-01-05 04:35:54 -08:00
log.Debugf("%d provider entries decoded", len(provs))
2014-12-11 05:08:39 +00:00
// Add unique providers from request, up to 'count'
for _, prov := range provs {
2015-01-05 04:35:54 -08:00
log.Debugf("got provider: %s", prov)
if ps.TryAdd(prov.ID) {
2015-01-05 04:35:54 -08:00
log.Debugf("using provider: %s", prov)
2014-12-11 05:42:05 +00:00
select {
case peerOut <- prov:
case <-ctx.Done():
2015-01-26 19:12:12 -08:00
log.Debug("Context timed out sending more providers")
2014-12-11 05:42:05 +00:00
return nil, ctx.Err()
}
}
2014-12-11 05:08:39 +00:00
if ps.Size() >= count {
2015-01-05 04:35:54 -08:00
log.Debugf("got enough providers (%d/%d)", ps.Size(), count)
2014-12-11 05:08:39 +00:00
return &dhtQueryResult{success: true}, nil
}
}
2014-12-11 05:08:39 +00:00
// Give closer peers back to the query to be queried
closer := pmes.GetCloserPeers()
clpeers := pb.PBPeersToPeerInfos(closer)
2015-01-05 04:35:54 -08:00
log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
notif.PublishQueryEvent(ctx, &notif.QueryEvent{
Type: notif.PeerResponse,
ID: p,
Responses: pointerizePeerInfos(clpeers),
})
2014-12-11 05:08:39 +00:00
return &dhtQueryResult{closerPeers: clpeers}, nil
})
peers := dht.routingTable.ListPeers()
2014-12-11 05:08:39 +00:00
_, err := query.Run(ctx, peers)
if err != nil {
2015-01-26 19:12:12 -08:00
log.Debugf("Query error: %s", err)
notif.PublishQueryEvent(ctx, &notif.QueryEvent{
Type: notif.QueryError,
Extra: err.Error(),
})
2014-12-11 05:08:39 +00:00
}
}
2014-07-23 04:48:30 -07:00
// FindPeer searches for a peer with given ID.
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (peer.PeerInfo, error) {
2015-01-15 04:45:34 +00:00
defer log.EventBegin(ctx, "FindPeer", id).Done()
2014-09-17 07:19:40 -07:00
// Check if were already connected to them
2014-12-28 23:46:25 +00:00
if pi := dht.FindLocal(id); pi.ID != "" {
return pi, nil
}
peers := dht.routingTable.ListPeers()
if len(peers) == 0 {
2015-01-02 08:36:32 -08:00
return peer.PeerInfo{}, errors.Wrap(kb.ErrLookupFailure)
}
2014-10-24 18:32:28 -07:00
// Sanity...
for _, p := range peers {
if p == id {
2015-01-26 19:12:12 -08:00
log.Debug("Found target peer in list of closest peers...")
return dht.peerstore.PeerInfo(p), nil
}
}
2014-09-17 07:19:40 -07:00
2014-10-24 18:32:28 -07:00
// setup the Query
2015-01-01 12:45:39 -08:00
query := dht.newQuery(u.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
notif.PublishQueryEvent(ctx, &notif.QueryEvent{
Type: notif.SendingQuery,
ID: p,
})
2014-10-24 18:32:28 -07:00
pmes, err := dht.findPeerSingle(ctx, p, id)
2014-09-17 07:19:40 -07:00
if err != nil {
2014-09-18 19:30:04 -07:00
return nil, err
2014-09-17 07:19:40 -07:00
}
2014-10-24 18:32:28 -07:00
closer := pmes.GetCloserPeers()
clpeerInfos := pb.PBPeersToPeerInfos(closer)
2014-11-21 08:03:11 -08:00
// see it we got the peer here
for _, npi := range clpeerInfos {
if npi.ID == id {
2014-10-24 18:32:28 -07:00
return &dhtQueryResult{
peer: npi,
2014-10-24 18:32:28 -07:00
success: true,
}, nil
}
2014-09-17 07:19:40 -07:00
}
notif.PublishQueryEvent(ctx, &notif.QueryEvent{
Type: notif.PeerResponse,
Responses: pointerizePeerInfos(clpeerInfos),
})
return &dhtQueryResult{closerPeers: clpeerInfos}, nil
2014-09-18 19:30:04 -07:00
})
2014-10-24 18:32:28 -07:00
// run it!
result, err := query.Run(ctx, peers)
2014-09-17 07:19:40 -07:00
if err != nil {
return peer.PeerInfo{}, err
2014-09-17 07:19:40 -07:00
}
2014-10-30 06:35:29 -07:00
log.Debugf("FindPeer %v %v", id, result.success)
if result.peer.ID == "" {
return peer.PeerInfo{}, routing.ErrNotFound
}
2014-10-24 18:32:28 -07:00
2014-09-18 19:30:04 -07:00
return result.peer, nil
}
2014-11-24 14:58:51 -05:00
// FindPeersConnectedToPeer searches for peers directly connected to a given peer.
func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan peer.PeerInfo, error) {
2014-11-24 14:58:51 -05:00
peerchan := make(chan peer.PeerInfo, asyncQueryBuffer)
peersSeen := peer.Set{}
2014-11-24 14:58:51 -05:00
peers := dht.routingTable.ListPeers()
if len(peers) == 0 {
2015-01-02 08:36:32 -08:00
return nil, errors.Wrap(kb.ErrLookupFailure)
2014-11-24 14:58:51 -05:00
}
// setup the Query
2015-01-01 12:45:39 -08:00
query := dht.newQuery(u.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
2014-11-24 14:58:51 -05:00
pmes, err := dht.findPeerSingle(ctx, p, id)
2014-11-24 14:58:51 -05:00
if err != nil {
return nil, err
}
var clpeers []peer.PeerInfo
2014-11-24 14:58:51 -05:00
closer := pmes.GetCloserPeers()
for _, pbp := range closer {
pi := pb.PBPeerToPeerInfo(pbp)
2014-11-24 14:58:51 -05:00
// skip peers already seen
if _, found := peersSeen[pi.ID]; found {
2014-11-24 14:58:51 -05:00
continue
}
peersSeen[pi.ID] = struct{}{}
2014-11-24 14:58:51 -05:00
// if peer is connected, send it to our client.
if pb.Connectedness(*pbp.Connection) == inet.Connected {
select {
case <-ctx.Done():
return nil, ctx.Err()
case peerchan <- pi:
2014-11-24 14:58:51 -05:00
}
}
// if peer is the peer we're looking for, don't bother querying it.
// TODO maybe query it?
2014-11-24 14:58:51 -05:00
if pb.Connectedness(*pbp.Connection) != inet.Connected {
clpeers = append(clpeers, pi)
2014-11-24 14:58:51 -05:00
}
}
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, peers); err != nil {
2015-01-26 19:12:12 -08:00
log.Debug(err)
2014-11-24 14:58:51 -05:00
}
// close the peerchan channel when done.
close(peerchan)
}()
return peerchan, nil
}
// Ping a peer, log the time it took
func (dht *IpfsDHT) Ping(ctx context.Context, p peer.ID) (time.Duration, error) {
// Thoughts: maybe this should accept an ID and do a peer lookup?
log.Debugf("ping %s start", p)
before := time.Now()
pmes := pb.NewMessage(pb.Message_PING, "", 0)
2014-09-17 07:19:40 -07:00
_, err := dht.sendRequest(ctx, p, pmes)
log.Debugf("ping %s end (err = %s)", p, err)
return time.Now().Sub(before), err
}