forked from asjoyner/shade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.go
298 lines (267 loc) · 7.52 KB
/
local.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
// Package local is a persistent local storage backend for Shade.
//
// It stores files and chunks locally to disk. You may define full filepaths
// to store the files and chunks in the config, or via flag. If you define
// neither, the flags will choose sensible defaults for your operating system.
package local
import (
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"sync"
"time"
"github.com/asjoyner/shade"
"github.com/asjoyner/shade/drive"
"github.com/google/btree"
)
func init() {
drive.RegisterProvider("local", NewClient)
}
// NewClient returns a fully initlized local client.
func NewClient(c drive.Config) (drive.Client, error) {
// Sanity check the config
if c.ChunkParentID == "" {
return nil, errors.New("specify the path to store local chunks as ChunkParentID")
}
if c.FileParentID == "" {
return nil, errors.New("specify the path to store local files as FileParentID")
}
for _, dir := range []string{
c.ChunkParentID,
c.FileParentID,
} {
if fh, err := os.Open(dir); err != nil {
if err := os.Mkdir(dir, 0700); err != nil {
return nil, err
}
} else {
fh.Close()
}
}
// Initialize the internal accounting
s := &Drive{
config: c,
files: btree.New(2),
chunks: btree.New(2),
}
// Make note of all the filenames in FileParentID
files, err := ioutil.ReadDir(c.FileParentID)
if err != nil {
return nil, err
}
for _, fi := range files {
if !fi.IsDir() {
sha256sum, err := hex.DecodeString(fi.Name())
if err != nil {
log.Printf("file with non-hex string value name: %s", fi.Name())
continue
}
s.files.ReplaceOrInsert(Chunk{
sum: sha256sum,
mtime: fi.ModTime().Unix(),
})
}
}
// Count the bytes in the local storage
chunks, err := ioutil.ReadDir(c.ChunkParentID)
if err != nil {
return nil, err
}
for _, fi := range chunks {
if !fi.IsDir() {
sha256sum, err := hex.DecodeString(fi.Name())
if err != nil {
log.Printf("file with non-hex string value name: %s", fi.Name())
continue
}
s.chunks.ReplaceOrInsert(Chunk{
sum: sha256sum,
mtime: fi.ModTime().Unix(),
})
s.chunkBytes += uint64(fi.Size())
}
}
return s, nil
}
// Drive implements the drive.Client interface by storing Files and Chunks
// to the local filesystem. It treats the ChunkParentID and FileParentID as
// filepaths to the directory to store data in.
type Drive struct {
sync.RWMutex // serializes accesses to the directories on local disk
config drive.Config
files *btree.BTree // for accounting
chunks *btree.BTree // for accounting
chunkBytes uint64 // for accounting
}
// Chunk describes an object cached to the filesystem, in a way that the btree
// implementaiton can sort it. This allows garbage collection by mtime.
type Chunk struct {
sum []byte
mtime int64
}
// Less ultimately describes the order chunks are deleted in.
func (a Chunk) Less(bt btree.Item) bool {
b := bt.(Chunk)
if a.mtime < b.mtime {
return true
} else if a.mtime == b.mtime && string(a.sum) < string(b.sum) {
return true
}
return false
}
// ListFiles retrieves all of the File objects known to the client. The return
// values are the sha256sum of the file object. The keys may be passed to
// GetChunk() to retrieve the corresponding shade.File.
func (s *Drive) ListFiles() ([][]byte, error) {
var resp [][]byte
s.Lock()
defer s.Unlock()
s.files.Ascend(func(item btree.Item) bool {
resp = append(resp, item.(Chunk).sum)
return true
})
return resp, nil
}
// GetFile retrieves a chunk with a given SHA-256 sum
func (s *Drive) GetFile(sha256sum []byte) ([]byte, error) {
return s.GetChunk(sha256sum, nil)
}
// PutFile writes the metadata describing a new file.
// f should be marshalled JSON, and may be encrypted.
//
// TODO(asjoyner): collapse the logic in PutFile and PutChunk into shared code.
func (s *Drive) PutFile(sha256sum, data []byte) error {
s.Lock()
defer s.Unlock()
filename := path.Join(s.config.FileParentID, hex.EncodeToString(sha256sum))
// Optimize duplicate push
if fi, err := os.Stat(filename); err == nil {
now := time.Now()
if err := os.Chtimes(filename, now, now); err != nil {
return fmt.Errorf("could not update mtime: %s", err)
}
s.files.Delete(Chunk{sum: sha256sum, mtime: fi.ModTime().Unix()})
s.files.ReplaceOrInsert(Chunk{sum: sha256sum, mtime: now.Unix()})
return nil
}
if s.config.MaxFiles > 0 {
if err := s.cleanup(true, 1); err != nil {
return err
}
}
if fh, err := os.Open(filename); err == nil {
fh.Close()
return nil
}
if err := ioutil.WriteFile(filename, data, 0400); err != nil {
return err
}
fi, err := os.Stat(filename)
if err != nil {
return fmt.Errorf("could not stat file after write: %s", err)
}
s.files.ReplaceOrInsert(Chunk{
sum: sha256sum,
mtime: fi.ModTime().Unix(),
})
return nil
}
// GetChunk retrieves a chunk with a given SHA-256 sum
func (s *Drive) GetChunk(sha256sum []byte, f *shade.File) ([]byte, error) {
s.RLock()
defer s.RUnlock()
paths := []string{s.config.FileParentID, s.config.ChunkParentID}
for _, p := range paths {
filename := path.Join(p, hex.EncodeToString(sha256sum))
if f, err := ioutil.ReadFile(filename); err == nil {
return f, nil
}
}
return nil, errors.New("chunk not found")
}
// PutChunk writes a chunk to local disk
func (s *Drive) PutChunk(sha256sum []byte, data []byte, f *shade.File) error {
s.Lock()
defer s.Unlock()
filename := path.Join(s.config.ChunkParentID, hex.EncodeToString(sha256sum))
// Optimize duplicate push
if fi, err := os.Stat(filename); err == nil {
now := time.Now()
if err := os.Chtimes(filename, now, now); err != nil {
return fmt.Errorf("could not update mtime: %s", err)
}
s.chunks.Delete(Chunk{sum: sha256sum, mtime: fi.ModTime().Unix()})
s.chunks.ReplaceOrInsert(Chunk{sum: sha256sum, mtime: now.Unix()})
return nil
}
if s.config.MaxChunkBytes > 0 {
if err := s.cleanup(false, uint64(len(data))); err != nil {
return err
}
}
if fh, err := os.Open(filename); err == nil {
fh.Close()
return nil
}
if err := ioutil.WriteFile(filename, data, 0400); err != nil {
return err
}
fi, err := os.Stat(filename)
if err != nil {
return fmt.Errorf("could not stat file after write: %s", err)
}
s.chunks.ReplaceOrInsert(Chunk{
sum: sha256sum,
mtime: fi.ModTime().Unix(),
})
s.chunkBytes += uint64(len(data))
return nil
}
// GetConfig returns the config used to initialize this client.
func (s *Drive) GetConfig() drive.Config {
return s.config
}
// Local returns whether the storage is local to this machine.
func (s *Drive) Local() bool { return true }
// Persistent returns whether the storage is persistent across task restarts.
func (s *Drive) Persistent() bool { return true }
// cleanup iterates the provided BTree and removes the oldest entries from the
// filesystem, in the provided directory, to bring the length below the
// provided maximum size. cleanup is called at insert time, so size is Max-1,
// to make space for the new entry being inserted.
func (s *Drive) cleanup(file bool, size uint64) error {
var bt *btree.BTree
var dir string
if file {
bt = s.files
dir = s.config.FileParentID
} else {
bt = s.chunks
dir = s.config.ChunkParentID
}
for {
if file {
len := s.files.Len()
if len == 0 || uint64(len) <= s.config.MaxFiles-size {
return nil
}
} else {
if s.chunkBytes <= s.config.MaxChunkBytes-size {
return nil
}
}
oldest := hex.EncodeToString(bt.Min().(Chunk).sum)
r := path.Join(dir, oldest)
if err := os.Remove(r); err != nil {
return err
}
bt.DeleteMin()
if !file {
s.chunkBytes -= size
}
}
}