forked from folbricht/desync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal.go
More file actions
218 lines (201 loc) · 5.49 KB
/
Copy pathlocal.go
File metadata and controls
218 lines (201 loc) · 5.49 KB
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
package desync
import (
"context"
"crypto/sha512"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
)
const chunkFileExt = ".cacnk"
// LocalStore casync store
type LocalStore struct {
Base string
// When accessing chunks, should mtime be updated? Useful when this is
// a cache. Old chunks can be identified and removed from the store that way
UpdateTimes bool
}
// NewLocalStore creates an instance of a local castore, it only checks presence
// of the store
func NewLocalStore(dir string) (LocalStore, error) {
info, err := os.Stat(dir)
if err != nil {
return LocalStore{}, err
}
if !info.IsDir() {
return LocalStore{}, fmt.Errorf("%s is not a directory", dir)
}
return LocalStore{Base: dir}, nil
}
// GetChunk reads and returns one (compressed!) chunk from the store
func (s LocalStore) GetChunk(id ChunkID) ([]byte, error) {
sID := id.String()
p := filepath.Join(s.Base, sID[0:4], sID) + chunkFileExt
b, err := ioutil.ReadFile(p)
if os.IsNotExist(err) {
err = ChunkMissing{id}
}
return b, err
}
// RemoveChunk deletes a chunk, typically an invalid one, from the filesystem.
// Used when verifying and repairing caches.
func (s LocalStore) RemoveChunk(id ChunkID) error {
sID := id.String()
p := filepath.Join(s.Base, sID[0:4], sID) + chunkFileExt
if _, err := os.Stat(p); err != nil {
return ChunkMissing{id}
}
return os.Remove(p)
}
// StoreChunk adds a new chunk to the store
func (s LocalStore) StoreChunk(id ChunkID, b []byte) error {
sID := id.String()
d := filepath.Join(s.Base, sID[0:4])
if err := os.MkdirAll(d, 0755); err != nil {
return err
}
tmpfile, err := ioutil.TempFile(d, ".tmp-cacnk")
if err != nil {
return err
}
tmpfile.Close()
defer os.Remove(tmpfile.Name()) // in case we don't get to the rename, clean up
if err = ioutil.WriteFile(tmpfile.Name(), b, 0644); err != nil {
return err
}
p := filepath.Join(d, sID) + chunkFileExt
return os.Rename(tmpfile.Name(), p)
}
// Verify all chunks in the store. If repair is set true, bad chunks are deleted.
// n determines the number of concurrent operations.
func (s LocalStore) Verify(ctx context.Context, n int, repair bool) error {
var wg sync.WaitGroup
ids := make(chan ChunkID)
// Start the workers
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
for id := range ids {
err := s.verifyChunk(id)
switch err.(type) {
case ChunkInvalid: // bad chunk, report and delete (if repair=true)
msg := err.Error()
if repair {
if err = s.RemoveChunk(id); err != nil {
msg = msg + ":" + err.Error()
} else {
msg = msg + ": removed"
}
}
fmt.Fprintln(os.Stderr, msg)
case nil: // all good, move to the next
default: // unexpected, print the error and carry on
fmt.Fprintln(os.Stderr, err)
}
}
wg.Done()
}()
}
// Go trough all chunks underneath Base, filtering out other files, then feed
// the IDs to the workers
err := filepath.Walk(s.Base, func(path string, info os.FileInfo, err error) error {
// See if we're meant to stop
select {
case <-ctx.Done():
return Interrupted{}
default:
}
if err != nil { // failed to walk? => fail
return err
}
if info.IsDir() { // Skip dirs
return nil
}
if !strings.HasSuffix(path, chunkFileExt) { // Skip files without chunk extension
return nil
}
// Convert the name into a checksum, if that fails we're probably not looking
// at a chunk file and should skip it.
id, err := ChunkIDFromString(strings.TrimSuffix(filepath.Base(path), ".cacnk"))
if err != nil {
return nil
}
// Feed the workers
ids <- id
return nil
})
close(ids)
wg.Wait()
return err
}
// Prune removes any chunks from the store that are not contained in a list
// of chunks
func (s LocalStore) Prune(ctx context.Context, ids map[ChunkID]struct{}) error {
// Go trough all chunks underneath Base, filtering out other directories and files
err := filepath.Walk(s.Base, func(path string, info os.FileInfo, err error) error {
// See if we're meant to stop
select {
case <-ctx.Done():
return Interrupted{}
default:
}
if err != nil { // failed to walk? => fail
return err
}
if info.IsDir() { // Skip dirs
return nil
}
if !strings.HasSuffix(path, chunkFileExt) { // Skip files without chunk extension
return nil
}
// Convert the name into a checksum, if that fails we're probably not looking
// at a chunk file and should skip it.
id, err := ChunkIDFromString(strings.TrimSuffix(filepath.Base(path), ".cacnk"))
if err != nil {
return nil
}
// See if the chunk we're looking at is in the list we want to keep, if not
// remove it.
if _, ok := ids[id]; !ok {
if err = s.RemoveChunk(id); err != nil {
return err
}
}
return nil
})
return err
}
// Unpack a chunk, calculate the checksum of its content and return nil if
// they match.
func (s LocalStore) verifyChunk(id ChunkID) error {
b, err := s.GetChunk(id)
if err != nil {
return err
}
// The the chunk is compressed. Decompress it here
db, err := Decompress(nil, b)
if err != nil {
return err
}
// Verify the checksum of the chunk matches the ID
sum := sha512.Sum512_256(db)
if sum != id {
return ChunkInvalid{ID: id, Sum: sum}
}
return nil
}
// HasChunk returns true if the chunk is in the store
func (s LocalStore) HasChunk(id ChunkID) bool {
sID := id.String()
p := filepath.Join(s.Base, sID[0:4], sID) + chunkFileExt
if _, err := os.Stat(p); err == nil {
return true
}
return false
}
func (s LocalStore) String() string {
return s.Base
}
func (s LocalStore) Close() error { return nil }