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

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

12 13
	repo "github.com/jbenet/go-ipfs/repo"
	common "github.com/jbenet/go-ipfs/repo/common"
14
	config "github.com/jbenet/go-ipfs/repo/config"
15
	lockfile "github.com/jbenet/go-ipfs/repo/fsrepo/lock"
16
	opener "github.com/jbenet/go-ipfs/repo/fsrepo/opener"
17
	util "github.com/jbenet/go-ipfs/util"
18
	debugerror "github.com/jbenet/go-ipfs/util/debugerror"
19 20
)

21
var (
22 23 24 25 26 27 28

	// packageLock must be held to while performing any operation that modifies an
	// FSRepo's state field. This includes Init, Open, Close, and Remove.
	packageLock sync.Mutex // protects openerCounter and lockfiles
	// lockfiles holds references to the Closers that ensure that repos are
	// only accessed by one process at a time.
	lockfiles map[string]io.Closer
29
	// openerCounter prevents the fsrepo from being removed while there exist open
30 31 32 33 34 35
	// FSRepo handles. It also ensures that the Init is atomic.
	//
	// 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.
36
	openerCounter *opener.Counter
37 38 39
)

func init() {
40
	openerCounter = opener.NewCounter()
41
	lockfiles = make(map[string]io.Closer)
42 43
}

