routing.go 9.07 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
Jeromy's avatar
Jeromy committed
20 21 22 23 24
func (dht *IpfsDHT) PutValue(key u.Key, value []byte) error {
	err := dht.putLocal(key, value)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25

Jeromy's avatar
Jeromy committed
26
	var peers []*peer.Peer
27
	for _, route := range dht.routingTables {
28 29
		npeers := route.NearestPeers(kb.ConvertKey(key), KValue)
		peers = append(peers, npeers...)
Jeromy's avatar
Jeromy committed
30
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31

32
	query := newQuery(key, func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
		u.DOut("[%s] PutValue qry part %v\n", dht.self.ID.Pretty(), p.ID.Pretty())
34 35 36 37 38 39
		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
40

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

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

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

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

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

71 72 73 74
		val, peers, err := dht.getValueOrPeers(ctx, p, key, routeLevel)
		if err != nil {
			return nil, err
		}
75

76 77 78 79 80 81 82
		res := &dhtQueryResult{value: val, closerPeers: peers}
		if val != nil {
			res.success = true
		}

		return res, nil
	})
83

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

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

	return result.value, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96 97 98 99 100
}

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

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

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

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

122 123
// NB: not actually async. Used to keep the interface consistent while the
// actual async method, FindProvidersAsync2 is under construction
124
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan *peer.Peer {
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	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 {
142 143 144 145 146 147
	peerOut := make(chan *peer.Peer, count)
	go func() {
		ps := newPeerSet()
		provs := dht.providers.GetProviders(key)
		for _, p := range provs {
			count--
148
			// NOTE: assuming that this list of peers is unique
149 150 151 152 153 154 155 156 157
			ps.Add(p)
			peerOut <- p
			if count <= 0 {
				return
			}
		}

		peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), AlphaValue)
		for _, pp := range peers {
Jeromy's avatar
Jeromy committed
158 159
			go func(p *peer.Peer) {
				pmes, err := dht.findProvidersSingle(p, key, 0, timeout)
160 161 162 163
				if err != nil {
					u.PErr("%v\n", err)
					return
				}
Jeromy's avatar
Jeromy committed
164 165
				dht.addPeerListAsync(key, pmes.GetPeers(), ps, count, peerOut)
			}(pp)
166 167 168 169 170 171 172
		}

	}()
	return peerOut
}

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

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

182 183 184 185 186 187 188 189 190
		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
191
// FindProviders searches for peers who can provide the value for given key.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
func (dht *IpfsDHT) FindProviders(ctx context.Context, key u.Key) ([]*peer.Peer, error) {
193
	ll := startNewRPC("FindProviders")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194 195 196
	ll.EndAndPrint()

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

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

283 284 285 286 287 288
	// 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
289
	// get the peers we need to announce to
290 291 292
	routeLevel := 0
	peers := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if len(peers) == 0 {
293
		return nil, nil
294
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295 296

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

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

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

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

			nxtprs[i] = nxtp
		}

324 325
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
326

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343 344
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345
	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
346
	return err
347
}
348

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

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

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

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

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

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