fsrepo.go 15.1 KB
Newer Older
1 2 3
package fsrepo

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4 5
	"errors"
	"fmt"
6
	"io"
7
	"os"
8
	"path"
9
	"strconv"
10
	"strings"
11
	"sync"
12

13
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
14
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/flatfs"
15
	levelds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/leveldb"
16
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/measure"
17
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/mount"
18 19 20 21 22
	ldbopts "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt"
	repo "github.com/ipfs/go-ipfs/repo"
	"github.com/ipfs/go-ipfs/repo/common"
	config "github.com/ipfs/go-ipfs/repo/config"
	lockfile "github.com/ipfs/go-ipfs/repo/fsrepo/lock"
23
	mfsr "github.com/ipfs/go-ipfs/repo/fsrepo/migrations"
24 25 26 27 28 29
	serialize "github.com/ipfs/go-ipfs/repo/fsrepo/serialize"
	dir "github.com/ipfs/go-ipfs/thirdparty/dir"
	"github.com/ipfs/go-ipfs/thirdparty/eventlog"
	u "github.com/ipfs/go-ipfs/util"
	util "github.com/ipfs/go-ipfs/util"
	ds2 "github.com/ipfs/go-ipfs/util/datastore2"
30 31
)

32
// version number that we are currently expecting to see
33 34
var RepoVersion = "2"

35 36
var migrationInstructions = `See https://github.com/ipfs/fs-repo-migrations/blob/master/run.md
Sorry for the inconvenience. In the future, these will run automatically.`
37

38 39 40 41 42 43 44 45 46
var errIncorrectRepoFmt = `Repo has incorrect version: %s
Program version is: %s
Please run the ipfs migration tool before continuing.
` + migrationInstructions

var (
	ErrNoVersion = errors.New("no version file found, please run 0-to-1 migration tool.\n" + migrationInstructions)
	ErrOldRepo   = errors.New("ipfs repo found in old '~/.go-ipfs' location, please run migration tool.\n" + migrationInstructions)
)
47

48 49 50 51 52 53 54
type NoRepoError struct {
	Path string
}

var _ error = NoRepoError{}

func (err NoRepoError) Error() string {
rht's avatar
rht committed
55
	return fmt.Sprintf("no ipfs repo found in %s. please run: ipfs init", err.Path)
56 57
}

58
const (
59
	leveldbDirectory = "datastore"
60
	flatfsDirectory  = "blocks"
61 62
)

63
var (
64 65 66

	// packageLock must be held to while performing any operation that modifies an
	// FSRepo's state field. This includes Init, Open, Close, and Remove.
Tommi Virtanen's avatar
Tommi Virtanen committed
67
	packageLock sync.Mutex
68

69 70 71 72 73 74 75 76 77 78 79 80 81
	// onlyOne keeps track of open FSRepo instances.
	//
	// TODO: once command Context / Repo integration is cleaned up,
	// this can be removed. Right now, this makes ConfigCmd.Run
	// function try to open the repo twice:
	//
	//     $ ipfs daemon &
	//     $ ipfs config foo
	//
	// The reason for the above is that in standalone mode without the
	// daemon, `ipfs config` tries to save work by not building the
	// full IpfsNode, but accessing the Repo directly.
	onlyOne repo.OnlyOne
82 83
)

84 85
// FSRepo represents an IPFS FileSystem Repo. It is safe for use by multiple
// callers.
86
type FSRepo struct {
87 88
	// has Close been called already
	closed bool
Brian Tiger Chow's avatar
Brian Tiger Chow committed
89 90
	// path is the file-system path
	path string
91 92 93
	// lockfile is the file system lock to prevent others from opening
	// the same fsrepo path concurrently
	lockfile io.Closer
94
	config   *config.Config
95 96
	ds       ds.ThreadSafeDatastore
	// tracked separately for use in Close; do not use directly.
97 98 99
	leveldbDS      levelds.Datastore
	metricsBlocks  measure.DatastoreCloser
	metricsLevelDB measure.DatastoreCloser
100 101
}

Tommi Virtanen's avatar
Tommi Virtanen committed
102 103
var _ repo.Repo = (*FSRepo)(nil)

104 105
// Open the FSRepo at path. Returns an error if the repo is not
// initialized.
106 107 108 109 110 111 112 113
func Open(repoPath string) (repo.Repo, error) {
	fn := func() (repo.Repo, error) {
		return open(repoPath)
	}
	return onlyOne.Open(repoPath, fn)
}

