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

import (
4
	"errors"
5
	"fmt"
6
	"io"
7
	"os"
8
	"path"
9
	"strconv"
10
	"sync"
11

12
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
13 14
	levelds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/leveldb"
	ldbopts "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt"
15
	repo "github.com/jbenet/go-ipfs/repo"
16
	"github.com/jbenet/go-ipfs/repo/common"
17
	config "github.com/jbenet/go-ipfs/repo/config"
18
	counter "github.com/jbenet/go-ipfs/repo/fsrepo/counter"
19
	lockfile "github.com/jbenet/go-ipfs/repo/fsrepo/lock"
20
	serialize "github.com/jbenet/go-ipfs/repo/fsrepo/serialize"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
21
	dir "github.com/jbenet/go-ipfs/thirdparty/dir"
22
	"github.com/jbenet/go-ipfs/thirdparty/eventlog"
Jeromy's avatar
Jeromy committed
23
	u "github.com/jbenet/go-ipfs/util"
24
	util "github.com/jbenet/go-ipfs/util"
25
	ds2 "github.com/jbenet/go-ipfs/util/datastore2"
26
	debugerror "github.com/jbenet/go-ipfs/util/debugerror"
27 28
)

29 30 31 32
const (
	defaultDataStoreDirectory = "datastore"
)

33
var (
34 35 36

	// packageLock must be held to while performing any operation that modifies an
	// FSRepo's state field. This includes Init, Open, Close, and Remove.
37
	packageLock sync.Mutex // protects openersCounter and lockfiles
38 39 40
	// lockfiles holds references to the Closers that ensure that repos are
	// only accessed by one process at a time.
	lockfiles map[string]io.Closer
41
	// openersCounter ensures that the Init is atomic.
42 43 44 45 46
	//
	// packageLock also protects numOpenedRepos
	//
	// If an operation is used when repo is Open and the operation does not
	// change the repo's state, the package lock does not need to be acquired.
47
	openersCounter *counter.Openers
48 49 50 51 52

	// protects dsOpenersCounter and datastores
	dsLock           sync.Mutex
	dsOpenersCounter *counter.Openers
	datastores       map[string]ds2.ThreadSafeDatastoreCloser
53 54 55
)

func init() {
56
	openersCounter = counter.NewOpenersCounter()
57
	lockfiles = make(map[string]io.Closer)
58 59 60

	dsOpenersCounter = counter.NewOpenersCounter()
	datastores = make(map[string]ds2.ThreadSafeDatastoreCloser)
61 62
}

63 64
// FSRepo represents an IPFS FileSystem Repo. It is safe for use by multiple
// callers.
65
type FSRepo struct {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
66 67 68 69
	// state is the FSRepo's state (unopened, opened, closed)
	state state
	// path is the file-system path
	path string
70 71
	// config is set on Open, guarded by packageLock
	config *config.Config
72 73
	// ds is set on Open
	ds ds2.ThreadSafeDatastoreCloser
74 75
}

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
78
// At returns a handle to an FSRepo at the provided |path|.
79
func At(repoPath string) *FSRepo {
80
	// This method must not have side-effects.
81
	return &FSRepo{
82 83
		path:  path.Clean(repoPath),
		state: unopened, // explicitly set for clarity
84 85 86
	}
}

87 88 89
// 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
90
func ConfigAt(repoPath string) (*config.Config, error) {
91 92 93 94 95

	// 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
96 97 98 99
	configFilename, err := config.Filename(repoPath)
	if err != nil {
		return nil, err
	}
100
	return serialize.Load(configFilename)
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
101 102
}

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
// 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
133
// Init initializes a new FSRepo at the given path with the provided config.
134
// TODO add support for custom datastores.
135
func Init(repoPath string, conf *config.Config) error {
136 137 138 139

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

142
	if isInitializedUnsynced(repoPath) {
143 144
		return nil
	}
145

146
	if err := initConfig(repoPath, conf); err != nil {
147 148 149
		return err
	}

150 151 152 153 154
	// The actual datastore contents are initialized lazily when Opened.
	// During Init, we merely check that the directory is writeable.
	p := path.Join(repoPath, defaultDataStoreDirectory)
	if err := dir.Writable(p); err != nil {
		return debugerror.Errorf("datastore: %s", err)
155
	}
156 157 158 159 160

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

161 162 163
	return nil
}

164
// Remove recursively removes the FSRepo at |path|.
165 166 167
func Remove(repoPath string) error {
	repoPath = path.Clean(repoPath)
	return os.RemoveAll(repoPath)
168 169
}

170 171 172
// 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 {
173 174
	repoPath = path.Clean(repoPath)

175 176
	// TODO replace this with the "api" file
	// https://github.com/ipfs/specs/tree/master/repo/fs-repo
177

178
	// NB: the lock is only held when repos are Open
179
	return lockfile.Locked(repoPath)
180 181
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195
// 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
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
// openDatastore returns an error if the config file is not present.
func (r *FSRepo) openDatastore() error {
	dsLock.Lock()
	defer dsLock.Unlock()

	dsPath := path.Join(r.path, defaultDataStoreDirectory)

	// if no other goroutines have the datastore Open, initialize it and assign
	// it to the package-scoped map for the goroutines that follow.
	if dsOpenersCounter.NumOpeners(dsPath) == 0 {
		ds, err := levelds.NewDatastore(dsPath, &levelds.Options{
			Compression: ldbopts.NoCompression,
		})
		if err != nil {
			return debugerror.New("unable to open leveldb datastore")
		}
		datastores[dsPath] = ds
	}

	// get the datastore from the package-scoped map and record self as an
	// opener.
	ds, dsIsPresent := datastores[dsPath]
	if !dsIsPresent {
		// This indicates a programmer error has occurred.
		return errors.New("datastore should be available, but it isn't")
	}
	r.ds = ds
	dsOpenersCounter.AddOpener(dsPath) // only after success
	return nil
}

