-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsrepo.go
372 lines (320 loc) · 10.2 KB
/
fsrepo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
365
366
367
368
369
370
371
372
package fsrepo
import (
"errors"
"fmt"
"io"
"os"
"path"
"sync"
ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
repo "github.com/jbenet/go-ipfs/repo"
config "github.com/jbenet/go-ipfs/repo/config"
component "github.com/jbenet/go-ipfs/repo/fsrepo/component"
counter "github.com/jbenet/go-ipfs/repo/fsrepo/counter"
lockfile "github.com/jbenet/go-ipfs/repo/fsrepo/lock"
serialize "github.com/jbenet/go-ipfs/repo/fsrepo/serialize"
dir "github.com/jbenet/go-ipfs/thirdparty/dir"
u "github.com/jbenet/go-ipfs/util"
debugerror "github.com/jbenet/go-ipfs/util/debugerror"
)
var (
// 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 openersCounter 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
// openersCounter 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.
openersCounter *counter.Openers
)
func init() {
openersCounter = counter.NewOpenersCounter()
lockfiles = make(map[string]io.Closer)
}
// FSRepo represents an IPFS FileSystem Repo. It is safe for use by multiple
// callers.
type FSRepo struct {
// state is the FSRepo's state (unopened, opened, closed)
state state
// path is the file-system path
path string
// configComponent is loaded when FSRepo is opened and kept up to date when
// the FSRepo is modified.
// TODO test
configComponent component.ConfigComponent
datastoreComponent component.DatastoreComponent
eventlogComponent component.EventlogComponent
}
type componentBuilder struct {
Init component.Initializer
IsInitialized component.InitializationChecker
OpenHandler func(*FSRepo) error
}
// At returns a handle to an FSRepo at the provided |path|.
func At(repoPath string) *FSRepo {
// This method must not have side-effects.
return &FSRepo{
path: path.Clean(repoPath),
state: unopened, // explicitly set for clarity
}
}
// 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.
func ConfigAt(repoPath string) (*config.Config, error) {
// packageLock must be held to ensure that the Read is atomic.
packageLock.Lock()
defer packageLock.Unlock()
configFilename, err := config.Filename(repoPath)
if err != nil {
return nil, err
}
return serialize.Load(configFilename)
}
// Init initializes a new FSRepo at the given path with the provided config.
// TODO add support for custom datastores.
func Init(path string, conf *config.Config) error {
// packageLock must be held to ensure that the repo is not initialized more
// than once.
packageLock.Lock()
defer packageLock.Unlock()
if isInitializedUnsynced(path) {
return nil
}
for _, b := range componentBuilders() {
if err := b.Init(path, conf); err != nil {
return err
}
}
return nil
}
// Remove recursively removes the FSRepo at |path|.
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.
packageLock.Lock()
defer packageLock.Unlock()
if openersCounter.NumOpeners(repoPath) != 0 {
return errors.New("repo in use")
}
return os.RemoveAll(repoPath)
}
// 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 {
repoPath = path.Clean(repoPath)
// packageLock must be held to check the number of openers.
packageLock.Lock()
defer packageLock.Unlock()
// NB: the lock is only held when repos are Open
return lockfile.Locked(repoPath) && openersCounter.NumOpeners(repoPath) == 0
}
// Open returns an error if the repo is not initialized.
func (r *FSRepo) Open() error {
// 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.
packageLock.Lock()
defer packageLock.Unlock()
expPath, err := u.TildeExpansion(r.path)
if err != nil {
return err
}
r.path = expPath
if r.state != unopened {
return debugerror.Errorf("repo is %s", r.state)
}
if !isInitializedUnsynced(r.path) {
return 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 err
}
for _, b := range componentBuilders() {
if err := b.OpenHandler(r); err != nil {
return err
}
}
return r.transitionToOpened()
}
// 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)
}
for _, closer := range r.components() {
if err := closer.Close(); err != nil {
return err
}
}
return r.transitionToClosed()
}
// 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.
func (r *FSRepo) Config() *config.Config {
// 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()
if r.state != opened {
panic(fmt.Sprintln("repo is", r.state))
}
return r.configComponent.Config()
}
// SetConfig updates the FSRepo's config.
func (r *FSRepo) SetConfig(updated *config.Config) error {
// packageLock is held to provide thread-safety.
packageLock.Lock()
defer packageLock.Unlock()
return r.configComponent.SetConfig(updated)
}
// GetConfigKey retrieves only the value of a particular key.
func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
packageLock.Lock()
defer packageLock.Unlock()
if r.state != opened {
return nil, debugerror.Errorf("repo is %s", r.state)
}
return r.configComponent.GetConfigKey(key)
}
// SetConfigKey writes the value of a particular key.
func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
packageLock.Lock()
defer packageLock.Unlock()
if r.state != opened {
return debugerror.Errorf("repo is %s", r.state)
}
return r.configComponent.SetConfigKey(key, value)
}
// Datastore returns a repo-owned datastore. If FSRepo is Closed, return value
// is undefined.
func (r *FSRepo) Datastore() ds.ThreadSafeDatastore {
packageLock.Lock()
d := r.datastoreComponent.Datastore()
packageLock.Unlock()
return d
}
var _ io.Closer = &FSRepo{}
var _ repo.Repo = &FSRepo{}
// IsInitialized returns true if the repo is initialized at provided |path|.
func IsInitialized(path string) bool {
// packageLock is held to ensure that another caller doesn't attempt to
// Init or Remove the repo while this call is in progress.
packageLock.Lock()
defer packageLock.Unlock()
return isInitializedUnsynced(path)
}
// private methods below this point. NB: packageLock must held by caller.
// isInitializedUnsynced reports whether the repo is initialized. Caller must
// hold the packageLock.
func isInitializedUnsynced(path string) bool {
for _, b := range componentBuilders() {
if !b.IsInitialized(path) {
return false
}
}
return true
}
// transitionToOpened manages the state transition to |opened|. Caller must hold
// the package mutex.
func (r *FSRepo) transitionToOpened() error {
r.state = opened
if countBefore := openersCounter.NumOpeners(r.path); countBefore == 0 { // #first
closer, err := lockfile.Lock(r.path)
if err != nil {
return err
}
lockfiles[r.path] = closer
}
return openersCounter.AddOpener(r.path)
}
// transitionToClosed manages the state transition to |closed|. Caller must
// hold the package mutex.
func (r *FSRepo) transitionToClosed() error {
r.state = closed
if err := openersCounter.RemoveOpener(r.path); err != nil {
return err
}
if countAfter := openersCounter.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
}
delete(lockfiles, r.path)
}
return nil
}
// components returns the FSRepo's constituent components
func (r *FSRepo) components() []component.Component {
return []component.Component{
&r.configComponent,
&r.datastoreComponent,
}
}
func componentBuilders() []componentBuilder {
return []componentBuilder{
// ConfigComponent must be initialized first because other components
// depend on it.
componentBuilder{
Init: component.InitConfigComponent,
IsInitialized: component.ConfigComponentIsInitialized,
OpenHandler: func(r *FSRepo) error {
c := component.ConfigComponent{}
c.SetPath(r.path)
if err := c.Open(nil); err != nil {
return err
}
r.configComponent = c
return nil
},
},
// DatastoreComponent
componentBuilder{
Init: component.InitDatastoreComponent,
IsInitialized: component.DatastoreComponentIsInitialized,
OpenHandler: func(r *FSRepo) error {
c := component.DatastoreComponent{}
c.SetPath(r.path)
if err := c.Open(r.configComponent.Config()); err != nil {
return err
}
r.datastoreComponent = c
return nil
},
},
// EventlogComponent
componentBuilder{
Init: component.InitEventlogComponent,
IsInitialized: component.EventlogComponentIsInitialized,
OpenHandler: func(r *FSRepo) error {
c := component.EventlogComponent{}
c.SetPath(r.path)
if err := c.Open(r.configComponent.Config()); err != nil {
return err
}
r.eventlogComponent = c
return nil
},
},
}
}