func open(repoPath string) (repo.Repo, error) {
114 115 116
	packageLock.Lock()
	defer packageLock.Unlock()

117
	r, err := newFSRepo(repoPath)
118 119 120 121
	if err != nil {
		return nil, err
	}

122 123 124
	// Check if its initialized
	if err := checkInitialized(r.path); err != nil {
		return nil, err
125
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
126

Tommi Virtanen's avatar
Tommi Virtanen committed
127 128 129 130 131 132 133 134 135 136 137 138
	r.lockfile, err = lockfile.Lock(r.path)
	if err != nil {
		return nil, err
	}
	keepLocked := false
	defer func() {
		// unlock on error, leave it locked on success
		if !keepLocked {
			r.lockfile.Close()
		}
	}()

139
	// Check version, and error out if not matching
140
	ver, err := mfsr.RepoPath(r.path).Version()
141 142
	if err != nil {
		if os.IsNotExist(err) {
143
			return nil, ErrNoVersion
144 145 146 147
		}
		return nil, err
	}

148
	if ver != RepoVersion {
149
		return nil, fmt.Errorf(errIncorrectRepoFmt, ver, RepoVersion)
150 151
	}

152 153 154 155 156 157 158 159 160 161 162 163 164
	// check repo path, then check all constituent parts.
	if err := dir.Writable(r.path); err != nil {
		return nil, err
	}

	if err := r.openConfig(); err != nil {
		return nil, err
	}

	if err := r.openDatastore(); err != nil {
		return nil, err
	}

165
	// setup eventlogger
166 167
	configureEventLoggerAtRepoPath(r.config, r.path)

Tommi Virtanen's avatar
Tommi Virtanen committed
168
	keepLocked = true
169
	return r, nil
170 171
}

172 173 174 175 176 177 178 179 180 181 182 183 184
func newFSRepo(rpath string) (*FSRepo, error) {
	expPath, err := u.TildeExpansion(path.Clean(rpath))
	if err != nil {
		return nil, err
	}

	return &FSRepo{path: expPath}, nil
}

func checkInitialized(path string) error {
	if !isInitializedUnsynced(path) {
		alt := strings.Replace(path, ".ipfs", ".go-ipfs", 1)
		if isInitializedUnsynced(alt) {
185
			return ErrOldRepo
186
		}
187
		return NoRepoError{Path: path}
188 189 190 191
	}
	return nil
}

192 193 194
// ConfigAt returns an error if the FSRepo at the given path is not
// initialized. This function allows callers to read the config file even when
// another process is running and holding the lock.
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
195
func ConfigAt(repoPath string) (*config.Config, error) {
196 197 198 199 200

	// packageLock must be held to ensure that the Read is atomic.
	packageLock.Lock()
	defer packageLock.Unlock()

Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
201 202 203 204
	configFilename, err := config.Filename(repoPath)
	if err != nil {
		return nil, err
	}
205
	return serialize.Load(configFilename)
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
206 207
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
// configIsInitialized returns true if the repo is initialized at
// provided |path|.
func configIsInitialized(path string) bool {
	configFilename, err := config.Filename(path)
	if err != nil {
		return false
	}
	if !util.FileExists(configFilename) {
		return false
	}
	return true
}

func initConfig(path string, conf *config.Config) error {
	if configIsInitialized(path) {
		return nil
	}
	configFilename, err := config.Filename(path)
	if err != nil {
		return err
	}
	// initialization is the one time when it's okay to write to the config
	// without reading the config from disk and merging any user-provided keys
	// that may exist.
	if err := serialize.WriteConfigFile(configFilename, conf); err != nil {
		return err
	}
	return nil
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
238
// Init initializes a new FSRepo at the given path with the provided config.
239
// TODO add support for custom datastores.
240
func Init(repoPath string, conf *config.Config) error {
241 242 243 244

	// packageLock must be held to ensure that the repo is not initialized more
	// than once.
	packageLock.Lock()
245
	defer packageLock.Unlock()
246

247
	if isInitializedUnsynced(repoPath) {
248 249
		return nil
	}
250

251
	if err := initConfig(repoPath, conf); err != nil {
252 253 254
		return err
	}

255 256
	// The actual datastore contents are initialized lazily when Opened.
	// During Init, we merely check that the directory is writeable.
257 258
	leveldbPath := path.Join(repoPath, leveldbDirectory)
	if err := dir.Writable(leveldbPath); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259
		return fmt.Errorf("datastore: %s", err)
260
	}
261

262 263 264 265 266
	flatfsPath := path.Join(repoPath, flatfsDirectory)
	if err := dir.Writable(flatfsPath); err != nil {
		return fmt.Errorf("datastore: %s", err)
	}

267 268 269 270
	if err := dir.Writable(path.Join(repoPath, "logs")); err != nil {
		return err
	}

271 272 273 274
	if err := mfsr.RepoPath(repoPath).WriteVersion(RepoVersion); err != nil {
		return err
	}

275 276 277
	return nil
}

278
// Remove recursively removes the FSRepo at |path|.
279 280 281
func Remove(repoPath string) error {
	repoPath = path.Clean(repoPath)
	return os.RemoveAll(repoPath)
282 283
}

284 285
// LockedByOtherProcess returns true if the FSRepo is locked by another
// process. If true, then the repo cannot be opened by this process.
286
func LockedByOtherProcess(repoPath string) (bool, error) {
287 288
	repoPath = path.Clean(repoPath)

289 290
	// TODO replace this with the "api" file
	// https://github.com/ipfs/specs/tree/master/repo/fs-repo
291

292
	// NB: the lock is only held when repos are Open
293
	return lockfile.Locked(repoPath)
294 295
}

296 297 298 299 300 301 302 303 304 305 306 307 308 309
// openConfig returns an error if the config file is not present.
func (r *FSRepo) openConfig() error {
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
	conf, err := serialize.Load(configFilename)
	if err != nil {
		return err
	}
	r.config = conf
	return nil
}

310 311
// openDatastore returns an error if the config file is not present.
func (r *FSRepo) openDatastore() error {
312
	leveldbPath := path.Join(r.path, leveldbDirectory)
313 314 315
	var err error
	// save leveldb reference so it can be neatly closed afterward
	r.leveldbDS, err = levelds.NewDatastore(leveldbPath, &levelds.Options{
316 317 318
		Compression: ldbopts.NoCompression,
	})
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
319
		return errors.New("unable to open leveldb datastore")
320
	}
321 322 323 324 325 326 327 328 329 330 331 332 333 334

	// 4TB of 256kB objects ~=17M objects, splitting that 256-way
	// leads to ~66k objects per dir, splitting 256*256-way leads to
	// only 256.
	//
	// The keys seen by the block store have predictable prefixes,
	// including "/" from datastore.Key and 2 bytes from multihash. To
	// reach a uniform 256-way split, we need approximately 4 bytes of
	// prefix.
	blocksDS, err := flatfs.New(path.Join(r.path, flatfsDirectory), 4)
	if err != nil {
		return errors.New("unable to open flatfs datastore")
	}

335 336 337 338 339 340 341 342 343 344 345 346
	// Add our PeerID to metrics paths to keep them unique
	//
	// As some tests just pass a zero-value Config to fsrepo.Init,
	// cope with missing PeerID.
	id := r.config.Identity.PeerID
	if id == "" {
		// the tests pass in a zero Config; cope with it
		id = fmt.Sprintf("uninitialized_%p", r)
	}
	prefix := "fsrepo." + id + ".datastore."
	r.metricsBlocks = measure.New(prefix+"blocks", blocksDS)
	r.metricsLevelDB = measure.New(prefix+"leveldb", r.leveldbDS)
347
	mountDS := mount.New([]mount.Mount{
348 349 350 351 352 353 354 355
		{
			Prefix:    ds.NewKey("/blocks"),
			Datastore: r.metricsBlocks,
		},
		{
			Prefix:    ds.NewKey("/"),
			Datastore: r.metricsLevelDB,
		},
356 357 358 359 360 361 362 363 364
	})
	// Make sure it's ok to claim the virtual datastore from mount as
	// threadsafe. There's no clean way to make mount itself provide
	// this information without copy-pasting the code into two
	// variants. This is the same dilemma as the `[].byte` attempt at
	// introducing const types to Go.
	var _ ds.ThreadSafeDatastore = blocksDS
	var _ ds.ThreadSafeDatastore = r.leveldbDS
	r.ds = ds2.ClaimThreadSafe{mountDS}
365 366 367
	return nil
}

368 369 370 371 372 373 374 375 376 377 378 379
func configureEventLoggerAtRepoPath(c *config.Config, repoPath string) {
	eventlog.Configure(eventlog.LevelInfo)
	eventlog.Configure(eventlog.LdJSONFormatter)
	rotateConf := eventlog.LogRotatorConfig{
		Filename:   path.Join(repoPath, "logs", "events.log"),
		MaxSizeMB:  c.Log.MaxSizeMB,
		MaxBackups: c.Log.MaxBackups,
		MaxAgeDays: c.Log.MaxAgeDays,
	}
	eventlog.Configure(eventlog.OutputRotatingLogFile(rotateConf))
}

380 381 382 383 384
// Close closes the FSRepo, releasing held resources.
func (r *FSRepo) Close() error {
	packageLock.Lock()
	defer packageLock.Unlock()

385
	if r.closed {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
386
		return errors.New("repo is closed")
387
	}
388

389 390 391 392 393 394
	if err := r.metricsBlocks.Close(); err != nil {
		return err
	}
	if err := r.metricsLevelDB.Close(); err != nil {
		return err
	}
395
	if err := r.leveldbDS.Close(); err != nil {
396
		return err
397
	}
398 399 400 401 402 403 404 405 406

	// This code existed in the previous versions, but
	// EventlogComponent.Close was never called. Preserving here
	// pending further discussion.
	//
	// TODO It isn't part of the current contract, but callers may like for us
	// to disable logging once the component is closed.
	// eventlog.Configure(eventlog.Output(os.Stderr))

407 408 409 410 411
	r.closed = true
	if err := r.lockfile.Close(); err != nil {
		return err
	}
	return nil
412 413
}

414 415 416 417
// Config returns the FSRepo's config. This method must not be called if the
// repo is not open.
//
// Result when not Open is undefined. The method may panic if it pleases.
418
func (r *FSRepo) Config() *config.Config {
419 420 421 422 423 424 425 426 427

	// It is not necessary to hold the package lock since the repo is in an
	// opened state. The package lock is _not_ meant to ensure that the repo is
	// thread-safe. The package lock is only meant to guard againt removal and
	// coordinate the lockfile. However, we provide thread-safety to keep
	// things simple.
	packageLock.Lock()
	defer packageLock.Unlock()

428 429
	if r.closed {
		panic("repo is closed")
430
	}
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	return r.config
}

// setConfigUnsynced is for private use.
func (r *FSRepo) setConfigUnsynced(updated *config.Config) error {
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
	// to avoid clobbering user-provided keys, must read the config from disk
	// as a map, write the updated struct values to the map and write the map
	// to disk.
	var mapconf map[string]interface{}
	if err := serialize.ReadConfigFile(configFilename, &mapconf); err != nil {
		return err
	}
	m, err := config.ToMap(updated)
	if err != nil {
		return err
	}
	for k, v := range m {
		mapconf[k] = v
	}
	if err := serialize.WriteConfigFile(configFilename, mapconf); err != nil {
		return err
	}
	*r.config = *updated // copy so caller cannot modify this private config
	return nil
459 460
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
461
// SetConfig updates the FSRepo's config.
462
func (r *FSRepo) SetConfig(updated *config.Config) error {
463 464 465 466 467

	// packageLock is held to provide thread-safety.
	packageLock.Lock()
	defer packageLock.Unlock()

468
	return r.setConfigUnsynced(updated)
469 470
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
471
// GetConfigKey retrieves only the value of a particular key.
472
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
473 474 475
	packageLock.Lock()
	defer packageLock.Unlock()

476
	if r.closed {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
477
		return nil, errors.New("repo is closed")
478
	}
479 480 481 482 483 484 485 486 487 488

	filename, err := config.Filename(r.path)
	if err != nil {
		return nil, err
	}
	var cfg map[string]interface{}
	if err := serialize.ReadConfigFile(filename, &cfg); err != nil {
		return nil, err
	}
	return common.MapGetKV(cfg, key)
489 490
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
491
// SetConfigKey writes the value of a particular key.
492
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
493 494 495
	packageLock.Lock()
	defer packageLock.Unlock()

496
	if r.closed {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
497
		return errors.New("repo is closed")
498
	}
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

	filename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
	switch v := value.(type) {
	case string:
		if i, err := strconv.Atoi(v); err == nil {
			value = i
		}
	}
	var mapconf map[string]interface{}
	if err := serialize.ReadConfigFile(filename, &mapconf); err != nil {
		return err
	}
	if err := common.MapSetKV(mapconf, key, value); err != nil {
		return err
	}
	conf, err := config.FromMap(mapconf)
	if err != nil {
		return err
	}
	if err := serialize.WriteConfigFile(filename, mapconf); err != nil {
		return err
	}
	return r.setConfigUnsynced(conf) // TODO roll this into this method
525 526
}

527 528 529 530
// Datastore returns a repo-owned datastore. If FSRepo is Closed, return value
// is undefined.
func (r *FSRepo) Datastore() ds.ThreadSafeDatastore {
	packageLock.Lock()
531
	d := r.ds
532 533 534 535
	packageLock.Unlock()
	return d
}

536
var _ io.Closer = &FSRepo{}
537
var _ repo.Repo = &FSRepo{}
538

539 540
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
541 542
	// packageLock is held to ensure that another caller doesn't attempt to
	// Init or Remove the repo while this call is in progress.
543 544
	packageLock.Lock()
	defer packageLock.Unlock()
545

546
	return isInitializedUnsynced(path)
547 548
}

549 550
// private methods below this point. NB: packageLock must held by caller.

551
// isInitializedUnsynced reports whether the repo is initialized. Caller must
552
// hold the packageLock.
553 554
func isInitializedUnsynced(repoPath string) bool {
	if !configIsInitialized(repoPath) {
555 556
		return false
	}
557
	if !util.FileExists(path.Join(repoPath, leveldbDirectory)) {
558
		return false
559 560
	}
	return true
561
}