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

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

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

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

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

// Basic Put/Get

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

24
	peers := []*peer.Peer{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26

	// get the peers we need to announce to
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
49 50
func (dht *IpfsDHT) GetValue(key u.Key, timeout time.Duration) ([]byte, error) {
	ll := startNewRPC("GET")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51 52 53
	defer ll.EndAndPrint()

	ctx, _ := context.WithTimeout(context.TODO(), timeout)
54

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

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

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

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

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

		return res, nil
	})
85

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

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

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

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

103 104
// Provide makes this node announce that it can provide a value for the given key
func (dht *IpfsDHT) Provide(key u.Key) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106
	ctx := context.TODO()

107
	dht.providers.AddProvider(key, dht.self)
108
	peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), PoolSize)
109
	if len(peers) == 0 {
110
		return kb.ErrLookupFailure
111 112
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124
// FindProvidersAsync runs FindProviders and sends back results over a channel
125
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan *peer.Peer {
126 127 128 129 130 131
	peerOut := make(chan *peer.Peer, count)
	go func() {
		ps := newPeerSet()
		provs := dht.providers.GetProviders(key)
		for _, p := range provs {
			count--
132
			// NOTE: assuming that this list of peers is unique
133 134 135 136 137 138 139 140 141
			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
142
			ppp := pp
143
			go func() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144
				pmes, err := dht.findProvidersSingle(ctx, ppp, key, 0)
145 146 147 148
				if err != nil {
					u.PErr("%v\n", err)
					return
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149
				dht.addPeerListAsync(key, pmes.GetProviderPeers(), ps, count, peerOut)
150 151 152 153 154 155 156 157
			}()
		}

	}()
	return peerOut
}

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

		// construct new peer
		p, err := dht.ensureConnectedToPeer(pbp)
163 164 165
		if err != nil {
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166

167 168 169 170 171 172 173 174 175
		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
176
// FindProviders searches for peers who can provide the value for given key.
177 178
func (dht *IpfsDHT) FindProviders(key u.Key, timeout time.Duration) ([]*peer.Peer, error) {
	ll := startNewRPC("FindProviders")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180 181 182 183
	ll.EndAndPrint()

	ctx, _ := context.WithTimeout(context.TODO(), timeout)

	// get closest peer
184
	u.DOut("Find providers for: '%s'\n", key)
185
	p := dht.routingTables[0].NearestPeer(kb.ConvertKey(key))
186 187 188
	if p == nil {
		return nil, kb.ErrLookupFailure
	}
189

190
	for level := 0; level < len(dht.routingTables); {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191 192 193

		// attempt retrieving providers
		pmes, err := dht.findProvidersSingle(ctx, p, key, level)
194 195 196
		if err != nil {
			return nil, err
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198 199 200

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

Jeromy's avatar
Jeromy committed
205
		u.DOut("Didnt get providers, just closer peers.\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206
		closer := pmes.GetCloserPeers()
207 208 209 210 211
		if len(closer) == 0 {
			level++
			continue
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212
		np, err := dht.peerFromInfo(closer[0])
213
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214
			u.DOut("no peerFromInfo")
215 216
			level++
			continue
Jeromy's avatar
Jeromy committed
217
		}
218
		p = np
219
	}
Jeromy's avatar
Jeromy committed
220
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222 223 224 225
}

// Find specific Peer

// FindPeer searches for a peer with given ID.
226
func (dht *IpfsDHT) FindPeer(id peer.ID, timeout time.Duration) (*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228
	ctx, _ := context.WithTimeout(context.TODO(), timeout)

229
	// Check if were already connected to them
230
	p, _ := dht.Find(id)
231 232 233 234
	if p != nil {
		return p, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
	// @whyrusleeping why is this here? doesn't the dht.Find above cover it?
236 237
	routeLevel := 0
	p = dht.routingTables[routeLevel].NearestPeer(kb.ConvertPeerID(id))
238 239
	if p == nil {
		return nil, kb.ErrLookupFailure
240
	}
241 242 243
	if p.ID.Equal(id) {
		return p, nil
	}
244

245
	for routeLevel < len(dht.routingTables) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246 247
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		plist := pmes.GetCloserPeers()
248
		if plist == nil || len(plist) == 0 {
249
			routeLevel++
250
			continue
251
		}
252 253
		found := plist[0]

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254
		nxtPeer, err := dht.ensureConnectedToPeer(found)
Jeromy's avatar
Jeromy committed
255
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256 257
			routeLevel++
			continue
Jeromy's avatar
Jeromy committed
258 259
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
		if nxtPeer.ID.Equal(id) {
261
			return nxtPeer, nil
Jeromy's avatar
Jeromy committed
262
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
263

264
		p = nxtPeer
265
	}
266
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267
}
268

269
func (dht *IpfsDHT) findPeerMultiple(id peer.ID, timeout time.Duration) (*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
270 271
	ctx, _ := context.WithTimeout(context.TODO(), timeout)

272 273 274 275 276 277
	// 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
278
	// get the peers we need to announce to
279 280 281 282 283
	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
284 285

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293 294 295 296
		plist := pmes.GetCloserPeers()
		if len(plist) == 0 {
			routeLevel++
		}
297

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306
			if nxtp.ID.Equal(id) {
307
				return &dhtQueryResult{peer: nxtp, success: true}, nil
308
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309 310 311 312

			nxtprs[i] = nxtp
		}

313 314
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
315

316
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
317 318 319 320
	if err != nil {
		return nil, err
	}

321 322
	if result.peer == nil {
		return nil, u.ErrNotFound
323
	}
324
	return result.peer, nil
325 326
}

327 328
// Ping a peer, log the time it took
func (dht *IpfsDHT) Ping(p *peer.Peer, timeout time.Duration) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329 330
	ctx, _ := context.WithTimeout(context.TODO(), timeout)

331
	// Thoughts: maybe this should accept an ID and do a peer lookup?
Jeromy's avatar
Jeromy committed
332
	u.DOut("Enter Ping.\n")
333

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334 335 336
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
	return err
337
}
338

339
func (dht *IpfsDHT) getDiagnostic(timeout time.Duration) ([]*diagInfo, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
340
	ctx, _ := context.WithTimeout(context.TODO(), timeout)
341

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

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

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

			out = append(out, di)
362
		}
363 364
		return &dhtQueryResult{success: true}, nil
	})
365

366
	_, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
367
	return out, err
368
}