227 228 229 230 231 232 233 234 235 236 237 238
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))
}

239
// Open returns an error if the repo is not initialized.
240
func (r *FSRepo) Open() error {
241

242 243
	packageLock.Lock()
	defer packageLock.Unlock()
244

Jeromy's avatar
Jeromy committed
245 246 247 248 249 250
	expPath, err := u.TildeExpansion(r.path)
	if err != nil {
		return err
	}
	r.path = expPath

251 252 253
	if r.state != unopened {
		return debugerror.Errorf("repo is %s", r.state)
	}
254
	if !isInitializedUnsynced(r.path) {
255
		return debugerror.New("ipfs not initialized, please run 'ipfs init'")
256
	}
257
	// check repo path, then check all constituent parts.
258
	// TODO acquire repo lock
259
	// TODO if err := initCheckDir(logpath); err != nil { // }
260
	if err := dir.Writable(r.path); err != nil {
261 262 263
		return err
	}

264 265 266 267
	if err := r.openConfig(); err != nil {
		return err
	}

268 269
	if err := r.openDatastore(); err != nil {
		return err
270 271
	}

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

275
	return r.transitionToOpened()
276 277
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
func (r *FSRepo) closeDatastore() error {
	dsLock.Lock()
	defer dsLock.Unlock()

	dsPath := path.Join(r.path, defaultDataStoreDirectory)

	// decrement the Opener count. if this goroutine is the last, also close
	// the underlying datastore (and remove its reference from the map)

	dsOpenersCounter.RemoveOpener(dsPath)

	if dsOpenersCounter.NumOpeners(dsPath) == 0 {
		delete(datastores, dsPath) // remove the reference
		return r.ds.Close()
	}
	return nil
}

296 297 298 299 300 301 302 303
// Close closes the FSRepo, releasing held resources.
func (r *FSRepo) Close() error {
	packageLock.Lock()
	defer packageLock.Unlock()

	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
304

305 306
	if err := r.closeDatastore(); err != nil {
		return err
307
	}
308 309 310 311 312 313 314 315 316

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

317
	return r.transitionToClosed()
318 319
}

320 321 322 323
// 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.
324
func (r *FSRepo) Config() *config.Config {
325 326 327 328 329 330 331 332 333

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

334 335 336
	if r.state != opened {
		panic(fmt.Sprintln("repo is", r.state))
	}
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
	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
365 366
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
367
// SetConfig updates the FSRepo's config.
368
func (r *FSRepo) SetConfig(updated *config.Config) error {
369 370 371 372 373

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

374
	return r.setConfigUnsynced(updated)
375 376
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
377
// GetConfigKey retrieves only the value of a particular key.
378
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
379 380 381
	packageLock.Lock()
	defer packageLock.Unlock()

382 383 384
	if r.state != opened {
		return nil, debugerror.Errorf("repo is %s", r.state)
	}
385 386 387 388 389 390 391 392 393 394

	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)
395 396
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
397
// SetConfigKey writes the value of a particular key.
398
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
399 400 401
	packageLock.Lock()
	defer packageLock.Unlock()

402 403 404
	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

	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
431 432
}

433 434 435 436
// Datastore returns a repo-owned datastore. If FSRepo is Closed, return value
// is undefined.
func (r *FSRepo) Datastore() ds.ThreadSafeDatastore {
	packageLock.Lock()
437
	d := r.ds
438 439 440 441
	packageLock.Unlock()
	return d
}

442
var _ io.Closer = &FSRepo{}
443
var _ repo.Repo = &FSRepo{}
444

445 446
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
447 448
	// packageLock is held to ensure that another caller doesn't attempt to
	// Init or Remove the repo while this call is in progress.
449 450
	packageLock.Lock()
	defer packageLock.Unlock()
451

452
	return isInitializedUnsynced(path)
453 454
}

455 456
// private methods below this point. NB: packageLock must held by caller.

457
// isInitializedUnsynced reports whether the repo is initialized. Caller must
458
// hold the packageLock.
459 460
func isInitializedUnsynced(repoPath string) bool {
	if !configIsInitialized(repoPath) {
461 462
		return false
	}
463 464
	if !util.FileExists(path.Join(repoPath, defaultDataStoreDirectory)) {
		return false
465 466
	}
	return true
467
}
468

469
// transitionToOpened manages the state transition to |opened|. Caller must hold
470
// the package mutex.
471
func (r *FSRepo) transitionToOpened() error {
472
	r.state = opened
473
	if countBefore := openersCounter.NumOpeners(r.path); countBefore == 0 { // #first
474 475 476 477 478 479
		closer, err := lockfile.Lock(r.path)
		if err != nil {
			return err
		}
		lockfiles[r.path] = closer
	}
480
	return openersCounter.AddOpener(r.path)
481 482 483
}

// transitionToClosed manages the state transition to |closed|. Caller must
484
// hold the package mutex.
485
func (r *FSRepo) transitionToClosed() error {
486
	r.state = closed
487
	if err := openersCounter.RemoveOpener(r.path); err != nil {
488 489
		return err
	}
490
	if countAfter := openersCounter.NumOpeners(r.path); countAfter == 0 {
491 492 493 494 495 496 497
		closer, ok := lockfiles[r.path]
		if !ok {
			return errors.New("package error: lockfile is not held")
		}
		if err := closer.Close(); err != nil {
			return err
		}
498
		delete(lockfiles, r.path)
499 500 501
	}
	return nil
}