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

92 93
	if result.value == nil {
		return nil, u.ErrNotFound
94
	}
95 96

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

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

102 103
// 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
104 105
	ctx := context.TODO()

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

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
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
// FindProvidersAsync runs FindProviders and sends back results over a channel
122
func (dht *IpfsDHT) FindProvidersAsync(key u.Key, count int, timeout time.Duration) <-chan *peer.Peer {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124
	ctx, _ := context.WithTimeout(context.TODO(), timeout)

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

	}()
	return peerOut
}

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

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

166 167 168 169 170 171 172 173 174
		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
175
// FindProviders searches for peers who can provide the value for given key.
176 177
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
178 179 180 181 182
	ll.EndAndPrint()

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

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

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

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

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

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

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

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

			nxtprs[i] = nxtp
		}

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

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

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

326 327
// 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
328 329
	ctx, _ := context.WithTimeout(context.TODO(), timeout)

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

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

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

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

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

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

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

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