forked from zach-klippenstein/adbfs
/
open_files.go
81 lines (65 loc) · 2.01 KB
/
open_files.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
package adbfs
import (
"os"
"sync"
"time"
"github.com/mheyse/adbfs/internal/cli"
)
type OpenFilesOptions struct {
DeviceSerial string
DefaultPermissions os.FileMode
ClientFactory DeviceClientFactory
// The length of time the file can be dirty before the next write will force a flush.
DirtyTimeout time.Duration
}
// OpenFiles tracks and manages the set of all open files in a filesystem.
type OpenFiles struct {
OpenFilesOptions
lock sync.Mutex
buffersByPath map[string]*FileBuffer
}
func NewOpenFiles(opts OpenFilesOptions) *OpenFiles {
if opts.DirtyTimeout.Nanoseconds() == 0 {
opts.DirtyTimeout = DefaultDirtyTimeout
}
return &OpenFiles{
OpenFilesOptions: opts,
buffersByPath: make(map[string]*FileBuffer),
}
}
func (f *OpenFiles) GetOrLoad(path string, openFlags FileOpenFlags, perms os.FileMode, logEntry *LogEntry) (file *FileBuffer, err error) {
f.lock.Lock()
defer f.lock.Unlock()
if file = f.buffersByPath[path]; file == nil {
file, err = NewFileBuffer(openFlags, FileBufferOptions{
Path: path,
Client: f.ClientFactory(),
DirtyTimeout: f.DirtyTimeout,
Perms: perms,
ZeroRefCountHandler: f.release,
}, logEntry)
if err != nil {
return nil, err
}
f.buffersByPath[path] = file
}
// The refcount will be decremented when the AdbFile is released.
refCount := file.IncRefCount()
cli.Log.Debugf("OpenFiles: refcount is now %d for %s", refCount, path)
return file, nil
}
func (f *OpenFiles) release(file *FileBuffer) {
// Acquire the lock first, so that a concurrent call to GetOrLoad won't be able to increment
// the refcount before we remove it from the map.
f.lock.Lock()
defer f.lock.Unlock()
// However, the GetOrLoad may already have beat us to the punch.
if file.RefCount() != 0 {
return
}
cli.Log.Debugf("OpenFiles: releasing FileBuffer for %s", file.Path)
if file.IsDirty() {
cli.Log.Warnln("OpenFiles: FileBuffer released while still dirty:", file)
}
delete(f.buffersByPath, file.Path)
}