routing.go 8.6 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
}

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

	}()
	return peerOut
}

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

		// construct new peer
		p, err := dht.ensureConnectedToPeer(pbp)
157 158 159
		if err != nil {
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160

161 162 163 164 165 166 167 168 169
		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
170
// FindProviders searches for peers who can provide the value for given key.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171
func (dht *IpfsDHT) FindProviders(ctx context.Context, key u.Key) ([]*peer.Peer, error) {
172
	ll := startNewRPC("FindProviders")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175
	ll.EndAndPrint()

	// get closest peer
176
	u.DOut("Find providers for: '%s'\n", key)
177
	p := dht.routingTables[0].NearestPeer(kb.ConvertKey(key))
178 179 180
	if p == nil {
		return nil, kb.ErrLookupFailure
	}
181

182
	for level := 0; level < len(dht.routingTables); {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184 185

		// attempt retrieving providers
		pmes, err := dht.findProvidersSingle(ctx, p, key, level)
186 187 188
		if err != nil {
			return nil, err
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189 190 191 192

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

Jeromy's avatar
Jeromy committed
197
		u.DOut("Didnt get providers, just closer peers.\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198
		closer := pmes.GetCloserPeers()
199 200 201 202 203
		if len(closer) == 0 {
			level++
			continue
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
		np, err := dht.peerFromInfo(closer[0])
205
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206
			u.DOut("no peerFromInfo")
207 208
			level++
			continue
Jeromy's avatar
Jeromy committed
209
		}
210
		p = np
211
	}
Jeromy's avatar
Jeromy committed
212
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214 215 216 217
}

// Find specific Peer

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

220
	// Check if were already connected to them
221
	p, _ := dht.Find(id)
222 223 224 225
	if p != nil {
		return p, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
	// @whyrusleeping why is this here? doesn't the dht.Find above cover it?
227 228
	routeLevel := 0
	p = dht.routingTables[routeLevel].NearestPeer(kb.ConvertPeerID(id))
229 230
	if p == nil {
		return nil, kb.ErrLookupFailure
231
	}
232 233 234
	if p.ID.Equal(id) {
		return p, nil
	}
235

236
	for routeLevel < len(dht.routingTables) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237 238
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		plist := pmes.GetCloserPeers()
239
		if plist == nil || len(plist) == 0 {
240
			routeLevel++
241
			continue
242
		}
243 244
		found := plist[0]

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
		nxtPeer, err := dht.ensureConnectedToPeer(found)
Jeromy's avatar
Jeromy committed
246
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248
			routeLevel++
			continue
Jeromy's avatar
Jeromy committed
249 250
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251
		if nxtPeer.ID.Equal(id) {
252
			return nxtPeer, nil
Jeromy's avatar
Jeromy committed
253
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254

255
		p = nxtPeer
256
	}
257
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
}
259

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

262 263 264 265 266 267
	// 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
268
	// get the peers we need to announce to
269 270 271 272 273
	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
274 275

	// setup query function
276
	query := newQuery(u.Key(id), func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277 278 279
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
			u.DErr("getPeer error: %v\n", err)
280
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
281
		}
282

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283 284 285 286
		plist := pmes.GetCloserPeers()
		if len(plist) == 0 {
			routeLevel++
		}
287

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288 289 290
		nxtprs := make([]*peer.Peer, len(plist))
		for i, fp := range plist {
			nxtp, err := dht.peerFromInfo(fp)
291
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292 293
				u.DErr("findPeer error: %v\n", err)
				continue
294 295
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
296
			if nxtp.ID.Equal(id) {
297
				return &dhtQueryResult{peer: nxtp, success: true}, nil
298
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299 300 301 302

			nxtprs[i] = nxtp
		}

303 304
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
305

306
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307 308 309 310
	if err != nil {
		return nil, err
	}

311 312
	if result.peer == nil {
		return nil, u.ErrNotFound
313
	}
314
	return result.peer, nil
315 316
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322 323 324
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
	return err
325
}
326

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

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

333
	query := newQuery(dht.self.Key(), func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334 335 336
		pmes := newMessage(Message_DIAGNOSTIC, "", 0)
		rpmes, err := dht.sendRequest(ctx, p, pmes)
		if err != nil {
337
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
338
		}
339

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
340 341 342 343 344 345
		dec := json.NewDecoder(bytes.NewBuffer(rpmes.GetValue()))
		for {
			di := new(diagInfo)
			err := dec.Decode(di)
			if err != nil {
				break
346
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
347 348

			out = append(out, di)
349
		}
350 351
		return &dhtQueryResult{success: true}, nil
	})
352

353
	_, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
354
	return out, err
355
}