forked from talent-plan/tinykv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snap.go
804 lines (744 loc) · 18.7 KB
/
snap.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
package snap
import (
"fmt"
"hash"
"hash/crc32"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
"github.com/Connor1996/badger"
"github.com/Connor1996/badger/table"
"github.com/pingcap-incubator/tinykv/kv/util"
"github.com/pingcap-incubator/tinykv/kv/util/engine_util"
"github.com/pingcap-incubator/tinykv/log"
"github.com/pingcap-incubator/tinykv/proto/pkg/eraftpb"
"github.com/pingcap-incubator/tinykv/proto/pkg/metapb"
rspb "github.com/pingcap-incubator/tinykv/proto/pkg/raft_serverpb"
"github.com/pingcap/errors"
)
type SnapStateType int
const (
SnapState_Relax SnapStateType = 0 + iota
SnapState_Generating
SnapState_Applying
)
type SnapState struct {
StateType SnapStateType
Receiver chan *eraftpb.Snapshot
}
const (
snapGenPrefix = "gen" // Name prefix for the self-generated snapshot file.
snapRevPrefix = "rev" // Name prefix for the received snapshot file.
sstFileSuffix = ".sst"
tmpFileSuffix = ".tmp"
cloneFileSuffix = ".clone"
metaFileSuffix = ".meta"
deleteRetryMaxTime = 6
deleteRetryDuration = 500 * time.Millisecond
)
type ApplySnapAbortError string
func (e ApplySnapAbortError) Error() string {
return string(e)
}
var (
errAbort = ApplySnapAbortError("abort")
)
type SnapKeyWithSending struct {
SnapKey SnapKey
IsSending bool
}
type SnapKey struct {
RegionID uint64
Term uint64
Index uint64
}
func (k SnapKey) String() string {
return fmt.Sprintf("%d_%d_%d", k.RegionID, k.Term, k.Index)
}
func SnapKeyFromRegionSnap(regionID uint64, snap *eraftpb.Snapshot) SnapKey {
return SnapKey{
RegionID: regionID,
Term: snap.Metadata.Term,
Index: snap.Metadata.Index,
}
}
func SnapKeyFromSnap(snap *eraftpb.Snapshot) (SnapKey, error) {
data := new(rspb.RaftSnapshotData)
err := data.Unmarshal(snap.Data)
if err != nil {
return SnapKey{}, err
}
return SnapKeyFromRegionSnap(data.Region.Id, snap), nil
}
type SnapStatistics struct {
Size uint64
KVCount int
}
type ApplyOptions struct {
DB *badger.DB
Region *metapb.Region
}
func NewApplyOptions(db *badger.DB, region *metapb.Region) *ApplyOptions {
return &ApplyOptions{
DB: db,
Region: region,
}
}
// `Snapshot` is an interface for snapshot.
// It's used in these scenarios:
// 1. build local snapshot
// 2. read local snapshot and then replicate it to remote raftstores
// 3. receive snapshot from remote raftstore and write it to local storage
// 4. apply snapshot
// 5. snapshot gc
type Snapshot interface {
io.Reader
io.Writer
Build(dbSnap *badger.Txn, region *metapb.Region, snapData *rspb.RaftSnapshotData, stat *SnapStatistics, deleter SnapshotDeleter) error
Path() string
Exists() bool
Delete()
Meta() (os.FileInfo, error)
TotalSize() uint64
Save() error
Apply(option ApplyOptions) error
}
// `SnapshotDeleter` is a trait for deleting snapshot.
// It's used to ensure that the snapshot deletion happens under the protection of locking
// to avoid race case for concurrent read/write.
type SnapshotDeleter interface {
// DeleteSnapshot returns true if it successfully delete the specified snapshot.
DeleteSnapshot(key SnapKey, snapshot Snapshot, checkEntry bool) bool
}
func retryDeleteSnapshot(deleter SnapshotDeleter, key SnapKey, snap Snapshot) bool {
for i := 0; i < deleteRetryMaxTime; i++ {
if deleter.DeleteSnapshot(key, snap, true) {
return true
}
time.Sleep(deleteRetryDuration)
}
return false
}
func genSnapshotMeta(cfFiles []*CFFile) (*rspb.SnapshotMeta, error) {
cfMetas := make([]*rspb.SnapshotCFFile, 0, len(engine_util.CFs))
for _, cfFile := range cfFiles {
var found bool
for _, snapCF := range engine_util.CFs {
if snapCF == cfFile.CF {
found = true
break
}
}
if !found {
return nil, errors.Errorf("failed to encode invalid snapshot CF %s", cfFile.CF)
}
cfMeta := &rspb.SnapshotCFFile{
Cf: cfFile.CF,
Size_: cfFile.Size,
Checksum: cfFile.Checksum,
}
cfMetas = append(cfMetas, cfMeta)
}
return &rspb.SnapshotMeta{
CfFiles: cfMetas,
}, nil
}
func checkFileSize(path string, expectedSize uint64) error {
size, err := util.GetFileSize(path)
if err != nil {
return err
}
if size != expectedSize {
return errors.Errorf("invalid size %d for snapshot cf file %s, expected %d", size, path, expectedSize)
}
return nil
}
func checkFileChecksum(path string, expectedChecksum uint32) error {
checksum, err := util.CalcCRC32(path)
if err != nil {
return err
}
if checksum != expectedChecksum {
return errors.Errorf("invalid checksum %d for snapshot cf file %s, expected %d",
checksum, path, expectedChecksum)
}
return nil
}
func checkFileSizeAndChecksum(path string, expectedSize uint64, expectedChecksum uint32) error {
err := checkFileSize(path, expectedSize)
if err == nil {
err = checkFileChecksum(path, expectedChecksum)
}
return err
}
type CFFile struct {
CF string
Path string
TmpPath string
SstWriter *table.Builder
File *os.File
KVCount int
Size uint64
WrittenSize uint64
Checksum uint32
WriteDigest hash.Hash32
}
type MetaFile struct {
Meta *rspb.SnapshotMeta
Path string
File *os.File
// for writing snapshot
TmpPath string
}
var _ Snapshot = new(Snap)
type Snap struct {
key SnapKey
displayPath string
CFFiles []*CFFile
cfIndex int
MetaFile *MetaFile
SizeTrack *int64
holdTmpFiles bool
}
func NewSnap(dir string, key SnapKey, sizeTrack *int64, isSending, toBuild bool,
deleter SnapshotDeleter) (*Snap, error) {
if !util.DirExists(dir) {
err := os.MkdirAll(dir, 0700)
if err != nil {
return nil, errors.WithStack(err)
}
}
var snapPrefix string
if isSending {
snapPrefix = snapGenPrefix
} else {
snapPrefix = snapRevPrefix
}
prefix := fmt.Sprintf("%s_%s", snapPrefix, key)
displayPath := getDisplayPath(dir, prefix)
cfFiles := make([]*CFFile, 0, len(engine_util.CFs))
for _, cf := range engine_util.CFs {
fileName := fmt.Sprintf("%s_%s%s", prefix, cf, sstFileSuffix)
path := filepath.Join(dir, fileName)
tmpPath := path + tmpFileSuffix
cfFile := &CFFile{
CF: cf,
Path: path,
TmpPath: tmpPath,
}
cfFiles = append(cfFiles, cfFile)
}
metaFileName := fmt.Sprintf("%s%s", prefix, metaFileSuffix)
metaFilePath := filepath.Join(dir, metaFileName)
metaTmpPath := metaFilePath + tmpFileSuffix
metaFile := &MetaFile{
Path: metaFilePath,
TmpPath: metaTmpPath,
}
s := &Snap{
key: key,
displayPath: displayPath,
CFFiles: cfFiles,
MetaFile: metaFile,
SizeTrack: sizeTrack,
}
// load snapshot meta if meta file exists.
if util.FileExists(metaFile.Path) {
err := s.loadSnapMeta()
if err != nil {
if !toBuild {
return nil, err
}
log.Warnf("failed to load existent snapshot meta when try to build %s: %v", s.Path(), err)
if !retryDeleteSnapshot(deleter, key, s) {
log.Warnf("failed to delete snapshot %s because it's already registered elsewhere", s.Path())
return nil, err
}
}
}
return s, nil
}
func NewSnapForBuilding(dir string, key SnapKey, sizeTrack *int64, deleter SnapshotDeleter) (*Snap, error) {
s, err := NewSnap(dir, key, sizeTrack, true, true, deleter)
if err != nil {
return nil, err
}
err = s.initForBuilding()
if err != nil {
return nil, err
}
return s, nil
}
func NewSnapForSending(dir string, key SnapKey, sizeTrack *int64, deleter SnapshotDeleter) (*Snap, error) {
s, err := NewSnap(dir, key, sizeTrack, true, false, deleter)
if err != nil {
return nil, err
}
if !s.Exists() {
// Skip the initialization below if it doesn't exists.
return s, nil
}
for _, cfFile := range s.CFFiles {
// initialize cf file size and reader
if cfFile.Size > 0 {
cfFile.File, err = os.Open(cfFile.Path)
if err != nil {
return nil, errors.WithStack(err)
}
}
}
return s, nil
}
func NewSnapForReceiving(dir string, key SnapKey, snapshotMeta *rspb.SnapshotMeta,
sizeTrack *int64, deleter SnapshotDeleter) (*Snap, error) {
s, err := NewSnap(dir, key, sizeTrack, false, false, deleter)
if err != nil {
return nil, err
}
err = s.setSnapshotMeta(snapshotMeta)
if err != nil {
return nil, err
}
if s.Exists() {
return s, nil
}
f, err := os.OpenFile(s.MetaFile.TmpPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return nil, err
}
s.MetaFile.File = f
s.holdTmpFiles = true
for _, cfFile := range s.CFFiles {
if cfFile.Size == 0 {
continue
}
f, err = os.OpenFile(cfFile.TmpPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return nil, err
}
cfFile.File = f
cfFile.WriteDigest = crc32.NewIEEE()
}
return s, nil
}
func NewSnapForApplying(dir string, key SnapKey, sizeTrack *int64, deleter SnapshotDeleter) (*Snap, error) {
return NewSnap(dir, key, sizeTrack, false, false, deleter)
}
func (s *Snap) initForBuilding() error {
if s.Exists() {
return nil
}
file, err := os.OpenFile(s.MetaFile.TmpPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
s.MetaFile.File = file
s.holdTmpFiles = true
for _, cfFile := range s.CFFiles {
file, err = os.OpenFile(cfFile.TmpPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
cfFile.SstWriter = table.NewExternalTableBuilder(file, nil, badger.DefaultOptions.TableBuilderOptions)
}
return nil
}
func (s *Snap) readSnapshotMeta() (*rspb.SnapshotMeta, error) {
fi, err := os.Stat(s.MetaFile.Path)
if err != nil {
return nil, errors.WithStack(err)
}
file, err := os.Open(s.MetaFile.Path)
if err != nil {
return nil, errors.WithStack(err)
}
size := fi.Size()
buf := make([]byte, size)
_, err = io.ReadFull(file, buf)
if err != nil {
return nil, errors.WithStack(err)
}
snapshotMeta := new(rspb.SnapshotMeta)
err = snapshotMeta.Unmarshal(buf)
if err != nil {
return nil, errors.WithStack(err)
}
return snapshotMeta, nil
}
func (s *Snap) setSnapshotMeta(snapshotMeta *rspb.SnapshotMeta) error {
if snapshotMeta == nil {
return errors.Errorf("invalid snapshot meta data")
}
if len(snapshotMeta.CfFiles) != len(s.CFFiles) {
return errors.Errorf("invalid CF number of snapshot meta, expect %d, got %d",
len(s.CFFiles), len(snapshotMeta.CfFiles))
}
for i, cfFile := range s.CFFiles {
meta := snapshotMeta.CfFiles[i]
if meta.Cf != cfFile.CF {
return errors.Errorf("invalid %d CF in snapshot meta, expect %s, got %s", i, cfFile.CF, meta.Cf)
}
if util.FileExists(cfFile.Path) {
// Check only the file size for `exists()` to work correctly.
err := checkFileSize(cfFile.Path, meta.GetSize_())
if err != nil {
return err
}
}
cfFile.Size = uint64(meta.GetSize_())
cfFile.Checksum = meta.GetChecksum()
}
s.MetaFile.Meta = snapshotMeta
return nil
}
func (s *Snap) loadSnapMeta() error {
snapshotMeta, err := s.readSnapshotMeta()
if err != nil {
return err
}
err = s.setSnapshotMeta(snapshotMeta)
if err != nil {
return err
}
// check if there is a data corruption when the meta file exists
// but cf files are deleted.
if !s.Exists() {
return errors.Errorf("snapshot %s is corrupted, some cf file is missing", s.Path())
}
return nil
}
func getDisplayPath(dir string, prefix string) string {
cfNames := "(" + strings.Join(engine_util.CFs[:], "|") + ")"
return fmt.Sprintf("%s/%s_%s%s", dir, prefix, cfNames, sstFileSuffix)
}
func (s *Snap) validate() error {
for _, cfFile := range s.CFFiles {
if cfFile.Size == 0 {
// Skip empty file. The checksum of this cf file should be 0 and
// this is checked when loading the snapshot meta.
continue
}
// TODO: prepare and validate for ingestion
}
return nil
}
func (s *Snap) saveCFFiles() error {
for _, cfFile := range s.CFFiles {
if cfFile.KVCount > 0 {
err := cfFile.SstWriter.Finish()
if err != nil {
return err
}
}
cfFile.SstWriter.Close()
size, err := util.GetFileSize(cfFile.TmpPath)
if err != nil {
return err
}
if size > 0 {
err = os.Rename(cfFile.TmpPath, cfFile.Path)
if err != nil {
return errors.WithStack(err)
}
cfFile.Size = size
// add size
atomic.AddInt64(s.SizeTrack, int64(size))
cfFile.Checksum, err = util.CalcCRC32(cfFile.Path)
if err != nil {
return err
}
} else {
// Clean up the `tmp_path` if this cf file is empty.
_, err = util.DeleteFileIfExists(cfFile.TmpPath)
if err != nil {
return err
}
}
}
return nil
}
func (s *Snap) saveMetaFile() error {
bin, err := s.MetaFile.Meta.Marshal()
if err != nil {
return errors.WithStack(err)
}
_, err = s.MetaFile.File.Write(bin)
if err != nil {
return errors.WithStack(err)
}
err = os.Rename(s.MetaFile.TmpPath, s.MetaFile.Path)
if err != nil {
return errors.WithStack(err)
}
s.holdTmpFiles = false
return nil
}
func (s *Snap) Build(dbSnap *badger.Txn, region *metapb.Region, snapData *rspb.RaftSnapshotData, stat *SnapStatistics, deleter SnapshotDeleter) error {
if s.Exists() {
err := s.validate()
if err == nil {
// set snapshot meta data
snapData.FileSize = s.TotalSize()
snapData.Meta = s.MetaFile.Meta
return nil
}
log.Errorf("[region %d] file %s is corrupted, will rebuild: %v", region.Id, s.Path(), err)
if !retryDeleteSnapshot(deleter, s.key, s) {
log.Errorf("[region %d] failed to delete corrupted snapshot %s because it's already registered elsewhere",
region.Id, s.Path())
return err
}
err = s.initForBuilding()
if err != nil {
return err
}
}
builder := newSnapBuilder(s.CFFiles, dbSnap, region)
err := builder.build()
if err != nil {
return err
}
err = s.saveCFFiles()
if err != nil {
return err
}
stat.KVCount = builder.kvCount
snapshotMeta, err := genSnapshotMeta(s.CFFiles)
if err != nil {
return err
}
s.MetaFile.Meta = snapshotMeta
err = s.saveMetaFile()
if err != nil {
return err
}
totalSize := s.TotalSize()
stat.Size = totalSize
// set snapshot meta data
snapData.FileSize = totalSize
snapData.Meta = s.MetaFile.Meta
return nil
}
func (s *Snap) Path() string {
return s.displayPath
}
func (s *Snap) Exists() bool {
for _, cfFile := range s.CFFiles {
if cfFile.Size > 0 && !util.FileExists(cfFile.Path) {
return false
}
}
return util.FileExists(s.MetaFile.Path)
}
func (s *Snap) Delete() {
log.Debugf("deleting %s", s.Path())
for _, cfFile := range s.CFFiles {
if s.holdTmpFiles {
_, err := util.DeleteFileIfExists(cfFile.TmpPath)
if err != nil {
panic(err)
}
}
deleted, err := util.DeleteFileIfExists(cfFile.Path)
if err != nil {
panic(err)
}
if deleted {
atomic.AddInt64(s.SizeTrack, -int64(cfFile.Size))
}
}
_, err := util.DeleteFileIfExists(s.MetaFile.Path)
if err != nil {
panic(err)
}
if s.holdTmpFiles {
_, err := util.DeleteFileIfExists(s.MetaFile.TmpPath)
if err != nil {
panic(err)
}
}
}
func (s *Snap) Meta() (os.FileInfo, error) {
fi, err := os.Stat(s.MetaFile.Path)
if err != nil {
return nil, errors.WithStack(err)
}
return fi, nil
}
func (s *Snap) TotalSize() (total uint64) {
for _, cf := range s.CFFiles {
total += cf.Size
}
return
}
func (s *Snap) Save() error {
for _, cfFile := range s.CFFiles {
if cfFile.Size == 0 {
// skip empty cf file.
continue
}
// Check each cf file has been fully written, and the checksum matches.
if cfFile.WrittenSize != cfFile.Size {
return errors.Errorf("snapshot file %s for CF %s size mismatch, real size %d, expected %d",
cfFile.Path, cfFile.CF, cfFile.WrittenSize, cfFile.Size)
}
checksum := cfFile.WriteDigest.Sum32()
if cfFile.Checksum != checksum {
return errors.Errorf("snapshot file %s for CF %s checksum mismatch, real checksum %d, expected %d",
cfFile.Path, cfFile.CF, checksum, cfFile.Checksum)
}
err := os.Rename(cfFile.TmpPath, cfFile.Path)
if err != nil {
return errors.WithStack(err)
}
atomic.AddInt64(s.SizeTrack, int64(cfFile.Size))
}
// write meta file
bin, err := s.MetaFile.Meta.Marshal()
if err != nil {
return errors.WithStack(err)
}
_, err = s.MetaFile.File.Write(bin)
if err != nil {
return errors.WithStack(err)
}
err = s.MetaFile.File.Sync()
if err != nil {
return errors.WithStack(err)
}
err = os.Rename(s.MetaFile.TmpPath, s.MetaFile.Path)
if err != nil {
return errors.WithStack(err)
}
s.holdTmpFiles = false
return nil
}
func (s *Snap) Apply(opts ApplyOptions) error {
err := s.validate()
if err != nil {
return err
}
externalFiles := make([]*os.File, 0, len(s.CFFiles))
for _, cfFile := range s.CFFiles {
if cfFile.Size == 0 {
// Skip empty cf file
continue
}
file, err := os.Open(cfFile.Path)
if err != nil {
log.Errorf("open ingest file %s failed: %s", cfFile.Path, err)
return err
}
// Make a copy of the snapshot files as they are hardlinked into badger
input, err := ioutil.ReadFile(cfFile.Path)
if err != nil {
panic(err)
}
dir, name := filepath.Split(cfFile.Path)
err = ioutil.WriteFile(filepath.Join(dir, "bak-"+name), input, 0644)
if err != nil {
panic(err)
}
file.Close()
dest, err := os.Open(filepath.Join(dir, "bak-"+name))
if err != nil {
panic(err)
}
externalFiles = append(externalFiles, dest)
}
n, err := opts.DB.IngestExternalFiles(externalFiles)
for _, file := range externalFiles {
file.Close()
}
if err != nil {
log.Errorf("ingest sst failed (first %d files succeeded): %s", n, err)
return err
}
log.Infof("apply snapshot ingested %d tables", n)
return nil
}
func (s *Snap) Read(b []byte) (int, error) {
if len(b) == 0 {
return 0, nil
}
for s.cfIndex < len(s.CFFiles) {
cfFile := s.CFFiles[s.cfIndex]
if cfFile.Size == 0 {
s.cfIndex++
continue
}
n, err := cfFile.File.Read(b)
if n > 0 {
return n, nil
}
if err != nil {
if err == io.EOF {
s.cfIndex++
continue
}
return 0, errors.WithStack(err)
}
}
return 0, io.EOF
}
func (s *Snap) Write(b []byte) (int, error) {
if len(b) == 0 {
return 0, nil
}
nextBuf := b
for s.cfIndex < len(s.CFFiles) {
cfFile := s.CFFiles[s.cfIndex]
if cfFile.Size == 0 {
s.cfIndex++
continue
}
left := cfFile.Size - cfFile.WrittenSize
if left == 0 {
s.cfIndex++
continue
}
file := cfFile.File
digest := cfFile.WriteDigest
if len(nextBuf) > int(left) {
_, err := file.Write(nextBuf[:left])
if err != nil {
return 0, errors.WithStack(err)
}
digest.Write(nextBuf[:left])
cfFile.WrittenSize += left
s.cfIndex++
nextBuf = nextBuf[left:]
} else {
_, err := file.Write(nextBuf)
if err != nil {
return 0, errors.WithStack(err)
}
digest.Write(nextBuf)
cfFile.WrittenSize += uint64(len(nextBuf))
return len(b), nil
}
}
return len(b) - len(nextBuf), nil
}
func (s *Snap) Drop() {
var cfTmpFileExists bool
for _, cfFile := range s.CFFiles {
// cleanup if some of the cf files and meta file is partly written
if util.FileExists(cfFile.TmpPath) {
cfTmpFileExists = true
break
}
}
if cfTmpFileExists || util.FileExists(s.MetaFile.TmpPath) {
s.Delete()
return
}
// cleanup if data corruption happens and any file goes missing
if !s.Exists() {
s.Delete()
}
}