routing.go 8.85 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 93
	u.DOut("[%s] GetValue %v %v\n", dht.self.ID.Pretty(), key, result.value)

94 95
	if result.value == nil {
		return nil, u.ErrNotFound
96
	}
97 98

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

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

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

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

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

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

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

	}()
	return peerOut
}

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

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

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

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

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

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

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

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

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

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

// Find specific Peer

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

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

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

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

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

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

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

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

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

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

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

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

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

			nxtprs[i] = nxtp
		}

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

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

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

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

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

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

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

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

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

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

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

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