routing.go 6.55 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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
	log.Debugf("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) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33
		log.Debugf("%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) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49
	log.Debugf("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!")
Jeromy's avatar
Jeromy committed
64
		return nil, kb.ErrLookupFailure
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
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89
	log.Debugf("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(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
	}()
	return peerOut
}

155
func (dht *IpfsDHT) addPeerListAsync(k u.Key, peers []*Message_Peer, ps *peerSet, count int, out chan peer.Peer) {
Jeromy's avatar
Jeromy committed
156
	done := make(chan struct{})
157
	for _, pbp := range peers {
Jeromy's avatar
Jeromy committed
158 159 160 161 162 163 164 165 166 167 168 169
		go func(mp *Message_Peer) {
			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
170

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

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
216 217 218 219
		closer := pmes.GetCloserPeers()
		var clpeers []peer.Peer
		for _, pbp := range closer {
			np, err := dht.getPeer(peer.ID(pbp.GetId()))
220
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
				log.Warningf("Received invalid peer from query: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222
				continue
223
			}
Jeromy's avatar
Jeromy committed
224 225 226 227
			ma, err := pbp.Address()
			if err != nil {
				log.Warning("Received peer with bad or missing address.")
				continue
228
			}
Jeromy's avatar
Jeromy committed
229 230 231 232 233 234 235 236
			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
237 238
		}

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

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

Jeromy's avatar
Jeromy committed
248
	log.Debug("FindPeer %v %v", id, result.success)
249 250
	if result.peer == nil {
		return nil, u.ErrNotFound
251
	}
Jeromy's avatar
Jeromy committed
252

253
	return result.peer, nil
254 255
}

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

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