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

import (
4
	"bytes"
5
	"encoding/json"
Jeromy's avatar
Jeromy committed
6
	"sync"
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(ctx context.Context, key u.Key, value []byte) error {
22
	log.Debug("PutValue %s", key)
Jeromy's avatar
Jeromy committed
23 24 25 26
	err := dht.putLocal(key, value)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27

Jeromy's avatar
Jeromy committed
28
	var peers []*peer.Peer
29
	for _, route := range dht.routingTables {
30 31
		npeers := route.NearestPeers(kb.ConvertKey(key), KValue)
		peers = append(peers, npeers...)
Jeromy's avatar
Jeromy committed
32
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33

34
	query := newQuery(key, func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
35
		log.Debug("%s PutValue qry part %v", dht.self, p)
36 37 38 39 40 41
		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
42

43
	_, err = query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45 46 47
}

// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
48 49
// 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
50
func (dht *IpfsDHT) GetValue(ctx context.Context, key u.Key) ([]byte, error) {
51
	log.Debug("Get Value [%s]", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
	if err == nil {
57
		log.Debug("Got value locally!")
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
		return nil, nil
66 67
	}

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
	}

Jeromy's avatar
Jeromy committed
90
	log.Debug("GetValue %v %v", key, result.value)
91 92
	if result.value == nil {
		return nil, u.ErrNotFound
93
	}
94 95

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111
	//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.
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
}

121
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan *peer.Peer {
122 123 124 125 126 127
	peerOut := make(chan *peer.Peer, count)
	go func() {
		ps := newPeerSet()
		provs := dht.providers.GetProviders(key)
		for _, p := range provs {
			count--
128
			// NOTE: assuming that this list of peers is unique
129 130 131 132 133 134 135
			ps.Add(p)
			peerOut <- p
			if count <= 0 {
				return
			}
		}

Jeromy's avatar
Jeromy committed
136
		wg := new(sync.WaitGroup)
137 138
		peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), AlphaValue)
		for _, pp := range peers {
Jeromy's avatar
Jeromy committed
139
			wg.Add(1)
Jeromy's avatar
Jeromy committed
140
			go func(p *peer.Peer) {
Jeromy's avatar
Jeromy committed
141
				defer wg.Done()
142
				pmes, err := dht.findProvidersSingle(ctx, p, key, 0)
143
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144
					log.Error("%s", err)
145 146
					return
				}
147
				dht.addPeerListAsync(key, pmes.GetProviderPeers(), ps, count, peerOut)
Jeromy's avatar
Jeromy committed
148
			}(pp)
149
		}
Jeromy's avatar
Jeromy committed
150 151
		wg.Wait()
		close(peerOut)
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 176
// Find specific Peer
// FindPeer searches for a peer with given ID.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178

179
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
180
	p, _ := dht.FindLocal(id)
181 182 183 184
	if p != nil {
		return p, nil
	}

185 186
	routeLevel := 0
	p = dht.routingTables[routeLevel].NearestPeer(kb.ConvertPeerID(id))
187
	if p == nil {
188
		return nil, nil
189
	}
190 191 192
	if p.ID.Equal(id) {
		return p, nil
	}
193

194
	for routeLevel < len(dht.routingTables) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195 196
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		plist := pmes.GetCloserPeers()
197
		if plist == nil || len(plist) == 0 {
198
			routeLevel++
199
			continue
200
		}
201 202
		found := plist[0]

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
		nxtPeer, err := dht.ensureConnectedToPeer(found)
Jeromy's avatar
Jeromy committed
204
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205 206
			routeLevel++
			continue
Jeromy's avatar
Jeromy committed
207 208
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
		if nxtPeer.ID.Equal(id) {
210
			return nxtPeer, nil
Jeromy's avatar
Jeromy committed
211
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212

213
		p = nxtPeer
214
	}
215
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
}
217

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
218
func (dht *IpfsDHT) findPeerMultiple(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
Jeromy's avatar
Jeromy committed
221
	p, _ := dht.FindLocal(id)
222 223 224 225
	if p != nil {
		return p, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
	// get the peers we need to announce to
227 228 229
	routeLevel := 0
	peers := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if len(peers) == 0 {
230
		return nil, nil
231
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233

	// setup query function
234
	query := newQuery(u.Key(id), func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235 236
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237
			log.Error("%s getPeer error: %v", dht.self, err)
238
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
		}
240

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242 243 244
		plist := pmes.GetCloserPeers()
		if len(plist) == 0 {
			routeLevel++
		}
245

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246 247 248
		nxtprs := make([]*peer.Peer, len(plist))
		for i, fp := range plist {
			nxtp, err := dht.peerFromInfo(fp)
249
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
				log.Error("%s findPeer error: %v", dht.self, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251
				continue
252 253
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
254
			if nxtp.ID.Equal(id) {
255
				return &dhtQueryResult{peer: nxtp, success: true}, nil
256
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257 258 259 260

			nxtprs[i] = nxtp
		}

261 262
		return &dhtQueryResult{closerPeers: nxtprs}, nil
	})
263

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

269 270
	if result.peer == nil {
		return nil, u.ErrNotFound
271
	}
272
	return result.peer, nil
273 274
}

275
// Ping a peer, log the time it took
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276
func (dht *IpfsDHT) Ping(ctx context.Context, p *peer.Peer) error {
277
	// Thoughts: maybe this should accept an ID and do a peer lookup?
278
	log.Info("ping %s start", p)
279

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280 281
	pmes := newMessage(Message_PING, "", 0)
	_, err := dht.sendRequest(ctx, p, pmes)
282
	log.Info("ping %s end (err = %s)", p, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283
	return err
284
}
285

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

Jeromy's avatar
Jeromy committed
288
	log.Info("Begin Diagnostic")
289
	peers := dht.routingTables[0].NearestPeers(kb.ConvertPeerID(dht.self.ID), 10)
290 291
	var out []*diagInfo

292
	query := newQuery(dht.self.Key(), func(ctx context.Context, p *peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293 294 295
		pmes := newMessage(Message_DIAGNOSTIC, "", 0)
		rpmes, err := dht.sendRequest(ctx, p, pmes)
		if err != nil {
296
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
297
		}
298

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299 300 301 302 303 304
		dec := json.NewDecoder(bytes.NewBuffer(rpmes.GetValue()))
		for {
			di := new(diagInfo)
			err := dec.Decode(di)
			if err != nil {
				break
305
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306 307

			out = append(out, di)
308
		}
309 310
		return &dhtQueryResult{success: true}, nil
	})
311

312
	_, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313
	return out, err
314
}