routing.go 6.65 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
	"github.com/jbenet/go-ipfs/routing"
10
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
	log.Debugf("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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34
	query := newQuery(key, dht.dialer, func(ctx context.Context, p peer.Peer) (*dhtQueryResult, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
		log.Debugf("%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) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
	log.Debugf("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
		log.Warning("Got no peers back from routing table!")
Jeromy's avatar
Jeromy committed
66
		return nil, kb.ErrLookupFailure
67 68
	}

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

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

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

		return res, nil
	})
84

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
	log.Debugf("GetValue %v %v", key, result.value)
92
	if result.value == nil {
93
		return nil, routing.ErrNotFound
94
	}
95 96

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

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

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

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

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

122 123
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key u.Key, count int) <-chan peer.Peer {
	peerOut := make(chan peer.Peer, count)
124 125 126 127 128
	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
			ps.Add(p)
			peerOut <- p
			if count <= 0 {
				return
			}
		}

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

157
func (dht *IpfsDHT) addPeerListAsync(k u.Key, peers []*pb.Message_Peer, ps *peerSet, count int, out chan peer.Peer) {
Jeromy's avatar
Jeromy committed
158
	done := make(chan struct{})
159
	for _, pbp := range peers {
160
		go func(mp *pb.Message_Peer) {
Jeromy's avatar
Jeromy committed
161 162 163 164 165 166 167 168 169 170 171
			defer func() { done <- struct{}{} }()
			// construct new peer
			p, err := dht.ensureConnectedToPeer(mp)
			if err != nil {
				log.Error("%s", err)
				return
			}
			if p == nil {
				log.Error("Got nil peer from ensureConnectedToPeer")
				return
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172

Jeromy's avatar
Jeromy committed
173 174 175 176 177 178 179 180 181 182
			dht.providers.AddProvider(k, p)
			if ps.AddIfSmallerThan(p, count) {
				out <- p
			} else if ps.Size() >= count {
				return
			}
		}(pbp)
	}
	for _ = range peers {
		<-done
183 184 185
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186 187
// Find specific Peer
// FindPeer searches for a peer with given ID.
188
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189

190
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
191
	p, _ := dht.FindLocal(id)
192 193 194 195
	if p != nil {
		return p, nil
	}

196
	routeLevel := 0
Jeromy's avatar
Jeromy committed
197 198 199
	closest := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
	if closest == nil || len(closest) == 0 {
		return nil, kb.ErrLookupFailure
200
	}
201

Jeromy's avatar
Jeromy committed
202 203 204 205 206
	// Sanity...
	for _, p := range closest {
		if p.ID().Equal(id) {
			log.Error("Found target peer in list of closest peers...")
			return p, nil
207
		}
208
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214
		pmes, err := dht.findPeerSingle(ctx, p, id, routeLevel)
		if err != nil {
215
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
		}
217

Jeromy's avatar
Jeromy committed
218 219 220 221
		closer := pmes.GetCloserPeers()
		var clpeers []peer.Peer
		for _, pbp := range closer {
			np, err := dht.getPeer(peer.ID(pbp.GetId()))
222
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
223
				log.Warningf("Received invalid peer from query: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
				continue
225
			}
Jeromy's avatar
Jeromy committed
226 227 228 229
			ma, err := pbp.Address()
			if err != nil {
				log.Warning("Received peer with bad or missing address.")
				continue
230
			}
Jeromy's avatar
Jeromy committed
231 232 233 234 235 236 237 238
			np.AddAddress(ma)
			if pbp.GetId() == string(id) {
				return &dhtQueryResult{
					peer:    np,
					success: true,
				}, nil
			}
			clpeers = append(clpeers, np)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239 240
		}

Jeromy's avatar
Jeromy committed
241
		return &dhtQueryResult{closerPeers: clpeers}, nil
242
	})
243

Jeromy's avatar
Jeromy committed
244 245
	// run it!
	result, err := query.Run(ctx, closest)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246 247 248 249
	if err != nil {
		return nil, err
	}

250
	log.Debugf("FindPeer %v %v", id, result.success)
251
	if result.peer == nil {
252
		return nil, routing.ErrNotFound
253
	}
Jeromy's avatar
Jeromy committed
254

255
	return result.peer, nil
256 257
}

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

263
	pmes := pb.NewMessage(pb.Message_PING, "", 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
264
	_, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265
	log.Infof("ping %s end (err = %s)", p, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266
	return err
267
}