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

import (
4
	"bytes"
5
	"encoding/json"
6

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

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

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

// Basic Put/Get

// PutValue adds value corresponding to given Key.
19
// This is the top level "Store" operation of the DHT
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
func (dht *IpfsDHT) PutValue(ctx context.Context, key u.Key, value []byte) error {
21
	peers := []*peer.Peer{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23

	// get the peers we need to announce to
24
	for _, route := range dht.routingTables {
25 26
		npeers := route.NearestPeers(kb.ConvertKey(key), KValue)
		peers = append(peers, npeers...)
Jeromy's avatar
Jeromy committed
27
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28

29
	query := newQuery(key, func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
		u.DOut("[%s] PutValue qry part %v\n", dht.self.ID.Pretty(), p.ID.Pretty())
31 32 33 34 35 36
		err := dht.putValueToNetwork(ctx, p, string(key), value)
		if err != nil {
			return nil, err
		}
		return &dhtQueryResult{success: true}, nil
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37

38
	_, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
	u.DOut("[%s] PutValue %v %v\n", dht.self.ID.Pretty(), key, value)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41 42 43
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
44 45
// 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
46
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
47
	ll := startNewRPC("GET")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48 49
	defer ll.EndAndPrint()

Jeromy's avatar
Jeromy committed
50 51
	// If we have it local, dont bother doing an RPC!
	// NOTE: this might not be what we want to do...
52
	val, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
53 54
	if err == nil {
		ll.Success = true
Jeromy's avatar
Jeromy committed
55 56 57
		return val, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58
	// get closest peers in the routing tables
59 60
	routeLevel := 0
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertKey(key), PoolSize)
61
	if closest == nil || len(closest) == 0 {
62
		return nil, nil
63 64
	}

65 66
	// setup the Query
	query := newQuery(key, func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
67

68 69 70 71
		val, peers, err := dht.getValueOrPeers(ctx, p, key, routeLevel)
		if err != nil {
			return nil, err
		}
72

73 74 75 76 77 78 79
		res := &dhtQueryResult{value: val, closerPeers: peers}
		if val != nil {
			res.success = true
		}

		return res, nil
	})
80

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81
	// run it!
82
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84
	if err != nil {
		return nil, err
85 86
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87
	u.DOut("[%s] GetValue %v %v\n", dht.self.ID.Pretty(), key, result.value)
88 89
	if result.value == nil {
		return nil, u.ErrNotFound
90
	}
91 92

	return result.value, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93 94 95 96 97
}

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

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

101
	dht.providers.AddProvider(key, dht.self)
102
	peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), PoolSize)
103
	if len(peers) == 0 {
Jeromy's avatar
Jeromy committed
104
		// Early out for no targets
105
		return nil
106 107
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108 109
	//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.
110
	for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112 113 114
		err := dht.putProvider(ctx, p, string(key))
		if err != nil {
			return err
		}
115 116
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117 118
}

119 120
// NB: not actually async. Used to keep the interface consistent while the
// actual async method, FindProvidersAsync2 is under construction
121
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan *peer.Peer {
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	ch := make(chan *peer.Peer)
	providers, err := dht.FindProviders(ctx, key)
	if err != nil {
		close(ch)
		return ch
	}
	go func() {
		defer close(ch)
		for _, p := range providers {
			ch <- p
		}
	}()
	return ch
}

// FIXME: there's a bug here!
func (dht *IpfsDHT) FindProvidersAsync2(ctx context.Context, key u.Key, count int) <-chan *peer.Peer {
139 140 141 142 143 144
	peerOut := make(chan *peer.Peer, count)
	go func() {
		ps := newPeerSet()
		provs := dht.providers.GetProviders(key)
		for _, p := range provs {
			count--
145
			// NOTE: assuming that this list of peers is unique
146 147 148 149 150 151 152 153 154
			ps.Add(p)
			peerOut <- p
			if count <= 0 {
				return
			}
		}

		peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), AlphaValue)
		for _, pp := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155
			ppp := pp
156
			go func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
				pmes, err := dht.findProvidersSingle(ctx, ppp, key, 0)
158 159 160 161
				if err != nil {
					u.PErr("%v\n", err)
					return
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
				dht.addPeerListAsync(key, pmes.GetProviderPeers(), ps, count, peerOut)
163 164 165 166 167 168 169 170
			}()
		}

	}()
	return peerOut
}

