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

import (
4
	"bytes"
5
	"encoding/json"
6
	"errors"
7
	"math/rand"
8
	"sync"
9
	"time"
10

11 12
	proto "code.google.com/p/goprotobuf/proto"

13 14
	ma "github.com/jbenet/go-multiaddr"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	peer "github.com/jbenet/go-ipfs/peer"
16
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
	swarm "github.com/jbenet/go-ipfs/swarm"
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
)

21 22 23
// Pool size is the number of nodes used for group find/set RPC calls
var PoolSize = 6

Jeromy's avatar
Jeromy committed
24 25 26 27 28 29
// We put the 'K' in kademlia!
var KValue = 10

// Its in the paper, i swear
var AlphaValue = 3

30 31
// TODO: determine a way of creating and managing message IDs
func GenerateMessageID() uint64 {
32 33
	//return (uint64(rand.Uint32()) << 32) & uint64(rand.Uint32())
	return uint64(rand.Uint32())
34 35
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36 37 38 39 40
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
41
// This is the top level "Store" operation of the DHT
Jeromy's avatar
Jeromy committed
42 43
func (s *IpfsDHT) PutValue(key u.Key, value []byte) {
	complete := make(chan struct{})
Jeromy's avatar
Jeromy committed
44
	count := 0
45
	for _, route := range s.routes {
Jeromy's avatar
Jeromy committed
46 47 48 49 50 51 52 53 54 55 56 57
		peers := route.NearestPeers(kb.ConvertKey(key), KValue)
		for _, p := range peers {
			if p == nil {
				s.network.Error(kb.ErrLookupFailure)
				continue
			}
			count++
			go func(sp *peer.Peer) {
				err := s.putValueToNetwork(sp, string(key), value)
				if err != nil {
					s.network.Error(err)
				}
Jeromy's avatar
Jeromy committed
58
				complete <- struct{}{}
Jeromy's avatar
Jeromy committed
59
			}(p)
Jeromy's avatar
Jeromy committed
60 61
		}
	}
Jeromy's avatar
Jeromy committed
62
	for i := 0; i < count; i++ {
Jeromy's avatar
Jeromy committed
63
		<-complete
64
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
}

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
// A counter for incrementing a variable across multiple threads
type counter struct {
	n   int
	mut sync.RWMutex
}

func (c *counter) Increment() {
	c.mut.Lock()
	c.n++
	c.mut.Unlock()
}

func (c *counter) Decrement() {
	c.mut.Lock()
	c.n--
	c.mut.Unlock()
}

func (c *counter) Size() int {
	c.mut.RLock()
	defer c.mut.RUnlock()
	return c.n
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
type peerSet struct {
	ps map[string]bool
	lk sync.RWMutex
}

func newPeerSet() *peerSet {
	ps := new(peerSet)
	ps.ps = make(map[string]bool)
	return ps
}

func (ps *peerSet) Add(p *peer.Peer) {
	ps.lk.Lock()
	ps.ps[string(p.ID)] = true
	ps.lk.Unlock()
}

func (ps *peerSet) Contains(p *peer.Peer) bool {
	ps.lk.RLock()
	_, ok := ps.ps[string(p.ID)]
	ps.lk.RUnlock()
	return ok
}

func (ps *peerSet) Size() int {
	ps.lk.RLock()
	defer ps.lk.RUnlock()
	return len(ps.ps)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
// GetValue searches for the value corresponding to given Key.
Jeromy's avatar
Jeromy committed
122 123
// 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
124
func (s *IpfsDHT) GetValue(key u.Key, timeout time.Duration) ([]byte, error) {
Jeromy's avatar
Jeromy committed
125 126 127 128 129
	ll := startNewRpc("GET")
	defer func() {
		ll.EndLog()
		ll.Print()
	}()
130

Jeromy's avatar
Jeromy committed
131 132
	// If we have it local, dont bother doing an RPC!
	// NOTE: this might not be what we want to do...
Jeromy's avatar
Jeromy committed
133 134 135 136
	val, err := s.GetLocal(key)
	if err == nil {
		ll.Success = true
		u.DOut("Found local, returning.")
Jeromy's avatar
Jeromy committed
137 138 139
		return val, nil
	}

140 141 142
	route_level := 0
	closest := s.routes[route_level].NearestPeers(kb.ConvertKey(key), PoolSize)
	if closest == nil || len(closest) == 0 {
143 144 145
		return nil, kb.ErrLookupFailure
	}

146 147 148 149 150
	val_chan := make(chan []byte)
	npeer_chan := make(chan *peer.Peer, 30)
	proc_peer := make(chan *peer.Peer, 30)
	err_chan := make(chan error)
	after := time.After(timeout)
151
	pset := newPeerSet()
152

153
	for _, p := range closest {
154
		pset.Add(p)
155 156
		npeer_chan <- p
	}
157

158 159 160 161 162 163 164 165
	c := counter{}

	count := 0
	go func() {
		for {
			select {
			case p := <-npeer_chan:
				count++
Jeromy's avatar
Jeromy committed
166
				if count >= KValue {
167
					break
Jeromy's avatar
Jeromy committed
168
				}
169
				c.Increment()
170

171 172 173 174
				proc_peer <- p
			default:
				if c.Size() == 0 {
					err_chan <- u.ErrNotFound
175
				}
176 177 178
			}
		}
	}()
179

180 181 182 183 184 185 186 187 188
	process := func() {
		for {
			select {
			case p, ok := <-proc_peer:
				if !ok || p == nil {
					c.Decrement()
					return
				}
				val, peers, err := s.getValueOrPeers(p, key, timeout/4, route_level)
189
				if err != nil {
190 191
					u.DErr(err.Error())
					c.Decrement()
Jeromy's avatar
Jeromy committed
192
					continue
193
				}
194 195 196 197 198 199 200 201
				if val != nil {
					val_chan <- val
					c.Decrement()
					return
				}

				for _, np := range peers {
					// TODO: filter out peers that arent closer
Jeromy's avatar
Jeromy committed
202
					if !pset.Contains(np) && pset.Size() < KValue {
203 204 205
						pset.Add(np) //This is racey... make a single function to do operation
						npeer_chan <- np
					}
206 207
				}
				c.Decrement()
208
			}
209
		}
210
	}
211

Jeromy's avatar
Jeromy committed
212
	for i := 0; i < AlphaValue; i++ {
213 214 215 216 217 218 219 220 221 222 223
		go process()
	}

	select {
	case val := <-val_chan:
		return val, nil
	case err := <-err_chan:
		return nil, err
	case <-after:
		return nil, u.ErrTimeout
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226 227 228 229
}

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

// Announce that this node can provide value for given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230
func (s *IpfsDHT) Provide(key u.Key) error {
231
	peers := s.routes[0].NearestPeers(kb.ConvertKey(key), PoolSize)
232
	if len(peers) == 0 {
233
		return kb.ErrLookupFailure
234 235
	}

236 237 238
	pmes := DHTMessage{
		Type: PBDHTMessage_ADD_PROVIDER,
		Key:  string(key),
239 240 241
	}
	pbmes := pmes.ToProtobuf()

242
	for _, p := range peers {
243
		mes := swarm.NewMessage(p, pbmes)
244
		s.network.Send(mes)
245 246
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249
}

// FindProviders searches for peers who can provide the value for given key.
250
func (s *IpfsDHT) FindProviders(key u.Key, timeout time.Duration) ([]*peer.Peer, error) {
Jeromy's avatar
Jeromy committed
251 252 253 254 255 256
	ll := startNewRpc("FindProviders")
	defer func() {
		ll.EndLog()
		ll.Print()
	}()
	u.DOut("Find providers for: '%s'", key)
257
	p := s.routes[0].NearestPeer(kb.ConvertKey(key))
258 259 260
	if p == nil {
		return nil, kb.ErrLookupFailure
	}
261

Jeromy's avatar
Jeromy committed
262 263
	for level := 0; level < len(s.routes); {
		pmes, err := s.findProvidersSingle(p, key, level, timeout)
264 265 266
		if err != nil {
			return nil, err
		}
Jeromy's avatar
Jeromy committed
267 268 269 270 271 272 273 274
		if pmes.GetSuccess() {
			provs := s.addPeerList(key, pmes.GetPeers())
			ll.Success = true
			return provs, nil
		} else {
			closer := pmes.GetPeers()
			if len(closer) == 0 {
				level++
Jeromy's avatar
Jeromy committed
275 276
				continue
			}
Jeromy's avatar
Jeromy committed
277 278 279 280 281 282 283 284
			if peer.ID(closer[0].GetId()).Equal(s.self.ID) {
				u.DOut("Got myself back as a closer peer.")
				return nil, u.ErrNotFound
			}
			maddr, err := ma.NewMultiaddr(closer[0].GetAddr())
			if err != nil {
				// ??? Move up route level???
				panic("not yet implemented")
285 286
			}

Jeromy's avatar
Jeromy committed
287 288 289 290 291 292 293 294
			np, err := s.network.GetConnection(peer.ID(closer[0].GetId()), maddr)
			if err != nil {
				u.PErr("[%s] Failed to connect to: %s", s.self.ID.Pretty(), closer[0].GetAddr())
				level++
				continue
			}
			p = np
		}
295
	}
Jeromy's avatar
Jeromy committed
296
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
297 298 299 300 301 302
}

// Find specific Peer

// FindPeer searches for a peer with given ID.
func (s *IpfsDHT) FindPeer(id peer.ID, timeout time.Duration) (*peer.Peer, error) {
303 304 305 306 307 308
	// Check if were already connected to them
	p, _ := s.Find(id)
	if p != nil {
		return p, nil
	}

309
	route_level := 0
310
	p = s.routes[route_level].NearestPeer(kb.ConvertPeerID(id))
311 312
	if p == nil {
		return nil, kb.ErrLookupFailure
313
	}
314 315 316
	if p.ID.Equal(id) {
		return p, nil
	}
317

318 319 320 321 322
	for route_level < len(s.routes) {
		pmes, err := s.findPeerSingle(p, id, timeout, route_level)
		plist := pmes.GetPeers()
		if len(plist) == 0 {
			route_level++
323
		}
324 325 326
		found := plist[0]

		addr, err := ma.NewMultiaddr(found.GetAddr())
Jeromy's avatar
Jeromy committed
327
		if err != nil {
328
			return nil, err
Jeromy's avatar
Jeromy committed
329 330
		}

331
		nxtPeer, err := s.network.GetConnection(peer.ID(found.GetId()), addr)
Jeromy's avatar
Jeromy committed
332
		if err != nil {
333
			return nil, err
Jeromy's avatar
Jeromy committed
334
		}
335
		if pmes.GetSuccess() {
336 337 338
			if !id.Equal(nxtPeer.ID) {
				return nil, errors.New("got back invalid peer from 'successful' response")
			}
339 340 341
			return nxtPeer, nil
		} else {
			p = nxtPeer
Jeromy's avatar
Jeromy committed
342
		}
343
	}
344
	return nil, u.ErrNotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345
}
346 347 348 349 350 351

// Ping a peer, log the time it took
func (dht *IpfsDHT) Ping(p *peer.Peer, timeout time.Duration) error {
	// Thoughts: maybe this should accept an ID and do a peer lookup?
	u.DOut("Enter Ping.")

352
	pmes := DHTMessage{Id: GenerateMessageID(), Type: PBDHTMessage_PING}
353 354 355
	mes := swarm.NewMessage(p, pmes.ToProtobuf())

	before := time.Now()
356
	response_chan := dht.listener.Listen(pmes.Id, 1, time.Minute)
357
	dht.network.Send(mes)
358 359 360 361 362

	tout := time.After(timeout)
	select {
	case <-response_chan:
		roundtrip := time.Since(before)
363
		p.SetLatency(roundtrip)
364
		u.DOut("Ping took %s.", roundtrip.String())
365 366 367 368
		return nil
	case <-tout:
		// Timed out, think about removing peer from network
		u.DOut("Ping peer timed out.")
369
		dht.listener.Unlisten(pmes.Id)
370 371 372
		return u.ErrTimeout
	}
}
373 374 375 376

func (dht *IpfsDHT) GetDiagnostic(timeout time.Duration) ([]*diagInfo, error) {
	u.DOut("Begin Diagnostic")
	//Send to N closest peers
377
	targets := dht.routes[0].NearestPeers(kb.ConvertPeerID(dht.self.ID), 10)
378 379

	// TODO: Add timeout to this struct so nodes know when to return
380 381 382
	pmes := DHTMessage{
		Type: PBDHTMessage_DIAGNOSTIC,
		Id:   GenerateMessageID(),
383 384
	}

385
	listenChan := dht.listener.Listen(pmes.Id, len(targets), time.Minute*2)
386 387

	pbmes := pmes.ToProtobuf()
388
	for _, p := range targets {
389
		mes := swarm.NewMessage(p, pbmes)
390
		dht.network.Send(mes)
391 392 393 394 395 396 397 398 399
	}

	var out []*diagInfo
	after := time.After(timeout)
	for count := len(targets); count > 0; {
		select {
		case <-after:
			u.DOut("Diagnostic request timed out.")
			return out, u.ErrTimeout
Jeromy's avatar
Jeromy committed
400
		case resp := <-listenChan:
401
			pmes_out := new(PBDHTMessage)
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
			err := proto.Unmarshal(resp.Data, pmes_out)
			if err != nil {
				// NOTE: here and elsewhere, need to audit error handling,
				//		some errors should be continued on from
				return out, err
			}

			dec := json.NewDecoder(bytes.NewBuffer(pmes_out.GetValue()))
			for {
				di := new(diagInfo)
				err := dec.Decode(di)
				if err != nil {
					break
				}

				out = append(out, di)
			}
		}
	}

422
	return nil, nil
423
}