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

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

11
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
12 13
	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"
14
	repo "github.com/jbenet/go-ipfs/repo"
15
	"github.com/jbenet/go-ipfs/repo/common"
16
	config "github.com/jbenet/go-ipfs/repo/config"
17
	lockfile "github.com/jbenet/go-ipfs/repo/fsrepo/lock"
18
	serialize "github.com/jbenet/go-ipfs/repo/fsrepo/serialize"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
19
	dir "github.com/jbenet/go-ipfs/thirdparty/dir"
20
	"github.com/jbenet/go-ipfs/thirdparty/eventlog"
Jeromy's avatar
Jeromy committed
21
	u "github.com/jbenet/go-ipfs/util"
22
	util "github.com/jbenet/go-ipfs/util"
23
	ds2 "github.com/jbenet/go-ipfs/util/datastore2"
24
	debugerror "github.com/jbenet/go-ipfs/util/debugerror"
25 26
)

27 28 29 30
const (
	defaultDataStoreDirectory = "datastore"
)

31
var (
32 33 34

	// 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
35
	packageLock sync.Mutex
36

37 38 39 40 41 42 43 44 45 46 47 48 49
	// 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
50 51
)

52 53
// FSRepo represents an IPFS FileSystem Repo. It is safe for use by multiple
// callers.
54
type FSRepo struct {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
55 56 57 58
	// state is the FSRepo's state (unopened, opened, closed)
	state state
	// path is the file-system path
	path string
59 60 61
	// lockfile is the file system lock to prevent others from opening
	// the same fsrepo path concurrently
	lockfile io.Closer
62 63
	// config is set on Open, guarded by packageLock
	config *config.Config
64 65
	// ds is set on Open
	ds ds2.ThreadSafeDatastoreCloser
66 67
}

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

70 71
// Open the FSRepo at path. Returns an error if the repo is not
// initialized.
72 73 74 75 76 77 78 79
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) {
80 81 82 83
	packageLock.Lock()
	defer packageLock.Unlock()

	r := &FSRepo{
84 85
		path:  path.Clean(repoPath),
		state: unopened, // explicitly set for clarity
86
	}
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

	expPath, err := u.TildeExpansion(r.path)
	if err != nil {
		return nil, err
	}
	r.path = expPath

	if r.state != unopened {
		return nil, debugerror.Errorf("repo is %s", r.state)
	}
	if !isInitializedUnsynced(r.path) {
		return nil, debugerror.New("ipfs not initialized, please run 'ipfs init'")
	}
	// 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)

	if err := r.transitionToOpened(); err != nil {
		return nil, err
	}
	return r, nil
122 123
}

124 125 126
// 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
127
func ConfigAt(repoPath string) (*config.Config, error) {
128 129 130 131 132

	// 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
133 134 135 136
	configFilename, err := config.Filename(repoPath)
	if err != nil {
		return nil, err
	}
137
	return serialize.Load(configFilename)
Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
138 139
}

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
// 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
170
// Init initializes a new FSRepo at the given path with the provided config.
171
// TODO add support for custom datastores.
172
func Init(repoPath string, conf *config.Config) error {
173 174 175 176

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

179
	if isInitializedUnsynced(repoPath) {
180 181
		return nil
	}
182

183
	if err := initConfig(repoPath, conf); err != nil {
184 185 186
		return err
	}

187 188 189 190 191
	// 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)
192
	}
193 194 195 196 197

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

198 199 200
	return nil
}

201
// Remove recursively removes the FSRepo at |path|.
202 203 204
func Remove(repoPath string) error {
	repoPath = path.Clean(repoPath)
	return os.RemoveAll(repoPath)
205 206
}

207 208 209
// 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 {
210 211
	repoPath = path.Clean(repoPath)

212 213
	// TODO replace this with the "api" file
	// https://github.com/ipfs/specs/tree/master/repo/fs-repo
214

215
	// NB: the lock is only held when repos are Open
