fsrepo.go 13.5 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
	"io/ioutil"
8
	"os"
9
	"path"
10
	"strconv"
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/mount"
17 18 19 20 21
	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"
22
	mfsr "github.com/ipfs/go-ipfs/repo/fsrepo/migrations"
23 24 25 26 27 28
	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"
29 30
)

31 32
var RepoVersion = "2"

33
const (
34
	leveldbDirectory = "datastore"
35
	flatfsDirectory  = "blocks"
36 37
)

38
var (
39 40 41

	// 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
42
	packageLock sync.Mutex
43

44 45 46 47 48 49 50 51 52 53 54 55 56
	// 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
57 58
)

59 60
// FSRepo represents an IPFS FileSystem Repo. It is safe for use by multiple
// callers.
61
type FSRepo struct {
62 63
	// has Close been called already
	closed bool
Brian Tiger Chow's avatar
Brian Tiger Chow committed
64 65
	// path is the file-system path
	path string
66 67 68
	// lockfile is the file system lock to prevent others from opening
	// the same fsrepo path concurrently
	lockfile io.Closer
69
	config   *config.Config
70 71 72
	ds       ds.ThreadSafeDatastore
	// tracked separately for use in Close; do not use directly.
	leveldbDS levelds.Datastore
73 74
}

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

77 78
// Open the FSRepo at path. Returns an error if the repo is not
// initialized.
79 80 81 82 83 84 85 86
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) {
87 88 89
	packageLock.Lock()
	defer packageLock.Unlock()

Tommi Virtanen's avatar
Tommi Virtanen committed
90
	expPath, err := u.TildeExpansion(path.Clean(repoPath))
91 92 93 94
	if err != nil {
		return nil, err
	}

Tommi Virtanen's avatar
Tommi Virtanen committed
95 96
	r := &FSRepo{
		path: expPath,
97
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
98

Tommi Virtanen's avatar
Tommi Virtanen committed
99 100 101 102 103 104 105 106 107 108 109 110
	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()
		}
	}()

111
	if !isInitializedUnsynced(r.path) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
		return nil, errors.New("ipfs not initialized, please run 'ipfs init'")
113
	}
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

	// Check version, and error out if not matching
	ver, err := ioutil.ReadFile(path.Join(expPath, "version"))
	if err != nil {
		if os.IsNotExist(err) {
			return nil, errors.New("version check failed, no version file found, please run 0-to-1 migration tool.")
		}
		return nil, err
	}

	vers := string(ver)[:1]

	if vers != RepoVersion {
		return nil, fmt.Errorf("Repo has incorrect version: '%s'\nProgram version is: '%s'\nPlease run the appropriate migration tool before continuing",
			vers, RepoVersion)

	}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
	// check repo path, then check all constituent parts.
	// TODO acquire repo lock
	// TODO if err := initCheckDir(logpath); err != nil { // }
	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
	}

	// log.Debugf("writing eventlogs to ...", c.path)
	configureEventLoggerAtRepoPath(r.config, r.path)

Tommi Virtanen's avatar
Tommi Virtanen committed
150
	keepLocked = true
151
	return r, nil
152 153
}

154 155 156
// 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
157
func ConfigAt(repoPath string) (*config.Config, error) {
158 159 160 161 162

	// 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
163 164 165 166
	configFilename, err := config.Filename(repoPath)
	if err != nil {
		return nil, err
	}
167
	return serialize.Load(configFilename)
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
168 169
}

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
// 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
200
// Init initializes a new FSRepo at the given path with the provided config.
201
// TODO add support for custom datastores.
202
func Init(repoPath string, conf *config.Config) error {
203 204 205 206

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

209
	if isInitializedUnsynced(repoPath) {
210 211
		return nil
	}
212

213
	if err := initConfig(repoPath, conf); err != nil {
214 215 216
		return err
	}

217 218
	// The actual datastore contents are initialized lazily when Opened.
	// During Init, we merely check that the directory is writeable.
219 220
	leveldbPath := path.Join(repoPath, leveldbDirectory)
	if err := dir.Writable(leveldbPath); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
		return fmt.Errorf("datastore: %s", err)
222
	}
223

224 225 226 227 228
	flatfsPath := path.Join(repoPath, flatfsDirectory)
	if err := dir.Writable(flatfsPath); err != nil {
		return fmt.Errorf("datastore: %s", err)
	}

229 230 231 232
	if err := dir.Writable(path.Join(repoPath, "logs")); err != nil {
		return err
	}