//TODO: this function could also be done asynchronously
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171
func (dht *IpfsDHT) addPeerListAsync(k u.Key, peers []*Message_Peer, ps *peerSet, count int, out chan *peer.Peer) {
172
	for _, pbp := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175

		// construct new peer
		p, err := dht.ensureConnectedToPeer(pbp)
176 177 178
		if err != nil {
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179

180 181 182 183 184 185 186 187 188
		dht.providers.AddProvider(k, p)
		if ps.AddIfSmallerThan(p, count) {
			out <- p
		} else if ps.Size() >= count {
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189
// FindProviders searches for peers who can provide the value for given key.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190
func (dht *IpfsDHT) FindProviders(ctx context.Context, key u.Key) ([]*peer.Peer, error) {
191
	ll := startNewRPC("FindProviders")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193 194
	ll.EndAndPrint()

	// get closest peer
195
	u.DOut("Find providers for: '%s'\n", key)
196
	p := dht.routingTables[0].NearestPeer(kb.ConvertKey(key))
197
	if p == nil {
198
		return nil, nil
199
	}
200

201
	for level := 0; level < len(dht.routingTables); {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203 204

		// attempt retrieving providers
		pmes, err := dht.findProvidersSingle(ctx, p, key, level)
205 206 207
		if err != nil {
			return nil, err
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208 209 210 211

		// handle providers
		provs := pmes.GetProviderPeers()
		if provs != nil {
Jeromy's avatar
Jeromy committed
212
			u.DOut("Got providers back from findProviders call!\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213
			return dht.addProviders(key, provs), nil
214
		}
215

Jeromy's avatar
Jeromy committed
216
		u.DOut("Didnt get providers, just closer peers.\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217
		closer := pmes.GetCloserPeers()
218 219 220 221 222
		if len(closer) == 0 {
			level++
			continue
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
223
		np, err := dht.peerFromInfo(closer[0])
224
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225
			u.DOut("no peerFromInfo")
226 227
			level++
			continue
Jeromy's avatar
Jeromy committed
228
		}
229
		p = np
230
	}
Jeromy's avatar
Jeromy committed
231
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233 234 235 236
}

// Find specific Peer

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

239
	// Check if were already connected to them
240
	p, _ := dht.Find(id)
241 242 243 244
	if p != nil {
		return p, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
	// @whyrusleeping why is this here? doesn't the dht.Find above cover it?
246 247
	routeLevel := 0
	p = dht.routingTables[routeLevel].NearestPeer(kb.ConvertPeerID(id))
248
	if p == nil {
249
		return nil, nil
250
	}
251 252 253
	if p.ID.Equal(id) {
		return p, nil
	}
254

255
	for routeLevel < len(dht.routingTables) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256 257
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		plist := pmes.GetCloserPeers()
258
		if plist == nil || len(plist) == 0 {
259
			routeLevel++
260
			continue
261
		}
262 263
		found := plist[0]

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
264
		nxtPeer, err := dht.ensureConnectedToPeer(found)
Jeromy's avatar
Jeromy committed
265
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266 267
			routeLevel++
			continue
Jeromy's avatar
Jeromy committed
268 269
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
270
		if nxtPeer.ID.Equal(id) {
271
			return nxtPeer, nil
Jeromy's avatar
Jeromy committed
272
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
273

274
		p = nxtPeer
275
	}
276
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277
}
278

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279
func (dht *IpfsDHT) findPeerMultiple(ctx context.Context, id peer.ID) (*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280

281 282 283 284 285 286
	// Check if were already connected to them
	p, _ := dht.Find(id)
	if p != nil {
		return p, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
287
	// get the peers we need to announce to
288 289 290
	routeLevel := 0
	peers := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if len(peers) == 0 {
291
		return nil, nil
292
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293 294

	// setup query function
295
	query := newQuery(u.Key(id), func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296 297 298
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
			u.DErr("getPeer error: %v\n", err)
299
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
300
		}
301

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302 303 304 305
		plist := pmes.GetCloserPeers()
		if len(plist) == 0 {
			routeLevel++
		}
306

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307 308 309
		nxtprs := make([]*peer.Peer, len(plist))
		for i, fp := range plist {
			nxtp, err := dht.peerFromInfo(fp)
310
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311 312
				u.DErr("findPeer error: %v\n", err)
				continue
313 314
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
315
			if nxtp.ID.Equal(id) {
316
				return &dhtQueryResult{peer: nxtp, success: true}, nil
317
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318 319 320 321

			nxtprs[i] = nxtp
		}

322 323
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
324

325
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326 327 328 329
	if err != nil {
		return nil, err
	}

330 331
	if result.peer == nil {
		return nil, u.ErrNotFound
332
	}
333
	return result.peer, nil
334 335
}

336
// Ping a peer, log the time it took
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
337
func (dht *IpfsDHT) Ping(ctx context.Context, p *peer.Peer) error {
338
	// Thoughts: maybe this should accept an ID and do a peer lookup?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339
	u.DOut("[%s] ping %s start\n", dht.self.ID.Pretty(), p.ID.Pretty())
340

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341 342
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343
	u.DOut("[%s] ping %s end (err = %s)\n", dht.self.ID.Pretty(), p.ID.Pretty(), err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
344
	return err
345
}
346

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
347
func (dht *IpfsDHT) getDiagnostic(ctx context.Context) ([]*diagInfo, error) {
348

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
349
	u.DOut("Begin Diagnostic")
350
	peers := dht.routingTables[0].NearestPeers(kb.ConvertPeerID(dht.self.ID), 10)
351 352
	var out []*diagInfo

353
	query := newQuery(dht.self.Key(), func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
354 355 356
		pmes := newMessage(Message_DIAGNOSTIC, "", 0)
		rpmes, err := dht.sendRequest(ctx, p, pmes)
		if err != nil {
357
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
358
		}
359

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
360 361 362 363 364 365
		dec := json.NewDecoder(bytes.NewBuffer(rpmes.GetValue()))
		for {
			di := new(diagInfo)
			err := dec.Decode(di)
			if err != nil {
				break
366
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
367 368

			out = append(out, di)
369
		}
370 371
		return &dhtQueryResult{success: true}, nil
	})
372

373
	_, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
374
	return out, err
375
}