forked from asjoyner/shade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
284 lines (263 loc) · 7.58 KB
/
tree.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
package fusefs
import (
"encoding/json"
"errors"
"fmt"
"log"
"path"
"strings"
"sync"
"time"
"github.com/asjoyner/shade"
"github.com/asjoyner/shade/drive"
)
// Node is a very compact representation of a shade.File. It can also be used
// to represent a sythetic directory, for tree traversal.
type Node struct {
// Filename is the complete path to a node, with no leading or trailing
// slash.
Filename string
Filesize int64 // in bytes
ModifiedTime time.Time
// Deleted indicates the file was Deleted at ModifiedTime. NodeByPath
// responds exactly as if the node did not exist.
Deleted bool
Sha256sum []byte // the sha of the full shade.File
// Children is a map indicating the presence of a node immediately
// below the current node in the tree. The key is only the name of that
// node, a relative path, not fully qualified.
// TODO(asjoyner): use a struct{} here for efficiency?
// unsafe.Sizeof indicates it would save 1 byte per FS entry
Children map[string]bool
// TODO(asjoyner): update LastSeen each poll, timeout entries so deleted
// files eventually disappear from Tree.
// LastSeen time.Time
}
// Synthetic returns true for synthetically created directories.
func (n *Node) Synthetic() bool {
if n.Sha256sum == nil {
return true
}
return false
}
// Tree is a representation of all files known to the provided drive.Client.
// It initially downlods, then periodically refreshes, the set of files by
// calling ListFiles and GetChunk. It presents methods to query for what file
// object currently describes what path, and can return a Node or shade.File
// struct representing that node in the tree.
type Tree struct {
client drive.Client
nodes map[string]Node // full path to node
nm sync.RWMutex // protects nodes
debug bool
}
// NewTree queries client to discover all the shade.File(s). It returns a Tree
// object which is ready to answer questions about the nodes in the file tree.
// If the initial query fails, an error is returned instead.
func NewTree(client drive.Client, refresh *time.Ticker) (*Tree, error) {
t := &Tree{
client: client,
nodes: map[string]Node{
"": {
Filename: "",
Children: make(map[string]bool),
}},
}
if err := t.Refresh(); err != nil {
return nil, fmt.Errorf("initializing Tree: %s", err)
}
if refresh != nil {
go t.periodicRefresh(refresh)
}
return t, nil
}
// NodeByPath returns a Node describing the given path.
func (t *Tree) NodeByPath(p string) (Node, error) {
p = strings.TrimPrefix(p, "/")
t.nm.RLock()
defer t.nm.RUnlock()
n, ok := t.nodes[p]
if !ok || n.Deleted {
t.log("known nodes:\n")
for _, n := range t.nodes {
t.log(fmt.Sprintf("%+v\n", n))
}
return Node{}, fmt.Errorf("no such node: %q", p)
}
return n, nil
}
func unmarshalChunk(fj, sha []byte) (*shade.File, error) {
file := &shade.File{}
if err := json.Unmarshal(fj, file); err != nil {
return nil, fmt.Errorf("Failed to unmarshal sha256sum %x: %s", sha, err)
}
return file, nil
}
// FileByNode returns the full shade.File object for a given node.
func (t *Tree) FileByNode(n Node) (*shade.File, error) {
if n.Synthetic() {
return nil, errors.New("no shade.File defined")
}
fj, err := t.client.GetFile(n.Sha256sum)
if err != nil {
return nil, fmt.Errorf("GetChunk(%x): %s", n.Sha256sum, err)
}
if fj == nil || len(fj) == 0 {
return nil, fmt.Errorf("Could not find JSON for node: %q", n.Filename)
}
f := &shade.File{}
if err := f.FromJSON(fj); err != nil {
return nil, err
}
return f, nil
}
// HasChild returns true if child exists immediately below parent in the file
// tree.
func (t *Tree) HasChild(parent, child string) bool {
t.nm.RLock()
defer t.nm.RUnlock()
return t.nodes[parent].Children[child]
}
// NumNodes returns the number of nodes (files + synthetic directories) in the
// system.
func (t *Tree) NumNodes() int {
t.nm.RLock()
defer t.nm.RUnlock()
return len(t.nodes)
}
// Mkdir provides a way to create synthetic directories, for the Mkdir Fuse op
func (t *Tree) Mkdir(dir string) Node {
dir = strings.TrimPrefix(dir, "/")
t.nm.Lock()
defer t.nm.Unlock()
t.nodes[dir] = Node{
Filename: dir,
Children: make(map[string]bool),
}
t.addParents(dir)
return t.nodes[dir]
}
// Create adds a new shade.File node to the tree
func (t *Tree) Create(filename string) Node {
t.nm.Lock()
defer t.nm.Unlock()
node := Node{
Filename: filename,
Sha256sum: []byte("f00d"),
}
t.nodes[node.Filename] = node
t.addParents(node.Filename)
return node
}
// Update accepts a replacement shade.File node
func (t *Tree) Update(n Node) {
t.nm.Lock()
defer t.nm.Unlock()
on, ok := t.nodes[n.Filename]
if !ok {
t.log(fmt.Sprintf("Attempt to update a non-existent node: %+v", n))
return
}
if on.ModifiedTime.After(n.ModifiedTime) {
t.log(fmt.Sprintf("Update mtime (%s) older than current Node (%s)", n.ModifiedTime, on.ModifiedTime))
return
}
t.nodes[n.Filename] = n
if n.Deleted {
dir, f := path.Split(n.Filename)
dir = strings.TrimSuffix(dir, "/")
parent, ok := t.nodes[dir]
if !ok {
t.log(fmt.Sprintf("Updated node without a parent: %+v", n))
return
}
delete(parent.Children, f)
}
}
// Refresh updates the cached view of the Tree by calling ListFiles and
// processing the result.
func (t *Tree) Refresh() error {
t.log("Begining cache refresh cycle.")
// key is a string([]byte) representation of the file's SHA2
knownNodes := make(map[string]bool)
newFiles, err := t.client.ListFiles()
if err != nil {
return fmt.Errorf("%q ListFiles(): %s", t.client.GetConfig().Provider, err)
}
t.log(fmt.Sprintf("Found %d file(s) via %s", len(newFiles), t.client.GetConfig().Provider))
// fetch all those files into the local disk cache
for _, sha256sum := range newFiles {
// check if we have already processed this Node
if knownNodes[string(sha256sum)] {
continue // we've already processed this file
}
// fetch the file Chunk
f, err := t.client.GetFile(sha256sum)
if err != nil {
// TODO(asjoyner): if !client.Local()... retry?
log.Printf("Failed to fetch file %x: %s", sha256sum, err)
continue
}
// unmarshal and populate t.nodes as the shade.files go by
file := &shade.File{}
if err := file.FromJSON(f); err != nil {
log.Printf("%v", err)
continue
}
node := Node{
Filename: file.Filename,
Filesize: file.Filesize,
ModifiedTime: file.ModifiedTime,
Deleted: file.Deleted,
Sha256sum: sha256sum,
Children: nil,
}
t.nm.Lock()
// TODO(asjoyner): handle file + directory collisions
if existing, ok := t.nodes[node.Filename]; ok && existing.ModifiedTime.After(node.ModifiedTime) {
t.nm.Unlock()
continue
}
t.nodes[node.Filename] = node
t.addParents(node.Filename)
t.nm.Unlock()
knownNodes[string(sha256sum)] = true
}
t.log(fmt.Sprintf("Refresh complete with %d file(s).", len(knownNodes)))
return nil
}
// recursive function to update parent dirs
func (t *Tree) addParents(filepath string) {
dir, f := path.Split(filepath)
dir = strings.TrimSuffix(dir, "/")
t.log(fmt.Sprintf("adding %q as a child of %q", f, dir))
// TODO(asjoyner): handle file + directory collisions
if parent, ok := t.nodes[dir]; !ok {
// if the parent node doesn't yet exist, initialize it
t.nodes[dir] = Node{
Filename: dir,
Children: map[string]bool{f: true},
}
} else {
parent.Children[f] = true
return
}
if dir != "" {
t.addParents(dir)
}
}
func (t *Tree) periodicRefresh(refresh *time.Ticker) {
for {
<-refresh.C
t.Refresh()
}
}
// Debug causes the client to print helpful message via the log library.
func (t *Tree) Debug() {
t.debug = true
}
func (t *Tree) log(msg string) {
if t.debug {
log.Printf("CACHE: %s", msg)
}
}