routing.go 6.96 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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	peer "github.com/jbenet/go-ipfs/peer"
9
	"github.com/jbenet/go-ipfs/routing"
10
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
11
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13 14 15 16 17 18 19
)

// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
20
// This is the top level "Store" operation of the DHT
21
func (dht *IpfsDHT) PutValue(ctx context.Context, key u.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
23 24 25 26
	err := dht.putLocal(key, value)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27

28 29 30 31 32 33
	rec, err := dht.makePutRecord(key, value)
	if err != nil {
		log.Error("Creation of record failed!")
		return err
	}

34
	var peers []peer.Peer
35
	for _, route := range dht.routingTables {
36 37
		npeers := route.NearestPeers(kb.ConvertKey(key), KValue)
		peers = append(peers, npeers...)
Jeromy's avatar
Jeromy committed
38
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40
	query := newQuery(key, dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
		log.Debugf("%s PutValue qry part %v", dht.self, p)
42
		err := dht.putValueToNetwork(ctx, p, string(key), rec)
43 44 45 46 47
		if err != nil {
			return nil, err
		}
		return &dhtQueryResult{success: true}, nil
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48

49
	_, err = query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51 52 53
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
54 55
// 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
56
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
	log.Debugf("Get Value [%s]", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58

Jeromy's avatar
Jeromy committed
59 60
	// If we have it local, dont bother doing an RPC!
	// NOTE: this might not be what we want to do...
61
	val, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
62
	if err == nil {
63
		log.Debug("Got value locally!")
Jeromy's avatar
Jeromy committed
64 65 66
		return val, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
	// get closest peers in the routing tables
68 69
	routeLevel := 0
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertKey(key), PoolSize)
70
	if closest == nil || len(closest) == 0 {
71
		log.Warning("Got no peers back from routing table!")
Jeromy's avatar
Jeromy committed
72
		return nil, kb.ErrLookupFailure
73 74
	}

75
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
	query := newQuery(key, dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
77

78 79 80 81
		val, peers, err := dht.getValueOrPeers(ctx, p, key, routeLevel)
		if err != nil {
			return nil, err
		}
82

83 84 85 86 87 88 89
		res := &dhtQueryResult{value: val, closerPeers: peers}
		if val != nil {
			res.success = true
		}

		return res, nil
	})
90

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
	// run it!
92
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93 94
	if err != nil {
		return nil, err
95 96
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
	log.Debugf("GetValue %v %v", key, result.value)
98
	if result.value == nil {
99
		return nil, routing.ErrNotFound
100
	}
101 102

	return result.value, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104 105 106 107
}

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

108
// Provide makes this node announce that it can provide a value for the given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
func (dht *IpfsDHT) Provide(ctx context.Context, key u.Key) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110

111
	dht.providers.AddProvider(key, dht.self)
112
	peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), PoolSize)
113
	if len(peers) == 0 {
114
		return nil
115 116
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117 118
	//TODO FIX: this doesn't work! it needs to be sent to the actual nearest peers.
	// `peers` are the closest peers we have, not the ones that should get the value.
119
	for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120 121 122 123
		err := dht.putProvider(ctx, p, string(key))
		if err != nil {
			return err
		}
124 125
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126 127
}

128
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.Peer {
129
	log.Event(ctx, "findProviders", &key)
130
	peerOut := make(chan peer.Peer, count)
131
	go func() {
132 133
		defer close(peerOut)

134
		ps := newPeerSet()
135
		// TODO may want to make this function async to hide latency
136 137 138
		provs := dht.providers.GetProviders(key)
		for _, p := range provs {
			count--
139
			// NOTE: assuming that this list of peers is unique
140
			ps.Add(p)
141 142 143 144 145
			select {
			case peerOut <- p:
			case <-ctx.Done():
				return
			}
146 147 148 149 150
			if count <= 0 {
				return
			}
		}

151 152
		var wg sync.WaitGroup
		for _, pp := range dht.routingTables[0].NearestPeers(kb.ConvertKey(key), AlphaValue) {
Jeromy's avatar
Jeromy committed
153
			wg.Add(1)
154
			go func(p peer.Peer) {
Jeromy's avatar
Jeromy committed
155
				defer wg.Done()
156
				pmes, err := dht.findProvidersSingle(ctx, p, key, 0)
157
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
					log.Error(err)
159 160
					return
				}
161
				dht.addPeerListAsync(ctx, key, pmes.GetProviderPeers(), ps, count, peerOut)
Jeromy's avatar
Jeromy committed
162
			}(pp)
163
		}
Jeromy's avatar
Jeromy committed
164
		wg.Wait()
165 166 167 168
	}()
	return peerOut
}

