-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
115 lines (94 loc) · 2.2 KB
/
api.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
package main
import (
"fmt"
"path"
"sync"
)
// TODO: upon file close, ensure consistent FS cache!
// API represents the logical file system API.
type API interface {
Open(path string) (File, error)
Close(path string) error
Remove(path string) error
}
// NewAPI returns a file system API instance.
func NewAPI(mutex sync.Locker, ring Ring, sharder Sharder, cache Cache, fs FileSystem) API {
return &api{
mutex: mutex,
ring: ring,
sharder: sharder,
cache: cache,
fs: fs,
}
}
type api struct {
mutex sync.Locker
ring Ring
sharder Sharder
cache Cache
fs FileSystem
}
func (a *api) Open(filePath string) (File, error) {
a.mutex.Lock()
defer a.mutex.Unlock()
shard := a.sharder.ShardOf(filePath)
node := a.ring.NodeOf(shard)
if node != a.ring.Self() {
return nil, fmt.Errorf("ErrOtherNode")
}
err := a.sharder.Acquire(shard)
if err != nil {
return nil, fmt.Errorf("ErrShardLock")
}
if item, ok := a.cache.Get(filePath); ok {
return item.(File), nil
}
err = a.fs.MkdirAll(path.Dir(filePath), dirMode)
if err != nil {
return nil, err
}
f, err := a.fs.OpenFile(filePath, fileFlags, fileMode)
if err != nil {
return nil, err
}
a.cache.Add(filePath, f)
return f, nil
}
func (a *api) Close(filePath string) error {
a.mutex.Lock()
defer a.mutex.Unlock()
shard := a.sharder.ShardOf(filePath)
node := a.ring.NodeOf(shard)
if node != a.ring.Self() {
return fmt.Errorf("ErrOtherNode")
}
err := a.sharder.Acquire(shard)
if err != nil {
return fmt.Errorf("ErrShardLock")
}
if item, ok := a.cache.Remove(filePath); ok {
item.(File).Close()
}
return nil
}
func (a *api) Remove(filePath string) error {
a.mutex.Lock()
defer a.mutex.Unlock()
shard := a.sharder.ShardOf(filePath)
node := a.ring.NodeOf(shard)
if node != a.ring.Self() {
return fmt.Errorf("ErrOtherNode")
}
err := a.sharder.Acquire(shard)
if err != nil {
return fmt.Errorf("ErrShardLock")
}
if item, ok := a.cache.Remove(filePath); ok {
item.(File).Close()
}
err = a.fs.RemoveAll(filePath)
if err != nil {
return fmt.Errorf("ErrRemoveFile")
}
return nil
}