Debian Codegraph @

sparse-file.go

raw
1 package desync
2
3 import (
4 "errors"
5 "io"
6 "os"
7 "sort"
8 "sync"
9
10 "github.com/boljen/go-bitmap"
11 )
12
13 // SparseFile represents a file that is written as it is read (Copy-on-read). It is
14 // used as a fast cache. Any chunk read from the store to satisfy a read operation
15 // is written to the file.
16 type SparseFile struct {
17 name string
18 idx Index
19 opt SparseFileOptions
20
21 loader *sparseFileLoader
22 }
23 type SparseFileOptions struct {
24 // Optional, save the state of the sparse file on exit or SIGHUP. The state file
25 // contains information which chunks from the index have been read and are
26 // populated in the sparse file. If the state and sparse file exist and match,
27 // the sparse file is used as is (not re-populated).
28 StateSaveFile string
29
30 // Optional, load all chunks that are marked as read in this state file. It is used
31 // to pre-populate a new sparse file if the sparse file or the save state file aren't
32 // present or don't match the index. SaveStateFile and StateInitFile can be the same.
33 StateInitFile string
34
35 // Optional, number of goroutines to preload chunks from StateInitFile.
36 StateInitConcurrency int
37 }
38
39 // SparseFileHandle is used to access a sparse file. All read operations performed
40 // on the handle are either done on the file if the required ranges are available
41 // or loaded from the store and written to the file.
42 type SparseFileHandle struct {
43 sf *SparseFile
44 file *os.File
45 }
46
47 func NewSparseFile(name string, idx Index, s Store, opt SparseFileOptions) (*SparseFile, error) {
48 f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0755)
49 if err != nil {
50 return nil, err
51 }
52 defer f.Close()
53 loader := newSparseFileLoader(name, idx, s)
54 sf := &SparseFile{
55 name: name,
56 idx: idx,
57 loader: loader,
58 opt: opt,
59 }
60
61 // Simple check to see if the file is correct for the given index by
62 // just comparing the size. If it's not, then just reset the file and
63 // don't load a state.
64 stat, err := f.Stat()
65 if err != nil {
66 return nil, err
67 }
68 sparseFileMatch := stat.Size() == idx.Length()
69
70 // If the sparse-file looks like it's of the right size, and we have a
71 // save state file, try to use those. No need to further initialize if
72 // that's successful
73 if sparseFileMatch && opt.StateSaveFile != "" {
74 stateFile, err := os.Open(opt.StateSaveFile)
75 if err == nil {
76 defer stateFile.Close()
77
78 // If we can load the state file, we have everything needed,
79 // no need to initialize it.
80 if err := loader.loadState(stateFile); err == nil {
81 return sf, nil
82 }
83 }
84 }
85
86 // Create the new file at full size, that was we can skip loading null-chunks,
87 // this should be a NOP if the file matches the index size already.
88 if err = f.Truncate(idx.Length()); err != nil {
89 return nil, err
90 }
91
92 // Try to initialize the sparse file from a prior state file if one is provided.
93 // This will concurrently load all chunks marked "done" in the state file and
94 // write them to the sparse file.
95 if opt.StateInitFile != "" {
96 initFile, err := os.Open(opt.StateInitFile)
97 if err != nil {
98 return nil, err
99 }
100 defer initFile.Close()
101 if err := loader.preloadChunksFromState(initFile, opt.StateInitConcurrency); err != nil {
102 return nil, err
103 }
104 }
105
106 return sf, nil
107 }
108
109 // Open returns a handle for a sparse file.
110 func (sf *SparseFile) Open() (*SparseFileHandle, error) {
111 file, err := os.Open(sf.name)
112 return &SparseFileHandle{
113 sf: sf,
114 file: file,
115 }, err
116 }
117
118 // Length returns the size of the index used for the sparse file.
119 func (sf *SparseFile) Length() int64 {
120 return sf.idx.Length()
121 }
122
123 // WriteState saves the state of file, basically which chunks were loaded
124 // and which ones weren't.
125 func (sf *SparseFile) WriteState() error {
126 if sf.opt.StateSaveFile == "" {
127 return nil
128 }
129 f, err := os.Create(sf.opt.StateSaveFile)
130 if err != nil {
131 return err
132 }
133 defer f.Close()
134 return sf.loader.writeState(f)
135 }
136
137 // ReadAt reads from the sparse file. All accessed ranges are first written
138 // to the file and then returned.
139 func (h *SparseFileHandle) ReadAt(b []byte, offset int64) (int, error) {
140 if err := h.sf.loader.loadRange(offset, int64(len(b))); err != nil {
141 return 0, err
142 }
143 return h.file.ReadAt(b, offset)
144 }
145
146 func (h *SparseFileHandle) Close() error {
147 return h.file.Close()
148 }
149
150 type sparseIndexChunk struct {
151 IndexChunk
152 mu sync.Mutex
153 }
154
155 // Loader for sparse files
156 type sparseFileLoader struct {
157 name string
158 done bitmap.Bitmap
159 mu sync.RWMutex
160 s Store
161
162 nullChunk *NullChunk
163 chunks []*sparseIndexChunk
164 }
165
166 func newSparseFileLoader(name string, idx Index, s Store) *sparseFileLoader {
167 chunks := make([]*sparseIndexChunk, 0, len(idx.Chunks))
168 for _, c := range idx.Chunks {
169 chunks = append(chunks, &sparseIndexChunk{IndexChunk: c})
170 }
171
172 return &sparseFileLoader{
173 name: name,
174 done: bitmap.New(len(idx.Chunks)),
175 chunks: chunks,
176 s: s,
177 nullChunk: NewNullChunk(idx.Index.ChunkSizeMax),
178 }
179 }
180
181 // For a given byte range, returns the index of the first and last chunk needed to populate it
182 func (l *sparseFileLoader) indexRange(start, length int64) (int, int) {
183 end := uint64(start + length - 1)
184 firstChunk := sort.Search(len(l.chunks), func(i int) bool { return start < int64(l.chunks[i].Start+l.chunks[i].Size) })
185 if length < 1 {
186 return firstChunk, firstChunk
187 }
188 if firstChunk >= len(l.chunks) { // reading past the end, load the last chunk
189 return len(l.chunks) - 1, len(l.chunks) - 1
190 }
191
192 // Could do another binary search to find the last, but in reality, most reads are short enough to fall
193 // into one or two chunks only, so may as well use a for loop here.
194 lastChunk := firstChunk
195 for i := firstChunk + 1; i < len(l.chunks); i++ {
196 if end < l.chunks[i].Start {
197 break
198 }
199 lastChunk++
200 }
201 return firstChunk, lastChunk
202 }
203
204 // Loads all the chunks needed to populate the given byte range (if not already loaded)
205 func (l *sparseFileLoader) loadRange(start, length int64) error {
206 first, last := l.indexRange(start, length)
207 var chunksNeeded []int
208 l.mu.RLock()
209 for i := first; i <= last; i++ {
210 b := l.done.Get(i)
211 if b {
212 continue
213 }
214 // The file is truncated and blank, so no need to load null chunks
215 if l.chunks[i].ID == l.nullChunk.ID {
216 continue
217 }
218 chunksNeeded = append(chunksNeeded, i)
219 }
220 l.mu.RUnlock()
221
222 // TODO: Load the chunks concurrently
223 for _, chunk := range chunksNeeded {
224 if err := l.loadChunk(chunk); err != nil {
225 return err
226 }
227 }
228 return nil
229 }
230
231 func (l *sparseFileLoader) loadChunk(i int) error {
232 c := l.chunks[i]
233
234 // Serialize loads of the same chunk so concurrent reads don't fetch it
235 // twice or race on the write to the sparse file. Different chunks still
236 // load in parallel.
237 c.mu.Lock()
238 defer c.mu.Unlock()
239
240 // Already loaded by an earlier successful call? The done bitmap is the
241 // authoritative record of what has actually been written to the sparse
242 // file. A failed load never sets it, so this stays false and the load
243 // is retried until it succeeds.
244 l.mu.RLock()
245 loaded := l.done.Get(i)
246 l.mu.RUnlock()
247 if loaded {
248 return nil
249 }
250
251 chunk, err := l.s.GetChunk(c.ID)
252 if err != nil {
253 return err
254 }
255 b, err := chunk.Data()
256 if err != nil {
257 return err
258 }
259
260 f, err := os.OpenFile(l.name, os.O_RDWR, 0666)
261 if err != nil {
262 return err
263 }
264 defer f.Close()
265
266 if _, err := f.WriteAt(b, int64(c.Start)); err != nil {
267 return err
268 }
269
270 l.mu.Lock()
271 l.done.Set(i, true)
272 l.mu.Unlock()
273 return nil
274 }
275
276 // writeState saves the current internal state about which chunks have
277 // been loaded. It's a bitmap of the
278 // same length as the index, with 0 = chunk has not been loaded and
279 // 1 = chunk has been loaded.
280 func (l *sparseFileLoader) writeState(w io.Writer) error {
281 l.mu.Lock()
282 defer l.mu.Unlock()
283
284 _, err := w.Write(l.done.Data(false))
285 return err
286 }
287
288 // loadState reads the "done" state from a reader. It's expected to be
289 // a list of '0' and '1' bytes where 0 means the chunk hasn't been
290 // written to the sparse file yet.
291 func (l *sparseFileLoader) loadState(r io.Reader) error {
292 done, err := l.stateFromReader(r)
293 if err != nil {
294 return err
295 }
296 l.mu.Lock()
297 defer l.mu.Unlock()
298
299 l.done = done
300 return nil
301 }
302
303 // Starts n goroutines to pre-load chunks that were marked as "done" in a state
304 // file.
305 func (l *sparseFileLoader) preloadChunksFromState(r io.Reader, n int) error {
306 state, err := l.stateFromReader(r)
307 if err != nil {
308 return err
309 }
310
311 // Start the workers for parallel pre-loading
312 ch := make(chan int)
313 for range n {
314 go func() {
315 for chunkIdx := range ch {
316 _ = l.loadChunk(chunkIdx)
317 }
318 }()
319 }
320
321 // Start the feeder. Iterate over the chunks and see if any of them
322 // are marked done in the state. If so, load those chunks.
323 go func() {
324 for chunkIdx := range l.chunks {
325 if state.Get(chunkIdx) {
326 ch <- chunkIdx
327 }
328 }
329 close(ch)
330 }()
331 return nil
332 }
333
334 func (l *sparseFileLoader) stateFromReader(r io.Reader) (bitmap.Bitmap, error) {
335 b, err := io.ReadAll(r)
336 if err != nil {
337 return nil, err
338 }
339
340 // Very basic check that the state file really is for the sparse
341 // file and not something else.
342 chunks := len(l.chunks)
343 if (chunks%8 == 0 && len(b) != chunks/8) || (chunks%8 != 0 && len(b) != 1+chunks/8) {
344 return nil, errors.New("sparse state file does not match the index")
345 }
346 return b, nil
347 }