routing.go 9 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 63 64
		return nil, kb.ErrLookupFailure
	}

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 {
104
		return kb.ErrLookupFailure
105 106
	}

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

118 119
// NB: not actually async. Used to keep the interface consistent while the
// actual async method, FindProvidersAsync2 is under construction
120
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan *peer.Peer {
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	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 {
138 139 140 141 142 143
	peerOut := make(chan *peer.Peer, count)
	go func() {
		ps := newPeerSet()
		provs := dht.providers.GetProviders(key)
		for _, p := range provs {
			count--
144
			// NOTE: assuming that this list of peers is unique
145 146 147 148 149 150 151 152 153
			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
154
			ppp := pp
155
			go func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156
				pmes, err := dht.findProvidersSingle(ctx, ppp, key, 0)
157 158 159 160
				if err != nil {
					u.PErr("%v\n", err)
					return
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
				dht.addPeerListAsync(key, pmes.GetProviderPeers(), ps, count, peerOut)
162 163 164 165 166 167 168 169
			}()
		}

	}()
	return peerOut
}

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

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

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

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

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

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

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

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

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

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

			nxtprs[i] = nxtp
		}

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
340 341 342
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
	return err
343
}
344

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

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

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

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

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

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