routing.go 6.8 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

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

// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
18
// This is the top level "Store" operation of the DHT
19
func (dht *IpfsDHT) PutValue(ctx context.Context, key u.Key, value []byte) error {
20
	log.Debug("PutValue %s", key)
Jeromy's avatar
Jeromy committed
21 22 23 24
	err := dht.putLocal(key, value)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25

26
	var peers []peer.Peer
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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32
	query := newQuery(key, dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
33
		log.Debug("%s PutValue qry part %v", dht.self, p)
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
	return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45
}

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

Jeromy's avatar
Jeromy committed
51 52
	// If we have it local, dont bother doing an RPC!
	// NOTE: this might not be what we want to do...
53
	val, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
54
	if err == nil {
55
		log.Debug("Got value locally!")
Jeromy's avatar
Jeromy committed
56 57 58
		return val, nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59
	// get closest peers in the routing tables
60 61
	routeLevel := 0
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertKey(key), PoolSize)
62
	if closest == nil || len(closest) == 0 {
63
		log.Warning("Got no peers back from routing table!")
64
		return nil, nil
65 66
	}

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

70 71 72 73
		val, peers, err := dht.getValueOrPeers(ctx, p, key, routeLevel)
		if err != nil {
			return nil, err
		}
74

75 76 77 78 79 80 81
		res := &dhtQueryResult{value: val, closerPeers: peers}
		if val != nil {
			res.success = true
		}

		return res, nil
	})
82

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
	// run it!
84
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85 86
	if err != nil {
		return nil, err
87 88
	}

Jeromy's avatar
Jeromy committed
89
	log.Debug("GetValue %v %v", key, result.value)
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
// Provide makes this node announce that it can provide a value for the given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
func (dht *IpfsDHT) Provide(ctx context.Context, key u.Key) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102

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

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

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

Jeromy's avatar
Jeromy committed
135
		wg := new(sync.WaitGroup)
136 137
		peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(key), AlphaValue)
		for _, pp := range peers {
Jeromy's avatar
Jeromy committed
138
			wg.Add(1)
139
			go func(p peer.Peer) {
Jeromy's avatar
Jeromy committed
140
				defer wg.Done()
141
				pmes, err := dht.findProvidersSingle(ctx, p, key, 0)
142
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
					log.Error("%s", err)
144 145
					return
				}
146
				dht.addPeerListAsync(key, pmes.GetProviderPeers(), ps, count, peerOut)
Jeromy's avatar
Jeromy committed
147
			}(pp)
148
		}
Jeromy's avatar
Jeromy committed
149 150
		wg.Wait()
		close(peerOut)
151 152 153 154 155
	}()
	return peerOut
}

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

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

165 166 167 168 169 170 171 172 173
		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
174 175
// Find specific Peer
// FindPeer searches for a peer with given ID.
176
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177

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

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

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

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

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

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

217
func (dht *IpfsDHT) findPeerMultiple(ctx context.Context, id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
218

219
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
220
	p, _ := dht.FindLocal(id)
221 222 223 224
	if p != nil {
		return p, nil
	}

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

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

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

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

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

			nxtprs[i] = nxtp
		}

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

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

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

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

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