-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.go
456 lines (356 loc) · 9.01 KB
/
index.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package bltfs
import (
"bytes"
"context"
"encoding/xml"
"fmt"
"io"
"path/filepath"
"sort"
"time"
"github.com/boltdb/bolt"
pb "github.com/golang/protobuf/proto"
"github.com/google/uuid"
"github.com/pkg/errors"
"hpt.space/bltfs/ltfs"
"hpt.space/bltfs/proto"
"hpt.space/bltfs/util/xmlutil"
)
// Index is the binary index computed from the LTFS index.
type index struct {
db *bolt.DB
blkSize uint64
extents extents
root *proto.Entry
nextUID int
meta struct {
uuid uuid.UUID
gen int
prevgen int
}
}
func NewIndex(idx *ltfs.Index, db *bolt.DB) (*index, error) {
binIdx := &index{
db: db,
}
type wrap struct {
path string
buf []byte
}
var ws []*wrap
collector := make(chan *wrap)
done := make(chan struct{})
go func() {
for w := range collector {
ws = append(ws, w)
}
close(done)
}()
var tmp proto.Entry
// get the protobuf representation of the ltfs.Directory
if err := proto.MarshalDirectory(idx.Root, &tmp); err != nil {
panic(err)
}
// marshal to bytes
buf, err := pb.Marshal(&tmp)
if err != nil {
panic(err)
}
collector <- &wrap{"/", buf}
for _, f := range idx.Root.Contents.Files {
// get the protobuf representation of the ltfs.Directory
if err := proto.MarshalFile(f, &tmp); err != nil {
panic(err)
}
// marshal to bytes
buf, err := pb.Marshal(&tmp)
if err != nil {
panic(err)
}
collector <- &wrap{filepath.Join("/", f.Name), buf}
}
// the visit function is called concurrently, so we take care not to fuck
// this up.
begin := time.Now()
idx.Root.VisitAllEntries(func(d *ltfs.Directory, subtree string) {
var pbentry proto.Entry
// get the protobuf representation of the ltfs.Directory
if err := proto.MarshalDirectory(d, &pbentry); err != nil {
panic(err)
}
// compose path name (insert root, add subtree, the directory we are in and
// then directory we're inserting)
path := filepath.Join("/", subtree, d.Name)
path = path + "/"
// marshal to bytes
buf, err := pb.Marshal(&pbentry)
if err != nil {
panic(err)
}
collector <- &wrap{path, buf}
for _, file := range d.Contents.Files {
var pbentry proto.Entry
// get the protobuf representation of the ltfs.File
if err := proto.MarshalFile(file, &pbentry); err != nil {
panic(err)
}
// compose path name (insert root, add subtree and then file name)
path := filepath.Join("/", subtree, d.Name, file.Name)
// marshal to bytes
buf, err := pb.Marshal(&pbentry)
if err != nil {
panic(err)
}
collector <- &wrap{path, buf}
}
})
close(collector)
<-done
fmt.Printf("building protobufs from parsed LTFS index took: %v\n", time.Since(begin))
fmt.Printf("number of entries: %d\n", len(ws))
// sort the index entries according to the filepath
begin = time.Now()
sort.Slice(ws, func(i, j int) bool {
return ws[i].path < ws[j].path
})
fmt.Printf("sorting entries took: %v\n", time.Since(begin))
// insert into database
begin = time.Now()
err = db.Update(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte("index"))
if bkt == nil {
return errors.New("index bucket not found")
}
// We set the fill percentage to 100%. This ensures that Bolt doesn't split
// pages before the page is full. This is good when we only expect
// read-only on this index.
bkt.FillPercent = 1
// insert
for _, w := range ws {
if err := bkt.Put([]byte(w.path), w.buf); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
fmt.Printf("inserting to BoltDB took: %v\n", time.Since(begin))
return binIdx, nil
}
func (idx *index) MakeLTFSIndex() (*ltfs.Index, error) {
tree, err := idx.root.MakeTree()
if err != nil {
return nil, err
}
ltfsIndex := ltfs.Index{
XMLName: xml.Name{Space: "", Local: "ltfsindex"},
IndexPreface: ltfs.IndexPreface{
Version: ltfs.Version,
Creator: ltfs.Creator,
VolumeUUID: idx.meta.uuid,
Generation: idx.meta.gen,
UpdateTime: xmlutil.TimeNow(),
Partition: "a", // TODO(kbj): DO NOT HARD CODE THIS
StartBlock: 6,
PreviousGeneration: ltfs.PreviousGeneration{
Partition: "b",
StartBlock: 20,
},
HighestFileUID: 4,
},
Root: tree,
}
return <fsIndex, nil
}
// Insert inserts a *pb.Entry into the binary index.
func (idx *index) Insert(path string, entry *proto.Entry) error {
buf, err := pb.Marshal(entry)
if err != nil {
return errors.Wrap(err, "failed to marshal entry")
}
return idx.db.Update(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte("index"))
if bkt == nil {
return errors.New("index bucket not found")
}
if err := bkt.Put([]byte(path), buf); err != nil {
return errors.Wrap(err, "failed to insert entry")
}
return nil
})
}
// Stat returns the entry at path.
func (idx *index) stat(path string) (*proto.Entry, error) {
var entry proto.Entry
err := idx.db.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte("index"))
if bkt == nil {
return errors.New("index bucket not found")
}
if v := bkt.Get([]byte(path)); v != nil {
if err := pb.Unmarshal(v, &entry); err != nil {
return errors.Wrap(err, "failed to unmarshal entry")
}
}
return errors.New("path not found")
})
if err != nil {
return nil, err
}
return &entry, nil
}
func (idx *index) Marshal() (*proto.Entry, error) {
// TODO(kbj): this function is a bit hairy.
type chainT struct {
path []byte
dir *proto.Directory
prev *chainT
}
base := &proto.Directory{
Entries: make([]*proto.Entry, 0),
}
path := []byte("/")
chain := &chainT{
path: path,
dir: base,
}
err := idx.db.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte("index"))
if bkt == nil {
return errors.New("index bucket not found")
}
// iterate over all pairs in the bucket (in-order)
err := bkt.ForEach(func(k, v []byte) error {
var entry proto.Entry
if err := pb.Unmarshal(v, &entry); err != nil {
return errors.Wrap(err, "failed to unmarshal buffer")
}
// if we see a new prefix, move back up the chain
for !bytes.HasPrefix(k, chain.path) {
chain = chain.prev
}
if chain.dir.Entries == nil {
// initialize the entries
chain.dir.Entries = make([]*proto.Entry, 0)
}
// if the entry is a directory, add it to the chain
switch x := entry.Elem.(type) {
case *proto.Entry_Dir:
// add the directory entry before updating the chain
chain.dir.Entries = append(chain.dir.Entries, &entry)
// update the path chain
new := &chainT{
path: k,
dir: x.Dir,
prev: chain,
}
chain = new
case *proto.Entry_File:
chain.dir.Entries = append(chain.dir.Entries, &entry)
}
return nil
})
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return base.Entries[0], nil
}
func (idx *index) Scan(path string) ([]*proto.Entry, error) {
return idx.scan(path, true)
}
func (idx *index) List(path string) ([]*proto.Entry, error) {
return idx.scan(path, false)
}
func (idx *index) scan(path string, resursive bool) ([]*proto.Entry, error) {
var entries []*proto.Entry
err := idx.db.View(func(tx *bolt.Tx) error {
bkt := tx.Bucket([]byte("index"))
if bkt == nil {
return errors.New("index bucket not found")
}
c := bkt.Cursor()
prefix := []byte(path)
for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
if !resursive {
k = k[len(prefix):]
if bytes.IndexByte(k, '/') != -1 {
continue
}
}
var entry proto.Entry
// unmarshal the entry
if err := pb.Unmarshal(v, &entry); err != nil {
return errors.Wrap(err, "failed to unmarshal entry")
}
entries = append(entries, &entry)
}
return nil
})
if err != nil {
return nil, err
}
return entries, nil
}
type extentList []*proto.Extent
func (es extentList) last() *proto.Extent {
return es[len(es)-1]
}
type extents map[uint64]extentList
func (e extents) last(f *File) *proto.Extent {
if es, ok := e[f.id]; ok {
return es.last()
}
return nil
}
func (idx *index) addExtent(f *File, e *proto.Extent) {
prev := idx.extents.last(f)
if prev.Block+prev.Length/idx.blkSize == e.Block {
}
}
type indexWriter struct {
idx *index
rw io.ReadWriter
}
func (idx *index) newIndexWriter() *indexWriter {
return &indexWriter{
idx: idx,
}
}
func (w *indexWriter) start(ctx context.Context, pol *RecoveryPolicy) {
go func() {
for {
select {
case <-time.After(pol.FullIndexInterval):
}
}
}()
}
// ReadLTFSIndex reads the LTFS index from the device and returns a ltfs.Index
// representation.
func (b *Store) ReadLTFSIndex() (*ltfs.Index, error) {
// seek to EOD
if err := b.mu.backend.Locate(0, TapeBlockMax); err != nil {
return nil, errors.Wrap(err, "failed to seek to EOD")
}
// space backwards to find the LTFS index
if err := b.mu.backend.SpaceFMB(2); err != nil {
return nil, errors.Wrap(err, "failed to space backward")
}
buf, err := b.ReadFile()
if err != nil {
return nil, errors.Wrap(err, "failed to read file")
}
var idx ltfs.Index
// unmarshal the LTFS index
if err := xml.Unmarshal(buf, &idx); err != nil {
return nil, err
}
return &idx, nil
}