dht_bootstrap.go 5.72 KB
Newer Older
1 2 3 4 5 6
// Package dht implements a distributed hash table that satisfies the ipfs routing
// interface. This DHT is modeled after kademlia with Coral and S/Kademlia modifications.
package dht

import (
	"crypto/rand"
7
	"errors"
8 9 10 11 12 13 14 15 16 17
	"fmt"
	"sync"
	"time"

	peer "github.com/jbenet/go-ipfs/p2p/peer"
	routing "github.com/jbenet/go-ipfs/routing"
	u "github.com/jbenet/go-ipfs/util"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	goprocess "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
18
	periodicproc "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/periodic"
19 20
)

21
// BootstrapConfig specifies parameters used bootstrapping the DHT.
22
//
23 24 25 26 27 28 29 30
// Note there is a tradeoff between the bootstrap period and the
// number of queries. We could support a higher period with less
// queries.
type BootstrapConfig struct {
	Queries int           // how many queries to run per period
	Period  time.Duration // how often to run periodi cbootstrap.
	Timeout time.Duration // how long to wait for a bootstrao query to run
}
31

32 33 34 35 36 37
var DefaultBootstrapConfig = BootstrapConfig{
	// For now, this is set to 1 query.
	// We are currently more interested in ensuring we have a properly formed
	// DHT than making sure our dht minimizes traffic. Once we are more certain
	// of our implementation's robustness, we should lower this down to 8 or 4.
	Queries: 1,
38

39 40 41 42 43
	// For now, this is set to 10 seconds, which is an aggressive period. We are
	// We are currently more interested in ensuring we have a properly formed
	// DHT than making sure our dht minimizes traffic. Once we are more certain
	// implementation's robustness, we should lower this down to 30s or 1m.
	Period: time.Duration(20 * time.Second),
44

45 46 47
	Timeout: time.Duration(20 * time.Second),
}

48 49 50 51 52
func (dht *IpfsDHT) Bootstrap(context.Context) error {
	// Bootstrap satisfies the routing interface
	return errors.New("TODO: perform DHT bootstrap")
}

53 54 55 56 57 58
// Bootstrap ensures the dht routing table remains healthy as peers come and go.
// it builds up a list of peers by requesting random peer IDs. The Bootstrap
// process will run a number of queries each time, and run every time signal fires.
// These parameters are configurable.
//
// Bootstrap returns a process, so the user can stop it.
59
func (dht *IpfsDHT) BootstrapWithConfig(config BootstrapConfig) (goprocess.Process, error) {
60 61
	sig := time.Tick(config.Period)
	return dht.BootstrapOnSignal(config, sig)
62 63 64 65 66 67 68 69
}

// SignalBootstrap ensures the dht routing table remains healthy as peers come and go.
// it builds up a list of peers by requesting random peer IDs. The Bootstrap
// process will run a number of queries each time, and run every time signal fires.
// These parameters are configurable.
//
// SignalBootstrap returns a process, so the user can stop it.
70 71 72
func (dht *IpfsDHT) BootstrapOnSignal(cfg BootstrapConfig, signal <-chan time.Time) (goprocess.Process, error) {
	if cfg.Queries <= 0 {
		return nil, fmt.Errorf("invalid number of queries: %d", cfg.Queries)
73 74 75 76 77 78
	}

	if signal == nil {
		return nil, fmt.Errorf("invalid signal: %v", signal)
	}

79 80 81 82 83
	proc := periodicproc.Ticker(signal, func(worker goprocess.Process) {
		// it would be useful to be able to send out signals of when we bootstrap, too...
		// maybe this is a good case for whole module event pub/sub?

		ctx := dht.Context()
84
		if err := dht.runBootstrap(ctx, cfg); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85
			log.Warning(err)
86
			// A bootstrapping error is important to notice but not fatal.
87 88 89 90 91 92 93
		}
	})

	return proc, nil
}

// runBootstrap builds up list of peers by requesting random peer IDs
94
func (dht *IpfsDHT) runBootstrap(ctx context.Context, cfg BootstrapConfig) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95 96 97 98 99 100
	bslog := func(msg string) {
		log.Debugf("DHT %s dhtRunBootstrap %s -- routing table size: %d", dht.self, msg, dht.routingTable.Size())
	}
	bslog("start")
	defer bslog("end")
	defer log.EventBegin(ctx, "dhtRunBootstrap").Done()
101 102 103 104 105 106 107 108

	var merr u.MultiErr

	randomID := func() peer.ID {
		// 16 random bytes is not a valid peer id. it may be fine becuase
		// the dht will rehash to its own keyspace anyway.
		id := make([]byte, 16)
		rand.Read(id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
		id = u.Hash(id)
110 111 112 113
		return peer.ID(id)
	}

	// bootstrap sequentially, as results will compound
114
	ctx, cancel := context.WithTimeout(ctx, cfg.Timeout)
115
	defer cancel()
116 117 118 119 120 121 122 123 124 125
	runQuery := func(ctx context.Context, id peer.ID) {
		p, err := dht.FindPeer(ctx, id)
		if err == routing.ErrNotFound {
			// this isn't an error. this is precisely what we expect.
		} else if err != nil {
			merr = append(merr, err)
		} else {
			// woah, actually found a peer with that ID? this shouldn't happen normally
			// (as the ID we use is not a real ID). this is an odd error worth logging.
			err := fmt.Errorf("Bootstrap peer error: Actually FOUND peer. (%s, %s)", id, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126
			log.Warningf("%s", err)
127 128 129 130 131 132 133 134
			merr = append(merr, err)
		}
	}

	sequential := true
	if sequential {
		// these should be parallel normally. but can make them sequential for debugging.
		// note that the core/bootstrap context deadline should be extended too for that.
135
		for i := 0; i < cfg.Queries; i++ {
136
			id := randomID()
137
			log.Debugf("Bootstrapping query (%d/%d) to random ID: %s", i+1, cfg.Queries, id)
138 139 140 141 142 143 144 145 146
			runQuery(ctx, id)
		}

	} else {
		// note on parallelism here: the context is passed in to the queries, so they
		// **should** exit when it exceeds, making this function exit on ctx cancel.
		// normally, we should be selecting on ctx.Done() here too, but this gets
		// complicated to do with WaitGroup, and doesnt wait for the children to exit.
		var wg sync.WaitGroup
147
		for i := 0; i < cfg.Queries; i++ {
148 149 150 151 152
			wg.Add(1)
			go func() {
				defer wg.Done()

				id := randomID()
153
				log.Debugf("Bootstrapping query (%d/%d) to random ID: %s", i+1, cfg.Queries, id)
154 155 156 157 158 159 160 161 162 163 164
				runQuery(ctx, id)
			}()
		}
		wg.Wait()
	}

	if len(merr) > 0 {
		return merr
	}
	return nil
}