-
Notifications
You must be signed in to change notification settings - Fork 10
/
filesystem.go
492 lines (389 loc) · 9.45 KB
/
filesystem.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package sivafs
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"syscall"
"time"
"gopkg.in/src-d/go-billy.v4"
"gopkg.in/src-d/go-billy.v4/helper/chroot"
"gopkg.in/src-d/go-billy.v4/helper/mount"
"gopkg.in/src-d/go-billy.v4/util"
"gopkg.in/src-d/go-siva.v1"
)
var (
ErrNonSeekableFile = errors.New("file non-seekable")
ErrFileWriteModeAlreadyOpen = errors.New("previous file in write mode already open")
ErrReadOnlyFile = errors.New("file is read-only")
ErrWriteOnlyFile = errors.New("file is write-only")
)
const sivaCapabilities = billy.ReadCapability |
billy.WriteCapability |
billy.SeekCapability
type SivaSync interface {
// Sync closes any open files, this method should be called at the end of
// program to ensure that all the files are properly closed, otherwise the
// siva file will be corrupted.
Sync() error
}
type SivaBasicFS interface {
billy.Basic
billy.Dir
SivaSync
}
type SivaFS interface {
billy.Filesystem
SivaSync
}
type sivaFS struct {
underlying billy.Filesystem
path string
f billy.File
rw *siva.ReadWriter
index siva.Index
fileWriteModeOpen bool
}
// New creates a new filesystem backed by a siva file with the given path in
// the given filesystem. The siva file will be opened or created lazily with
// the first operation.
//
// All files opened in write mode must be closed, otherwise the siva file will
// be corrupted.
func New(fs billy.Filesystem, path string) SivaBasicFS {
return &sivaFS{
underlying: fs,
path: path,
}
}
// NewFilesystem creates an entire filesystem using siva as the main backend,
// but supplying unsupported functionality using as a temporal files backend
// the main filesystem. It needs an additional parameter `tmpFs` where temporary
// files will be stored. Note that `tmpFs` will be mounted as /tmp.
func NewFilesystem(fs billy.Filesystem, path string, tmpFs billy.Filesystem) (SivaFS, error) {
tempdir := "/tmp"
root := New(fs, path)
m := mount.New(root, tempdir, tmpFs)
t := &temp{
defaultDir: tempdir,
SivaSync: root,
Filesystem: chroot.New(m, "/"),
}
return t, nil
}
// Create creates a new file. This file is created using CREATE, TRUNCATE and
// WRITE ONLY flags due to limitations working on siva files.
func (fs *sivaFS) Create(path string) (billy.File, error) {
return fs.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0666))
}
func (fs *sivaFS) Open(path string) (billy.File, error) {
return fs.OpenFile(path, os.O_RDONLY, 0)
}
func (fs *sivaFS) OpenFile(path string, flag int, mode os.FileMode) (billy.File, error) {
path = normalizePath(path)
if flag&os.O_CREATE != 0 && flag&os.O_TRUNC == 0 {
return nil, billy.ErrNotSupported
}
if err := fs.ensureOpen(); err != nil {
return nil, err
}
if flag&os.O_CREATE != 0 {
if fs.fileWriteModeOpen {
return nil, ErrFileWriteModeAlreadyOpen
}
return fs.createFile(path, flag, mode)
}
return fs.openFile(path, flag, mode)
}
func (fs *sivaFS) Stat(p string) (os.FileInfo, error) {
p = normalizePath(p)
if err := fs.ensureOpen(); err != nil {
return nil, err
}
index, err := fs.getIndex()
if err != nil {
return nil, err
}
e := index.Find(p)
if e != nil {
return newFileInfo(e), nil
}
stat, err := getDir(index, p)
if err != nil {
return nil, err
}
if stat == nil {
return nil, os.ErrNotExist
}
return stat, nil
}
func (fs *sivaFS) ReadDir(path string) ([]os.FileInfo, error) {
path = normalizePath(path)
if err := fs.ensureOpen(); err != nil {
return nil, err
}
index, err := fs.getIndex()
if err != nil {
return nil, err
}
files, err := listFiles(index, path)
if err != nil {
return nil, err
}
dirs, err := listDirs(index, path)
if err != nil {
return nil, err
}
return append(dirs, files...), nil
}
func (fs *sivaFS) MkdirAll(filename string, perm os.FileMode) error {
if err := fs.ensureOpen(); err != nil {
return err
}
index, err := fs.getIndex()
if err != nil {
return err
}
e := index.Find(filename)
if e != nil {
return &os.PathError{
Op: "mkdir",
Path: filename,
Err: syscall.ENOTDIR,
}
}
return nil
}
// Join joins the specified elements using the filesystem separator.
func (fs *sivaFS) Join(elem ...string) string {
return filepath.Join(elem...)
}
func (fs *sivaFS) Remove(path string) error {
path = normalizePath(path)
if err := fs.ensureOpen(); err != nil {
return err
}
index, err := fs.getIndex()
if err != nil {
return err
}
e := index.Find(path)
if e != nil {
// delete index cache on modification
fs.index = nil
return fs.rw.WriteHeader(&siva.Header{
Name: path,
ModTime: time.Now(),
Mode: 0,
Flags: siva.FlagDeleted,
})
}
dir, err := getDir(index, path)
if err != nil {
return err
}
if dir != nil {
return &os.PathError{
Op: "remove",
Path: path,
Err: syscall.ENOTEMPTY,
}
}
// there are no file and no directory with this path
return os.ErrNotExist
}
func (fs *sivaFS) Rename(from, to string) error {
return billy.ErrNotSupported
}
func (fs *sivaFS) Sync() error {
return fs.ensureClosed()
}
// Capability implements billy.Capable interface.
func (fs *sivaFS) Capabilities() billy.Capability {
return sivaCapabilities
}
func (fs *sivaFS) ensureOpen() error {
if fs.rw != nil {
return nil
}
f, err := fs.underlying.OpenFile(fs.path, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
rw, err := siva.NewReaderWriter(f)
if err != nil {
f.Close()
return err
}
fs.rw = rw
fs.f = f
return nil
}
func (fs *sivaFS) ensureClosed() error {
if fs.rw == nil {
return nil
}
if err := fs.rw.Close(); err != nil {
return err
}
fs.rw = nil
f := fs.f
fs.f = nil
return f.Close()
}
func (fs *sivaFS) createFile(path string, flag int, mode os.FileMode) (billy.File, error) {
if flag&os.O_RDWR != 0 || flag&os.O_RDONLY != 0 {
return nil, billy.ErrNotSupported
}
header := &siva.Header{
Name: path,
Mode: mode,
ModTime: time.Now(),
}
// delete index cache on modification
fs.index = nil
if err := fs.rw.WriteHeader(header); err != nil {
return nil, err
}
closeFunc := func() error {
if fs.rw == nil {
return nil
}
if flag&os.O_WRONLY != 0 || flag&os.O_RDWR != 0 {
fs.fileWriteModeOpen = false
}
return fs.rw.Flush()
}
defer func() { fs.fileWriteModeOpen = true }()
return newFile(path, fs.rw, closeFunc), nil
}
func (fs *sivaFS) openFile(path string, flag int, mode os.FileMode) (billy.File, error) {
if flag&os.O_RDWR != 0 || flag&os.O_WRONLY != 0 {
return nil, billy.ErrNotSupported
}
index, err := fs.getIndex()
if err != nil {
return nil, err
}
e := index.Find(path)
if e == nil {
return nil, os.ErrNotExist
}
sr, err := fs.rw.Get(e)
if err != nil {
return nil, err
}
return openFile(path, sr), nil
}
func (fs *sivaFS) getIndex() (siva.Index, error) {
// return cached index
if fs.index != nil {
return fs.index, nil
}
index, err := fs.rw.Index()
if err != nil {
return nil, err
}
fs.index = index.Filter()
return fs.index, nil
}
func listFiles(index siva.Index, dir string) ([]os.FileInfo, error) {
dir = addTrailingSlash(dir)
entries, err := index.Glob(fmt.Sprintf("%s*", dir))
if err != nil {
return nil, err
}
contents := []os.FileInfo{}
for _, e := range entries {
contents = append(contents, newFileInfo(e))
}
return contents, nil
}
func getDir(index siva.Index, dir string) (os.FileInfo, error) {
dir = addTrailingSlash(dir)
lenDir := len(dir)
entries := make([]*siva.IndexEntry, 0)
for _, e := range index {
if len(e.Name) > lenDir {
if e.Name[:lenDir] == dir {
entries = append(entries, e)
}
}
}
if len(entries) == 0 {
return nil, nil
}
var oldDir time.Time
for _, e := range entries {
if oldDir.Before(e.ModTime) {
oldDir = e.ModTime
}
}
return newDirFileInfo(path.Clean(dir), oldDir), nil
}
func listDirs(index siva.Index, dir string) ([]os.FileInfo, error) {
dir = addTrailingSlash(dir)
depth := strings.Count(dir, "/")
dirs := map[string]time.Time{}
dirOrder := make([]string, 0)
for _, e := range index {
if !strings.HasPrefix(e.Name, dir) {
continue
}
targetParts := strings.Split(e.Name, "/")
if len(targetParts) <= depth+1 {
continue
}
dir := strings.Join(targetParts[:depth+1], "/")
oldDir, ok := dirs[dir]
if !ok || oldDir.Before(e.ModTime) {
dirs[dir] = e.ModTime
if !ok {
dirOrder = append(dirOrder, dir)
}
}
}
contents := []os.FileInfo{}
for _, dir := range dirOrder {
contents = append(contents, newDirFileInfo(dir, dirs[dir]))
}
return contents, nil
}
// addTrailingSlash adds trailing slash to the path if it does not have one.
func addTrailingSlash(path string) string {
if path == "" {
return path
}
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
return path
}
// normalizePath returns a path relative to '/'.
// It assumes UNIX-style slash-delimited paths.
func normalizePath(path string) string {
path = filepath.Join("/", path)
return removeLeadingSlash(path)
}
// removeLeadingSlash removes leading slash of the path, if any.
func removeLeadingSlash(path string) string {
if strings.HasPrefix(path, "/") {
return path[1:]
}
return path
}
type temp struct {
billy.Filesystem
SivaSync
defaultDir string
}
// Capability implements billy.Capable interface.
func (h *temp) Capabilities() billy.Capability {
return sivaCapabilities
}
func (h *temp) TempFile(dir, prefix string) (billy.File, error) {
dir = h.Join(h.defaultDir, dir)
return util.TempFile(h.Filesystem, dir, prefix)
}