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

import (
Jeromy's avatar
Jeromy committed
4
	"sync"
5

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

8
	inet "github.com/jbenet/go-ipfs/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	peer "github.com/jbenet/go-ipfs/peer"
10
	"github.com/jbenet/go-ipfs/routing"
11
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
12
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14 15
)

16 17 18 19 20 21
// asyncQueryBuffer is the size of buffered channels in async queries. This
// buffer allows multiple queries to execute simultaneously, return their
// results and continue querying closer peers. Note that different query
// results will wait for the channel to drain.
var asyncQueryBuffer = 10

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23 24 25 26
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
27
// This is the top level "Store" operation of the DHT
28
func (dht *IpfsDHT) PutValue(ctx context.Context, key u.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
30 31 32 33
	err := dht.putLocal(key, value)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34

35 36 37 38 39 40
	rec, err := dht.makePutRecord(key, value)
	if err != nil {
		log.Error("Creation of record failed!")
		return err
	}

41
	var peers []peer.Peer
42
	for _, route := range dht.routingTables {
43 44
		npeers := route.NearestPeers(kb.ConvertKey(key), KValue)
		peers = append(peers, npeers...)
Jeromy's avatar
Jeromy committed
45
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
	query := newQuery(key, dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48
		log.Debugf("%s PutValue qry part %v", dht.self, p)
49
		err := dht.putValueToNetwork(ctx, p, string(key), rec)
50 51 52 53 54
		if err != nil {
			return nil, err
		}
		return &dhtQueryResult{success: true}, nil
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55

56
	_, err = query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58 59 60
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
61 62
// 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
63
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64
	log.Debugf("Get Value [%s]", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65

Jeromy's avatar
Jeromy committed
66 67
	// If we have it local, dont bother doing an RPC!
	// NOTE: this might not be what we want to do...
68
	val, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
69
	if err == nil {
70
		log.Debug("Got value locally!")
Jeromy's avatar
Jeromy committed
71 72 73
		return val, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
	// get closest peers in the routing tables
75 76
	routeLevel := 0
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertKey(key), PoolSize)
77
	if closest == nil || len(closest) == 0 {
78
		log.Warning("Got no peers back from routing table!")
Jeromy's avatar
Jeromy committed
79
		return nil, kb.ErrLookupFailure
80 81
	}

82
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
	query := newQuery(key, dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
84

85 86 87 88
		val, peers, err := dht.getValueOrPeers(ctx, p, key, routeLevel)
		if err != nil {
			return nil, err
		}
89

90 91 92 93 94 95 96
		res := &dhtQueryResult{value: val, closerPeers: peers}
		if val != nil {
			res.success = true
		}

		return res, nil
	})
97

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98
	// run it!
99
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100 101
	if err != nil {
		return nil, err
102 103
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
	log.Debugf("GetValue %v %v", key, result.value)
105
	if result.value == nil {
106
		return nil, routing.ErrNotFound
107
	}
108 109

	return result.value, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111 112 113 114
}

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

115
// Provide makes this node announce that it can provide a value for the given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
func (dht *IpfsDHT) Provide(ctx context.Context, key u.Key) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117

118
	dht.providers.AddProvider(key, dht.self)
119
	peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), PoolSize)
120
	if len(peers) == 0 {
121
		return nil
122 123
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125
	//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.
126
	for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127 128 129 130
		err := dht.putProvider(ctx, p, string(key))
		if err != nil {
			return err
		}
131 132
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136 137
// FindProvidersAsync is the same thing as FindProviders, but returns a channel.
// Peers will be returned on the channel as soon as they are found, even before
// the search query completes.
138
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.Peer {
139
	log.Event(ctx, "findProviders", &key)
140
	peerOut := make(chan peer.Peer, count)
141
	go func() {
142 143
		defer close(peerOut)

144
		ps := newPeerSet()
145
		// TODO may want to make this function async to hide latency
146
		provs := dht.providers.GetProviders(ctx, key)
147 148
		for _, p := range provs {
			count--
149
			// NOTE: assuming that this list of peers is unique
150
			ps.Add(p)
151 152 153 154 155
			select {
			case peerOut <- p:
			case <-ctx.Done():
				return
			}
156 157 158 159 160
			if count <= 0 {
				return
			}
		}

161
		var wg sync.WaitGroup
Brian Tiger Chow's avatar
Brian Tiger Chow committed
162 163
		peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), AlphaValue)
		for _, pp := range peers {
Jeromy's avatar
Jeromy committed
164
			wg.Add(1)
165
			go func(p peer.Peer) {
Jeromy's avatar
Jeromy committed
166
				defer wg.Done()
167
				pmes, err := dht.findProvidersSingle(ctx, p, key, 0)
168
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
					log.Error(err)
170 171
					return
				}
172
				dht.addPeerListAsync(ctx, key, pmes.GetProviderPeers(), ps, count, peerOut)
Jeromy's avatar
Jeromy committed
173
			}(pp)
174
		}
Jeromy's avatar
Jeromy committed
175
		wg.Wait()
176 177 178 179
	}()
	return peerOut
}

