-
Notifications
You must be signed in to change notification settings - Fork 387
/
dir.go
1137 lines (1011 loc) · 36.2 KB
/
dir.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) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package filestore
import (
"bytes"
"context"
"encoding/base32"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/zeebo/errs"
"go.uber.org/zap"
"golang.org/x/exp/slices"
"storj.io/common/storj"
"storj.io/storj/storagenode/blobstore"
)
const (
blobPermission = 0600 // matches os.CreateTemp
dirPermission = 0700
v0PieceFileSuffix = ""
v1PieceFileSuffix = ".sj1"
unknownPieceFileSuffix = "/..error_unknown_format../"
verificationFileName = "storage-dir-verification"
// TrashUsesDayDirsIndicator is the name of a file whose presence under
// trashdir indicates per-day directories can be used. absence of this file
// means there is still trash in trash/$namespace/?? directories that needs
// to be migrated to per-day directories.
TrashUsesDayDirsIndicator = ".trash-uses-day-dirs-indicator"
)
// PathEncoding is the encoding used for the namespace and key in the filestore.
var PathEncoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding)
// Dir represents single folder for storing blobs.
type Dir struct {
log *zap.Logger
path string
mu sync.Mutex
info atomic.Pointer[infoAge]
}
const infoMaxAge = time.Second
type infoAge struct {
info blobstore.DiskInfo
age time.Time
}
// OpenDir opens existing folder for storing blobs.
func OpenDir(log *zap.Logger, path string, now time.Time) (*Dir, error) {
dir := &Dir{
log: log,
path: path,
}
stat := func(path string) error {
_, err := os.Stat(path)
return err
}
err := errs.Combine(
stat(dir.blobsdir()),
stat(dir.tempdir()),
stat(dir.trashdir()),
)
if err != nil {
return nil, err
}
indicatorFile := filepath.Join(dir.trashdir(), TrashUsesDayDirsIndicator)
if stat(indicatorFile) != nil {
err = dir.migrateTrashToPerDayDirs(now)
if err != nil {
return nil, err
}
err = os.WriteFile(indicatorFile, []byte("do not delete this file"), 0644)
if err != nil {
return nil, err
}
}
return dir, nil
}
// NewDir returns folder for storing blobs.
func NewDir(log *zap.Logger, path string) (dir *Dir, err error) {
dir = &Dir{
log: log,
path: path,
}
err = errs.Combine(
os.MkdirAll(dir.blobsdir(), dirPermission),
os.MkdirAll(dir.tempdir(), dirPermission),
os.MkdirAll(dir.trashdir(), dirPermission),
)
if err != nil {
return nil, err
}
// this should fail if the file already exists; thus, O_EXCL, and we can't use os.WriteFile for it
f, err := os.OpenFile(filepath.Join(dir.trashdir(), TrashUsesDayDirsIndicator), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
defer func() {
err = errs.Combine(err, f.Close())
}()
_, err = f.WriteString("do not delete this file")
return dir, err
}
// Path returns the directory path.
func (dir *Dir) Path() string { return dir.path }
// blobsdir is the sub-directory containing the blobs.
func (dir *Dir) blobsdir() string { return filepath.Join(dir.path, "blobs") }
// tempdir is used for temp files prior to being moved into blobsdir.
func (dir *Dir) tempdir() string { return filepath.Join(dir.path, "temp") }
// trashdir contains files staged for deletion for a period of time.
func (dir *Dir) trashdir() string { return filepath.Join(dir.path, "trash") }
// trashPath returns the toplevel trash directory for the given namespace and timestamp.
func (dir *Dir) trashPath(namespace []byte, forTime time.Time) string {
namespaceStr := PathEncoding.EncodeToString(namespace)
dayDirName := forTime.UTC().Format("2006-01-02")
return filepath.Join(dir.trashdir(), namespaceStr, dayDirName)
}
// refToTrashPath converts a blob reference to a filepath in the trash hierarchy with the given timestamp.
func (dir *Dir) refToTrashPath(ref blobstore.BlobRef, forTime time.Time) (string, error) {
if !ref.IsValid() {
return "", blobstore.ErrInvalidBlobRef.New("")
}
key := PathEncoding.EncodeToString(ref.Key)
if len(key) < 3 {
// ensure we always have enough characters to split [:2] and [2:]
key = "11" + key
}
return filepath.Join(dir.trashPath(ref.Namespace, forTime), key[:2], key[2:]), nil
}
// CreateVerificationFile creates a file to be used for storage directory verification.
func (dir *Dir) CreateVerificationFile(ctx context.Context, id storj.NodeID) error {
f, err := os.Create(filepath.Join(dir.path, verificationFileName))
if err != nil {
return err
}
defer func() {
err = errs.Combine(err, f.Close())
}()
_, err = f.Write(id.Bytes())
return err
}
// Verify verifies that the storage directory is correct by checking for the existence and validity
// of the verification file.
func (dir *Dir) Verify(ctx context.Context, id storj.NodeID) error {
content, err := os.ReadFile(filepath.Join(dir.path, verificationFileName))
if err != nil {
return err
}
if !bytes.Equal(content, id.Bytes()) {
verifyID, err := storj.NodeIDFromBytes(content)
if err != nil {
return errs.New("content of file is not a valid node ID: %x", content)
}
return errs.New("node ID in file (%s) does not match running node's ID (%s)", verifyID, id.String())
}
return nil
}
// CreateTemporaryFile creates a preallocated temporary file in the temp directory.
func (dir *Dir) CreateTemporaryFile(ctx context.Context) (_ *os.File, err error) {
file, err := os.CreateTemp(dir.tempdir(), "blob-*.partial")
if err != nil {
return nil, err
}
return file, nil
}
// CreateNamedFile creates a preallocated file in the correct destination directory.
func (dir *Dir) CreateNamedFile(ctx context.Context, ref blobstore.BlobRef, formatVersion blobstore.FormatVersion) (file *os.File, err error) {
path, err := dir.blobToBasePath(ref)
if err != nil {
return nil, err
}
path = blobPathForFormatVersion(path, formatVersion)
file, err = os.Create(path)
if err != nil {
mkdirErr := os.MkdirAll(filepath.Dir(path), dirPermission)
if mkdirErr != nil {
return nil, Error.Wrap(errs.Combine(err, mkdirErr))
}
file, err = os.Create(path)
if err != nil {
return nil, err
}
}
return file, nil
}
// DeleteTemporary deletes a temporary file.
func (dir *Dir) DeleteTemporary(ctx context.Context, file *os.File) (err error) {
defer mon.Task()(&ctx)(&err)
closeErr := file.Close()
return errs.Combine(closeErr, os.Remove(file.Name()))
}
// blobToBasePath converts a blob reference to a filepath in permanent storage. This may not be the
// entire path; blobPathForFormatVersion() must also be used. This is a separate call because this
// part of the filepath is constant, and blobPathForFormatVersion may need to be called multiple
// times with different storage.FormatVersion values.
func (dir *Dir) blobToBasePath(ref blobstore.BlobRef) (string, error) {
return dir.refToDirPath(ref, dir.blobsdir())
}
// refToDirPath converts a blob reference to a filepath in the specified sub-directory.
func (dir *Dir) refToDirPath(ref blobstore.BlobRef, subDir string) (string, error) {
if !ref.IsValid() {
return "", blobstore.ErrInvalidBlobRef.New("")
}
namespace := PathEncoding.EncodeToString(ref.Namespace)
key := PathEncoding.EncodeToString(ref.Key)
if len(key) < 3 {
// ensure we always have enough characters to split [:2] and [2:]
key = "11" + key
}
return filepath.Join(subDir, namespace, key[:2], key[2:]), nil
}
func (dir *Dir) findBlobInTrash(ctx context.Context, ref blobstore.BlobRef) (dirTime time.Time, formatVer blobstore.FormatVersion, path string, err error) {
defer mon.Task()(&ctx)(&err)
err = dir.forEachTrashDayDir(ctx, ref.Namespace, func(dayDirTime time.Time) error {
trashBasePath, err := dir.refToTrashPath(ref, dayDirTime)
if err != nil {
// something was wrong with our input; don't need to keep looking
return err
}
for ver := MinFormatVersionSupportedInTrash; ver <= MaxFormatVersionSupported; ver++ {
trashVerPath := blobPathForFormatVersion(trashBasePath, ver)
_, err = os.Stat(trashVerPath)
if err == nil {
dirTime = dayDirTime
path = trashVerPath
formatVer = ver
break
}
}
return nil
})
if err != nil {
return time.Time{}, 0, "", err
}
if path == "" {
return time.Time{}, 0, "", os.ErrNotExist
}
return dirTime, formatVer, path, nil
}
// blobPathForFormatVersion adjusts a bare blob path (as might have been generated by a call to
// blobToBasePath()) to what it should be for the given storage format version.
func blobPathForFormatVersion(path string, formatVersion blobstore.FormatVersion) string {
switch formatVersion {
case FormatV0:
return path + v0PieceFileSuffix
case FormatV1:
return path + v1PieceFileSuffix
}
return path + unknownPieceFileSuffix
}
// Commit commits the temporary file to permanent storage.
func (dir *Dir) Commit(ctx context.Context, file *os.File, sync bool, ref blobstore.BlobRef, formatVersion blobstore.FormatVersion) (err error) {
defer mon.Task()(&ctx)(&err)
var syncErr error
if sync {
syncErr = file.Sync()
}
closeErr := file.Close()
if syncErr != nil || closeErr != nil {
removeErr := os.Remove(file.Name())
return errs.Combine(syncErr, closeErr, removeErr)
}
path, err := dir.blobToBasePath(ref)
if err != nil {
removeErr := os.Remove(file.Name())
return errs.Combine(err, removeErr)
}
path = blobPathForFormatVersion(path, formatVersion)
if file.Name() != path {
mkdirErr := os.MkdirAll(filepath.Dir(path), dirPermission)
if os.IsExist(mkdirErr) {
mkdirErr = nil
}
if mkdirErr != nil {
removeErr := os.Remove(file.Name())
return errs.Combine(mkdirErr, removeErr)
}
renameErr := rename(file.Name(), path)
if renameErr != nil {
removeErr := os.Remove(file.Name())
return errs.Combine(renameErr, removeErr)
}
}
return nil
}
// Open opens the file with the specified ref. It may need to check in more than one location in
// order to find the blob, if it was stored with an older version of the storage node software.
// In cases where the storage format version of a blob is already known, OpenWithStorageFormat()
// will generally be a better choice.
func (dir *Dir) Open(ctx context.Context, ref blobstore.BlobRef) (_ *os.File, _ blobstore.FormatVersion, err error) {
defer mon.Task()(&ctx)(&err)
path, err := dir.blobToBasePath(ref)
if err != nil {
return nil, FormatV0, err
}
for formatVer := MaxFormatVersionSupported; formatVer >= MinFormatVersionSupported; formatVer-- {
vPath := blobPathForFormatVersion(path, formatVer)
file, err := openFileReadOnly(vPath, blobPermission)
if err == nil {
return file, formatVer, nil
}
if !os.IsNotExist(err) {
return nil, FormatV0, Error.New("unable to open %q: %v", vPath, err)
}
}
return nil, FormatV0, os.ErrNotExist
}
// OpenWithStorageFormat opens an already-located blob file with a known storage format version,
// which avoids the potential need to search through multiple storage formats to find the blob.
func (dir *Dir) OpenWithStorageFormat(ctx context.Context, ref blobstore.BlobRef, formatVer blobstore.FormatVersion) (_ *os.File, err error) {
defer mon.Task()(&ctx)(&err)
path, err := dir.blobToBasePath(ref)
if err != nil {
return nil, err
}
vPath := blobPathForFormatVersion(path, formatVer)
file, err := openFileReadOnly(vPath, blobPermission)
if err == nil {
return file, nil
}
if os.IsNotExist(err) {
// we don't want to wrap something matching os.IsNotExist, because IsNotExist
// does _not_ unwrap.
return nil, err
}
return nil, Error.Wrap(err)
}
// Stat looks up disk metadata on the blob file. It may need to check in more than one location
// in order to find the blob, if it was stored with an older version of the storage node software.
// In cases where the storage format version of a blob is already known, StatWithStorageFormat()
// will generally be a better choice.
func (dir *Dir) Stat(ctx context.Context, ref blobstore.BlobRef) (_ blobstore.BlobInfo, err error) {
defer mon.Task()(&ctx)(&err)
path, err := dir.blobToBasePath(ref)
if err != nil {
return nil, err
}
for formatVer := MaxFormatVersionSupported; formatVer >= MinFormatVersionSupported; formatVer-- {
vPath := blobPathForFormatVersion(path, formatVer)
stat, err := os.Stat(vPath)
if err == nil {
return newBlobInfo(ref, vPath, stat, formatVer), nil
}
if !os.IsNotExist(err) {
return nil, Error.New("unable to stat %q: %v", vPath, err)
}
}
return nil, os.ErrNotExist
}
// StatWithStorageFormat looks up disk metadata on the blob file with the given storage format
// version. This avoids the need for checking for the file in multiple different storage format
// types.
func (dir *Dir) StatWithStorageFormat(ctx context.Context, ref blobstore.BlobRef, formatVer blobstore.FormatVersion) (_ blobstore.BlobInfo, err error) {
defer mon.Task()(&ctx)(&err)
path, err := dir.blobToBasePath(ref)
if err != nil {
return nil, err
}
vPath := blobPathForFormatVersion(path, formatVer)
stat, err := os.Stat(vPath)
if err == nil {
return newBlobInfo(ref, vPath, stat, formatVer), nil
}
if os.IsNotExist(err) {
return nil, err
}
return nil, Error.New("unable to stat %q: %v", vPath, err)
}
// Trash moves the blob specified by ref to the trash for every format version.
func (dir *Dir) Trash(ctx context.Context, ref blobstore.BlobRef, timestamp time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
return dir.iterateStorageFormatVersions(ctx, ref, func(ctx context.Context, ref blobstore.BlobRef, formatVersion blobstore.FormatVersion) error {
return dir.TrashWithStorageFormat(ctx, ref, formatVersion, timestamp)
})
}
// TrashWithStorageFormat moves the blob specified by ref to the trash for the specified format version.
func (dir *Dir) TrashWithStorageFormat(ctx context.Context, ref blobstore.BlobRef, formatVer blobstore.FormatVersion, timestamp time.Time) (err error) {
blobsBasePath, err := dir.blobToBasePath(ref)
if err != nil {
return err
}
blobsVerPath := blobPathForFormatVersion(blobsBasePath, formatVer)
trashBasePath, err := dir.refToTrashPath(ref, timestamp)
if err != nil {
return err
}
trashVerPath := blobPathForFormatVersion(trashBasePath, formatVer)
// ensure the dirs exist for trash path
err = os.MkdirAll(filepath.Dir(trashVerPath), dirPermission)
if err != nil && !os.IsExist(err) {
return err
}
// move to trash
err = rename(blobsVerPath, trashVerPath)
if os.IsNotExist(err) {
// no blob at that path; either it has a different storage format
// version or there was a concurrent call. (This function is expected
// by callers to return a nil error in the case of concurrent calls.)
return nil
}
return err
}
// RestoreTrash moves every blob in the trash folder back into blobsdir.
func (dir *Dir) RestoreTrash(ctx context.Context, namespace []byte) (keysRestored [][]byte, err error) {
var errorsEncountered errs.Group
err = dir.walkNamespaceInTrash(ctx, namespace, func(info blobstore.BlobInfo, dirTime time.Time) error {
blobsBasePath, err := dir.blobToBasePath(info.BlobRef())
if err != nil {
errorsEncountered.Add(err)
return nil
}
blobsVerPath := blobPathForFormatVersion(blobsBasePath, info.StorageFormatVersion())
trashBasePath, err := dir.refToTrashPath(info.BlobRef(), dirTime)
if err != nil {
errorsEncountered.Add(err)
return nil
}
trashVerPath := blobPathForFormatVersion(trashBasePath, info.StorageFormatVersion())
// ensure the dirs exist for blobs path
err = os.MkdirAll(filepath.Dir(blobsVerPath), dirPermission)
if err != nil && !os.IsExist(err) {
errorsEncountered.Add(err)
return nil
}
// move back to blobsdir
err = rename(trashVerPath, blobsVerPath)
if os.IsNotExist(err) {
// no blob at that path; either it has a different storage format
// version or there was a concurrent call. (This function is expected
// by callers to return a nil error in the case of concurrent calls.)
return nil
}
if err != nil {
errorsEncountered.Add(err)
return nil
}
keysRestored = append(keysRestored, info.BlobRef().Key)
return nil
})
errorsEncountered.Add(err)
return keysRestored, errorsEncountered.Err()
}
// TryRestoreTrashBlob attempts to restore a blob from the trash if it exists.
// It returns nil if the blob was restored, or an error if the blob was not
// in the trash or could not be restored.
func (dir *Dir) TryRestoreTrashBlob(ctx context.Context, ref blobstore.BlobRef) (err error) {
defer mon.Task()(&ctx)(&err)
_, formatVer, blobPathInTrash, err := dir.findBlobInTrash(ctx, ref)
if err != nil {
return err
}
blobsBasePath, err := dir.blobToBasePath(ref)
if err != nil {
return err
}
// ensure the dirs exist for blobs path in main storage
blobsVerPath := blobPathForFormatVersion(blobsBasePath, formatVer)
err = os.MkdirAll(filepath.Dir(blobsVerPath), dirPermission)
if err != nil && !errors.Is(err, fs.ErrExist) {
return err
}
// move back to main storage
return rename(blobPathInTrash, blobsVerPath)
}
// EmptyTrash iterates through the toplevel trash directories for the given
// namespace and recursively deletes any of them more than 24h older than
// trashedBefore.
func (dir *Dir) EmptyTrash(ctx context.Context, namespace []byte, trashedBefore time.Time) (bytesEmptied int64, deletedKeys [][]byte, err error) {
defer mon.Task()(&ctx)(&err)
var errorsEncountered errs.Group
err = dir.forEachTrashDayDir(ctx, namespace, func(dirTime time.Time) error {
// add 24h since blobs in there might have been moved in as late as 23:59:59.999
if !dirTime.Add(24 * time.Hour).After(trashedBefore) {
emptied, keys, err := dir.deleteTrashDayDir(ctx, namespace, dirTime)
bytesEmptied += emptied
deletedKeys = append(deletedKeys, keys...)
errorsEncountered.Add(err)
}
return nil
})
errorsEncountered.Add(err)
return bytesEmptied, deletedKeys, errorsEncountered.Err()
}
// DeleteTrashNamespace deletes an entire namespace under the trash dir.
func (dir *Dir) DeleteTrashNamespace(ctx context.Context, namespace []byte) (err error) {
mon.Task()(&ctx)(&err)
var errorsEncountered errs.Group
err = dir.forEachTrashDayDir(ctx, namespace, func(dirTime time.Time) error {
_, _, err := dir.deleteTrashDayDir(ctx, namespace, dirTime)
errorsEncountered.Add(err)
return nil
})
errorsEncountered.Add(err)
namespaceEncoded := PathEncoding.EncodeToString(namespace)
namespaceTrashDir := filepath.Join(dir.trashdir(), namespaceEncoded)
err = removeButIgnoreIfNotExist(namespaceTrashDir)
errorsEncountered.Add(err)
return errorsEncountered.Err()
}
// walkNamespaceInTrash executes walkFunc for each blob stored in the trash under the given
// namespace. If walkFunc returns a non-nil error, walkNamespaceInTrash will stop iterating and
// return the error immediately. The ctx parameter is intended specifically to allow canceling
// iteration early.
func (dir *Dir) walkNamespaceInTrash(ctx context.Context, namespace []byte, f func(info blobstore.BlobInfo, dirTime time.Time) error) error {
return dir.forEachTrashDayDir(ctx, namespace, func(dirTime time.Time) error {
return dir.walkTrashDayDir(ctx, namespace, dirTime, func(info blobstore.BlobInfo) error {
return f(info, dirTime)
})
})
}
func (dir *Dir) forEachTrashDayDir(ctx context.Context, namespace []byte, f func(dirTime time.Time) error) error {
dirTimes, err := dir.listTrashDayDirs(ctx, namespace)
if err != nil {
return err
}
for _, dirTime := range dirTimes {
if err := ctx.Err(); err != nil {
return err
}
err = f(dirTime)
if err != nil {
return err
}
}
return nil
}
func (dir *Dir) walkTrashDayDir(ctx context.Context, namespace []byte, dirTime time.Time, f func(info blobstore.BlobInfo) error) (err error) {
trashPath := dir.trashPath(namespace, dirTime)
return dir.walkNamespaceUnderPath(ctx, namespace, trashPath, "", f)
}
func (dir *Dir) listTrashDayDirs(ctx context.Context, namespace []byte) (dirTimes []time.Time, err error) {
namespaceEncoded := PathEncoding.EncodeToString(namespace)
namespaceTrashDir := filepath.Join(dir.trashdir(), namespaceEncoded)
openDir, err := os.Open(namespaceTrashDir)
if err != nil {
if os.IsNotExist(err) {
dir.log.Debug("directory not found", zap.String("dir", namespaceTrashDir))
// job accomplished: there are no day dirs in this namespace!
return nil, nil
}
return nil, err
}
defer func() { err = errs.Combine(err, openDir.Close()) }()
for {
// check for context done both before and after our readdir() call
if err := ctx.Err(); err != nil {
return nil, err
}
subdirNames, err := openDir.Readdirnames(nameBatchSize)
if err != nil {
if errors.Is(err, io.EOF) {
return dirTimes, nil
}
return nil, err
}
if len(subdirNames) == 0 {
return dirTimes, nil
}
if err := ctx.Err(); err != nil {
return nil, err
}
for _, subdirName := range subdirNames {
subdirTime, err := time.Parse("2006-01-02", subdirName)
if err != nil {
// just an invalid subdir; could be garbage of many kinds. probably
// don't need to pass on this error
continue
}
dirTimes = append(dirTimes, subdirTime)
}
}
}
func removeButIgnoreIfNotExist(pathToRemove string) error {
err := os.Remove(pathToRemove)
if err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
func (dir *Dir) deleteTrashDayDir(ctx context.Context, namespace []byte, dirTime time.Time) (bytesEmptied int64, deletedKeys [][]byte, err error) {
var errorsEncountered errs.Group
err = dir.walkTrashDayDir(ctx, namespace, dirTime, func(info blobstore.BlobInfo) error {
thisBlobInfo, ok := info.(*blobInfo)
if !ok {
// if this happens, it's time to extend the code to handle the other type
errorsEncountered.Add(Error.New("%+v [unexpected type %T]: %w", info, info, err))
return nil
}
fileInfo, err := info.Stat(ctx)
if err != nil {
if os.IsNotExist(err) {
return nil
}
if errors.Is(err, ErrIsDir) {
return nil
}
errorsEncountered.Add(Error.New("%s: %w", thisBlobInfo.path, err))
return nil
}
err = removeButIgnoreIfNotExist(thisBlobInfo.path)
if err != nil {
errorsEncountered.Add(err)
return nil
}
bytesEmptied += fileInfo.Size()
deletedKeys = append(deletedKeys, info.BlobRef().Key)
return nil
})
if err != nil {
errorsEncountered.Add(err)
return bytesEmptied, deletedKeys, errorsEncountered.Err()
}
// Finish by attempting to remove the directory structure for this timestamp
// (this will fail if any files are left undeleted inside). This works like
// `rmdir "trash/$namespace/$timestamp"/??; rmdir "trash/$namespace/$timestamp"`.
trashDayDir := dir.trashPath(namespace, dirTime)
dirEntries, err := os.ReadDir(trashDayDir)
if err != nil {
errorsEncountered.Add(Error.New("list %s: %w", trashDayDir, err))
return bytesEmptied, deletedKeys, errorsEncountered.Err()
}
for _, entry := range dirEntries {
if entry.IsDir() && len(entry.Name()) == 2 {
err = removeButIgnoreIfNotExist(filepath.Join(trashDayDir, entry.Name()))
errorsEncountered.Add(err)
}
}
err = removeButIgnoreIfNotExist(trashDayDir)
errorsEncountered.Add(err)
return bytesEmptied, deletedKeys, errorsEncountered.Err()
}
// iterateStorageFormatVersions executes f for all storage format versions,
// starting with the oldest format version. It is more likely, in the general
// case, that we will find the blob with the newest format version instead,
// but if we iterate backward here then we run the risk of a race condition:
// the blob might have existed with _SomeOldVer before the call, and could
// then have been updated atomically with _MaxVer concurrently while we were
// iterating. If we iterate _forwards_, this race should not occur because it
// is assumed that blobs are never rewritten with an _older_ storage format
// version.
//
// f will be executed for every storage format version regardless of the
// result, and will aggregate errors into a single returned error.
func (dir *Dir) iterateStorageFormatVersions(ctx context.Context, ref blobstore.BlobRef, f func(ctx context.Context, ref blobstore.BlobRef, i blobstore.FormatVersion) error) (err error) {
defer mon.Task()(&ctx)(&err)
var combinedErrors errs.Group
for i := MinFormatVersionSupported; i <= MaxFormatVersionSupported; i++ {
combinedErrors.Add(f(ctx, ref, i))
}
return combinedErrors.Err()
}
// Delete deletes blobs with the specified ref (in all supported storage formats).
//
// It doesn't return an error if the blob is not found for any reason.
func (dir *Dir) Delete(ctx context.Context, ref blobstore.BlobRef) (err error) {
defer mon.Task()(&ctx)(&err)
return dir.iterateStorageFormatVersions(ctx, ref, dir.DeleteWithStorageFormat)
}
// DeleteWithStorageFormat deletes the blob with the specified ref for one
// specific format version.
//
// It doesn't return an error if the blob isn't found for any reason.
func (dir *Dir) DeleteWithStorageFormat(ctx context.Context, ref blobstore.BlobRef, formatVer blobstore.FormatVersion) (err error) {
defer mon.Task()(&ctx)(&err)
return dir.deleteWithStorageFormatInPath(ctx, dir.blobsdir(), ref, formatVer)
}
// DeleteNamespace deletes blobs folder for a specific namespace.
func (dir *Dir) DeleteNamespace(ctx context.Context, ref []byte) (err error) {
defer mon.Task()(&ctx)(&err)
return dir.deleteNamespace(ctx, dir.blobsdir(), ref)
}
func (dir *Dir) deleteWithStorageFormatInPath(ctx context.Context, path string, ref blobstore.BlobRef, formatVer blobstore.FormatVersion) (err error) {
defer mon.Task()(&ctx)(&err)
pathBase, err := dir.refToDirPath(ref, path)
if err != nil {
return err
}
verPath := blobPathForFormatVersion(pathBase, formatVer)
// try removing the file
return removeButIgnoreIfNotExist(verPath)
}
// deleteNamespace deletes folder with everything inside.
func (dir *Dir) deleteNamespace(ctx context.Context, path string, ref []byte) (err error) {
defer mon.Task()(&ctx)(&err)
namespace := PathEncoding.EncodeToString(ref)
folderPath := filepath.Join(path, namespace)
err = os.RemoveAll(folderPath)
return err
}
const nameBatchSize = 1024
// ListNamespaces finds all known namespace IDs in use in local storage. They are not
// guaranteed to contain any blobs.
func (dir *Dir) ListNamespaces(ctx context.Context) (ids [][]byte, err error) {
defer mon.Task()(&ctx)(&err)
return dir.listNamespacesInPath(ctx, dir.blobsdir())
}
// listNamespacesInTrash lists all known the namespace IDs in use in the trash. They are
// not guaranteed to contain any blobs, or to correspond to namespaces in main storage.
func (dir *Dir) listNamespacesInTrash(ctx context.Context) (ids [][]byte, err error) {
defer mon.Task()(&ctx)(&err)
return dir.listNamespacesInPath(ctx, dir.trashdir())
}
func (dir *Dir) listNamespacesInPath(ctx context.Context, path string) (ids [][]byte, err error) {
defer mon.Task()(&ctx)(&err)
openDir, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() { err = errs.Combine(err, openDir.Close()) }()
for {
dirNames, err := openDir.Readdirnames(nameBatchSize)
if err != nil {
if errors.Is(err, io.EOF) || os.IsNotExist(err) {
return ids, nil
}
return ids, err
}
if len(dirNames) == 0 {
return ids, nil
}
for _, name := range dirNames {
namespace, err := PathEncoding.DecodeString(name)
if err != nil {
// just an invalid directory entry, and not a namespace. probably
// don't need to pass on this error
continue
}
ids = append(ids, namespace)
}
}
}
// WalkNamespace executes walkFunc for each locally stored blob, stored with storage format V1 or
// greater, in the given namespace. If walkFunc returns a non-nil error, WalkNamespace will stop
// iterating and return the error immediately. The ctx parameter is intended specifically to allow
// canceling iteration early.
func (dir *Dir) WalkNamespace(ctx context.Context, namespace []byte, startFromPrefix string, walkFunc func(blobstore.BlobInfo) error) (err error) {
defer mon.Task()(&ctx)(&err)
return dir.walkNamespaceInPath(ctx, namespace, dir.blobsdir(), startFromPrefix, walkFunc)
}
func (dir *Dir) walkNamespaceInPath(ctx context.Context, namespace []byte, path, startPrefix string, walkFunc func(blobstore.BlobInfo) error) (err error) {
defer mon.Task()(&ctx)(&err)
namespaceDir := PathEncoding.EncodeToString(namespace)
nsDir := filepath.Join(path, namespaceDir)
return dir.walkNamespaceUnderPath(ctx, namespace, nsDir, startPrefix, walkFunc)
}
func (dir *Dir) walkNamespaceUnderPath(ctx context.Context, namespace []byte, nsDir, startPrefix string, walkFunc func(blobstore.BlobInfo) error) (err error) {
openDir, err := os.Open(nsDir)
if err != nil {
if os.IsNotExist(err) {
dir.log.Debug("directory not found", zap.String("dir", nsDir))
// job accomplished: there are no blobs in this namespace!
return nil
}
return err
}
defer func() { err = errs.Combine(err, openDir.Close()) }()
var subdirNames []string
for {
names, err := openDir.Readdirnames(nameBatchSize)
if err != nil {
if errors.Is(err, io.EOF) || os.IsNotExist(err) {
break
}
return err
}
if len(names) == 0 {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
subdirNames = append(subdirNames, names...)
}
dir.log.Debug("number of subdirs", zap.Int("count", len(subdirNames)))
// sort the dir names, so we can start from the startPrefix
sortPrefixes(subdirNames)
// just a little optimization: if we were somehow given a startPrefix that
// is the last subdir, we can skip the rest and just start from there.
if startPrefix != "" && subdirNames[len(subdirNames)-1] == startPrefix {
subdirNames = subdirNames[:len(subdirNames)-1]
}
for _, keyPrefix := range subdirNames {
if len(keyPrefix) != 2 {
// just an invalid subdir; could be garbage of many kinds. probably
// don't need to pass on this error
continue
}
if startPrefix != "" && startPrefix > keyPrefix {
continue
}
err := walkNamespaceWithPrefix(ctx, dir.log, namespace, nsDir, keyPrefix, walkFunc)
if err != nil {
return err
}
}
return nil
}
// migrateTrashToPerDayDirs migrates a trash directory that is _not_ using per-day directories
// to a trash directory that _does_ use per-day directories. This is accomplished by shunting
// everything in the trash into the directory for the current day.
//
// This will result in some things staying in the trash for longer than they otherwise would
// have, but it is likely that operators will welcome the improvement in performance anyway.
//
// In short, this moves:
//
// trash/$namespace/?? -> trash/$namespace/$day/??
//
// Or, in shell syntax, we are doing:
//
// mv trash/$namespace trash/$namespace-$day && \
// mkdir trash/$namespace && \
// mv trash/$namespace-$day trash/$namespace/$day
//
// This approach does the minimum number of filesystem changes to perform the migration.
func (dir *Dir) migrateTrashToPerDayDirs(now time.Time) (err error) {
defer mon.Task()(nil)(&err)
namespaces, err := dir.listNamespacesInTrash(context.Background())
for _, ns := range namespaces {
nsEncoded := PathEncoding.EncodeToString(ns)
todayDirName := now.Format("2006-01-02")
nsPath := filepath.Join(dir.trashdir(), nsEncoded)
tempTodayDirPath := filepath.Join(dir.trashdir(), nsEncoded+"-"+todayDirName)
dir.log.Info("migrating trash namespace to use per-day directories", zap.String("namespace", nsEncoded))
err = os.Rename(nsPath, tempTodayDirPath)
if err != nil {
return err
}
err = os.Mkdir(nsPath, dirPermission)
if err != nil {
return err
}
err = os.Rename(tempTodayDirPath, filepath.Join(nsPath, todayDirName))
if err != nil {
return err
}
dir.log.Info("trash namespace migration complete", zap.String("namespace", nsEncoded))
}
return nil
}
func decodeBlobInfo(namespace []byte, keyPrefix, keyDir, name string) (info blobstore.BlobInfo, ok bool) {
blobFileName := name
encodedKey := keyPrefix + blobFileName
formatVer := FormatV0
if strings.HasSuffix(blobFileName, v1PieceFileSuffix) {
formatVer = FormatV1
encodedKey = encodedKey[0 : len(encodedKey)-len(v1PieceFileSuffix)]
}
// in case we prepended '1' chars because the key was too short (1 is an invalid char in base32)
encodedKey = strings.TrimLeft(encodedKey, "1")
key, err := PathEncoding.DecodeString(encodedKey)
if err != nil {
return nil, false
}
ref := blobstore.BlobRef{
Namespace: namespace,
Key: key,
}
return newBlobInfo(ref, filepath.Join(keyDir, blobFileName), nil, formatVer), true
}
func walkNamespaceWithPrefix(ctx context.Context, log *zap.Logger, namespace []byte, nsDir, keyPrefix string, walkFunc func(blobstore.BlobInfo) error) (err error) {
keyDir := filepath.Join(nsDir, keyPrefix)
openDir, err := os.Open(keyDir)
if err != nil {
return err
}
defer func() { err = errs.Combine(err, openDir.Close()) }()
for {
// check for context done both before and after our readdir() call
if err := ctx.Err(); err != nil {
return err
}
names, err := openDir.Readdirnames(nameBatchSize)
if err != nil && !errors.Is(err, io.EOF) {
return err
}
if os.IsNotExist(err) || len(names) == 0 {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
for _, name := range names {
blobInfo, ok := decodeBlobInfo(namespace, keyPrefix, keyDir, name)
if !ok {
continue
}
err = walkFunc(blobInfo)
if err != nil {