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

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

33
	query := newQuery(key, func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
34
		log.Debug("%s PutValue qry part %v", dht.self, p)
35 36 37 38 39 40
		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
41

42
	_, err = query.Run(ctx, peers)
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
	log.Debug("Get Value [%s]", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51

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

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

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

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

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

		return res, nil
	})
82

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

Jeromy's avatar
Jeromy committed
89
	log.Debug("GetValue %v %v", key, result.value)
90 91
	if result.value == nil {
		return nil, u.ErrNotFound
92
	}
93 94

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

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

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

103
	dht.providers.AddProvider(key, dht.self)
104
	peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), PoolSize)
105
	if len(peers) == 0 {
106
		return nil
107 108
	}

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

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

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

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

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

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

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

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

			nxtprs[i] = nxtp
		}

319 320
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
321

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
338 339
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
340
	log.Info("ping %s end (err = %s)", p, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341
	return err
342
}
343

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

Jeromy's avatar
Jeromy committed
346
	log.Info("Begin Diagnostic")
347
	peers := dht.routingTables[0].NearestPeers(kb.ConvertPeerID(dht.self.ID), 10)
348 349
	var out []*diagInfo

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

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

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

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