180
func (dht *IpfsDHT) addPeerListAsync(ctx context.Context, k u.Key, peers []*pb.Message_Peer, ps *peerSet, count int, out chan peer.Peer) {
181
	var wg sync.WaitGroup
182
	for _, pbp := range peers {
183
		wg.Add(1)
184
		go func(mp *pb.Message_Peer) {
185
			defer wg.Done()
Jeromy's avatar
Jeromy committed
186
			// construct new peer
187
			p, err := dht.ensureConnectedToPeer(ctx, mp)
Jeromy's avatar
Jeromy committed
188
			if err != nil {
Jeromy's avatar
Jeromy committed
189
				log.Errorf("%s", err)
Jeromy's avatar
Jeromy committed
190 191 192 193 194 195
				return
			}
			if p == nil {
				log.Error("Got nil peer from ensureConnectedToPeer")
				return
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196

Jeromy's avatar
Jeromy committed
197 198
			dht.providers.AddProvider(k, p)
			if ps.AddIfSmallerThan(p, count) {
199 200 201 202 203
				select {
				case out <- p:
				case <-ctx.Done():
					return
				}
Jeromy's avatar
Jeromy committed
204 205 206 207 208
			} else if ps.Size() >= count {
				return
			}
		}(pbp)
	}
209
	wg.Wait()
210 211
}

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

215
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
216
	p, _ := dht.FindLocal(id)
217 218 219 220
	if p != nil {
		return p, nil
	}

221
	routeLevel := 0
Jeromy's avatar
Jeromy committed
222 223 224
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if closest == nil || len(closest) == 0 {
		return nil, kb.ErrLookupFailure
225
	}
226

Jeromy's avatar
Jeromy committed
227 228 229 230 231
	// Sanity...
	for _, p := range closest {
		if p.ID().Equal(id) {
			log.Error("Found target peer in list of closest peers...")
			return p, nil
232
		}
233
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234

Jeromy's avatar
Jeromy committed
235
	// setup the Query
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
	query := newQuery(u.Key(id), dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
237

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238 239
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
240
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
		}
242

Jeromy's avatar
Jeromy committed
243
		closer := pmes.GetCloserPeers()
244 245
		clpeers, errs := pb.PBPeersToPeers(dht.peerstore, closer)
		for _, err := range errs {
246
			if err != nil {
247
				log.Warning(err)
248
			}
249
		}
250

251 252 253
		// see it we got the peer here
		for _, np := range clpeers {
			if string(np.ID()) == string(id) {
Jeromy's avatar
Jeromy committed
254 255 256 257 258
				return &dhtQueryResult{
					peer:    np,
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259 260
		}

Jeromy's avatar
Jeromy committed
261
		return &dhtQueryResult{closerPeers: clpeers}, nil
262
	})
263

Jeromy's avatar
Jeromy committed
264 265
	// run it!
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266 267 268 269
	if err != nil {
		return nil, err
	}

270
	log.Debugf("FindPeer %v %v", id, result.success)
271
	if result.peer == nil {
272
		return nil, routing.ErrNotFound
273
	}
Jeromy's avatar
Jeromy committed
274

275
	return result.peer, nil
276 277
}

278 279 280
// FindPeersConnectedToPeer searches for peers directly connected to a given peer.
func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan peer.Peer, error) {

281
	peerchan := make(chan peer.Peer, asyncQueryBuffer)
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	peersSeen := map[string]peer.Peer{}

	routeLevel := 0
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if closest == nil || len(closest) == 0 {
		return nil, kb.ErrLookupFailure
	}

	// setup the Query
	query := newQuery(u.Key(id), dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {

		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
			return nil, err
		}

		var clpeers []peer.Peer
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
			// skip peers already seen
			if _, found := peersSeen[string(pbp.GetId())]; found {
				continue
			}

			// skip peers that fail to unmarshal
			p, err := pb.PBPeerToPeer(dht.peerstore, pbp)
			if err != nil {
				log.Warning(err)
				continue
			}

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
				case peerchan <- p:
				}
			}

			peersSeen[string(p.ID())] = p

			// if peer is the peer we're looking for, don't bother querying it.
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
				clpeers = append(clpeers, p)
			}
		}

		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
		if _, err := query.Run(ctx, closest); err != nil {
			log.Error(err)
		}

		// close the peerchan channel when done.
		close(peerchan)
	}()

	return peerchan, nil
}

347
// Ping a peer, log the time it took
348
func (dht *IpfsDHT) Ping(ctx context.Context, p peer.Peer) error {
349
	// Thoughts: maybe this should accept an ID and do a peer lookup?
Brian Tiger Chow's avatar
Brian Tiger Chow committed
350
	log.Debugf("ping %s start", p)
351

352
	pmes := pb.NewMessage(pb.Message_PING, "", 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
353
	_, err := dht.sendRequest(ctx, p, pmes)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
354
	log.Debugf("ping %s end (err = %s)", p, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
355
	return err
356
}