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

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

10 11
	repo "github.com/jbenet/go-ipfs/repo"
	common "github.com/jbenet/go-ipfs/repo/common"
12 13
	config "github.com/jbenet/go-ipfs/repo/config"
	util "github.com/jbenet/go-ipfs/util"
14
	debugerror "github.com/jbenet/go-ipfs/util/debugerror"
15 16
)

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
var (
	// pkgLock prevents the fsrepo from being removed while there exist open
	// 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.
	pkgLock *packageLock
)

func init() {
	pkgLock = makePackageLock()
}

// FSRepo represents an IPFS FileSystem Repo. It is not thread-safe.
33
type FSRepo struct {
34
	state  state
35
	path   string
36
	config *config.Config
37 38
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
39
// At returns a handle to an FSRepo at the provided |path|.
40
func At(path string) *FSRepo {
41
	// This method must not have side-effects.
42
	return &FSRepo{
43 44
		path:  path,
		state: unopened, // explicitly set for clarity
45 46 47
	}
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
48
// Init initializes a new FSRepo at the given path with the provided config.
49
func Init(path string, conf *config.Config) error {
50 51 52 53
	pkgLock.Lock() // lock must be held to ensure atomicity (prevent Removal)
	defer pkgLock.Unlock()

	if isInitializedUnsynced(path) {
54 55 56 57 58 59 60 61 62 63 64 65
		return nil
	}
	configFilename, err := config.Filename(path)
	if err != nil {
		return err
	}
	if err := writeConfigFile(configFilename, conf); err != nil {
		return err
	}
	return nil
}

66 67 68 69 70 71 72 73 74 75
// Remove recursively removes the FSRepo at |path|.
func Remove(path string) error {
	pkgLock.Lock()
	defer pkgLock.Unlock()
	if pkgLock.NumOpeners(path) != 0 {
		return errors.New("repo in use")
	}
	return os.RemoveAll(path)
}

76
// Open returns an error if the repo is not initialized.
77
func (r *FSRepo) Open() error {
78 79
	pkgLock.Lock()
	defer pkgLock.Unlock()
80 81 82
	if r.state != unopened {
		return debugerror.Errorf("repo is %s", r.state)
	}
83
	if !isInitializedUnsynced(r.path) {
84
		return debugerror.New("ipfs not initialized, please run 'ipfs init'")
85
	}
86
	// check repo path, then check all constituent parts.
87
	// TODO acquire repo lock
88 89 90 91 92
	// TODO if err := initCheckDir(logpath); err != nil { // }
	if err := initCheckDir(r.path); err != nil {
		return err
	}

93 94 95 96
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
97
	conf, err := load(configFilename)
98 99 100 101 102
	if err != nil {
		return err
	}
	r.config = conf

103 104 105 106 107 108 109 110 111
	// datastore
	dspath, err := config.DataStorePath("")
	if err != nil {
		return err
	}
	if err := initCheckDir(dspath); err != nil {
		return debugerror.Errorf("datastore: %s", err)
	}

112 113 114 115 116 117 118 119
	logpath, err := config.LogsPath("")
	if err != nil {
		return debugerror.Wrap(err)
	}
	if err := initCheckDir(logpath); err != nil {
		return debugerror.Errorf("logs: %s", err)
	}

120
	r.state = opened
121
	pkgLock.AddOpener(r.path)
122 123 124
	return nil
}

125 126 127 128
// 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.
129
func (r *FSRepo) Config() *config.Config {
130 131
	// no lock necessary because repo is either Open (and thus protected from
	// Removal) or has no side-effect
132 133 134 135 136 137
	if r.state != opened {
		panic(fmt.Sprintln("repo is", r.state))
	}
	return r.config
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
138
// SetConfig updates the FSRepo's config.
139
func (r *FSRepo) SetConfig(updated *config.Config) error {
140
	// no lock required because repo should be Open
141 142 143
	if r.state != opened {
		panic(fmt.Sprintln("repo is", r.state))
	}
144 145 146 147
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
	// 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 {
163 164
		return err
	}
165
	*r.config = *updated // copy so caller cannot modify this private config
166 167 168
	return nil
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
169
// GetConfigKey retrieves only the value of a particular key.
170
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
171 172 173
	if r.state != opened {
		return nil, debugerror.Errorf("repo is %s", r.state)
	}
174 175 176 177 178 179 180 181 182 183 184
	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
185
// SetConfigKey writes the value of a particular key.
186
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
187
	// no lock required because repo should be Open
188 189 190
	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
191 192 193 194 195 196 197 198 199 200 201 202 203 204
	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
205
	conf, err := config.FromMap(mapconf)
206 207 208 209 210 211
	if err != nil {
		return err
	}
	return r.SetConfig(conf)
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
212
// Close closes the FSRepo, releasing held resources.
213
func (r *FSRepo) Close() error {
214 215
	pkgLock.Lock()
	defer pkgLock.Unlock()
216 217 218
	if r.state != opened {
		return debugerror.Errorf("repo is %s", r.state)
	}
219
	pkgLock.RemoveOpener(r.path)
220 221 222 223
	return nil // TODO release repo lock
}

var _ io.Closer = &FSRepo{}
224
var _ repo.Interface = &FSRepo{}
225

226 227
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
228 229 230 231 232 233 234 235
	pkgLock.Lock()
	defer pkgLock.Unlock()
	return isInitializedUnsynced(path)
}

// isInitializedUnsynced reports whether the repo is initialized. Caller must
// hold pkgLock.
func isInitializedUnsynced(path string) bool {
236 237 238 239 240 241 242 243 244
	configFilename, err := config.Filename(path)
	if err != nil {
		return false
	}
	if !util.FileExists(configFilename) {
		return false
	}
	return true
}
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

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