builder.go 5.2 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3
package core

import (
4 5
	"crypto/rand"
	"encoding/base64"
Jeromy's avatar
Jeromy committed
6
	"errors"
7 8 9
	"os"
	"syscall"
	"time"
Jeromy's avatar
Jeromy committed
10

11 12 13 14 15 16
	bstore "github.com/ipfs/go-ipfs/blocks/blockstore"
	bserv "github.com/ipfs/go-ipfs/blockservice"
	offline "github.com/ipfs/go-ipfs/exchange/offline"
	dag "github.com/ipfs/go-ipfs/merkledag"
	path "github.com/ipfs/go-ipfs/path"
	pin "github.com/ipfs/go-ipfs/pin"
17
	repo "github.com/ipfs/go-ipfs/repo"
18
	cfg "github.com/ipfs/go-ipfs/repo/config"
Jeromy's avatar
Jeromy committed
19

20
	context "context"
George Antoniadis's avatar
George Antoniadis committed
21
	retry "gx/ipfs/QmPF5kxTYFkzhaY5LmkExood7aTTZBHWQC6cjdDQBuGrjp/retry-datastore"
22
	metrics "gx/ipfs/QmRg1gKTHzc3CZXSKzem8aR4E3TubFhbgXwfVuWnSK5CC5/go-metrics-interface"
23 24 25
	goprocessctx "gx/ipfs/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP/goprocess/context"
	pstore "gx/ipfs/QmXXCcQ7CLg5a81Ui9TTR35QcR4y7ZyihxwfjqaHfUVcVo/go-libp2p-peerstore"
	key "gx/ipfs/QmYEoKZXHoAToWfhGF3vryhMn3WWhE1o2MasQ8uzY5iDi9/go-key"
George Antoniadis's avatar
George Antoniadis committed
26 27
	ds "gx/ipfs/QmbzuUusHqaLLoNTDEVLcSF6vZDHZDLPC7p4bztRvvkXxU/go-datastore"
	dsync "gx/ipfs/QmbzuUusHqaLLoNTDEVLcSF6vZDHZDLPC7p4bztRvvkXxU/go-datastore/sync"
28
	ci "gx/ipfs/QmfWDLQjGjVe4fr5CoztYW2DYYjRysMJrFe1RCsXLPTf46/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
29 30
)

31 32 33
type BuildCfg struct {
	// If online is set, the node will have networking enabled
	Online bool
Jeromy's avatar
Jeromy committed
34

Jeromy's avatar
Jeromy committed
35 36 37
	// ExtraOpts is a map of extra options used to configure the ipfs nodes creation
	ExtraOpts map[string]bool

38 39 40 41
	// If permament then node should run more expensive processes
	// that will improve performance in long run
	Permament bool

42 43 44 45 46 47
	// If NilRepo is set, a repo backed by a nil datastore will be constructed
	NilRepo bool

	Routing RoutingOption
	Host    HostOption
	Repo    repo.Repo
Jeromy's avatar
Jeromy committed
48 49
}

Jeromy's avatar
Jeromy committed
50 51 52 53 54 55 56 57
func (cfg *BuildCfg) getOpt(key string) bool {
	if cfg.ExtraOpts == nil {
		return false
	}

	return cfg.ExtraOpts[key]
}

58 59 60
func (cfg *BuildCfg) fillDefaults() error {
	if cfg.Repo != nil && cfg.NilRepo {
		return errors.New("cannot set a repo and specify nilrepo at the same time")
Jeromy's avatar
Jeromy committed
61
	}
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

	if cfg.Repo == nil {
		var d ds.Datastore
		d = ds.NewMapDatastore()
		if cfg.NilRepo {
			d = ds.NewNullDatastore()
		}
		r, err := defaultRepo(dsync.MutexWrap(d))
		if err != nil {
			return err
		}
		cfg.Repo = r
	}

	if cfg.Routing == nil {
		cfg.Routing = DHTOption
	}

	if cfg.Host == nil {
		cfg.Host = DefaultHostOption
	}

	return nil
Jeromy's avatar
Jeromy committed
85 86
}

87
func defaultRepo(dstore repo.Datastore) (repo.Repo, error) {
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	c := cfg.Config{}
	priv, pub, err := ci.GenerateKeyPairWithReader(ci.RSA, 1024, rand.Reader)
	if err != nil {
		return nil, err
	}

	data, err := pub.Hash()
	if err != nil {
		return nil, err
	}

	privkeyb, err := priv.Bytes()
	if err != nil {
		return nil, err
	}

	c.Bootstrap = cfg.DefaultBootstrapAddresses
	c.Addresses.Swarm = []string{"/ip4/0.0.0.0/tcp/4001"}
	c.Identity.PeerID = key.Key(data).B58String()
	c.Identity.PrivKey = base64.StdEncoding.EncodeToString(privkeyb)

Jeromy's avatar
Jeromy committed
109
	return &repo.Mock{
Jeromy's avatar
Jeromy committed
110
		D: dstore,
111 112
		C: c,
	}, nil
Jeromy's avatar
Jeromy committed
113 114
}

