routing.go 8.64 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 33 34 35 36 37 38
	query := newQuery(key, func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
		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
39

40
	_, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43 44
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
45 46
// If the search does not succeed, a multiaddr string of a closer peer is
// returned along with util.ErrSearchIncomplete
47 48
func (dht *IpfsDHT) GetValue(key u.Key, timeout time.Duration) ([]byte, error) {
	ll := startNewRPC("GET")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49 50 51
	defer ll.EndAndPrint()

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

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 66 67
		return nil, kb.ErrLookupFailure
	}

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
	}

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

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
	}

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

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

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

	}()
	return peerOut
}

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

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

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

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

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

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

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

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

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

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

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

			nxtprs[i] = nxtp
		}

310 311
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
312

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

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

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

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

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

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

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

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

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

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

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