233 234 235 236
	if err := mfsr.RepoPath(repoPath).WriteVersion(RepoVersion); err != nil {
		return err
	}

237 238 239
	return nil
}

240
// Remove recursively removes the FSRepo at |path|.
241 242 243
func Remove(repoPath string) error {
	repoPath = path.Clean(repoPath)
	return os.RemoveAll(repoPath)
244 245
}

246 247 248
// LockedByOtherProcess returns true if the FSRepo is locked by another
// process. If true, then the repo cannot be opened by this process.
func LockedByOtherProcess(repoPath string) bool {
249 250
	repoPath = path.Clean(repoPath)

251 252
	// TODO replace this with the "api" file
	// https://github.com/ipfs/specs/tree/master/repo/fs-repo
253

254
	// NB: the lock is only held when repos are Open
255
	return lockfile.Locked(repoPath)
256 257
}

258 259 260 261 262 263 264 265 266 267 268 269 270 271
// 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
}

272 273
// openDatastore returns an error if the config file is not present.
func (r *FSRepo) openDatastore() error {
274
	leveldbPath := path.Join(r.path, leveldbDirectory)
275 276 277
	var err error
	// save leveldb reference so it can be neatly closed afterward
	r.leveldbDS, err = levelds.NewDatastore(leveldbPath, &levelds.Options{
278 279 280
		Compression: ldbopts.NoCompression,
	})
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
281
		return errors.New("unable to open leveldb datastore")
282
	}
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

	// 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")
	}

	mountDS := mount.New([]mount.Mount{
		{Prefix: ds.NewKey("/blocks"), Datastore: blocksDS},
		{Prefix: ds.NewKey("/"), Datastore: r.leveldbDS},
	})
	// 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}
309 310 311
	return nil
}

312 313 314 315 316 317 318 319 320 321 322 323
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))
}

324 325 326 327 328
// Close closes the FSRepo, releasing held resources.
func (r *FSRepo) Close() error {
	packageLock.Lock()
	defer packageLock.Unlock()

329
	if r.closed {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
330
		return errors.New("repo is closed")
331
	}
332

333
	if err := r.leveldbDS.Close(); err != nil {
334
		return err
335
	}
336 337 338 339 340 341 342 343 344

	// 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))

345 346 347 348 349
	r.closed = true
	if err := r.lockfile.Close(); err != nil {
		return err
	}
	return nil
350 351
}

352 353 354 355
// 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.
356
func (r *FSRepo) Config() *config.Config {
357 358 359 360 361 362 363 364 365

	// 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()

366 367
	if r.closed {
		panic("repo is closed")
368
	}
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
	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
397 398
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
399
// SetConfig updates the FSRepo's config.
400
func (r *FSRepo) SetConfig(updated *config.Config) error {
401 402 403 404 405

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

406
	return r.setConfigUnsynced(updated)
407 408
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
409
// GetConfigKey retrieves only the value of a particular key.
410
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
411 412 413
	packageLock.Lock()
	defer packageLock.Unlock()

414
	if r.closed {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
415
		return nil, errors.New("repo is closed")
416
	}
417 418 419 420 421 422 423 424 425 426

	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)
427 428
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
429
// SetConfigKey writes the value of a particular key.
430
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
431 432 433
	packageLock.Lock()
	defer packageLock.Unlock()

434
	if r.closed {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
435
		return errors.New("repo is closed")
436
	}
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

	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
463 464
}

465 466 467 468
// Datastore returns a repo-owned datastore. If FSRepo is Closed, return value
// is undefined.
func (r *FSRepo) Datastore() ds.ThreadSafeDatastore {
	packageLock.Lock()
469
	d := r.ds
470 471 472 473
	packageLock.Unlock()
	return d
}

474
var _ io.Closer = &FSRepo{}
475
var _ repo.Repo = &FSRepo{}
476

477 478
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
479 480
	// packageLock is held to ensure that another caller doesn't attempt to
	// Init or Remove the repo while this call is in progress.
481 482
	packageLock.Lock()
	defer packageLock.Unlock()
483

484
	return isInitializedUnsynced(path)
485 486
}

487 488
// private methods below this point. NB: packageLock must held by caller.

489
// isInitializedUnsynced reports whether the repo is initialized. Caller must
490
// hold the packageLock.
491 492
func isInitializedUnsynced(repoPath string) bool {
	if !configIsInitialized(repoPath) {
493 494
		return false
	}
495
	if !util.FileExists(path.Join(repoPath, leveldbDirectory)) {
496
		return false
497 498
	}
	return true
499
}