forked from kahing/goofys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
717 lines (590 loc) · 14.7 KB
/
file.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
// Copyright 2015 - 2017 Ka-Hing Cheung
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package internal
import (
"errors"
"fmt"
"io"
"sync"
"syscall"
"github.com/jacobsa/fuse"
"github.com/jacobsa/fuse/fuseops"
)
type FileHandle struct {
inode *Inode
cloud StorageBackend
key string
mpuName *string
dirty bool
writeInit sync.Once
mpuWG sync.WaitGroup
mu sync.Mutex
mpuId *MultipartBlobCommitInput
nextWriteOffset int64
lastPartId uint32
poolHandle *BufferPool
buf *MBuf
lastWriteError error
// read
reader io.ReadCloser
readBufOffset int64
// parallel read
buffers []*S3ReadBuffer
existingReadahead int
seqReadAmount uint64
numOOORead uint64 // number of out of order read
// User space PID. All threads created by a process will have the same TGID,
// but different PIDs[1].
// This value can be nil if we fail to get TGID from PID[2].
// [1] : https://godoc.org/github.com/shirou/gopsutil/process#Process.Tgid
// [2] : https://github.com/shirou/gopsutil#process-class
Tgid *int32
}
const MAX_READAHEAD = uint32(400 * 1024 * 1024)
const READAHEAD_CHUNK = uint32(20 * 1024 * 1024)
// NewFileHandle returns a new file handle for the given `inode` triggered by fuse
// operation with the given `opMetadata`
func NewFileHandle(inode *Inode, opMetadata fuseops.OpMetadata) *FileHandle {
tgid, err := GetTgid(opMetadata.Pid)
if err != nil {
log.Debugf(
"Failed to retrieve tgid for the given pid. pid: %v err: %v inode id: %v err: %v",
opMetadata.Pid, err, inode.Id, err)
}
fh := &FileHandle{inode: inode, Tgid: tgid}
fh.cloud, fh.key = inode.cloud()
return fh
}
func (fh *FileHandle) initWrite() {
fh.writeInit.Do(func() {
fh.mpuWG.Add(1)
go fh.initMPU()
})
}
func (fh *FileHandle) initMPU() {
defer func() {
fh.mpuWG.Done()
}()
fs := fh.inode.fs
fh.mpuName = &fh.key
resp, err := fh.cloud.MultipartBlobBegin(&MultipartBlobBeginInput{
Key: *fh.mpuName,
ContentType: fs.flags.GetMimeType(*fh.mpuName),
})
fh.mu.Lock()
defer fh.mu.Unlock()
if err != nil {
fh.lastWriteError = mapAwsError(err)
} else {
fh.mpuId = resp
}
return
}
func (fh *FileHandle) mpuPartNoSpawn(buf *MBuf, part uint32, total int64, last bool) (err error) {
fs := fh.inode.fs
fs.replicators.Take(1, true)
defer fs.replicators.Return(1)
if part == 0 || part > 10000 {
return errors.New(fmt.Sprintf("invalid part number: %v", part))
}
mpu := MultipartBlobAddInput{
Commit: fh.mpuId,
PartNumber: part,
Body: buf,
Size: uint64(buf.Len()),
Last: last,
Offset: uint64(total - int64(buf.Len())),
}
defer func() {
if mpu.Body != nil {
bufferLog.Debugf("Free %T", buf)
buf.Free()
}
}()
_, err = fh.cloud.MultipartBlobAdd(&mpu)
return
}
func (fh *FileHandle) mpuPart(buf *MBuf, part uint32, total int64) {
defer func() {
fh.mpuWG.Done()
}()
// maybe wait for CreateMultipartUpload
if fh.mpuId == nil {
fh.mpuWG.Wait()
// initMPU might have errored
if fh.mpuId == nil {
return
}
}
err := fh.mpuPartNoSpawn(buf, part, total, false)
if err != nil {
if fh.lastWriteError == nil {
fh.lastWriteError = err
}
}
}
func (fh *FileHandle) waitForCreateMPU() (err error) {
if fh.mpuId == nil {
fh.mu.Unlock()
fh.initWrite()
fh.mpuWG.Wait() // wait for initMPU
fh.mu.Lock()
if fh.lastWriteError != nil {
return fh.lastWriteError
}
}
return
}
func (fh *FileHandle) partSize() uint64 {
if _, ok := fh.cloud.(*ADLv1); ok {
// ADLv1 fails with 404 if we upload data larger than
// 30000000 bytes (28.6MB) (28MB also failed in reality)
return 20 * 1024 * 1024
}
if fh.lastPartId < 1000 {
return 5 * 1024 * 1024
} else if fh.lastPartId < 2000 {
return 25 * 1024 * 1024
} else {
maxPartSize := fh.cloud.Capabilities().MaxMultipartSize
tryPartSize := uint64(125 * 1024 * 1024)
if maxPartSize != 0 {
tryPartSize = MinUInt64(tryPartSize, maxPartSize)
}
return tryPartSize
}
}
func (fh *FileHandle) uploadCurrentBuf(parallel bool) (err error) {
err = fh.waitForCreateMPU()
if err != nil {
return
}
fh.lastPartId++
part := fh.lastPartId
buf := fh.buf
fh.buf = nil
if parallel {
fh.mpuWG.Add(1)
go fh.mpuPart(buf, part, fh.nextWriteOffset)
} else {
err = fh.mpuPartNoSpawn(buf, part, fh.nextWriteOffset, false)
if fh.lastWriteError == nil {
fh.lastWriteError = err
}
}
return
}
func (fh *FileHandle) WriteFile(offset int64, data []byte) (err error) {
fh.inode.logFuse("WriteFile", offset, len(data))
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.lastWriteError != nil {
return fh.lastWriteError
}
if offset != fh.nextWriteOffset {
fh.inode.errFuse("WriteFile: only sequential writes supported", fh.nextWriteOffset, offset)
fh.lastWriteError = syscall.ENOTSUP
return fh.lastWriteError
}
if offset == 0 {
fh.poolHandle = fh.inode.fs.bufferPool
fh.dirty = true
}
for {
if fh.buf == nil {
fh.buf = MBuf{}.Init(fh.poolHandle, fh.partSize(), true)
}
nCopied, _ := fh.buf.Write(data)
fh.nextWriteOffset += int64(nCopied)
if fh.buf.Full() {
err = fh.uploadCurrentBuf(!fh.cloud.Capabilities().NoParallelMultipart)
if err != nil {
return
}
}
if nCopied == len(data) {
break
}
data = data[nCopied:]
}
fh.inode.Attributes.Size = uint64(fh.nextWriteOffset)
return
}
type S3ReadBuffer struct {
s3 StorageBackend
offset uint64
size uint32
buf *Buffer
}
func (b S3ReadBuffer) Init(fh *FileHandle, offset uint64, size uint32) *S3ReadBuffer {
b.s3 = fh.cloud
b.offset = offset
b.size = size
mbuf := MBuf{}.Init(fh.poolHandle, uint64(size), false)
if mbuf == nil {
return nil
}
b.buf = Buffer{}.Init(mbuf, func() (io.ReadCloser, error) {
resp, err := b.s3.GetBlob(&GetBlobInput{
Key: fh.key,
Start: offset,
Count: uint64(size),
})
if err != nil {
return nil, err
}
return resp.Body, nil
})
return &b
}
func (b *S3ReadBuffer) Read(offset uint64, p []byte) (n int, err error) {
if b.offset == offset {
n, err = io.ReadFull(b.buf, p)
if n != 0 && err == io.ErrUnexpectedEOF {
err = nil
}
if n > 0 {
if uint32(n) > b.size {
panic(fmt.Sprintf("read more than available %v %v", n, b.size))
}
b.offset += uint64(n)
b.size -= uint32(n)
}
return
} else {
panic(fmt.Sprintf("not the right buffer, expecting %v got %v, %v left", b.offset, offset, b.size))
err = errors.New(fmt.Sprintf("not the right buffer, expecting %v got %v", b.offset, offset))
return
}
}
func (fh *FileHandle) readFromReadAhead(offset uint64, buf []byte) (bytesRead int, err error) {
var nread int
for len(fh.buffers) != 0 {
nread, err = fh.buffers[0].Read(offset+uint64(bytesRead), buf)
bytesRead += nread
if err != nil {
if err == io.EOF && fh.buffers[0].size != 0 {
// in case we hit
// https://github.com/kahing/goofys/issues/464
// again, this will convert that into
// an error
fuseLog.Errorf("got EOF when data remains: %v", *fh.inode.FullName())
err = io.ErrUnexpectedEOF
}
return
}
if fh.buffers[0].size == 0 {
// we've exhausted the first buffer
fh.buffers[0].buf.Close()
fh.buffers = fh.buffers[1:]
}
buf = buf[nread:]
if len(buf) == 0 {
// we've filled the user buffer
return
}
}
return
}
func (fh *FileHandle) readAhead(offset uint64, needAtLeast int) (err error) {
existingReadahead := uint32(0)
for _, b := range fh.buffers {
existingReadahead += b.size
}
readAheadAmount := MAX_READAHEAD
for readAheadAmount-existingReadahead >= READAHEAD_CHUNK {
off := offset + uint64(existingReadahead)
remaining := fh.inode.Attributes.Size - off
// only read up to readahead chunk each time
size := MinUInt32(readAheadAmount-existingReadahead, READAHEAD_CHUNK)
// but don't read past the file
size = uint32(MinUInt64(uint64(size), remaining))
if size != 0 {
fh.inode.logFuse("readahead", off, size, existingReadahead)
readAheadBuf := S3ReadBuffer{}.Init(fh, off, size)
if readAheadBuf != nil {
fh.buffers = append(fh.buffers, readAheadBuf)
existingReadahead += size
} else {
if existingReadahead != 0 {
// don't do more readahead now, but don't fail, cross our
// fingers that we will be able to allocate the buffers
// later
return nil
} else {
return syscall.ENOMEM
}
}
}
if size != READAHEAD_CHUNK {
// that was the last remaining chunk to readahead
break
}
}
return nil
}
func (fh *FileHandle) ReadFile(offset int64, buf []byte) (bytesRead int, err error) {
fh.inode.logFuse("ReadFile", offset, len(buf))
defer func() {
fh.inode.logFuse("< ReadFile", bytesRead, err)
if err != nil {
if err == io.EOF {
err = nil
}
}
}()
fh.mu.Lock()
defer fh.mu.Unlock()
nwant := len(buf)
var nread int
for bytesRead < nwant && err == nil {
nread, err = fh.readFile(offset+int64(bytesRead), buf[bytesRead:])
if nread > 0 {
bytesRead += nread
}
}
return
}
func (fh *FileHandle) readFile(offset int64, buf []byte) (bytesRead int, err error) {
defer func() {
if bytesRead > 0 {
fh.readBufOffset += int64(bytesRead)
fh.seqReadAmount += uint64(bytesRead)
}
fh.inode.logFuse("< readFile", bytesRead, err)
}()
if uint64(offset) >= fh.inode.Attributes.Size {
// nothing to read
if fh.inode.Invalid {
err = fuse.ENOENT
} else if fh.inode.KnownSize == nil {
err = io.EOF
} else {
err = io.EOF
}
return
}
fs := fh.inode.fs
if fh.poolHandle == nil {
fh.poolHandle = fs.bufferPool
}
if fh.readBufOffset != offset {
// XXX out of order read, maybe disable prefetching
fh.inode.logFuse("out of order read", offset, fh.readBufOffset)
fh.readBufOffset = offset
fh.seqReadAmount = 0
if fh.reader != nil {
fh.reader.Close()
fh.reader = nil
}
if fh.buffers != nil {
// we misdetected
fh.numOOORead++
}
for _, b := range fh.buffers {
b.buf.Close()
}
fh.buffers = nil
}
if !fs.flags.Cheap && fh.seqReadAmount >= uint64(READAHEAD_CHUNK) && fh.numOOORead < 3 {
if fh.reader != nil {
fh.inode.logFuse("cutover to the parallel algorithm")
fh.reader.Close()
fh.reader = nil
}
err = fh.readAhead(uint64(offset), len(buf))
if err == nil {
bytesRead, err = fh.readFromReadAhead(uint64(offset), buf)
return
} else {
// fall back to read serially
fh.inode.logFuse("not enough memory, fallback to serial read")
fh.seqReadAmount = 0
for _, b := range fh.buffers {
b.buf.Close()
}
fh.buffers = nil
}
}
bytesRead, err = fh.readFromStream(offset, buf)
return
}
func (fh *FileHandle) Release() {
// read buffers
for _, b := range fh.buffers {
b.buf.Close()
}
fh.buffers = nil
if fh.reader != nil {
fh.reader.Close()
}
// write buffers
if fh.poolHandle != nil {
if fh.buf != nil && fh.buf.buffers != nil {
if fh.lastWriteError == nil {
panic("buf not freed but error is nil")
}
fh.buf.Free()
// the other in-flight multipart PUT buffers will be
// freed when they finish/error out
}
}
fh.inode.mu.Lock()
defer fh.inode.mu.Unlock()
if fh.inode.fileHandles == 0 {
panic(fh.inode.fileHandles)
}
fh.inode.fileHandles -= 1
}
func (fh *FileHandle) readFromStream(offset int64, buf []byte) (bytesRead int, err error) {
defer func() {
if fh.inode.fs.flags.DebugFuse {
fh.inode.logFuse("< readFromStream", bytesRead)
}
}()
if uint64(offset) >= fh.inode.Attributes.Size {
// nothing to read
return
}
if fh.reader == nil {
resp, err := fh.cloud.GetBlob(&GetBlobInput{
Key: fh.key,
Start: uint64(offset),
})
if err != nil {
return bytesRead, err
}
fh.reader = resp.Body
}
bytesRead, err = fh.reader.Read(buf)
if err != nil {
if err != io.EOF {
fh.inode.logFuse("< readFromStream error", bytesRead, err)
}
// always retry error on read
fh.reader.Close()
fh.reader = nil
err = nil
}
return
}
func (fh *FileHandle) flushSmallFile() (err error) {
buf := fh.buf
fh.buf = nil
if buf == nil {
buf = MBuf{}.Init(fh.poolHandle, 0, true)
}
defer buf.Free()
fs := fh.inode.fs
fs.replicators.Take(1, true)
defer fs.replicators.Return(1)
// we want to get key from inode because the file could have been renamed
_, key := fh.inode.cloud()
resp, err := fh.cloud.PutBlob(&PutBlobInput{
Key: key,
Body: buf,
Size: PUInt64(uint64(buf.Len())),
ContentType: fs.flags.GetMimeType(*fh.inode.FullName()),
})
if err != nil {
fh.lastWriteError = err
} else {
inode := fh.inode
inode.mu.Lock()
defer inode.mu.Unlock()
if resp.ETag != nil {
inode.s3Metadata["etag"] = []byte(*resp.ETag)
}
if resp.StorageClass != nil {
inode.s3Metadata["storage-class"] = []byte(*resp.StorageClass)
}
}
return
}
func (fh *FileHandle) resetToKnownSize() {
if fh.inode.KnownSize != nil {
fh.inode.Attributes.Size = *fh.inode.KnownSize
} else {
fh.inode.Attributes.Size = 0
fh.inode.Invalid = true
}
}
func (fh *FileHandle) FlushFile() (err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
fh.inode.logFuse("FlushFile")
if !fh.dirty || fh.lastWriteError != nil {
if fh.lastWriteError != nil {
err = fh.lastWriteError
fh.resetToKnownSize()
}
return
}
fs := fh.inode.fs
// abort mpu on error
defer func() {
if err != nil {
if fh.mpuId != nil {
go func() {
_, _ = fh.cloud.MultipartBlobAbort(fh.mpuId)
fh.mpuId = nil
}()
}
fh.resetToKnownSize()
} else {
if fh.dirty {
// don't unset this if we never actually flushed
size := fh.inode.Attributes.Size
fh.inode.KnownSize = &size
fh.inode.Invalid = false
}
fh.dirty = false
}
fh.writeInit = sync.Once{}
fh.nextWriteOffset = 0
fh.lastPartId = 0
}()
if fh.lastPartId == 0 {
return fh.flushSmallFile()
}
fh.mpuWG.Wait()
if fh.lastWriteError != nil {
return fh.lastWriteError
}
if fh.mpuId == nil {
return
}
nParts := fh.lastPartId
if fh.buf != nil {
// upload last part
nParts++
err = fh.mpuPartNoSpawn(fh.buf, nParts, fh.nextWriteOffset, true)
if err != nil {
return
}
fh.buf = nil
}
_, err = fh.cloud.MultipartBlobCommit(fh.mpuId)
if err != nil {
return
}
fh.mpuId = nil
// we want to get key from inode because the file could have been renamed
_, key := fh.inode.cloud()
if *fh.mpuName != key {
// the file was renamed
err = fh.inode.renameObject(fs, PUInt64(uint64(fh.nextWriteOffset)), *fh.mpuName, *fh.inode.FullName())
}
return
}