44 45
// FSRepo represents an IPFS FileSystem Repo. It is safe for use by multiple
// callers.
46
type FSRepo struct {
47
	state  state
48
	path   string
49
	config *config.Config
50 51
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
52
// At returns a handle to an FSRepo at the provided |path|.
53
func At(repoPath string) *FSRepo {
54
	// This method must not have side-effects.
55
	return &FSRepo{
56
		path:  path.Clean(repoPath),
57
		state: unopened, // explicitly set for clarity
58 59 60
	}
}

Brian Tiger Chow's avatar
huh  
Brian Tiger Chow committed
61
func ConfigAt(repoPath string) (*config.Config, error) {
62 63 64 65 66

	// 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
67 68 69 70 71 72 73
	configFilename, err := config.Filename(repoPath)
	if err != nil {
		return nil, err
	}
	return load(configFilename)
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
74
// Init initializes a new FSRepo at the given path with the provided config.
75
func Init(path string, conf *config.Config) error {
76 77 78 79

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

	if isInitializedUnsynced(path) {
83 84 85 86 87 88
		return nil
	}
	configFilename, err := config.Filename(path)
	if err != nil {
		return err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
89 90 91
	// 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.
92 93 94 95 96 97
	if err := writeConfigFile(configFilename, conf); err != nil {
		return err
	}
	return nil
}

98
// Remove recursively removes the FSRepo at |path|.
99 100 101 102 103
func Remove(repoPath string) error {
	repoPath = path.Clean(repoPath)

	// packageLock must be held to ensure that the repo is not removed while
	// being accessed by others.
104 105
	packageLock.Lock()
	defer packageLock.Unlock()
106 107

	if openerCounter.NumOpeners(repoPath) != 0 {
108 109
		return errors.New("repo in use")
	}
110
	return os.RemoveAll(repoPath)
111 112
}

113 114 115
// 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 {
116 117 118
	repoPath = path.Clean(repoPath)

	// packageLock must be held to check the number of openers.
119 120
	packageLock.Lock()
	defer packageLock.Unlock()
121

122 123 124 125
	// NB: the lock is only held when repos are Open
	return lockfile.Locked(repoPath) && openerCounter.NumOpeners(repoPath) == 0
}

126
// Open returns an error if the repo is not initialized.
127
func (r *FSRepo) Open() error {
128 129 130 131

	// packageLock must be held to make sure that the repo is not destroyed by
	// another caller. It must not be released until initialization is complete
	// and the number of openers is incremeneted.
132 133
	packageLock.Lock()
	defer packageLock.Unlock()
134

135 136 137
	if r.state != unopened {
		return debugerror.Errorf("repo is %s", r.state)
	}
138
	if !isInitializedUnsynced(r.path) {
139
		return debugerror.New("ipfs not initialized, please run 'ipfs init'")
140
	}
141
	// check repo path, then check all constituent parts.
142
	// TODO acquire repo lock
143 144 145 146 147
	// TODO if err := initCheckDir(logpath); err != nil { // }
	if err := initCheckDir(r.path); err != nil {
		return err
	}

148 149 150 151
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
152
	conf, err := load(configFilename)
153 154 155 156 157
	if err != nil {
		return err
	}
	r.config = conf

158 159 160 161 162 163 164 165 166
	// datastore
	dspath, err := config.DataStorePath("")
	if err != nil {
		return err
	}
	if err := initCheckDir(dspath); err != nil {
		return debugerror.Errorf("datastore: %s", err)
	}

167 168 169 170 171 172 173 174
	logpath, err := config.LogsPath("")
	if err != nil {
		return debugerror.Wrap(err)
	}
	if err := initCheckDir(logpath); err != nil {
		return debugerror.Errorf("logs: %s", err)
	}

175
	return transitionToOpened(r)
176 177
}

178 179 180 181
// 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.
182
func (r *FSRepo) Config() *config.Config {
183 184 185 186 187 188 189 190 191

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

192 193 194 195 196 197
	if r.state != opened {
		panic(fmt.Sprintln("repo is", r.state))
	}
	return r.config
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
198
// SetConfig updates the FSRepo's config.
199
func (r *FSRepo) SetConfig(updated *config.Config) error {
200 201 202 203 204 205

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

	return r.setConfigUnsynced(updated)
206 207
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
208
// GetConfigKey retrieves only the value of a particular key.
209
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
210 211 212
	packageLock.Lock()
	defer packageLock.Unlock()

213 214 215
	if r.state != opened {
		return nil, debugerror.Errorf("repo is %s", r.state)
	}
216 217 218 219 220 221 222 223 224 225 226
	filename, err := config.Filename(r.path)
	if err != nil {
		return nil, err
	}
	var cfg map[string]interface{}
	if err := readConfigFile(filename, &cfg); err != nil {
		return nil, err
	}
	return common.MapGetKV(cfg, key)
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
227
// SetConfigKey writes the value of a particular key.
228
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
229 230 231
	packageLock.Lock()
	defer packageLock.Unlock()

232 233 234
	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
235 236 237 238 239 240 241 242 243 244 245 246 247 248
	filename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
	var mapconf map[string]interface{}
	if err := readConfigFile(filename, &mapconf); err != nil {
		return err
	}
	if err := common.MapSetKV(mapconf, key, value); err != nil {
		return err
	}
	if err := writeConfigFile(filename, mapconf); err != nil {
		return err
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
249
	conf, err := config.FromMap(mapconf)
250 251 252
	if err != nil {
		return err
	}
253
	return r.setConfigUnsynced(conf)
254 255
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
256
// Close closes the FSRepo, releasing held resources.
257
func (r *FSRepo) Close() error {
258 259
	packageLock.Lock()
	defer packageLock.Unlock()
260

261 262 263
	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
264
	return transitionToClosed(r)
265 266 267
}

var _ io.Closer = &FSRepo{}
268
var _ repo.Repo = &FSRepo{}
269

270 271
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
272 273
	// packageLock is held to ensure that another caller doesn't attempt to
	// Init or Remove the repo while this call is in progress.
274 275
	packageLock.Lock()
	defer packageLock.Unlock()
276 277 278
	return isInitializedUnsynced(path)
}

279 280
// private methods below this point. NB: packageLock must held by caller.

281
// isInitializedUnsynced reports whether the repo is initialized. Caller must
282
// hold openerCounter lock.
283
func isInitializedUnsynced(path string) bool {
284 285 286 287 288 289 290 291 292
	configFilename, err := config.Filename(path)
	if err != nil {
		return false
	}
	if !util.FileExists(configFilename) {
		return false
	}
	return true
}
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

// initCheckDir ensures the directory exists and is writable
func initCheckDir(path string) error {
	// Construct the path if missing
	if err := os.MkdirAll(path, os.ModePerm); err != nil {
		return err
	}
	// Check the directory is writeable
	if f, err := os.Create(filepath.Join(path, "._check_writeable")); err == nil {
		os.Remove(f.Name())
	} else {
		return debugerror.New("'" + path + "' is not writeable")
	}
	return nil
}
308 309

// transitionToOpened manages the state transition to |opened|. Caller must hold
310
// the package mutex.
311 312 313 314 315 316 317 318 319 320 321 322 323
func transitionToOpened(r *FSRepo) error {
	r.state = opened
	if countBefore := openerCounter.NumOpeners(r.path); countBefore == 0 { // #first
		closer, err := lockfile.Lock(r.path)
		if err != nil {
			return err
		}
		lockfiles[r.path] = closer
	}
	return openerCounter.AddOpener(r.path)
}

// transitionToClosed manages the state transition to |closed|. Caller must
324
// hold the package mutex.
325 326 327 328 329 330 331 332 333 334 335 336 337
func transitionToClosed(r *FSRepo) error {
	r.state = closed
	if err := openerCounter.RemoveOpener(r.path); err != nil {
		return err
	}
	if countAfter := openerCounter.NumOpeners(r.path); countAfter == 0 {
		closer, ok := lockfiles[r.path]
		if !ok {
			return errors.New("package error: lockfile is not held")
		}
		if err := closer.Close(); err != nil {
			return err
		}
338
		delete(lockfiles, r.path)
339 340 341
	}
	return nil
}
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

// setConfigUnsynced is for private use. Callers must hold the packageLock.
func (r *FSRepo) setConfigUnsynced(updated *config.Config) error {
	if r.state != opened {
		return fmt.Errorf("repo is", r.state)
	}
	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 := 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 := writeConfigFile(configFilename, mapconf); err != nil {
		return err
	}
	*r.config = *updated // copy so caller cannot modify this private config
	return nil
}