-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathfiles.go
1432 lines (1254 loc) · 45 KB
/
files.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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package fs
import (
"bufio"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/m3db/m3/src/dbnode/digest"
"github.com/m3db/m3/src/dbnode/generated/proto/index"
"github.com/m3db/m3/src/dbnode/persist"
"github.com/m3db/m3/src/dbnode/persist/fs/msgpack"
"github.com/m3db/m3/src/dbnode/persist/schema"
idxpersist "github.com/m3db/m3/src/m3ninx/persist"
xclose "github.com/m3db/m3x/close"
xerrors "github.com/m3db/m3x/errors"
"github.com/m3db/m3x/ident"
"github.com/m3db/m3x/instrument"
"github.com/pborman/uuid"
)
var timeZero time.Time
const (
dataDirName = "data"
indexDirName = "index"
snapshotDirName = "snapshots"
commitLogsDirName = "commitlogs"
commitLogComponentPosition = 2
indexFileSetComponentPosition = 2
numComponentsSnapshotMetadataFile = 4
numComponentsSnapshotMetadataCheckpointFile = 5
snapshotMetadataUUIDComponentPosition = 1
snapshotMetadataIndexComponentPosition = 2
)
var (
defaultBufioReaderSize = bufio.NewReader(nil).Size()
)
type fileOpener func(filePath string) (*os.File, error)
// FileSetFile represents a set of FileSet files for a given block start
type FileSetFile struct {
ID FileSetFileIdentifier
AbsoluteFilepaths []string
CachedSnapshotTime time.Time
CachedSnapshotID []byte
filePathPrefix string
}
// SnapshotTimeAndID returns the snapshot time and id for the given FileSetFile.
// Value is meaningless if the the FileSetFile is a flush instead of a snapshot.
func (f *FileSetFile) SnapshotTimeAndID() (time.Time, []byte, error) {
if !f.CachedSnapshotTime.IsZero() || f.CachedSnapshotID != nil {
// Return immediately if we've already cached it.
return f.CachedSnapshotTime, f.CachedSnapshotID, nil
}
snapshotTime, snapshotID, err := SnapshotTimeAndID(f.filePathPrefix, f.ID)
if err != nil {
return time.Time{}, nil, err
}
// Cache for future use and return.
f.CachedSnapshotTime = snapshotTime
f.CachedSnapshotID = snapshotID
return f.CachedSnapshotTime, f.CachedSnapshotID, nil
}
// IsZero returns whether the FileSetFile is a zero value.
func (f FileSetFile) IsZero() bool {
return len(f.AbsoluteFilepaths) == 0
}
// HasCheckpointFile returns a bool indicating whether the given set of
// fileset files has a checkpoint file.
func (f FileSetFile) HasCheckpointFile() bool {
for _, fileName := range f.AbsoluteFilepaths {
if strings.Contains(fileName, checkpointFileSuffix) {
return true
}
}
return false
}
// FileSetFilesSlice is a slice of FileSetFile
type FileSetFilesSlice []FileSetFile
// Filepaths flattens a slice of FileSetFiles to a single slice of filepaths.
// All paths returned are absolute.
func (f FileSetFilesSlice) Filepaths() []string {
flattened := []string{}
for _, fileset := range f {
flattened = append(flattened, fileset.AbsoluteFilepaths...)
}
return flattened
}
// LatestVolumeForBlock returns the latest (highest index) FileSetFile in the
// slice for a given block start, only applicable for index and snapshot file set files.
func (f FileSetFilesSlice) LatestVolumeForBlock(blockStart time.Time) (FileSetFile, bool) {
// Make sure we're already sorted
f.sortByTimeAndVolumeIndexAscending()
for i, curr := range f {
if curr.ID.BlockStart.Equal(blockStart) {
var (
bestSoFar FileSetFile
bestSoFarExists bool
)
for j := i; j < len(f); j++ {
curr = f[j]
if !curr.ID.BlockStart.Equal(blockStart) {
break
}
if curr.HasCheckpointFile() && curr.ID.VolumeIndex >= bestSoFar.ID.VolumeIndex {
bestSoFar = curr
bestSoFarExists = true
}
}
return bestSoFar, bestSoFarExists
}
}
return FileSetFile{}, false
}
// ignores the index in the FileSetFileIdentifier because fileset files should
// always have index 0.
func (f FileSetFilesSlice) sortByTimeAscending() {
sort.Slice(f, func(i, j int) bool {
return f[i].ID.BlockStart.Before(f[j].ID.BlockStart)
})
}
func (f FileSetFilesSlice) sortByTimeAndVolumeIndexAscending() {
sort.Slice(f, func(i, j int) bool {
if f[i].ID.BlockStart.Equal(f[j].ID.BlockStart) {
return f[i].ID.VolumeIndex < f[j].ID.VolumeIndex
}
return f[i].ID.BlockStart.Before(f[j].ID.BlockStart)
})
}
// SnapshotMetadata represents a SnapshotMetadata file, along with its checkpoint file,
// as well as all the information contained within the metadata file and paths to the
// physical files on disk.
type SnapshotMetadata struct {
ID SnapshotMetadataIdentifier
CommitlogIdentifier []byte
MetadataFilePath string
CheckpointFilePath string
}
// SnapshotMetadataErrorWithPaths contains an error that occurred while trying to
// read a snapshot metadata file, as well as paths for the metadata file path and
// the checkpoint file path so that they can be cleaned up. The checkpoint file may
// not exist if only the metadata file was written out (due to sudden node failure)
// or if the metadata file name was structured incorrectly (should never happen.)
type SnapshotMetadataErrorWithPaths struct {
Error error
MetadataFilePath string
CheckpointFilePath string
}
// SnapshotMetadataIdentifier is an identifier for a snapshot metadata file
type SnapshotMetadataIdentifier struct {
Index int64
UUID uuid.UUID
}
// NewFileSetFile creates a new FileSet file
func NewFileSetFile(id FileSetFileIdentifier, filePathPrefix string) FileSetFile {
return FileSetFile{
ID: id,
AbsoluteFilepaths: []string{},
filePathPrefix: filePathPrefix,
}
}
func openFiles(opener fileOpener, fds map[string]**os.File) error {
var firstErr error
for filePath, fdPtr := range fds {
fd, err := opener(filePath)
if err != nil {
firstErr = err
break
}
*fdPtr = fd
}
if firstErr == nil {
return nil
}
// If we have encountered an error when opening the files,
// close the ones that have been opened.
for _, fdPtr := range fds {
if *fdPtr != nil {
(*fdPtr).Close()
}
}
return firstErr
}
// TODO(xichen): move closeAll to m3x/close.
func closeAll(closers ...xclose.Closer) error {
multiErr := xerrors.NewMultiError()
for _, closer := range closers {
if err := closer.Close(); err != nil {
multiErr = multiErr.Add(err)
}
}
return multiErr.FinalError()
}
// DeleteFiles delete a set of files, returning all the errors encountered during
// the deletion process.
func DeleteFiles(filePaths []string) error {
multiErr := xerrors.NewMultiError()
for _, file := range filePaths {
if err := os.Remove(file); err != nil {
detailedErr := fmt.Errorf("failed to remove file %s: %v", file, err)
multiErr = multiErr.Add(detailedErr)
}
}
return multiErr.FinalError()
}
// DeleteDirectories delets a set of directories and its contents, returning all
// of the errors encountered during the deletion process.
func DeleteDirectories(dirPaths []string) error {
multiErr := xerrors.NewMultiError()
for _, dir := range dirPaths {
if err := os.RemoveAll(dir); err != nil {
detailedErr := fmt.Errorf("failed to remove dir %s: %v", dir, err)
multiErr = multiErr.Add(detailedErr)
}
}
return multiErr.FinalError()
}
// byTimeAscending sorts files by their block start times in ascending order.
// If the files do not have block start times in their names, the result is undefined.
type byTimeAscending []string
func (a byTimeAscending) Len() int { return len(a) }
func (a byTimeAscending) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTimeAscending) Less(i, j int) bool {
ti, _ := TimeFromFileName(a[i])
tj, _ := TimeFromFileName(a[j])
return ti.Before(tj)
}
// commitlogsByTimeAndIndexAscending sorts commitlogs by their block start times and index in ascending
// order. If the files do not have block start times or indexes in their names, the result is undefined.
type commitlogsByTimeAndIndexAscending []string
func (a commitlogsByTimeAndIndexAscending) Len() int { return len(a) }
func (a commitlogsByTimeAndIndexAscending) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a commitlogsByTimeAndIndexAscending) Less(i, j int) bool {
ti, ii, _ := TimeAndIndexFromCommitlogFilename(a[i])
tj, ij, _ := TimeAndIndexFromCommitlogFilename(a[j])
if ti.Before(tj) {
return true
}
return ti.Equal(tj) && ii < ij
}
// fileSetFilesByTimeAndIndexAscending sorts file sets files by their block start times and volume
// index in ascending order. If the files do not have block start times or indexes in their names,
// the result is undefined.
type fileSetFilesByTimeAndVolumeIndexAscending []string
func (a fileSetFilesByTimeAndVolumeIndexAscending) Len() int { return len(a) }
func (a fileSetFilesByTimeAndVolumeIndexAscending) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a fileSetFilesByTimeAndVolumeIndexAscending) Less(i, j int) bool {
ti, ii, _ := TimeAndVolumeIndexFromFileSetFilename(a[i])
tj, ij, _ := TimeAndVolumeIndexFromFileSetFilename(a[j])
if ti.Before(tj) {
return true
}
return ti.Equal(tj) && ii < ij
}
func componentsAndTimeFromFileName(fname string) ([]string, time.Time, error) {
components := strings.Split(filepath.Base(fname), separator)
if len(components) < 3 {
return nil, timeZero, fmt.Errorf("unexpected file name %s", fname)
}
str := strings.Replace(components[1], fileSuffix, "", 1)
nanoseconds, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return nil, timeZero, err
}
return components, time.Unix(0, nanoseconds), nil
}
// TimeFromFileName extracts the block start time from file name.
func TimeFromFileName(fname string) (time.Time, error) {
_, t, err := componentsAndTimeFromFileName(fname)
return t, err
}
// TimeAndIndexFromCommitlogFilename extracts the block start and index from file name for a commitlog.
func TimeAndIndexFromCommitlogFilename(fname string) (time.Time, int, error) {
return timeAndIndexFromFileName(fname, commitLogComponentPosition)
}
// TimeAndVolumeIndexFromFileSetFilename extracts the block start and volume index from file name.
func TimeAndVolumeIndexFromFileSetFilename(fname string) (time.Time, int, error) {
return timeAndIndexFromFileName(fname, indexFileSetComponentPosition)
}
func timeAndIndexFromFileName(fname string, componentPosition int) (time.Time, int, error) {
components, t, err := componentsAndTimeFromFileName(fname)
if err != nil {
return timeZero, 0, err
}
if componentPosition > len(components)-1 {
return timeZero, 0, fmt.Errorf("malformed filename: %s", fname)
}
str := strings.Replace(components[componentPosition], fileSuffix, "", 1)
index, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return timeZero, 0, err
}
return t, int(index), nil
}
// SnapshotTimeAndID returns the metadata for the snapshot.
func SnapshotTimeAndID(
filePathPrefix string, id FileSetFileIdentifier) (time.Time, []byte, error) {
decoder := msgpack.NewDecoder(nil)
return snapshotTimeAndID(filePathPrefix, id, decoder)
}
func snapshotTimeAndID(
filePathPrefix string,
id FileSetFileIdentifier,
decoder *msgpack.Decoder,
) (time.Time, []byte, error) {
infoBytes, err := readSnapshotInfoFile(filePathPrefix, id, defaultBufioReaderSize)
if err != nil {
return time.Time{}, nil, fmt.Errorf("error reading snapshot info file: %v", err)
}
decoder.Reset(msgpack.NewDecoderStream(infoBytes))
info, err := decoder.DecodeIndexInfo()
if err != nil {
return time.Time{}, nil, fmt.Errorf("error decoding snapshot info file: %v", err)
}
return time.Unix(0, info.SnapshotTime), info.SnapshotID, nil
}
func readSnapshotInfoFile(filePathPrefix string, id FileSetFileIdentifier, readerBufferSize int) ([]byte, error) {
var (
shardDir = ShardSnapshotsDirPath(filePathPrefix, id.Namespace, id.Shard)
checkpointFilePath = filesetPathFromTimeAndIndex(shardDir, id.BlockStart, id.VolumeIndex, checkpointFileSuffix)
digestFilePath = filesetPathFromTimeAndIndex(shardDir, id.BlockStart, id.VolumeIndex, digestFileSuffix)
infoFilePath = filesetPathFromTimeAndIndex(shardDir, id.BlockStart, id.VolumeIndex, infoFileSuffix)
)
checkpointFd, err := os.Open(checkpointFilePath)
if err != nil {
return nil, err
}
// Read digest of digests from the checkpoint file
digestBuf := digest.NewBuffer()
expectedDigestOfDigest, err := digestBuf.ReadDigestFromFile(checkpointFd)
closeErr := checkpointFd.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
// Read and validate the digest file
digestData, err := readAndValidate(
digestFilePath, readerBufferSize, expectedDigestOfDigest)
if err != nil {
return nil, err
}
// Read and validate the info file
expectedInfoDigest := digest.ToBuffer(digestData).ReadDigest()
return readAndValidate(
infoFilePath, readerBufferSize, expectedInfoDigest)
}
type forEachInfoFileSelector struct {
fileSetType persist.FileSetType
contentType persist.FileSetContentType
filePathPrefix string
namespace ident.ID
shard uint32 // shard only applicable for data content type
}
type infoFileFn func(fname string, id FileSetFileIdentifier, infoData []byte)
func forEachInfoFile(
args forEachInfoFileSelector,
readerBufferSize int,
fn infoFileFn,
) {
matched, err := filesetFiles(filesetFilesSelector{
fileSetType: args.fileSetType,
contentType: args.contentType,
filePathPrefix: args.filePathPrefix,
namespace: args.namespace,
shard: args.shard,
pattern: infoFilePattern,
})
if err != nil {
return
}
var dir string
switch args.fileSetType {
case persist.FileSetFlushType:
switch args.contentType {
case persist.FileSetDataContentType:
dir = ShardDataDirPath(args.filePathPrefix, args.namespace, args.shard)
case persist.FileSetIndexContentType:
dir = NamespaceIndexDataDirPath(args.filePathPrefix, args.namespace)
default:
return
}
case persist.FileSetSnapshotType:
switch args.contentType {
case persist.FileSetDataContentType:
dir = ShardSnapshotsDirPath(args.filePathPrefix, args.namespace, args.shard)
case persist.FileSetIndexContentType:
dir = NamespaceIndexSnapshotDirPath(args.filePathPrefix, args.namespace)
default:
return
}
default:
return
}
var indexDigests index.IndexDigests
digestBuf := digest.NewBuffer()
for i := range matched {
t := matched[i].ID.BlockStart
volume := matched[i].ID.VolumeIndex
var (
checkpointFilePath string
digestsFilePath string
infoFilePath string
)
switch args.fileSetType {
case persist.FileSetFlushType:
switch args.contentType {
case persist.FileSetDataContentType:
checkpointFilePath = filesetPathFromTime(dir, t, checkpointFileSuffix)
digestsFilePath = filesetPathFromTime(dir, t, digestFileSuffix)
infoFilePath = filesetPathFromTime(dir, t, infoFileSuffix)
case persist.FileSetIndexContentType:
checkpointFilePath = filesetPathFromTimeAndIndex(dir, t, volume, checkpointFileSuffix)
digestsFilePath = filesetPathFromTimeAndIndex(dir, t, volume, digestFileSuffix)
infoFilePath = filesetPathFromTimeAndIndex(dir, t, volume, infoFileSuffix)
}
case persist.FileSetSnapshotType:
checkpointFilePath = filesetPathFromTimeAndIndex(dir, t, volume, checkpointFileSuffix)
digestsFilePath = filesetPathFromTimeAndIndex(dir, t, volume, digestFileSuffix)
infoFilePath = filesetPathFromTimeAndIndex(dir, t, volume, infoFileSuffix)
}
checkpointExists, err := CompleteCheckpointFileExists(checkpointFilePath)
if err != nil {
continue
}
if !checkpointExists {
continue
}
checkpointFd, err := os.Open(checkpointFilePath)
if err != nil {
continue
}
// Read digest of digests from the checkpoint file
expectedDigestOfDigest, err := digestBuf.ReadDigestFromFile(checkpointFd)
checkpointFd.Close()
if err != nil {
continue
}
// Read and validate the digest file
digestData, err := readAndValidate(digestsFilePath, readerBufferSize,
expectedDigestOfDigest)
if err != nil {
continue
}
// Read and validate the info file
var expectedInfoDigest uint32
switch args.contentType {
case persist.FileSetDataContentType:
expectedInfoDigest = digest.ToBuffer(digestData).ReadDigest()
case persist.FileSetIndexContentType:
if err := indexDigests.Unmarshal(digestData); err != nil {
continue
}
expectedInfoDigest = indexDigests.GetInfoDigest()
}
infoData, err := readAndValidate(infoFilePath, readerBufferSize,
expectedInfoDigest)
if err != nil {
continue
}
if len(matched[i].AbsoluteFilepaths) != 1 {
continue
}
fn(matched[i].AbsoluteFilepaths[0], matched[i].ID, infoData)
}
}
// ReadInfoFileResult is the result of reading an info file
type ReadInfoFileResult struct {
Info schema.IndexInfo
Err ReadInfoFileResultError
}
// ReadInfoFileResultError is the interface for obtaining information about an error
// that occurred trying to read an info file
type ReadInfoFileResultError interface {
Error() error
Filepath() string
}
type readInfoFileResultError struct {
err error
filepath string
}
// Error returns the error that occurred reading the info file
func (r readInfoFileResultError) Error() error {
return r.err
}
// FilePath returns the filepath for the problematic file
func (r readInfoFileResultError) Filepath() string {
return r.filepath
}
// ReadInfoFiles reads all the valid info entries. Even if ReadInfoFiles returns an error,
// there may be some valid entries in the returned slice.
func ReadInfoFiles(
filePathPrefix string,
namespace ident.ID,
shard uint32,
readerBufferSize int,
decodingOpts msgpack.DecodingOptions,
) []ReadInfoFileResult {
var infoFileResults []ReadInfoFileResult
decoder := msgpack.NewDecoder(decodingOpts)
forEachInfoFile(
forEachInfoFileSelector{
fileSetType: persist.FileSetFlushType,
contentType: persist.FileSetDataContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
shard: shard,
},
readerBufferSize,
func(filepath string, id FileSetFileIdentifier, data []byte) {
decoder.Reset(msgpack.NewDecoderStream(data))
info, err := decoder.DecodeIndexInfo()
infoFileResults = append(infoFileResults, ReadInfoFileResult{
Info: info,
Err: readInfoFileResultError{
err: err,
filepath: filepath,
},
})
})
return infoFileResults
}
// ReadIndexInfoFileResult is the result of reading an info file
type ReadIndexInfoFileResult struct {
ID FileSetFileIdentifier
Info index.IndexInfo
Err ReadInfoFileResultError
}
// ReadIndexInfoFiles reads all the valid index info entries. Even if ReadIndexInfoFiles returns an error,
// there may be some valid entries in the returned slice.
func ReadIndexInfoFiles(
filePathPrefix string,
namespace ident.ID,
readerBufferSize int,
) []ReadIndexInfoFileResult {
var infoFileResults []ReadIndexInfoFileResult
forEachInfoFile(
forEachInfoFileSelector{
fileSetType: persist.FileSetFlushType,
contentType: persist.FileSetIndexContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
},
readerBufferSize,
func(filepath string, id FileSetFileIdentifier, data []byte) {
var info index.IndexInfo
err := info.Unmarshal(data)
infoFileResults = append(infoFileResults, ReadIndexInfoFileResult{
ID: id,
Info: info,
Err: readInfoFileResultError{
err: err,
filepath: filepath,
},
})
})
return infoFileResults
}
// SortedSnapshotMetadataFiles returns a slice of all the SnapshotMetadata files that are on disk, as well
// as any files that it encountered errors for (corrupt, missing checkpoints, etc) which facilitates
// cleanup of corrupt files. []SnapshotMetadata will be sorted by index (i.e the chronological order
// in which the snapshots were taken), but []SnapshotMetadataErrorWithPaths will not be in any particular
// order.
func SortedSnapshotMetadataFiles(opts Options) (
[]SnapshotMetadata, []SnapshotMetadataErrorWithPaths, error) {
var (
prefix = opts.FilePathPrefix()
snapshotsDirPath = SnapshotDirPath(prefix)
)
// Glob for metadata files directly instead of their checkpoint files.
// In the happy case this makes no difference, but in situations where
// the metadata file exists but the checkpoint file does not (due to sudden
// node failure) this strategy allows us to still cleanup the metadata file
// whereas if we looked for checkpoint files directly the dangling metadata
// file would hang around forever.
metadataFilePaths, err := filepath.Glob(
path.Join(
snapshotsDirPath,
fmt.Sprintf("*%s%s%s", separator, metadataFileSuffix, fileSuffix)))
if err != nil {
return nil, nil, err
}
var (
reader = NewSnapshotMetadataReader(opts)
metadatas = []SnapshotMetadata{}
errorsWithPaths = []SnapshotMetadataErrorWithPaths{}
)
for _, file := range metadataFilePaths {
id, err := snapshotMetadataIdentifierFromFilePath(file)
if err != nil {
errorsWithPaths = append(errorsWithPaths, SnapshotMetadataErrorWithPaths{
Error: err,
MetadataFilePath: file,
// Can't construct checkpoint file path without ID
})
continue
}
if file != snapshotMetadataFilePathFromIdentifier(prefix, id) {
// Should never happen
errorsWithPaths = append(errorsWithPaths, SnapshotMetadataErrorWithPaths{
Error: instrument.InvariantErrorf(
"actual snapshot metadata filepath: %s and generated filepath: %s do not match",
file, snapshotMetadataFilePathFromIdentifier(prefix, id)),
MetadataFilePath: file,
CheckpointFilePath: snapshotMetadataCheckpointFilePathFromIdentifier(prefix, id),
})
continue
}
metadata, err := reader.Read(id)
if err != nil {
errorsWithPaths = append(errorsWithPaths, SnapshotMetadataErrorWithPaths{
Error: err,
MetadataFilePath: file,
CheckpointFilePath: snapshotMetadataCheckpointFilePathFromIdentifier(prefix, id),
})
continue
}
metadatas = append(metadatas, metadata)
}
sort.Slice(metadatas, func(i, j int) bool {
return metadatas[i].ID.Index < metadatas[j].ID.Index
})
return metadatas, errorsWithPaths, nil
}
// SnapshotFiles returns a slice of all the names for all the fileset files
// for a given namespace and shard combination.
func SnapshotFiles(filePathPrefix string, namespace ident.ID, shard uint32) (FileSetFilesSlice, error) {
return filesetFiles(filesetFilesSelector{
fileSetType: persist.FileSetSnapshotType,
contentType: persist.FileSetDataContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
shard: shard,
pattern: filesetFilePattern,
})
}
// IndexSnapshotFiles returns a slice of all the names for all the index fileset files
// for a given namespace.
func IndexSnapshotFiles(filePathPrefix string, namespace ident.ID) (FileSetFilesSlice, error) {
return filesetFiles(filesetFilesSelector{
fileSetType: persist.FileSetSnapshotType,
contentType: persist.FileSetIndexContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
pattern: filesetFilePattern,
})
}
// FileSetAt returns a FileSetFile for the given namespace/shard/blockStart combination if it exists.
func FileSetAt(filePathPrefix string, namespace ident.ID, shard uint32, blockStart time.Time) (FileSetFile, bool, error) {
matched, err := filesetFiles(filesetFilesSelector{
fileSetType: persist.FileSetFlushType,
contentType: persist.FileSetDataContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
shard: shard,
pattern: filesetFileForTime(blockStart, anyLowerCaseCharsPattern),
})
if err != nil {
return FileSetFile{}, false, err
}
matched.sortByTimeAscending()
for i, fileset := range matched {
if fileset.ID.BlockStart.Equal(blockStart) {
nextIdx := i + 1
if nextIdx < len(matched) && matched[nextIdx].ID.BlockStart.Equal(blockStart) {
// Should never happen
return FileSetFile{}, false, fmt.Errorf(
"found multiple fileset files for blockStart: %d",
blockStart.Unix(),
)
}
if !fileset.HasCheckpointFile() {
continue
}
return fileset, true, nil
}
}
return FileSetFile{}, false, nil
}
// IndexFileSetsAt returns all FileSetFile(s) for the given namespace/blockStart combination.
// NB: It returns all complete Volumes found on disk.
func IndexFileSetsAt(filePathPrefix string, namespace ident.ID, blockStart time.Time) (FileSetFilesSlice, error) {
matches, err := filesetFiles(filesetFilesSelector{
fileSetType: persist.FileSetFlushType,
contentType: persist.FileSetIndexContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
pattern: filesetFileForTime(blockStart, anyLowerCaseCharsNumbersPattern),
})
if err != nil {
return nil, err
}
filesets := make(FileSetFilesSlice, 0, len(matches))
matches.sortByTimeAscending()
for _, fileset := range matches {
if fileset.ID.BlockStart.Equal(blockStart) {
if !fileset.HasCheckpointFile() {
continue
}
filesets = append(filesets, fileset)
}
}
return filesets, nil
}
// DeleteFileSetAt deletes a FileSetFile for a given namespace/shard/blockStart combination if it exists.
func DeleteFileSetAt(filePathPrefix string, namespace ident.ID, shard uint32, t time.Time) error {
fileset, ok, err := FileSetAt(filePathPrefix, namespace, shard, t)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("fileset for blockStart: %d does not exist", t.Unix())
}
return DeleteFiles(fileset.AbsoluteFilepaths)
}
// DataFileSetsBefore returns all the flush data fileset files whose timestamps are earlier than a given time.
func DataFileSetsBefore(filePathPrefix string, namespace ident.ID, shard uint32, t time.Time) ([]string, error) {
matched, err := filesetFiles(filesetFilesSelector{
fileSetType: persist.FileSetFlushType,
contentType: persist.FileSetDataContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
shard: shard,
pattern: filesetFilePattern,
})
if err != nil {
return nil, err
}
return FilesBefore(matched.Filepaths(), t)
}
// IndexFileSetsBefore returns all the flush index fileset files whose timestamps are earlier than a given time.
func IndexFileSetsBefore(filePathPrefix string, namespace ident.ID, t time.Time) ([]string, error) {
matched, err := filesetFiles(filesetFilesSelector{
fileSetType: persist.FileSetFlushType,
contentType: persist.FileSetIndexContentType,
filePathPrefix: filePathPrefix,
namespace: namespace,
pattern: filesetFilePattern,
})
if err != nil {
return nil, err
}
return FilesBefore(matched.Filepaths(), t)
}
// DeleteInactiveDirectories deletes any directories that are not currently active, as defined by the
// inputed active directories within the parent directory
func DeleteInactiveDirectories(parentDirectoryPath string, activeDirectories []string) error {
var toDelete []string
activeDirNames := make(map[string]struct{})
allSubDirs, err := findSubDirectoriesAndPaths(parentDirectoryPath)
if err != nil {
return nil
}
// Create shard set, might also be useful to just send in as strings?
for _, dir := range activeDirectories {
activeDirNames[dir] = struct{}{}
}
for dirName, dirPath := range allSubDirs {
if _, ok := activeDirNames[dirName]; !ok {
toDelete = append(toDelete, dirPath)
}
}
return DeleteDirectories(toDelete)
}
// SortedCommitLogFiles returns all the commit log files in the commit logs directory.
func SortedCommitLogFiles(commitLogsDir string) ([]string, error) {
return sortedCommitlogFiles(commitLogsDir, commitLogFilePattern)
}
type toSortableFn func(files []string) sort.Interface
func findFiles(fileDir string, pattern string, fn toSortableFn) ([]string, error) {
matched, err := filepath.Glob(path.Join(fileDir, pattern))
if err != nil {
return nil, err
}
sort.Sort(fn(matched))
return matched, nil
}
type directoryNamesToPaths map[string]string
func findSubDirectoriesAndPaths(directoryPath string) (directoryNamesToPaths, error) {
parent, err := os.Open(directoryPath)
if err != nil {
return nil, err
}
subDirectoriesToPaths := make(directoryNamesToPaths)
subDirNames, err := parent.Readdirnames(-1)
if err != nil {
return nil, err
}
err = parent.Close()
if err != nil {
return nil, err
}
for _, dirName := range subDirNames {
subDirectoriesToPaths[dirName] = path.Join(directoryPath, dirName)
}
return subDirectoriesToPaths, nil
}
type filesetFilesSelector struct {
fileSetType persist.FileSetType
contentType persist.FileSetContentType
filePathPrefix string
namespace ident.ID
shard uint32
pattern string
}
func filesetFiles(args filesetFilesSelector) (FileSetFilesSlice, error) {
var (
byTimeAsc []string
err error
)
switch args.fileSetType {
case persist.FileSetFlushType:
switch args.contentType {
case persist.FileSetDataContentType:
dir := ShardDataDirPath(args.filePathPrefix, args.namespace, args.shard)
byTimeAsc, err = findFiles(dir, args.pattern, func(files []string) sort.Interface {
return byTimeAscending(files)
})
case persist.FileSetIndexContentType:
dir := NamespaceIndexDataDirPath(args.filePathPrefix, args.namespace)
byTimeAsc, err = findFiles(dir, args.pattern, func(files []string) sort.Interface {
return fileSetFilesByTimeAndVolumeIndexAscending(files)
})
default:
return nil, fmt.Errorf("unknown content type: %d", args.contentType)
}
case persist.FileSetSnapshotType:
var dir string
switch args.contentType {
case persist.FileSetDataContentType:
dir = ShardSnapshotsDirPath(args.filePathPrefix, args.namespace, args.shard)
case persist.FileSetIndexContentType:
dir = NamespaceIndexSnapshotDirPath(args.filePathPrefix, args.namespace)
default:
return nil, fmt.Errorf("unknown content type: %d", args.contentType)
}
byTimeAsc, err = findFiles(dir, args.pattern, func(files []string) sort.Interface {
return fileSetFilesByTimeAndVolumeIndexAscending(files)
})
default:
return nil, fmt.Errorf("unknown type: %d", args.fileSetType)
}
if err != nil {
return nil, err
}
if len(byTimeAsc) == 0 {
return nil, nil
}
var (
latestBlockStart time.Time
latestVolumeIndex int
latestFileSetFile FileSetFile
filesetFiles = []FileSetFile{}
)
for _, file := range byTimeAsc {
var (
currentFileBlockStart time.Time
volumeIndex int
err error