115 116 117 118
func NewNode(ctx context.Context, cfg *BuildCfg) (*IpfsNode, error) {
	if cfg == nil {
		cfg = new(BuildCfg)
	}
Jeromy's avatar
Jeromy committed
119

120 121 122 123
	err := cfg.fillDefaults()
	if err != nil {
		return nil, err
	}
Jakub Sztandera's avatar
Jakub Sztandera committed
124
	ctx = metrics.CtxScope(ctx, "ipfs")
Jeromy's avatar
Jeromy committed
125

126 127 128 129
	n := &IpfsNode{
		mode:      offlineMode,
		Repo:      cfg.Repo,
		ctx:       ctx,
Jeromy's avatar
Jeromy committed
130
		Peerstore: pstore.NewPeerstore(),
131 132 133 134
	}
	if cfg.Online {
		n.mode = onlineMode
	}
Jeromy's avatar
Jeromy committed
135

136 137
	// TODO: this is a weird circular-ish dependency, rework it
	n.proc = goprocessctx.WithContextAndTeardown(ctx, n.teardown)
Jeromy's avatar
Jeromy committed
138

139 140 141 142
	if err := setupNode(ctx, n, cfg); err != nil {
		n.Close()
		return nil, err
	}
Jeromy's avatar
Jeromy committed
143

144
	return n, nil
Jeromy's avatar
Jeromy committed
145 146
}

147 148 149 150 151 152 153 154 155
func isTooManyFDError(err error) bool {
	perr, ok := err.(*os.PathError)
	if ok && perr.Err == syscall.EMFILE {
		return true
	}

	return false
}

156 157 158 159
func setupNode(ctx context.Context, n *IpfsNode, cfg *BuildCfg) error {
	// setup local peer ID (private key is loaded in online setup)
	if err := n.loadID(); err != nil {
		return err
Jeromy's avatar
Jeromy committed
160
	}
161

162 163 164 165 166 167 168
	rds := &retry.Datastore{
		Batching:    n.Repo.Datastore(),
		Delay:       time.Millisecond * 200,
		Retries:     6,
		TempErrFunc: isTooManyFDError,
	}

169
	var err error
170
	bs := bstore.NewBlockstore(rds)
171
	opts := bstore.DefaultCacheOpts()
172 173 174 175 176 177
	conf, err := n.Repo.Config()
	if err != nil {
		return err
	}

	opts.HasBloomFilterSize = conf.Datastore.BloomFilterSize
178 179 180 181 182
	if !cfg.Permament {
		opts.HasBloomFilterSize = 0
	}

	n.Blockstore, err = bstore.CachedBlockstore(bs, ctx, opts)
183 184 185 186
	if err != nil {
		return err
	}

187 188 189 190 191 192
	rcfg, err := n.Repo.Config()
	if err != nil {
		return err
	}

	if rcfg.Datastore.HashOnRead {
193
		bs.HashOnRead(true)
194 195
	}

196
	if cfg.Online {
197
		do := setupDiscoveryOption(rcfg.Discovery)
Jeromy's avatar
Jeromy committed
198
		if err := n.startOnlineServices(ctx, cfg.Routing, cfg.Host, do, cfg.getOpt("pubsub")); err != nil {
199
			return err
200
		}
201 202
	} else {
		n.Exchange = offline.Exchange(n.Blockstore)
Jeromy's avatar
Jeromy committed
203
	}
204 205 206

	n.Blocks = bserv.New(n.Blockstore, n.Exchange)
	n.DAG = dag.NewDAGService(n.Blocks)
207 208 209

	internalDag := dag.NewDAGService(bserv.New(n.Blockstore, offline.Exchange(n.Blockstore)))
	n.Pinning, err = pin.LoadPinner(n.Repo.Datastore(), n.DAG, internalDag)
210 211 212 213 214
	if err != nil {
		// TODO: we should move towards only running 'NewPinner' explicity on
		// node init instead of implicitly here as a result of the pinner keys
		// not being found in the datastore.
		// this is kinda sketchy and could cause data loss
215
		n.Pinning = pin.NewPinner(n.Repo.Datastore(), n.DAG, internalDag)
216
	}
217
	n.Resolver = path.NewBasicResolver(n.DAG)
218

Jeromy's avatar
Jeromy committed
219 220 221 222 223
	err = n.loadFilesRoot()
	if err != nil {
		return err
	}

224
	return nil
Jeromy's avatar
Jeromy committed
225
}