routing.go 9.04 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("[%s] PutValue %v %v", dht.self.ID.Pretty(), key, value)
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.ID.Pretty(), p.ID.Pretty())
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
	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 {
107
		return kb.ErrLookupFailure
108 109
	}

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

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

	}()
	return peerOut
}

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

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

181 182 183 184 185 186 187 188 189
		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
190
// FindProviders searches for peers who can provide the value for given key.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
func (dht *IpfsDHT) FindProviders(ctx context.Context, key u.Key) ([]*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
	// get closest peer
193
	u.DOut("Find providers for: '%s'\n", key.Pretty())
194
	p := dht.routingTables[0].NearestPeer(kb.ConvertKey(key))
195
	if p == nil {
196
		return nil, nil
197
	}
198

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

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

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

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

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

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

			nxtprs[i] = nxtp
		}

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339 340
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341
	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
342
	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
}