169
func (dht *IpfsDHT) addPeerListAsync(ctx context.Context, k u.Key, peers []*pb.Message_Peer, ps *peerSet, count int, out chan peer.Peer) {
170
	var wg sync.WaitGroup
171
	for _, pbp := range peers {
172
		wg.Add(1)
173
		go func(mp *pb.Message_Peer) {
174
			defer wg.Done()
Jeromy's avatar
Jeromy committed
175
			// construct new peer
176
			p, err := dht.ensureConnectedToPeer(ctx, mp)
Jeromy's avatar
Jeromy committed
177
			if err != nil {
Jeromy's avatar
Jeromy committed
178
				log.Errorf("%s", err)
Jeromy's avatar
Jeromy committed
179 180 181 182 183 184
				return
			}
			if p == nil {
				log.Error("Got nil peer from ensureConnectedToPeer")
				return
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185

Jeromy's avatar
Jeromy committed
186 187
			dht.providers.AddProvider(k, p)
			if ps.AddIfSmallerThan(p, count) {
188 189 190 191 192
				select {
				case out <- p:
				case <-ctx.Done():
					return
				}
Jeromy's avatar
Jeromy committed
193 194 195 196 197
			} else if ps.Size() >= count {
				return
			}
		}(pbp)
	}
198
	wg.Wait()
199 200
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202
// Find specific Peer
// FindPeer searches for a peer with given ID.
203
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204

205
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
206
	p, _ := dht.FindLocal(id)
207 208 209 210
	if p != nil {
		return p, nil
	}

211
	routeLevel := 0
Jeromy's avatar
Jeromy committed
212 213 214
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if closest == nil || len(closest) == 0 {
		return nil, kb.ErrLookupFailure
215
	}
216

Jeromy's avatar
Jeromy committed
217 218 219 220 221
	// Sanity...
	for _, p := range closest {
		if p.ID().Equal(id) {
			log.Error("Found target peer in list of closest peers...")
			return p, nil
222
		}
223
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224

Jeromy's avatar
Jeromy committed
225
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
	query := newQuery(u.Key(id), dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
227

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228 229
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
230
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
		}
232

Jeromy's avatar
Jeromy committed
233 234 235 236
		closer := pmes.GetCloserPeers()
		var clpeers []peer.Peer
		for _, pbp := range closer {
			np, err := dht.getPeer(peer.ID(pbp.GetId()))
237
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
				log.Warningf("Received invalid peer from query: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
				continue
240
			}
Jeromy's avatar
Jeromy committed
241 242 243 244
			ma, err := pbp.Address()
			if err != nil {
				log.Warning("Received peer with bad or missing address.")
				continue
245
			}
Jeromy's avatar
Jeromy committed
246 247 248 249 250 251 252 253
			np.AddAddress(ma)
			if pbp.GetId() == string(id) {
				return &dhtQueryResult{
					peer:    np,
					success: true,
				}, nil
			}
			clpeers = append(clpeers, np)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254 255
		}

Jeromy's avatar
Jeromy committed
256
		return &dhtQueryResult{closerPeers: clpeers}, nil
257
	})
258

Jeromy's avatar
Jeromy committed
259 260
	// run it!
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261 262 263 264
	if err != nil {
		return nil, err
	}

265
	log.Debugf("FindPeer %v %v", id, result.success)
266
	if result.peer == nil {
267
		return nil, routing.ErrNotFound
268
	}
Jeromy's avatar
Jeromy committed
269

270
	return result.peer, nil
271 272
}

273
// Ping a peer, log the time it took
274
func (dht *IpfsDHT) Ping(ctx context.Context, p peer.Peer) error {
275
	// Thoughts: maybe this should accept an ID and do a peer lookup?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276
	log.Infof("ping %s start", p)
277

278
	pmes := pb.NewMessage(pb.Message_PING, "", 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279
	_, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280
	log.Infof("ping %s end (err = %s)", p, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
281
	return err
282
}