216
	return lockfile.Locked(repoPath)
217 218
}

219 220 221 222 223 224 225 226 227 228 229 230 231 232
// 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
}

233 234 235
// openDatastore returns an error if the config file is not present.
func (r *FSRepo) openDatastore() error {
	dsPath := path.Join(r.path, defaultDataStoreDirectory)
236 237 238 239 240
	ds, err := levelds.NewDatastore(dsPath, &levelds.Options{
		Compression: ldbopts.NoCompression,
	})
	if err != nil {
		return debugerror.New("unable to open leveldb datastore")
241 242 243 244 245
	}
	r.ds = ds
	return nil
}

246 247 248 249 250 251 252 253 254 255 256 257
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))
}

258 259 260 261 262 263 264 265
// 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)
	}
266

267
	if err := r.ds.Close(); err != nil {
268
		return err
269
	}
270 271 272 273 274 275 276 277 278

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

279
	return r.transitionToClosed()
280 281
}

282 283 284 285
// 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.
286
func (r *FSRepo) Config() *config.Config {
287 288 289 290 291 292 293 294 295

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

296 297 298
	if r.state != opened {
		panic(fmt.Sprintln("repo is", r.state))
	}
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
	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
327 328
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
329
// SetConfig updates the FSRepo's config.
330
func (r *FSRepo) SetConfig(updated *config.Config) error {
331 332 333 334 335

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

336
	return r.setConfigUnsynced(updated)
337 338
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
339
// GetConfigKey retrieves only the value of a particular key.
340
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
341 342 343
	packageLock.Lock()
	defer packageLock.Unlock()

344 345 346
	if r.state != opened {
		return nil, debugerror.Errorf("repo is %s", r.state)
	}
347 348 349 350 351 352 353 354 355 356

	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)
357 358
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
359
// SetConfigKey writes the value of a particular key.
360
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
361 362 363
	packageLock.Lock()
	defer packageLock.Unlock()

364 365 366
	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
367 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

	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
393 394
}

395 396 397 398
// Datastore returns a repo-owned datastore. If FSRepo is Closed, return value
// is undefined.
func (r *FSRepo) Datastore() ds.ThreadSafeDatastore {
	packageLock.Lock()
399
	d := r.ds
400 401 402 403
	packageLock.Unlock()
	return d
}

404
var _ io.Closer = &FSRepo{}
405
var _ repo.Repo = &FSRepo{}
406

407 408
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
409 410
	// packageLock is held to ensure that another caller doesn't attempt to
	// Init or Remove the repo while this call is in progress.
411 412
	packageLock.Lock()
	defer packageLock.Unlock()
413

414
	return isInitializedUnsynced(path)
415 416
}

417 418
// private methods below this point. NB: packageLock must held by caller.

419
// isInitializedUnsynced reports whether the repo is initialized. Caller must
420
// hold the packageLock.
421 422
func isInitializedUnsynced(repoPath string) bool {
	if !configIsInitialized(repoPath) {
423 424
		return false
	}
425 426
	if !util.FileExists(path.Join(repoPath, defaultDataStoreDirectory)) {
		return false
427 428
	}
	return true
429
}
430

431
// transitionToOpened manages the state transition to |opened|. Caller must hold
432
// the package mutex.
433
func (r *FSRepo) transitionToOpened() error {
434
	r.state = opened
Tommi Virtanen's avatar
Tommi Virtanen committed
435 436 437
	closer, err := lockfile.Lock(r.path)
	if err != nil {
		return err
438
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
439 440
	r.lockfile = closer
	return nil
441 442 443
}

// transitionToClosed manages the state transition to |closed|. Caller must
444
// hold the package mutex.
445
func (r *FSRepo) transitionToClosed() error {
446
	r.state = closed
Tommi Virtanen's avatar
Tommi Virtanen committed
447
	if err := r.lockfile.Close(); err != nil {
448 449 450 451
		return err
	}
	return nil
}