mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2647a88994 | ||
|
|
6584bb4d54 | ||
|
|
af6b23f32d | ||
|
|
da19900464 | ||
|
|
318d868ee8 | ||
|
|
3b9a7ceef8 | ||
|
|
db13f03747 | ||
|
|
5e1671a4ad | ||
|
|
72ba251941 | ||
|
|
fd045baa4c | ||
|
|
4cc4180aa6 | ||
|
|
9d0c5ffe6a | ||
|
|
cec02fbf0e | ||
|
|
aa7d767827 | ||
|
|
529ca9032e | ||
|
|
9da5893425 |
No files matched your search
@@ -1056,18 +1056,9 @@ func (c *commandFsMergeVolumes) uploadManifestChunk(
|
||||
|
||||
uploadUrl := fmt.Sprintf("http://%s/%s", commandEnv.AdjustedUrl(assignResp.Location), assignResp.FileId)
|
||||
|
||||
jwt := security.EncodedJwt(assignResp.Auth)
|
||||
if jwt == "" {
|
||||
v := util.GetViper()
|
||||
if signingKey := v.GetString("jwt.signing.key"); signingKey != "" {
|
||||
expiresAfterSec := v.GetInt("jwt.signing.expires_after_seconds")
|
||||
jwt = security.GenJwtForVolumeServer(security.SigningKey(signingKey), expiresAfterSec, assignResp.FileId)
|
||||
}
|
||||
}
|
||||
|
||||
uploadResult, err := uploader.UploadData(ctx, data, &operation.UploadOption{
|
||||
UploadUrl: uploadUrl,
|
||||
Jwt: jwt,
|
||||
Jwt: volumeWriteJwt(assignResp.Auth, assignResp.FileId),
|
||||
})
|
||||
if err == nil && uploadResult.Error != "" {
|
||||
err = fmt.Errorf("upload: %s", uploadResult.Error)
|
||||
|
||||
+160
-62
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"go.uber.org/atomic"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -37,6 +38,8 @@ type commandFsVerify struct {
|
||||
verbose *bool
|
||||
metadataFromLog *bool
|
||||
pruneEntries *bool
|
||||
restore *restoreSource
|
||||
uploadRestored restoreUploadFn
|
||||
concurrency *int
|
||||
modifyTimeAgoAtSec int64
|
||||
writer io.Writer
|
||||
@@ -51,13 +54,32 @@ func (c *commandFsVerify) Name() string {
|
||||
func (c *commandFsVerify) Help() string {
|
||||
return `recursively verify all files under a directory
|
||||
|
||||
fs.verify [-v] [-modifyTimeAgo 1h] [-pruneEntries] [-concurrency 4] /buckets/dir
|
||||
fs.verify [-v] [-modifyTimeAgo 1h] [-pruneEntries] [-restoreFrom /dir] [-concurrency 4] /buckets/dir
|
||||
|
||||
-pruneEntries deletes filer entries whose needles are missing from every
|
||||
volume location holding the volume (data lost, e.g. after a volume
|
||||
truncation). The delete only applies when the entry is unchanged since
|
||||
verification, so a re-uploaded file is never pruned.
|
||||
|
||||
-restoreFrom recovers needles missing from every location out of regular
|
||||
volume files left on disk, <collection>_<vid>.dat/.idx or <vid>.dat/.idx in
|
||||
the given directory, opened read-only. A needle is restorable when the last
|
||||
live .idx record of its key holds the chunk's cookie, passes its CRC, covers
|
||||
the chunk's size and, for an MD5-sized chunk ETag, matches it. A later
|
||||
tombstone in the .idx does not prevent the restore: the filer still
|
||||
references the needle, so its intact bytes are kept.
|
||||
The bytes are uploaded in their stored form (a gzipped needle stays
|
||||
gzipped) to a file id the filer assigns in the volume file's collection,
|
||||
read back, and the entry's chunk is repointed at them, keeping its offset,
|
||||
size, ETag and flags. All restorable chunks of an entry go in one update,
|
||||
which only applies when the entry is unchanged since verification.
|
||||
A missing chunk held in a chunk manifest is restored by uploading a
|
||||
rewritten manifest; the chunks held by a restored manifest are checked on
|
||||
the next run. Chunks with a cipher key are not restored, nor is an entry
|
||||
without a TTL whose path rule sets one, since the update would take it.
|
||||
An entry is never pruned while the restore source holds, or cannot be read
|
||||
for, a missing needle of it.
|
||||
|
||||
`
|
||||
}
|
||||
|
||||
@@ -74,10 +96,22 @@ func (c *commandFsVerify) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
c.concurrency = fsVerifyCommand.Int("concurrency", 0, "number of parallel verification per volume server")
|
||||
c.metadataFromLog = fsVerifyCommand.Bool("metadataFromLog", false, "Using filer log to get metadata")
|
||||
c.pruneEntries = fsVerifyCommand.Bool("pruneEntries", false, "delete filer entries whose needles are missing from all volume locations (data lost); a changed entry is never deleted")
|
||||
restoreFrom := fsVerifyCommand.String("restoreFrom", "", "directory of leftover <collection>_<vid>.dat/.idx files to restore needles missing from all volume locations")
|
||||
if err = fsVerifyCommand.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *restoreFrom != "" {
|
||||
if c.restore, err = openRestoreSource(*restoreFrom); err != nil {
|
||||
return fmt.Errorf("open restore source: %w", err)
|
||||
}
|
||||
c.uploadRestored = c.uploadRestoredBytes
|
||||
defer func() {
|
||||
c.restore.Close()
|
||||
c.restore = nil
|
||||
}()
|
||||
}
|
||||
|
||||
path, parseErr := commandEnv.parseUrl(findInputDirectory(fsVerifyCommand.Args()))
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
@@ -105,15 +139,19 @@ func (c *commandFsVerify) Do(args []string, commandEnv *CommandEnv, writer io.Wr
|
||||
defer close(c.waitChan[volumeServerStr])
|
||||
}
|
||||
}
|
||||
var fCount, eCount, pCount uint64
|
||||
var counts fsVerifyCounts
|
||||
if *c.metadataFromLog {
|
||||
var wg sync.WaitGroup
|
||||
fCount, eCount, pCount, err = c.verifyProcessMetadata(path, &wg)
|
||||
counts, err = c.verifyProcessMetadata(path, &wg)
|
||||
wg.Wait()
|
||||
} else {
|
||||
fCount, eCount, pCount, err = c.verifyTraverseBfs(path)
|
||||
counts, err = c.verifyTraverseBfs(path)
|
||||
}
|
||||
if c.restore != nil {
|
||||
fmt.Fprintf(writer, "verified %d files, error %d files, pruned %d entries, restored %d entries \n", counts.verified, counts.errors, counts.pruned, counts.restored)
|
||||
} else {
|
||||
fmt.Fprintf(writer, "verified %d files, error %d files, pruned %d entries \n", counts.verified, counts.errors, counts.pruned)
|
||||
}
|
||||
fmt.Fprintf(writer, "verified %d files, error %d files, pruned %d entries \n", fCount, eCount, pCount)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -164,31 +202,65 @@ type ItemEntry struct {
|
||||
rawChunks []*filer_pb.FileChunk
|
||||
path util.FullPath
|
||||
attr *filer_pb.FuseAttributes
|
||||
// a manifest could not be resolved, so chunks are the readable ones
|
||||
manifestUnresolved bool
|
||||
}
|
||||
|
||||
type fsVerifyCounts struct {
|
||||
verified, errors, pruned, restored uint64
|
||||
}
|
||||
|
||||
// repairEntry restores an entry's missing needles when a restore source is
|
||||
// set, and prunes it when none of them is restorable.
|
||||
func (c *commandFsVerify) repairEntry(path util.FullPath, attr *filer_pb.FuseAttributes, rawChunks, missingChunks []*filer_pb.FileChunk, counts *fsVerifyCounts) {
|
||||
if len(missingChunks) == 0 {
|
||||
return
|
||||
}
|
||||
if c.restore != nil {
|
||||
restored, restorable := c.restoreEntry(path, attr, rawChunks, missingChunks)
|
||||
if restored {
|
||||
counts.restored++
|
||||
}
|
||||
if restorable {
|
||||
return
|
||||
}
|
||||
}
|
||||
if !*c.pruneEntries {
|
||||
return
|
||||
}
|
||||
pruned, pruneErr := c.pruneEntry(path, attr, rawChunks)
|
||||
if pruneErr != nil {
|
||||
fmt.Fprintf(c.writer, "prune %s failed: %v\n", path, pruneErr)
|
||||
} else if pruned {
|
||||
counts.pruned++
|
||||
}
|
||||
}
|
||||
|
||||
// resolveAndVerify expands chunk manifests, cut to their spans since chunks
|
||||
// past a shortened manifest are never read, and verifies the entry's needles.
|
||||
// An unresolvable manifest is an entry-level failure even when raw chunks are
|
||||
// healthy; raw chunks are still checked so a missing manifest needle can be pruned.
|
||||
func (c *commandFsVerify) resolveAndVerify(entryPath string, chunks []*filer_pb.FileChunk, errorChunksCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, hasMissingNeedles bool) {
|
||||
// healthy; the readable chunks are still checked so a missing manifest needle
|
||||
// can be pruned.
|
||||
func (c *commandFsVerify) resolveAndVerify(entryPath string, chunks []*filer_pb.FileChunk, errorChunksCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, missingChunks []*filer_pb.FileChunk) {
|
||||
dataChunks := chunks
|
||||
manifestResolveFailed := false
|
||||
if resolved, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), chunks, 0, math.MaxInt64, nil, true); resolveErr == nil {
|
||||
dataChunks = append(resolved, manifestChunks...)
|
||||
} else {
|
||||
manifestResolveFailed = true
|
||||
fmt.Fprintf(c.writer, "file: %s failed to resolve chunk manifest (%v), verifying raw chunks\n", entryPath, resolveErr)
|
||||
fmt.Fprintf(c.writer, "file: %s failed to resolve chunk manifest (%v), verifying readable chunks\n", entryPath, resolveErr)
|
||||
dataChunks = readableChunks(filer.LookupFn(c.env), chunks, math.MaxInt64)
|
||||
}
|
||||
verified, hasMissingNeedles = c.verifyEntry(entryPath, dataChunks, errorChunksCount, wg)
|
||||
verified, missingChunks = c.verifyEntry(entryPath, dataChunks, errorChunksCount, wg)
|
||||
if manifestResolveFailed && verified {
|
||||
// an unreadable manifest is an entry-level failure even with healthy raw needles
|
||||
verified = false
|
||||
errorChunksCount.CompareAndSwap(0, 1)
|
||||
}
|
||||
return verified, hasMissingNeedles
|
||||
return verified, missingChunks
|
||||
}
|
||||
|
||||
func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup) (fileCount uint64, errCount uint64, prunedCount uint64, err error) {
|
||||
func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup) (counts fsVerifyCounts, err error) {
|
||||
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
message := resp.EventNotification
|
||||
if resp.EventNotification.NewEntry == nil {
|
||||
@@ -200,7 +272,7 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
|
||||
}
|
||||
entryPath := fmt.Sprintf("%s/%s", message.NewParentPath, message.NewEntry.Name)
|
||||
errorChunksCount := atomic.NewUint64(0)
|
||||
verified, hasMissingNeedles := c.resolveAndVerify(entryPath, message.NewEntry.Chunks, errorChunksCount, wg)
|
||||
verified, missingChunks := c.resolveAndVerify(entryPath, message.NewEntry.Chunks, errorChunksCount, wg)
|
||||
if !verified {
|
||||
if err = c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
entryResp, errReq := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
@@ -216,18 +288,9 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
|
||||
if entryResp.Entry.Attributes.Mtime == message.NewEntry.Attributes.Mtime &&
|
||||
bytes.Equal(entryResp.Entry.Attributes.Md5, message.NewEntry.Attributes.Md5) {
|
||||
fmt.Fprintf(c.writer, "file: %s needles:%d failed:%d\n", entryPath, chunkCount, errorChunksCount.Load())
|
||||
errCount++
|
||||
if *c.pruneEntries && hasMissingNeedles {
|
||||
pruned, pruneErr := c.pruneEntry(
|
||||
util.NewFullPath(message.NewParentPath, message.NewEntry.Name),
|
||||
message.NewEntry.Attributes,
|
||||
message.NewEntry.Chunks)
|
||||
if pruneErr != nil {
|
||||
fmt.Fprintf(c.writer, "prune %s failed: %v\n", entryPath, pruneErr)
|
||||
} else if pruned {
|
||||
prunedCount++
|
||||
}
|
||||
}
|
||||
counts.errors++
|
||||
c.repairEntry(util.NewFullPath(message.NewParentPath, message.NewEntry.Name),
|
||||
message.NewEntry.Attributes, message.NewEntry.Chunks, missingChunks, &counts)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
@@ -238,7 +301,7 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
|
||||
if *c.verbose {
|
||||
fmt.Fprintf(c.writer, "file: %s needles:%d verified\n", entryPath, chunkCount)
|
||||
}
|
||||
fileCount++
|
||||
counts.verified++
|
||||
return nil
|
||||
}
|
||||
metadataFollowOption := &pb.MetadataFollowOption{
|
||||
@@ -255,7 +318,29 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
|
||||
FilerTokenSource: c.env.option.FilerTokenSource,
|
||||
}
|
||||
err = pb.FollowMetadata(c.env.FilerAddress(), c.env.option.GrpcDialOption, metadataFollowOption, processEventFn)
|
||||
return fileCount, errCount, prunedCount, err
|
||||
return counts, err
|
||||
}
|
||||
|
||||
// readableChunks expands the manifests it can read, one level at a time and
|
||||
// cut to their spans like ResolveChunkManifest, and keeps each one it cannot
|
||||
// read as a chunk to verify, so a missing manifest at any depth is checked
|
||||
// like any other needle. Chunks starting at or past end are never read.
|
||||
func readableChunks(lookupFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, end int64) (readable []*filer_pb.FileChunk) {
|
||||
for _, chunk := range chunks {
|
||||
if chunk.Offset >= end {
|
||||
continue
|
||||
}
|
||||
readable = append(readable, chunk)
|
||||
if !chunk.IsChunkManifest {
|
||||
continue
|
||||
}
|
||||
held, err := filer.ResolveOneChunkManifest(context.Background(), lookupFn, chunk, nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
readable = append(readable, readableChunks(lookupFn, held, min(end, chunk.Offset+int64(chunk.Size)))...)
|
||||
}
|
||||
return readable
|
||||
}
|
||||
|
||||
// isNeedleMissingError reports whether a VolumeNeedleStatus error means the
|
||||
@@ -286,13 +371,12 @@ func isNeedleMissingError(err error) bool {
|
||||
}
|
||||
|
||||
// verifyEntry verifies all chunks of an entry. It returns verified=false when
|
||||
// any chunk failed. hasMissingNeedles is true when at least one needle is
|
||||
// missing from every volume location holding its volume, i.e. the data is
|
||||
// lost rather than a transient or routing error.
|
||||
func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk, errorCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, hasMissingNeedles bool) {
|
||||
// any chunk failed. missingChunks are the chunks whose needle is missing from
|
||||
// every volume location holding its volume, i.e. the data is lost rather than
|
||||
// a transient or routing error.
|
||||
func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk, errorCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, missingChunks []*filer_pb.FileChunk) {
|
||||
fileMsg := fmt.Sprintf("file:%s", path)
|
||||
itemIsVerifed := atomic.NewBool(true)
|
||||
hasMissingNeedlesFlag := atomic.NewBool(false)
|
||||
// tracks this entry's in-flight verifications so the missing-needle
|
||||
// decision at the end of each chunk is deterministic
|
||||
itemWg := &sync.WaitGroup{}
|
||||
@@ -353,7 +437,7 @@ func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk,
|
||||
}
|
||||
itemWg.Wait()
|
||||
if chunkMissingLocations.Load() == uint64(len(volumeIds)) {
|
||||
hasMissingNeedlesFlag.Store(true)
|
||||
missingChunks = append(missingChunks, chunk)
|
||||
}
|
||||
} else {
|
||||
if !*c.metadataFromLog {
|
||||
@@ -365,10 +449,12 @@ func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk,
|
||||
itemIsVerifed.Store(false)
|
||||
errorCount.Add(1)
|
||||
}
|
||||
break
|
||||
if c.restore == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return itemIsVerifed.Load(), hasMissingNeedlesFlag.Load()
|
||||
return itemIsVerifed.Load(), missingChunks
|
||||
}
|
||||
|
||||
// deleteEntryCutoff splits an entry mtime into the conditional-delete fields:
|
||||
@@ -394,7 +480,6 @@ func deleteEntryCutoff(mtimeSec int64, mtimeNsec int32) (sec, ns int64, ok bool)
|
||||
// entry is only counted as pruned when a follow-up lookup confirms it is gone.
|
||||
func (c *commandFsVerify) pruneEntry(path util.FullPath, attr *filer_pb.FuseAttributes, expectedChunks []*filer_pb.FileChunk) (pruned bool, err error) {
|
||||
dir, name := path.DirAndName()
|
||||
expectedIds := chunkFingerprints(expectedChunks)
|
||||
lookupErr := c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
lookupResp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
@@ -406,16 +491,7 @@ func (c *commandFsVerify) pruneEntry(path util.FullPath, attr *filer_pb.FuseAttr
|
||||
}
|
||||
return err
|
||||
}
|
||||
att := lookupResp.Entry.GetAttributes()
|
||||
if att.GetMtime() != attr.GetMtime() || att.GetMtimeNs() != attr.GetMtimeNs() {
|
||||
fmt.Fprintf(c.writer, "skip pruning %s: entry changed since verification\n", path)
|
||||
return nil
|
||||
}
|
||||
if md5 := attr.GetMd5(); len(md5) > 0 && !bytes.Equal(att.GetMd5(), md5) {
|
||||
fmt.Fprintf(c.writer, "skip pruning %s: entry changed since verification\n", path)
|
||||
return nil
|
||||
}
|
||||
if !chunksEqual(chunkFingerprints(lookupResp.Entry.GetChunks()), expectedIds) {
|
||||
if entryChangedSince(lookupResp.Entry, attr, expectedChunks) {
|
||||
fmt.Fprintf(c.writer, "skip pruning %s: entry changed since verification\n", path)
|
||||
return nil
|
||||
}
|
||||
@@ -463,6 +539,19 @@ func (c *commandFsVerify) pruneEntry(path util.FullPath, attr *filer_pb.FuseAttr
|
||||
return pruned, lookupErr
|
||||
}
|
||||
|
||||
// entryChangedSince reports whether the entry differs from the one verified,
|
||||
// by mtime, md5, or chunk set (a same-second rewrite changes only the chunks).
|
||||
func entryChangedSince(entry *filer_pb.Entry, attr *filer_pb.FuseAttributes, chunks []*filer_pb.FileChunk) bool {
|
||||
att := entry.GetAttributes()
|
||||
if att.GetMtime() != attr.GetMtime() || att.GetMtimeNs() != attr.GetMtimeNs() {
|
||||
return true
|
||||
}
|
||||
if md5 := attr.GetMd5(); len(md5) > 0 && !bytes.Equal(att.GetMd5(), md5) {
|
||||
return true
|
||||
}
|
||||
return !chunksEqual(chunkFingerprints(entry.GetChunks()), chunkFingerprints(chunks))
|
||||
}
|
||||
|
||||
// chunkFingerprints maps the file id of every chunk to a set, so two chunk
|
||||
// lists count as identical when they reference the same needles.
|
||||
func chunkFingerprints(chunks []*filer_pb.FileChunk) map[string]struct{} {
|
||||
@@ -488,27 +577,35 @@ func chunksEqual(a, b map[string]struct{}) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *commandFsVerify) verifyTraverseBfs(path string) (fileCount uint64, errCount uint64, prunedCount uint64, err error) {
|
||||
func (c *commandFsVerify) verifyTraverseBfs(path string) (counts fsVerifyCounts, err error) {
|
||||
timeNowAtSec := time.Now().Unix()
|
||||
return fileCount, errCount, prunedCount, doTraverseBfsAndSaving(c.env, c.writer, path, false, false,
|
||||
err = doTraverseBfsAndSaving(c.env, c.writer, path, false, false,
|
||||
func(ctx context.Context, entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
|
||||
if c.modifyTimeAgoAtSec > 0 {
|
||||
if entry.Entry.Attributes != nil && c.modifyTimeAgoAtSec < timeNowAtSec-entry.Entry.Attributes.Mtime {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
entryPath := util.NewFullPath(entry.Dir, entry.Entry.Name)
|
||||
manifestUnresolved := false
|
||||
dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), entry.Entry.GetChunks(), 0, math.MaxInt64, nil, true)
|
||||
if resolveErr != nil {
|
||||
return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
|
||||
if c.restore == nil {
|
||||
return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
|
||||
}
|
||||
// a missing manifest needle may be restorable
|
||||
fmt.Fprintf(c.writer, "file: %s failed to resolve chunk manifest (%v), verifying readable chunks\n", entryPath, resolveErr)
|
||||
dataChunks, manifestChunks, manifestUnresolved = readableChunks(filer.LookupFn(c.env), entry.Entry.GetChunks(), math.MaxInt64), nil, true
|
||||
}
|
||||
dataChunks = append(dataChunks, manifestChunks...)
|
||||
if len(dataChunks) > 0 {
|
||||
select {
|
||||
case outputChan <- &ItemEntry{
|
||||
chunks: dataChunks,
|
||||
rawChunks: entry.Entry.GetChunks(),
|
||||
path: util.NewFullPath(entry.Dir, entry.Entry.Name),
|
||||
attr: entry.Entry.GetAttributes(),
|
||||
chunks: dataChunks,
|
||||
rawChunks: entry.Entry.GetChunks(),
|
||||
path: entryPath,
|
||||
attr: entry.Entry.GetAttributes(),
|
||||
manifestUnresolved: manifestUnresolved,
|
||||
}:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
@@ -522,22 +619,23 @@ func (c *commandFsVerify) verifyTraverseBfs(path string) (fileCount uint64, errC
|
||||
for itemEntry := range outputChan {
|
||||
i := itemEntry.(*ItemEntry)
|
||||
itemPath := string(i.path)
|
||||
if verified, hasMissingNeedles := c.verifyEntry(itemPath, i.chunks, itemErrCount, &wg); verified {
|
||||
verified, missingChunks := c.verifyEntry(itemPath, i.chunks, itemErrCount, &wg)
|
||||
if verified && i.manifestUnresolved {
|
||||
verified = false
|
||||
itemErrCount.Add(1)
|
||||
}
|
||||
if verified {
|
||||
if *c.verbose {
|
||||
fmt.Fprintf(c.writer, "file: %s needles:%d verified\n", itemPath, len(i.chunks))
|
||||
}
|
||||
fileCount++
|
||||
} else if *c.pruneEntries && hasMissingNeedles {
|
||||
pruned, pruneErr := c.pruneEntry(i.path, i.attr, i.rawChunks)
|
||||
if pruneErr != nil {
|
||||
fmt.Fprintf(c.writer, "prune %s failed: %v\n", itemPath, pruneErr)
|
||||
} else if pruned {
|
||||
prunedCount++
|
||||
}
|
||||
counts.verified++
|
||||
} else {
|
||||
c.repairEntry(i.path, i.attr, i.rawChunks, missingChunks, &counts)
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
errCount = itemErrCount.Load()
|
||||
counts.errors = itemErrCount.Load()
|
||||
return nil
|
||||
})
|
||||
return counts, err
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// restoreUploadFn stores data under a new file id; gzipped says data is
|
||||
// already gzip-compressed and must be stored that way.
|
||||
type restoreUploadFn func(target restoreTarget, data []byte, gzipped bool, mimeType string) (fileId string, err error)
|
||||
|
||||
// restoreTarget is where a restored needle is assigned: the entry's path and
|
||||
// lifetime, so the new needle expires with the entry, and the collection.
|
||||
type restoreTarget struct {
|
||||
path util.FullPath
|
||||
collection string
|
||||
ttlSec int32
|
||||
}
|
||||
|
||||
type restorableChunk struct {
|
||||
chunk *filer_pb.FileChunk
|
||||
collection string
|
||||
}
|
||||
|
||||
// restoreEntry copies the restorable missing chunks of an entry from the
|
||||
// restore source into new needles and repoints the entry at them in one
|
||||
// update. restorable reports that at least one missing chunk has intact bytes
|
||||
// in the restore source, or may have, whether or not the update landed.
|
||||
func (c *commandFsVerify) restoreEntry(path util.FullPath, attr *filer_pb.FuseAttributes, rawChunks, missing []*filer_pb.FileChunk) (restored, restorable bool) {
|
||||
var ready []restorableChunk
|
||||
mayHold := false
|
||||
seen := make(map[string]bool)
|
||||
for _, chunk := range missing {
|
||||
fileId := chunk.GetFileIdString()
|
||||
if seen[fileId] {
|
||||
continue
|
||||
}
|
||||
seen[fileId] = true
|
||||
_, collection, err := c.readRestorableNeedle(chunk)
|
||||
if err != nil {
|
||||
fmt.Fprintf(c.writer, "not restorable %s chunk %s: %v\n", path, fileId, err)
|
||||
mayHold = mayHold || restoreSourceMayHold(err)
|
||||
continue
|
||||
}
|
||||
ready = append(ready, restorableChunk{chunk: chunk, collection: collection})
|
||||
}
|
||||
if len(ready) == 0 {
|
||||
return false, mayHold
|
||||
}
|
||||
|
||||
dir, name := path.DirAndName()
|
||||
var current *filer_pb.Entry
|
||||
err := c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current = resp.Entry
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
fmt.Fprintf(c.writer, "skip restoring %s: entry deleted since verification\n", path)
|
||||
return false, true
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(c.writer, "restore %s failed: %v\n", path, err)
|
||||
return false, true
|
||||
}
|
||||
if entryChangedSince(current, attr, rawChunks) {
|
||||
fmt.Fprintf(c.writer, "skip restoring %s: entry changed since verification\n", path)
|
||||
return false, true
|
||||
}
|
||||
|
||||
ttlSec := current.GetAttributes().GetTtlSec()
|
||||
if ttlSec == 0 {
|
||||
// the filer gives an entry and needles without a TTL the path rule's
|
||||
ruleTtlSec, err := c.pathRuleTtlSec(path)
|
||||
if err != nil {
|
||||
fmt.Fprintf(c.writer, "restore %s failed: %v\n", path, err)
|
||||
return false, true
|
||||
}
|
||||
if ruleTtlSec > 0 {
|
||||
fmt.Fprintf(c.writer, "skip restoring %s: the entry has no TTL, but its path rule would give the restored entry and needles one\n", path)
|
||||
return false, true
|
||||
}
|
||||
}
|
||||
newFileIds := make(map[string]string)
|
||||
var uploaded []orphanedNeedle
|
||||
for _, r := range ready {
|
||||
// read again rather than held, so one needle at a time is in memory
|
||||
oldFileId := r.chunk.GetFileIdString()
|
||||
n, _, err := c.readRestorableNeedle(r.chunk)
|
||||
var fileId string
|
||||
if err == nil {
|
||||
fileId, err = c.uploadRestored(restoreTarget{path, r.collection, ttlSec}, n.Data, n.IsCompressed(), restoreMimeType(n))
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(c.writer, "not restored %s chunk %s: %v\n", path, oldFileId, err)
|
||||
continue
|
||||
}
|
||||
newFileIds[oldFileId] = fileId
|
||||
uploaded = append(uploaded, newOrphanedNeedle(fileId))
|
||||
}
|
||||
if len(newFileIds) == 0 {
|
||||
return false, true
|
||||
}
|
||||
|
||||
updated := proto.Clone(current).(*filer_pb.Entry)
|
||||
applied := make(map[string]string)
|
||||
for i, chunk := range updated.Chunks {
|
||||
oldFileId := chunk.GetFileIdString()
|
||||
if fileId, found := newFileIds[oldFileId]; found {
|
||||
updated.Chunks[i] = withFileId(chunk, fileId)
|
||||
applied[oldFileId] = fileId
|
||||
} else if chunk.IsChunkManifest {
|
||||
rewritten, manifestUploads, err := c.rewriteRestoredManifest(restoreTarget{path, ready[0].collection, ttlSec}, chunk, newFileIds, applied)
|
||||
if err != nil {
|
||||
fmt.Fprintf(c.writer, "restore %s: rewrite manifest %s: %v\n", path, oldFileId, err)
|
||||
continue
|
||||
}
|
||||
if rewritten != nil {
|
||||
updated.Chunks[i] = rewritten
|
||||
uploaded = append(uploaded, manifestUploads...)
|
||||
}
|
||||
}
|
||||
}
|
||||
var unused []orphanedNeedle
|
||||
for _, oldFileId := range slices.Sorted(maps.Keys(newFileIds)) {
|
||||
if _, found := applied[oldFileId]; !found {
|
||||
fmt.Fprintf(c.writer, "not restored %s chunk %s: no chunk list it is in could be rewritten\n", path, oldFileId)
|
||||
unused = append(unused, newOrphanedNeedle(newFileIds[oldFileId]))
|
||||
}
|
||||
}
|
||||
deleteOrphanedNeedles(c.env, path, unused, true)
|
||||
if len(applied) == 0 {
|
||||
return false, true
|
||||
}
|
||||
|
||||
// A conditional create replaces the entry: UpdateEntry refuses while the
|
||||
// stored entry holds a manifest the filer cannot read, which is the very
|
||||
// state a restored manifest repairs.
|
||||
err = c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return filer_pb.CreateEntry(context.Background(), client, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: updated,
|
||||
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
|
||||
{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: current},
|
||||
}},
|
||||
})
|
||||
})
|
||||
if errors.Is(err, filer_pb.ErrPreconditionFailed) {
|
||||
fmt.Fprintf(c.writer, "skip restoring %s: entry changed since verification\n", path)
|
||||
deleteOrphanedNeedles(c.env, path, uploaded, true)
|
||||
return false, true
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrReadOnly) {
|
||||
fmt.Fprintf(c.writer, "skip restoring %s: path is read-only\n", path)
|
||||
deleteOrphanedNeedles(c.env, path, uploaded, true)
|
||||
return false, true
|
||||
}
|
||||
if err != nil {
|
||||
// the update may still have landed, so the new needles stay
|
||||
fmt.Fprintf(c.writer, "restore %s failed: %v\n", path, err)
|
||||
return false, true
|
||||
}
|
||||
for _, oldFileId := range slices.Sorted(maps.Keys(applied)) {
|
||||
fmt.Fprintf(c.writer, "restored %s chunk %s -> %s\n", path, oldFileId, applied[oldFileId])
|
||||
}
|
||||
for _, r := range ready {
|
||||
if _, found := applied[r.chunk.GetFileIdString()]; found && r.chunk.IsChunkManifest {
|
||||
fmt.Fprintf(c.writer, "restored %s manifest %s: run fs.verify again to check the chunks it holds\n", path, r.chunk.GetFileIdString())
|
||||
}
|
||||
}
|
||||
return true, true
|
||||
}
|
||||
|
||||
// pathRuleTtlSec is the TTL the filer.conf rule for path sets, as the filer
|
||||
// reads it.
|
||||
func (c *commandFsVerify) pathRuleTtlSec(path util.FullPath) (int32, error) {
|
||||
fc, err := filer.ReadFilerConfFromClient(context.Background(), c.env, c.env.MasterClient)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
ttl, _ := needle.ReadTTL(fc.MatchStorageRule(string(path)).GetTtl())
|
||||
return int32(ttl.Minutes()) * 60, nil
|
||||
}
|
||||
|
||||
// readRestorableNeedle reads a missing chunk's needle from the restore source
|
||||
// and checks it is the content the chunk names.
|
||||
func (c *commandFsVerify) readRestorableNeedle(chunk *filer_pb.FileChunk) (*needle.Needle, string, error) {
|
||||
vid := needle.VolumeId(chunk.Fid.GetVolumeId())
|
||||
n, err := c.restore.readNeedle(vid, types.NeedleId(chunk.Fid.GetFileKey()), types.Cookie(chunk.Fid.GetCookie()))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if len(chunk.CipherKey) > 0 {
|
||||
return nil, "", restoreSourceMayHoldError{errors.New("encrypted chunk, skipped")}
|
||||
}
|
||||
if n.IsChunkedManifest() {
|
||||
return nil, "", restoreSourceMayHoldError{errors.New("needle is a volume-level chunk manifest")}
|
||||
}
|
||||
if err := checkRestoredContent(chunk, n); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return n, c.restore.volumes[vid].collection, nil
|
||||
}
|
||||
|
||||
// checkRestoredContent compares the needle's content with what the chunk
|
||||
// records: a manifest must parse; data must cover the chunk's size (a
|
||||
// truncated file keeps a shorter size) and match an MD5-sized ETag.
|
||||
func checkRestoredContent(chunk *filer_pb.FileChunk, n *needle.Needle) error {
|
||||
data := n.Data
|
||||
if n.IsCompressed() || chunk.IsCompressed {
|
||||
decompressed, err := util.DecompressData(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decompress: %w", err)
|
||||
}
|
||||
data = decompressed
|
||||
}
|
||||
if chunk.IsChunkManifest {
|
||||
if err := proto.Unmarshal(data, &filer_pb.FileChunkManifest{}); err != nil {
|
||||
return fmt.Errorf("manifest does not parse: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if uint64(len(data)) < chunk.Size {
|
||||
return fmt.Errorf("needle holds %d bytes, chunk needs %d", len(data), chunk.Size)
|
||||
}
|
||||
if chunk.SseType == filer_pb.SSEType_NONE && !chunkETagMatches(chunk.ETag, data) {
|
||||
err := fmt.Errorf("content does not match chunk etag %s", chunk.ETag)
|
||||
if util.CheckDigest(util.DigestMd5) != nil {
|
||||
// without MD5 an MD5 ETag of intact content cannot match either
|
||||
return restoreSourceMayHoldError{err}
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// chunkETagMatches checks an ETag holding a 16-byte digest, base64 or hex,
|
||||
// against MD5 and truncated SHA-256 of data. Other ETags, like the needle CRC
|
||||
// older writers recorded, say nothing about the content and pass.
|
||||
func chunkETagMatches(etag string, data []byte) bool {
|
||||
digest, err := base64.StdEncoding.DecodeString(etag)
|
||||
if err != nil || len(digest) != 16 {
|
||||
if digest, err = hex.DecodeString(etag); err != nil || len(digest) != 16 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if bytes.Equal(digest, util.Md5For(util.DigestSha256, data)) {
|
||||
return true
|
||||
}
|
||||
return util.CheckDigest(util.DigestMd5) == nil && bytes.Equal(digest, util.Md5For(util.DigestMd5, data))
|
||||
}
|
||||
|
||||
// restoreMimeType keeps the needle's mime unless the volume server would gzip
|
||||
// an uncompressed needle for it, which would change its stored form.
|
||||
func restoreMimeType(n *needle.Needle) string {
|
||||
mimeType := string(n.Mime)
|
||||
if n.IsCompressed() {
|
||||
return mimeType
|
||||
}
|
||||
if compress, sure := util.IsCompressableFileType("", mimeType); mimeType == "" || compress && sure {
|
||||
return "application/octet-stream"
|
||||
}
|
||||
return mimeType
|
||||
}
|
||||
|
||||
func withFileId(chunk *filer_pb.FileChunk, fileId string) *filer_pb.FileChunk {
|
||||
repointed := proto.Clone(chunk).(*filer_pb.FileChunk)
|
||||
repointed.Fid, _ = filer_pb.ToFileIdObject(fileId)
|
||||
repointed.FileId = ""
|
||||
return repointed
|
||||
}
|
||||
|
||||
func newOrphanedNeedle(fileId string) orphanedNeedle {
|
||||
fid, _ := filer_pb.ToFileIdObject(fileId)
|
||||
return orphanedNeedle{volumeId: fid.GetVolumeId(), fileId: fileId}
|
||||
}
|
||||
|
||||
// rewriteRestoredManifest repoints the chunks a manifest holds, nested
|
||||
// manifests included, and stores the result as a new manifest needle. It
|
||||
// returns nil when the manifest holds none of newFileIds, and the manifest
|
||||
// needles it uploaded otherwise.
|
||||
func (c *commandFsVerify) rewriteRestoredManifest(target restoreTarget, manifest *filer_pb.FileChunk, newFileIds, applied map[string]string) (*filer_pb.FileChunk, []orphanedNeedle, error) {
|
||||
if len(manifest.CipherKey) > 0 {
|
||||
return nil, nil, errors.New("encrypted manifest")
|
||||
}
|
||||
held, err := filer.ResolveOneChunkManifest(context.Background(), filer.LookupFn(c.env), manifest, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
repointed := make(map[string]string)
|
||||
var uploaded []orphanedNeedle
|
||||
fail := func(err error) (*filer_pb.FileChunk, []orphanedNeedle, error) {
|
||||
deleteOrphanedNeedles(c.env, target.path, uploaded, true)
|
||||
return nil, nil, err
|
||||
}
|
||||
for i, chunk := range held {
|
||||
oldFileId := chunk.GetFileIdString()
|
||||
if fileId, found := newFileIds[oldFileId]; found {
|
||||
held[i] = withFileId(chunk, fileId)
|
||||
repointed[oldFileId] = fileId
|
||||
} else if chunk.IsChunkManifest {
|
||||
nested, nestedUploads, err := c.rewriteRestoredManifest(target, chunk, newFileIds, repointed)
|
||||
if err != nil {
|
||||
// the parent keeps referencing it as before
|
||||
fmt.Fprintf(c.writer, "restore %s: rewrite manifest %s: %v\n", target.path, oldFileId, err)
|
||||
continue
|
||||
}
|
||||
if nested != nil {
|
||||
held[i] = nested
|
||||
uploaded = append(uploaded, nestedUploads...)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(repointed) == 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
filer_pb.BeforeEntrySerialization(held)
|
||||
blob, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held})
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
fileId, err := c.uploadRestored(target, blob, false, "")
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
maps.Copy(applied, repointed)
|
||||
// the ETag stays: an entry without an md5 derives its own from it
|
||||
rewritten := withFileId(manifest, fileId)
|
||||
rewritten.IsCompressed = false
|
||||
return rewritten, append(uploaded, newOrphanedNeedle(fileId)), nil
|
||||
}
|
||||
|
||||
// uploadRestoredBytes assigns a file id through the filer, uploads data in
|
||||
// the given stored form, and reads it back: the restore only counts when the
|
||||
// volume server holds exactly these bytes, gzipped exactly when asked.
|
||||
func (c *commandFsVerify) uploadRestoredBytes(target restoreTarget, data []byte, gzipped bool, mimeType string) (string, error) {
|
||||
var assign *filer_pb.AssignVolumeResponse
|
||||
err := c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Collection: target.collection,
|
||||
TtlSec: target.ttlSec,
|
||||
Path: target.path.Sanitized(),
|
||||
ExpectedDataSize: uint64(len(data)),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
if resp.Location == nil {
|
||||
return errors.New("no location")
|
||||
}
|
||||
assign = resp
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("assign volume: %w", err)
|
||||
}
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
url := fmt.Sprintf("http://%s/%s", c.env.AdjustedUrl(assign.Location), assign.FileId)
|
||||
option := &operation.UploadOption{
|
||||
UploadUrl: url,
|
||||
MimeType: mimeType,
|
||||
IsInputCompressed: gzipped,
|
||||
Jwt: volumeWriteJwt(assign.Auth, assign.FileId),
|
||||
}
|
||||
if !gzipped {
|
||||
// keeps the uploader from compressing; the checksum it computes
|
||||
// on its regular path is supplied here
|
||||
option.IsReplication = true
|
||||
option.ContentCrc32c = needle.ContentCrc32c(data)
|
||||
}
|
||||
result, err := uploader.UploadData(context.Background(), data, option)
|
||||
if err == nil && result.Error != "" {
|
||||
err = errors.New(result.Error)
|
||||
}
|
||||
if err == nil {
|
||||
err = readBackRestored(url, assign.FileId, data, gzipped)
|
||||
}
|
||||
if err != nil {
|
||||
deleteOrphanedNeedles(c.env, target.path, []orphanedNeedle{newOrphanedNeedle(assign.FileId)}, true)
|
||||
return "", fmt.Errorf("upload %s: %w", assign.FileId, err)
|
||||
}
|
||||
return assign.FileId, nil
|
||||
}
|
||||
|
||||
func readBackRestored(url, fileId string, data []byte, gzipped bool) error {
|
||||
resp, body, err := readUrl(url, filer.JwtForVolumeServer(fileId))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read back: %w", err)
|
||||
}
|
||||
defer util_http.CloseResponse(resp)
|
||||
got, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read back: %w", err)
|
||||
}
|
||||
if storedGzipped := resp.Header.Get("Content-Encoding") == "gzip"; storedGzipped != gzipped {
|
||||
return fmt.Errorf("read back: stored gzipped=%v, want %v", storedGzipped, gzipped)
|
||||
}
|
||||
if !bytes.Equal(got, data) {
|
||||
return fmt.Errorf("read back %d bytes differ from the %d uploaded", len(got), len(data))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// volumeWriteJwt is the assignment's write token, or one signed with the
|
||||
// configured key when the filer returned none.
|
||||
func volumeWriteJwt(auth, fileId string) security.EncodedJwt {
|
||||
if auth != "" {
|
||||
return security.EncodedJwt(auth)
|
||||
}
|
||||
v := util.GetViper()
|
||||
if signingKey := v.GetString("jwt.signing.key"); signingKey != "" {
|
||||
return security.GenJwtForVolumeServer(security.SigningKey(signingKey), v.GetInt("jwt.signing.expires_after_seconds"), fileId)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
// errNotInRestoreSource means the restore source holds no live record of the
|
||||
// needle, as opposed to holding bytes that fail a check.
|
||||
var errNotInRestoreSource = errors.New("not in restore source")
|
||||
|
||||
// restoreSourceMayHoldError marks a needle the restore source holds, or could
|
||||
// not be read to tell, that is still not restored; its entry is not pruned.
|
||||
type restoreSourceMayHoldError struct{ error }
|
||||
|
||||
func (e restoreSourceMayHoldError) Unwrap() error { return e.error }
|
||||
|
||||
func restoreSourceMayHold(err error) bool {
|
||||
return errors.As(err, new(restoreSourceMayHoldError))
|
||||
}
|
||||
|
||||
// restoreSource reads needles from regular volume files left on disk outside
|
||||
// any volume server, <collection>_<vid>.dat/.idx or <vid>.dat/.idx.
|
||||
type restoreSource struct {
|
||||
volumes map[needle.VolumeId]*restoreVolume
|
||||
}
|
||||
|
||||
// restoreVolume loads its .idx on the first lookup: a directory of many
|
||||
// volumes usually holds few that missing chunks name.
|
||||
type restoreVolume struct {
|
||||
collection string
|
||||
idxPath string
|
||||
datPath string
|
||||
dat backend.BackendStorageFile
|
||||
version needle.Version
|
||||
needles map[types.NeedleId]restoreNeedleLocation
|
||||
indexErr error
|
||||
}
|
||||
|
||||
type restoreNeedleLocation struct {
|
||||
offset types.Offset
|
||||
size types.Size
|
||||
}
|
||||
|
||||
func openRestoreSource(dir string) (*restoreSource, error) {
|
||||
dirEntries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source := &restoreSource{volumes: make(map[needle.VolumeId]*restoreVolume)}
|
||||
opened := false
|
||||
defer func() {
|
||||
if !opened {
|
||||
source.Close()
|
||||
}
|
||||
}()
|
||||
for _, dirEntry := range dirEntries {
|
||||
if !strings.HasSuffix(dirEntry.Name(), ".idx") {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimSuffix(dirEntry.Name(), ".idx")
|
||||
base := filepath.Join(dir, name)
|
||||
collection := ""
|
||||
if i := strings.LastIndex(name, "_"); i > 0 {
|
||||
collection, name = name[:i], name[i+1:]
|
||||
}
|
||||
vid, parseErr := needle.NewVolumeId(name)
|
||||
if parseErr != nil {
|
||||
continue
|
||||
}
|
||||
if existing, found := source.volumes[vid]; found {
|
||||
return nil, fmt.Errorf("volume %d is in both %s and %s", vid, existing.datPath, base+".dat")
|
||||
}
|
||||
volume, openErr := openRestoreVolume(base)
|
||||
if openErr != nil {
|
||||
return nil, fmt.Errorf("volume %d: %w", vid, openErr)
|
||||
}
|
||||
volume.collection = collection
|
||||
source.volumes[vid] = volume
|
||||
}
|
||||
if len(source.volumes) == 0 {
|
||||
return nil, fmt.Errorf("no <vid>.idx or <collection>_<vid>.idx volume files in %s", dir)
|
||||
}
|
||||
opened = true
|
||||
return source, nil
|
||||
}
|
||||
|
||||
func openRestoreVolume(base string) (*restoreVolume, error) {
|
||||
info, hasRemoteFile, _, err := volume_info.MaybeLoadVolumeInfo(base + ".vif")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if hasRemoteFile {
|
||||
return nil, fmt.Errorf("%s.vif points at a remote .dat", base)
|
||||
}
|
||||
if info.BytesOffset != 0 && info.BytesOffset != types.OffsetSize {
|
||||
return nil, fmt.Errorf("%s.vif records %d-byte offsets, this binary reads %d-byte offsets", base, info.BytesOffset, types.OffsetSize)
|
||||
}
|
||||
datFile, err := os.Open(base + ".dat")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dat := backend.NewDiskFile(datFile)
|
||||
superBlock, err := super_block.ReadSuperBlock(dat)
|
||||
if err != nil {
|
||||
dat.Close()
|
||||
return nil, err
|
||||
}
|
||||
if !needle.IsSupportedVersion(superBlock.Version) {
|
||||
dat.Close()
|
||||
return nil, fmt.Errorf("%s.dat has unsupported needle version %d", base, superBlock.Version)
|
||||
}
|
||||
return &restoreVolume{idxPath: base + ".idx", datPath: base + ".dat", dat: dat, version: superBlock.Version}, nil
|
||||
}
|
||||
|
||||
// loadRestoreIndex maps each key to its last live record. A later tombstone
|
||||
// does not hide an earlier record: a needle deleted on the volume but still
|
||||
// referenced by the filer is worth restoring when its bytes are intact.
|
||||
func loadRestoreIndex(idxPath string) (map[types.NeedleId]restoreNeedleLocation, error) {
|
||||
idxFile, err := os.Open(idxPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer idxFile.Close()
|
||||
// a cut-short last record would read as a key the volume never held
|
||||
if info, err := idxFile.Stat(); err != nil {
|
||||
return nil, err
|
||||
} else if info.Size()%types.NeedleMapEntrySize != 0 {
|
||||
return nil, fmt.Errorf("read %s: size %d is not a multiple of %d", idxPath, info.Size(), types.NeedleMapEntrySize)
|
||||
}
|
||||
needles := make(map[types.NeedleId]restoreNeedleLocation)
|
||||
err = idx.WalkIndexFile(idxFile, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
|
||||
if !offset.IsZero() && size.IsValid() {
|
||||
needles[key] = restoreNeedleLocation{offset: offset, size: size}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", idxPath, err)
|
||||
}
|
||||
return needles, nil
|
||||
}
|
||||
|
||||
func (s *restoreSource) Close() {
|
||||
for _, v := range s.volumes {
|
||||
v.dat.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// readNeedle returns the needle a file id names, after checking that the
|
||||
// record holds that key and cookie and that its data matches its CRC.
|
||||
func (s *restoreSource) readNeedle(vid needle.VolumeId, key types.NeedleId, cookie types.Cookie) (*needle.Needle, error) {
|
||||
v, found := s.volumes[vid]
|
||||
if !found {
|
||||
return nil, errNotInRestoreSource
|
||||
}
|
||||
if v.needles == nil && v.indexErr == nil {
|
||||
v.needles, v.indexErr = loadRestoreIndex(v.idxPath)
|
||||
}
|
||||
if v.indexErr != nil {
|
||||
return nil, restoreSourceMayHoldError{v.indexErr}
|
||||
}
|
||||
loc, found := v.needles[key]
|
||||
if !found {
|
||||
return nil, errNotInRestoreSource
|
||||
}
|
||||
n := &needle.Needle{}
|
||||
if err := n.ReadData(v.dat, loc.offset.ToActualOffset(), loc.size, v.version); err != nil {
|
||||
err = fmt.Errorf("read %s at %d: %w", v.datPath, loc.offset.ToActualOffset(), err)
|
||||
if errors.Is(err, needle.ErrorCorrupted) || errors.Is(err, needle.ErrorSizeMismatch) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, restoreSourceMayHoldError{err}
|
||||
}
|
||||
if n.Id != key {
|
||||
return nil, fmt.Errorf("%s at %d holds needle %s, want %s", v.datPath, loc.offset.ToActualOffset(), n.Id, key)
|
||||
}
|
||||
if n.Cookie != cookie {
|
||||
return nil, fmt.Errorf("needle %s in %s has cookie %08x, want %08x", key, v.datPath, uint32(n.Cookie), uint32(cookie))
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// testRestoreVolume writes a regular volume's .dat and .idx the way a volume
|
||||
// server lays them out, for restore source tests.
|
||||
type testRestoreVolume struct {
|
||||
t *testing.T
|
||||
dat *backend.DiskFile
|
||||
idx *os.File
|
||||
}
|
||||
|
||||
func newTestRestoreVolume(t *testing.T, base string) *testRestoreVolume {
|
||||
t.Helper()
|
||||
datFile, err := os.Create(base + ".dat")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
superBlock := super_block.SuperBlock{Version: needle.GetCurrentVersion(), ReplicaPlacement: &super_block.ReplicaPlacement{}, Ttl: &needle.TTL{}}
|
||||
if _, err := datFile.Write(superBlock.Bytes()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idxFile, err := os.Create(base + ".idx")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := &testRestoreVolume{t: t, dat: backend.NewDiskFile(datFile), idx: idxFile}
|
||||
t.Cleanup(v.close)
|
||||
return v
|
||||
}
|
||||
|
||||
func (v *testRestoreVolume) write(key uint64, cookie uint32, data []byte, compressed bool) {
|
||||
v.t.Helper()
|
||||
n := &needle.Needle{Id: types.NeedleId(key), Cookie: types.Cookie(cookie), Data: data}
|
||||
n.Checksum = needle.NewCRC(n.Data)
|
||||
if compressed {
|
||||
n.SetIsCompressed()
|
||||
}
|
||||
offset, _, _, err := n.Append(v.dat, needle.GetCurrentVersion())
|
||||
if err != nil {
|
||||
v.t.Fatal(err)
|
||||
}
|
||||
if _, err := v.idx.Write(needle_map.ToBytes(n.Id, types.ToOffset(int64(offset)), n.Size)); err != nil {
|
||||
v.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *testRestoreVolume) delete(key uint64) {
|
||||
v.t.Helper()
|
||||
if _, err := v.idx.Write(needle_map.ToBytes(types.NeedleId(key), types.Offset{}, types.TombstoneFileSize)); err != nil {
|
||||
v.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *testRestoreVolume) close() {
|
||||
v.dat.Close()
|
||||
v.idx.Close()
|
||||
}
|
||||
|
||||
func TestRestoreSourceReadsLastLiveRecord(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
|
||||
v.write(1, 0x11, []byte("first"), false)
|
||||
v.write(2, 0x22, []byte("overwritten"), false)
|
||||
v.write(2, 0x23, []byte("overwrite"), false)
|
||||
v.write(3, 0x33, []byte("deleted later"), false)
|
||||
v.delete(3)
|
||||
v.write(4, 0x44, []byte("deleted"), false)
|
||||
v.delete(4)
|
||||
v.close()
|
||||
|
||||
source, err := openRestoreSource(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer source.Close()
|
||||
volume := source.volumes[7]
|
||||
if volume == nil || volume.collection != "pics" {
|
||||
t.Fatalf("volume 7 = %+v, want collection pics", volume)
|
||||
}
|
||||
if volume.needles != nil {
|
||||
t.Errorf("index loaded before the first lookup")
|
||||
}
|
||||
|
||||
for _, c := range []struct {
|
||||
key uint64
|
||||
cookie uint32
|
||||
want string
|
||||
}{
|
||||
{1, 0x11, "first"},
|
||||
{2, 0x23, "overwrite"},
|
||||
{3, 0x33, "deleted later"},
|
||||
{4, 0x44, "deleted"},
|
||||
} {
|
||||
n, err := source.readNeedle(7, types.NeedleId(c.key), types.Cookie(c.cookie))
|
||||
if err != nil {
|
||||
t.Errorf("needle %d: %v", c.key, err)
|
||||
continue
|
||||
}
|
||||
if string(n.Data) != c.want {
|
||||
t.Errorf("needle %d holds %q, want %q", c.key, n.Data, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
if len(volume.needles) != 4 {
|
||||
t.Errorf("indexed %d needles, want 4", len(volume.needles))
|
||||
}
|
||||
|
||||
// the earlier record of key 2 carried another cookie
|
||||
if _, err := source.readNeedle(7, 2, 0x22); err == nil || !strings.Contains(err.Error(), "cookie") {
|
||||
t.Errorf("stale cookie: got %v, want a cookie mismatch", err)
|
||||
}
|
||||
if _, err := source.readNeedle(7, 9, 0x99); !errors.Is(err, errNotInRestoreSource) {
|
||||
t.Errorf("unknown key: got %v, want errNotInRestoreSource", err)
|
||||
}
|
||||
if _, err := source.readNeedle(8, 1, 0x11); !errors.Is(err, errNotInRestoreSource) {
|
||||
t.Errorf("unknown volume: got %v, want errNotInRestoreSource", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreSourceRejectsCorruptedNeedle(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, []byte("intact bytes"), false)
|
||||
v.close()
|
||||
|
||||
datPath := filepath.Join(dir, "7.dat")
|
||||
dat, err := os.ReadFile(datPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
i := bytes.Index(dat, []byte("intact"))
|
||||
dat[i] ^= 0xff
|
||||
if err := os.WriteFile(datPath, dat, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
source, err := openRestoreSource(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer source.Close()
|
||||
if source.volumes[7].collection != "" {
|
||||
t.Errorf("collection %q, want none", source.volumes[7].collection)
|
||||
}
|
||||
if _, err := source.readNeedle(7, 1, 0x11); !errors.Is(err, needle.ErrorCorrupted) {
|
||||
t.Fatalf("got %v, want a CRC failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreSourceOpen(t *testing.T) {
|
||||
t.Run("empty directory", func(t *testing.T) {
|
||||
if _, err := openRestoreSource(t.TempDir()); err == nil {
|
||||
t.Fatal("want an error for a directory without volume files")
|
||||
}
|
||||
})
|
||||
t.Run("same volume twice", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
newTestRestoreVolume(t, filepath.Join(dir, "a_7")).close()
|
||||
newTestRestoreVolume(t, filepath.Join(dir, "b_7")).close()
|
||||
if _, err := openRestoreSource(dir); err == nil || !strings.Contains(err.Error(), "volume 7") {
|
||||
t.Fatalf("got %v, want a duplicate volume error", err)
|
||||
}
|
||||
})
|
||||
t.Run("unreadable idx fails only its own lookups", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, []byte("kept"), false)
|
||||
v.close()
|
||||
newTestRestoreVolume(t, filepath.Join(dir, "8")).close()
|
||||
if err := os.Remove(filepath.Join(dir, "8.idx")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, "8.idx"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := openRestoreSource(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer source.Close()
|
||||
if _, err := source.readNeedle(7, 1, 0x11); err != nil {
|
||||
t.Errorf("volume 7: %v", err)
|
||||
}
|
||||
if _, err := source.readNeedle(8, 1, 0x11); err == nil || errors.Is(err, errNotInRestoreSource) {
|
||||
t.Errorf("volume 8: got %v, want the index read error", err)
|
||||
}
|
||||
})
|
||||
t.Run("directory name is not a pattern", func(t *testing.T) {
|
||||
parent := t.TempDir()
|
||||
dir := filepath.Join(parent, "restore[1]")
|
||||
if err := os.Mkdir(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, []byte("kept"), false)
|
||||
v.close()
|
||||
if err := os.Mkdir(filepath.Join(parent, "restore1"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newTestRestoreVolume(t, filepath.Join(parent, "restore1", "8")).close()
|
||||
source, err := openRestoreSource(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer source.Close()
|
||||
if _, err := source.readNeedle(7, 1, 0x11); err != nil {
|
||||
t.Errorf("volume 7: %v", err)
|
||||
}
|
||||
if _, found := source.volumes[8]; found {
|
||||
t.Error("volume 8 is read from another directory")
|
||||
}
|
||||
})
|
||||
t.Run("idx without dat", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
newTestRestoreVolume(t, filepath.Join(dir, "7")).close()
|
||||
if err := os.Remove(filepath.Join(dir, "7.dat")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := openRestoreSource(dir); err == nil {
|
||||
t.Fatal("want an error for a missing .dat")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRestoreSourceKeepsKeysOfACutShortIndex(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
|
||||
v.write(1, 0x11, []byte("first"), false)
|
||||
v.write(2, 0x22, []byte("second"), false)
|
||||
v.close()
|
||||
idxPath := filepath.Join(dir, "pics_7.idx")
|
||||
info, err := os.Stat(idxPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Truncate(idxPath, info.Size()-3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
source, err := openRestoreSource(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer source.Close()
|
||||
_, err = source.readNeedle(7, 2, 0x22)
|
||||
if !restoreSourceMayHold(err) {
|
||||
t.Fatalf("readNeedle = %v, want a may-hold error for a key the cut record held", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// restoreTestFiler replaces entries under the IF_ENTRY_EQUAL precondition the
|
||||
// way the filer does. changeBeforeUpdate makes a client write the entry
|
||||
// between the restore's lookup and its update.
|
||||
type restoreTestFiler struct {
|
||||
stubFilerServer
|
||||
updates []*filer_pb.CreateEntryRequest
|
||||
changeBeforeUpdate bool
|
||||
readOnly bool
|
||||
}
|
||||
|
||||
func (s *restoreTestFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
if s.readOnly {
|
||||
return &filer_pb.CreateEntryResponse{Error: "read only", ErrorCode: filer_pb.FilerError_READ_ONLY}, nil
|
||||
}
|
||||
path := string(util.NewFullPath(req.Directory, req.Entry.Name))
|
||||
current := s.entries[path]
|
||||
if s.changeBeforeUpdate {
|
||||
current.Attributes.Mtime++
|
||||
}
|
||||
for _, clause := range req.GetCondition().GetClauses() {
|
||||
if clause.Kind == filer_pb.WriteCondition_IF_ENTRY_EQUAL && !proto.Equal(clause.ExpectedEntry, current) {
|
||||
return &filer_pb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
|
||||
}
|
||||
}
|
||||
s.updates = append(s.updates, req)
|
||||
s.entries[path] = req.Entry
|
||||
return &filer_pb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
type restoreTestUpload struct {
|
||||
collection string
|
||||
ttlSec int32
|
||||
data []byte
|
||||
gzipped bool
|
||||
}
|
||||
|
||||
func etagOf(data []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(util.Md5For(util.DigestMd5, data))
|
||||
}
|
||||
|
||||
func testChunk(vid uint32, key uint64, cookie uint32, offset int64, size int, etag string) *filer_pb.FileChunk {
|
||||
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: vid, FileKey: key, Cookie: cookie}, Offset: offset, Size: uint64(size), ETag: etag, ModifiedTsNs: 1_700_000_000_000_000_000 + int64(key)}
|
||||
}
|
||||
|
||||
func newRestoreTestCommand(t *testing.T, filer *restoreTestFiler, restoreDir string) (*commandFsVerify, *bytes.Buffer, *[]restoreTestUpload) {
|
||||
t.Helper()
|
||||
commandEnv, _, cleanup := newFsVerifyTestCommandEnv(t, filer, &fsVerifyTestVolumeServer{})
|
||||
t.Cleanup(cleanup)
|
||||
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
|
||||
output := &bytes.Buffer{}
|
||||
c := newFsVerifyTestCommand(t, commandEnv, output)
|
||||
source, err := openRestoreSource(restoreDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(source.Close)
|
||||
c.restore = source
|
||||
uploads := &[]restoreTestUpload{}
|
||||
c.uploadRestored = func(target restoreTarget, data []byte, gzipped bool, _ string) (string, error) {
|
||||
*uploads = append(*uploads, restoreTestUpload{collection: target.collection, ttlSec: target.ttlSec, data: append([]byte(nil), data...), gzipped: gzipped})
|
||||
return needle.NewFileId(9, uint64(100+len(*uploads)), 0xabcd).String(), nil
|
||||
}
|
||||
return c, output, uploads
|
||||
}
|
||||
|
||||
func TestFsVerifyRestoreEntry(t *testing.T) {
|
||||
plain := []byte("hello restored world")
|
||||
text := bytes.Repeat([]byte("compressible "), 100)
|
||||
gzipped, err := util.GzipData(text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
|
||||
v.write(1, 0x11, plain, false)
|
||||
v.write(2, 0x22, gzipped, true)
|
||||
v.write(6, 0x66, []byte("other bytes"), false)
|
||||
v.close()
|
||||
|
||||
mtime := time.Now().Add(-time.Hour).Unix()
|
||||
attr := &filer_pb.FuseAttributes{Mtime: mtime, Md5: []byte("md5"), TtlSec: 86400}
|
||||
restorable := testChunk(7, 1, 0x11, 0, len(plain), etagOf(plain))
|
||||
healthy := testChunk(7, 3, 0x33, int64(len(plain)), 10, "")
|
||||
compressed := testChunk(7, 2, 0x22, int64(len(plain))+10, len(text), etagOf(text))
|
||||
compressed.IsCompressed = true
|
||||
lost := testChunk(7, 5, 0x55, int64(len(plain)+10+len(text)), 10, "")
|
||||
wrongContent := testChunk(7, 6, 0x66, int64(len(plain)+20+len(text)), 11, etagOf([]byte("expected bytes")))
|
||||
chunks := []*filer_pb.FileChunk{restorable, healthy, compressed, lost, wrongContent}
|
||||
missing := []*filer_pb.FileChunk{restorable, compressed, lost, wrongContent}
|
||||
newEntry := func() *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: "file", Attributes: proto.Clone(attr).(*filer_pb.FuseAttributes), Chunks: chunks}
|
||||
}
|
||||
path := util.NewFullPath("/buckets/b", "file")
|
||||
|
||||
t.Run("restores what it can in one update", func(t *testing.T) {
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}}}
|
||||
c, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
|
||||
if !restored || !isRestorable {
|
||||
t.Fatalf("restored=%v restorable=%v, want both\n%s", restored, isRestorable, output)
|
||||
}
|
||||
if len(filer.updates) != 1 {
|
||||
t.Fatalf("%d updates, want 1", len(filer.updates))
|
||||
}
|
||||
if len(*uploads) != 2 {
|
||||
t.Fatalf("%d uploads, want 2", len(*uploads))
|
||||
}
|
||||
// the new needle is assigned with the entry's lifetime
|
||||
if u := (*uploads)[0]; !bytes.Equal(u.data, plain) || u.gzipped || u.collection != "pics" || u.ttlSec != 86400 {
|
||||
t.Errorf("plain upload = %+v", u)
|
||||
}
|
||||
// the stored gzip bytes go up as they are, marked gzipped
|
||||
if u := (*uploads)[1]; !bytes.Equal(u.data, gzipped) || !u.gzipped {
|
||||
t.Errorf("compressed upload gzipped=%v, same bytes=%v", u.gzipped, bytes.Equal(u.data, gzipped))
|
||||
}
|
||||
|
||||
repointed := func(chunk *filer_pb.FileChunk, key uint64) *filer_pb.FileChunk {
|
||||
want := proto.Clone(chunk).(*filer_pb.FileChunk)
|
||||
want.Fid = &filer_pb.FileId{VolumeId: 9, FileKey: key, Cookie: 0xabcd}
|
||||
return want
|
||||
}
|
||||
got := filer.updates[0].Entry.Chunks
|
||||
for i, want := range []*filer_pb.FileChunk{
|
||||
repointed(restorable, 101),
|
||||
healthy,
|
||||
repointed(compressed, 102),
|
||||
lost,
|
||||
wrongContent,
|
||||
} {
|
||||
want.FileId, got[i].FileId = "", ""
|
||||
if !proto.Equal(got[i], want) {
|
||||
t.Errorf("chunk %d = %v, want %v", i, got[i], want)
|
||||
}
|
||||
}
|
||||
for _, line := range []string{
|
||||
"restored /buckets/b/file chunk " + restorable.GetFileIdString() + " -> " + needle.NewFileId(9, 101, 0xabcd).String(),
|
||||
"restored /buckets/b/file chunk " + compressed.GetFileIdString() + " -> " + needle.NewFileId(9, 102, 0xabcd).String(),
|
||||
"not restorable /buckets/b/file chunk " + lost.GetFileIdString() + ": not in restore source",
|
||||
"not restorable /buckets/b/file chunk " + wrongContent.GetFileIdString() + ": content does not match chunk etag",
|
||||
} {
|
||||
if !strings.Contains(output.String(), line) {
|
||||
t.Errorf("output lacks %q:\n%s", line, output)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("entry changed since verification", func(t *testing.T) {
|
||||
changed := newEntry()
|
||||
changed.Attributes.Mtime++
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): changed}}}
|
||||
c, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
|
||||
if restored || !isRestorable || len(*uploads) != 0 || len(filer.updates) != 0 {
|
||||
t.Fatalf("restored=%v restorable=%v uploads=%d updates=%d, want only restorable", restored, isRestorable, len(*uploads), len(filer.updates))
|
||||
}
|
||||
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: entry changed since verification") {
|
||||
t.Errorf("output:\n%s", output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("entry changes before the update", func(t *testing.T) {
|
||||
filer := &restoreTestFiler{
|
||||
stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}},
|
||||
changeBeforeUpdate: true,
|
||||
}
|
||||
c, output, _ := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
|
||||
if restored || !isRestorable || len(filer.updates) != 0 {
|
||||
t.Fatalf("restored=%v restorable=%v updates=%d, want only restorable", restored, isRestorable, len(filer.updates))
|
||||
}
|
||||
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: entry changed since verification") {
|
||||
t.Errorf("output:\n%s", output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("path turns read-only before the update", func(t *testing.T) {
|
||||
filer := &restoreTestFiler{
|
||||
stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}},
|
||||
readOnly: true,
|
||||
}
|
||||
c, output, _ := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
|
||||
if restored || !isRestorable || len(filer.updates) != 0 {
|
||||
t.Fatalf("restored=%v restorable=%v updates=%d, want only restorable", restored, isRestorable, len(filer.updates))
|
||||
}
|
||||
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: path is read-only") {
|
||||
t.Errorf("output:\n%s", output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("restorable entry is never pruned", func(t *testing.T) {
|
||||
changed := newEntry()
|
||||
changed.Attributes.Mtime++
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): changed}}}
|
||||
c, _, _ := newRestoreTestCommand(t, filer, dir)
|
||||
prune := true
|
||||
c.pruneEntries = &prune
|
||||
|
||||
var counts fsVerifyCounts
|
||||
c.repairEntry(path, attr, chunks, missing, &counts)
|
||||
if counts != (fsVerifyCounts{}) || len(filer.deleted) != 0 {
|
||||
t.Fatalf("counts=%+v deleted=%v, want the entry kept", counts, filer.deleted)
|
||||
}
|
||||
|
||||
// nothing restorable: pruned as before
|
||||
changed.Attributes.Mtime--
|
||||
c.repairEntry(path, attr, chunks, []*filer_pb.FileChunk{lost}, &counts)
|
||||
if counts.pruned != 1 || len(filer.deleted) != 1 {
|
||||
t.Fatalf("counts=%+v deleted=%v, want the entry pruned", counts, filer.deleted)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestFsVerifyRestoreKeepsEntryTheSourceMayHold(t *testing.T) {
|
||||
data := []byte("encrypted bytes")
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, data, false)
|
||||
v.write(2, 0x22, data, false)
|
||||
v.close()
|
||||
newTestRestoreVolume(t, filepath.Join(dir, "8")).close()
|
||||
if err := os.Truncate(filepath.Join(dir, "7.dat"), 8+int64(needle.GetActualSize(types.Size(len(data)), needle.GetCurrentVersion()))+10); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, "8.idx")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, "8.idx"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
|
||||
encrypted := testChunk(7, 1, 0x11, 0, len(data), "")
|
||||
encrypted.CipherKey = []byte("key")
|
||||
truncated := testChunk(7, 2, 0x22, 0, len(data), "")
|
||||
unreadable := testChunk(8, 3, 0x33, 0, 10, "")
|
||||
path := util.NewFullPath("/buckets/b", "file")
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
chunk *filer_pb.FileChunk
|
||||
kept bool
|
||||
}{
|
||||
{"encrypted chunk held by the source", encrypted, true},
|
||||
{"unreadable index", unreadable, true},
|
||||
{"needle cut off the .dat", truncated, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
chunks := []*filer_pb.FileChunk{c.chunk}
|
||||
entry := &filer_pb.Entry{Name: "file", Attributes: proto.Clone(attr).(*filer_pb.FuseAttributes), Chunks: chunks}
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): entry}}}
|
||||
cmd, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
prune := true
|
||||
cmd.pruneEntries = &prune
|
||||
|
||||
var counts fsVerifyCounts
|
||||
cmd.repairEntry(path, attr, chunks, chunks, &counts)
|
||||
if len(*uploads) != 0 || len(filer.updates) != 0 {
|
||||
t.Fatalf("uploads=%d updates=%d, want none\n%s", len(*uploads), len(filer.updates), output)
|
||||
}
|
||||
if kept := len(filer.deleted) == 0; kept != c.kept {
|
||||
t.Fatalf("kept=%v, want %v\n%s", kept, c.kept, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A missing chunk held in a manifest is restored by uploading a rewritten
|
||||
// manifest that points at the new needle and keeps every other chunk.
|
||||
func TestFsVerifyRestoreChunkInsideManifest(t *testing.T) {
|
||||
data := []byte("chunk held by a manifest")
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, data, false)
|
||||
v.close()
|
||||
|
||||
held := []*filer_pb.FileChunk{
|
||||
testChunk(7, 1, 0x11, 0, len(data), etagOf(data)),
|
||||
testChunk(7, 2, 0x22, int64(len(data)), 100, ""),
|
||||
}
|
||||
manifest := testChunk(8, 1, 0x88, 0, len(data)+100, "manifest-etag")
|
||||
manifest.IsChunkManifest = true
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix(), TtlSec: 3600}
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
|
||||
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{manifest}}},
|
||||
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{manifest: held})},
|
||||
}}
|
||||
c, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{manifest}, held[:1])
|
||||
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
|
||||
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
|
||||
}
|
||||
if (*uploads)[1].ttlSec != 3600 {
|
||||
t.Errorf("manifest assigned with ttl %d, want the entry's 3600", (*uploads)[1].ttlSec)
|
||||
}
|
||||
m := &filer_pb.FileChunkManifest{}
|
||||
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(m.Chunks) != 2 || m.Chunks[0].Fid.VolumeId != 9 || m.Chunks[0].Fid.FileKey != 101 || !proto.Equal(m.Chunks[1], held[1]) {
|
||||
t.Fatalf("rewritten manifest holds %v", m.Chunks)
|
||||
}
|
||||
if m.Chunks[0].Offset != 0 || m.Chunks[0].Size != uint64(len(data)) || m.Chunks[0].ETag != held[0].ETag {
|
||||
t.Errorf("restored chunk lost its fields: %v", m.Chunks[0])
|
||||
}
|
||||
got := filer.updates[0].Entry.Chunks[0]
|
||||
if !got.IsChunkManifest || got.Fid.FileKey != 102 || got.Size != manifest.Size || got.ETag != manifest.ETag {
|
||||
t.Errorf("entry manifest chunk = %v", got)
|
||||
}
|
||||
if !strings.Contains(output.String(), "restored /dir/file chunk "+held[0].GetFileIdString()+" -> "+needle.NewFileId(9, 101, 0xabcd).String()) {
|
||||
t.Errorf("output:\n%s", output)
|
||||
}
|
||||
}
|
||||
|
||||
// A needle referenced both directly and inside a manifest is repointed in both.
|
||||
func TestFsVerifyRestoreChunkDirectAndInsideManifest(t *testing.T) {
|
||||
data := []byte("chunk referenced twice")
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, data, false)
|
||||
v.close()
|
||||
|
||||
lost := testChunk(7, 1, 0x11, 0, len(data), etagOf(data))
|
||||
manifest := testChunk(8, 1, 0x88, int64(len(data)), len(data), "")
|
||||
manifest.IsChunkManifest = true
|
||||
held := []*filer_pb.FileChunk{testChunk(7, 1, 0x11, int64(len(data)), len(data), etagOf(data))}
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
|
||||
chunks := []*filer_pb.FileChunk{lost, manifest}
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
|
||||
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: chunks}},
|
||||
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{manifest: held})},
|
||||
}}
|
||||
c, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, _ := c.restoreEntry(path, attr, chunks, []*filer_pb.FileChunk{lost})
|
||||
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
|
||||
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
|
||||
}
|
||||
got := filer.updates[0].Entry.Chunks
|
||||
if got[0].Fid.FileKey != 101 || !got[1].IsChunkManifest || got[1].Fid.FileKey != 102 {
|
||||
t.Fatalf("entry chunks = %v", got)
|
||||
}
|
||||
m := &filer_pb.FileChunkManifest{}
|
||||
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(m.Chunks) != 1 || m.Chunks[0].Fid.FileKey != 101 {
|
||||
t.Fatalf("rewritten manifest holds %v", m.Chunks)
|
||||
}
|
||||
}
|
||||
|
||||
// An unreadable nested manifest stays referenced as it was, and the parent
|
||||
// is still rewritten for the restored chunk it holds.
|
||||
func TestFsVerifyRestoreBesideUnreadableNestedManifest(t *testing.T) {
|
||||
data := []byte("chunk beside a lost manifest")
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, data, false)
|
||||
v.close()
|
||||
|
||||
lost := testChunk(7, 1, 0x11, 0, len(data), etagOf(data))
|
||||
unreadable := testChunk(8, 2, 0x99, int64(len(data)), 100, "")
|
||||
unreadable.IsChunkManifest = true
|
||||
held := []*filer_pb.FileChunk{lost, unreadable}
|
||||
parent := testChunk(8, 1, 0x88, 0, len(data)+100, "")
|
||||
parent.IsChunkManifest = true
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
|
||||
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{parent}}},
|
||||
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{parent: held})},
|
||||
}}
|
||||
c, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{parent}, []*filer_pb.FileChunk{lost})
|
||||
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
|
||||
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
|
||||
}
|
||||
m := &filer_pb.FileChunkManifest{}
|
||||
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(m.Chunks) != 2 || m.Chunks[0].Fid.FileKey != 101 || !proto.Equal(m.Chunks[1], unreadable) {
|
||||
t.Fatalf("rewritten parent holds %v", m.Chunks)
|
||||
}
|
||||
}
|
||||
|
||||
// An entry without a TTL under a path rule with one is not restored: the
|
||||
// update and the new needles would take the rule's TTL.
|
||||
func TestFsVerifyRestoreSkipsEntryWithoutTtlUnderTtlRule(t *testing.T) {
|
||||
data := []byte("kept forever")
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(1, 0x11, data, false)
|
||||
v.close()
|
||||
|
||||
conf := filer.NewFilerConf()
|
||||
if err := conf.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/", Ttl: "7d"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var confText bytes.Buffer
|
||||
if err := conf.ToText(&confText); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lost := testChunk(7, 1, 0x11, 0, len(data), etagOf(data))
|
||||
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-30 * 24 * time.Hour).Unix()}
|
||||
confPath := util.NewFullPath(filer.DirectoryEtcSeaweedFS, filer.FilerConfName)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
path util.FullPath
|
||||
ttlSec int32
|
||||
restore bool
|
||||
}{
|
||||
{"no TTL under a TTL rule", "/buckets/b/file", 0, false},
|
||||
{"own TTL under a TTL rule", "/buckets/b/file", 3600, true},
|
||||
{"no TTL outside the rule", "/buckets/c/file", 0, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
entryAttr := proto.Clone(attr).(*filer_pb.FuseAttributes)
|
||||
entryAttr.TtlSec = tc.ttlSec
|
||||
testFiler := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{
|
||||
string(tc.path): {Name: tc.path.Name(), Attributes: entryAttr, Chunks: []*filer_pb.FileChunk{lost}},
|
||||
string(confPath): {Name: filer.FilerConfName, Content: confText.Bytes()},
|
||||
}}}
|
||||
c, output, uploads := newRestoreTestCommand(t, testFiler, dir)
|
||||
|
||||
restored, isRestorable := c.restoreEntry(tc.path, entryAttr, []*filer_pb.FileChunk{lost}, []*filer_pb.FileChunk{lost})
|
||||
if restored != tc.restore || !isRestorable || (len(*uploads) > 0) != tc.restore {
|
||||
t.Fatalf("restored=%v restorable=%v uploads=%d, want restored=%v\n%s", restored, isRestorable, len(*uploads), tc.restore, output)
|
||||
}
|
||||
if !tc.restore && !strings.Contains(output.String(), "skip restoring "+string(tc.path)+": the entry has no TTL") {
|
||||
t.Errorf("output:\n%s", output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckRestoredContent(t *testing.T) {
|
||||
data := []byte("0123456789")
|
||||
n := &needle.Needle{Data: data}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
chunk *filer_pb.FileChunk
|
||||
ok bool
|
||||
}{
|
||||
{"exact", testChunk(7, 1, 1, 0, 10, etagOf(data)), true},
|
||||
{"truncated chunk", testChunk(7, 1, 1, 0, 4, etagOf(data)), true},
|
||||
{"needle too short", testChunk(7, 1, 1, 0, 11, etagOf(data)), false},
|
||||
{"md5 mismatch", testChunk(7, 1, 1, 0, 10, etagOf([]byte("other"))), false},
|
||||
{"hex md5", testChunk(7, 1, 1, 0, 10, hex.EncodeToString(util.Md5For(util.DigestMd5, data))), true},
|
||||
{"hex md5 mismatch", testChunk(7, 1, 1, 0, 10, hex.EncodeToString(util.Md5For(util.DigestMd5, []byte("x")))), false},
|
||||
{"truncated sha256", testChunk(7, 1, 1, 0, 10, base64.StdEncoding.EncodeToString(util.Md5For(util.DigestSha256, data))), true},
|
||||
{"crc etag", testChunk(7, 1, 1, 0, 10, "1a2b3c4d"), true},
|
||||
{"no etag", testChunk(7, 1, 1, 0, 10, ""), true},
|
||||
{"sse chunk keeps ciphertext", &filer_pb.FileChunk{Size: 10, ETag: etagOf([]byte("plain")), SseType: filer_pb.SSEType_SSE_S3}, true},
|
||||
} {
|
||||
if err := checkRestoredContent(c.chunk, n); (err == nil) != c.ok {
|
||||
t.Errorf("%s: err=%v, want ok=%v", c.name, err, c.ok)
|
||||
}
|
||||
}
|
||||
|
||||
// a length-delimited field longer than the blob
|
||||
if err := checkRestoredContent(&filer_pb.FileChunk{IsChunkManifest: true}, &needle.Needle{Data: []byte{0x0a, 0xff}}); err == nil {
|
||||
t.Error("a manifest that does not parse must fail")
|
||||
}
|
||||
m, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: []*filer_pb.FileChunk{testChunk(7, 2, 2, 0, 1<<20, "")}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := checkRestoredContent(&filer_pb.FileChunk{Size: 1 << 20, IsChunkManifest: true}, &needle.Needle{Data: m}); err != nil {
|
||||
t.Errorf("manifest: %v", err)
|
||||
}
|
||||
|
||||
gzipped, err := util.GzipData(bytes.Repeat(data, 10))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
compressed := &needle.Needle{Data: gzipped}
|
||||
compressed.SetIsCompressed()
|
||||
if err := checkRestoredContent(testChunk(7, 1, 1, 0, 100, etagOf(bytes.Repeat(data, 10))), compressed); err != nil {
|
||||
t.Errorf("compressed needle: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A lost manifest held by a readable one is restored, and the parent is
|
||||
// rewritten to point at it.
|
||||
func TestFsVerifyRestoreNestedManifest(t *testing.T) {
|
||||
inner := []*filer_pb.FileChunk{testChunk(7, 5, 0x55, 100, 100, "")}
|
||||
blob, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: inner})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
|
||||
v.write(2, 0x22, blob, false)
|
||||
v.close()
|
||||
|
||||
nested := testChunk(7, 2, 0x22, 100, 100, "")
|
||||
nested.IsChunkManifest = true
|
||||
held := []*filer_pb.FileChunk{testChunk(7, 1, 0x11, 0, 100, ""), nested}
|
||||
parent := testChunk(8, 1, 0x88, 0, 200, "")
|
||||
parent.IsChunkManifest = true
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
|
||||
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
|
||||
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{parent}}},
|
||||
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{parent: held})},
|
||||
}}
|
||||
c, output, uploads := newRestoreTestCommand(t, filer, dir)
|
||||
|
||||
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{parent}, []*filer_pb.FileChunk{nested})
|
||||
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
|
||||
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
|
||||
}
|
||||
if !bytes.Equal((*uploads)[0].data, blob) {
|
||||
t.Error("the nested manifest was not uploaded as stored")
|
||||
}
|
||||
m := &filer_pb.FileChunkManifest{}
|
||||
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(m.Chunks) != 2 || !proto.Equal(m.Chunks[0], held[0]) || m.Chunks[1].Fid.FileKey != 101 || !m.Chunks[1].IsChunkManifest {
|
||||
t.Fatalf("rewritten parent holds %v", m.Chunks)
|
||||
}
|
||||
if got := filer.updates[0].Entry.Chunks[0]; got.Fid.FileKey != 102 || !got.IsChunkManifest {
|
||||
t.Errorf("entry chunk = %v", got)
|
||||
}
|
||||
if !strings.Contains(output.String(), "restored /dir/file manifest "+nested.GetFileIdString()) {
|
||||
t.Errorf("output:\n%s", output)
|
||||
}
|
||||
}
|
||||
@@ -201,27 +201,44 @@ func TestFsVerifyVerifyEntryPrunability(t *testing.T) {
|
||||
defer cleanup()
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
|
||||
|
||||
verified, prunable := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified {
|
||||
t.Error("expected verification failure for missing needle")
|
||||
}
|
||||
if !prunable {
|
||||
if len(missing) != 1 {
|
||||
t.Error("needle missing on the only location must be prunable")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("healthy on one of two locations", func(t *testing.T) {
|
||||
t.Run("healthy on both locations", func(t *testing.T) {
|
||||
commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t,
|
||||
&fsVerifyTestFilerServer{},
|
||||
&fsVerifyTestVolumeServer{})
|
||||
defer cleanup()
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc, loc)
|
||||
|
||||
verified, prunable := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if !verified {
|
||||
t.Error("needle present on one location should not fail verification")
|
||||
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if !verified || len(missing) != 0 {
|
||||
t.Errorf("verified=%v missing=%d, want verified and none missing", verified, len(missing))
|
||||
}
|
||||
if prunable {
|
||||
})
|
||||
|
||||
t.Run("healthy on one of two locations", func(t *testing.T) {
|
||||
commandEnv, healthyLoc, cleanup := newFsVerifyTestCommandEnv(t,
|
||||
&fsVerifyTestFilerServer{},
|
||||
&fsVerifyTestVolumeServer{})
|
||||
defer cleanup()
|
||||
_, missingLoc, missingCleanup := newFsVerifyTestCommandEnv(t,
|
||||
&fsVerifyTestFilerServer{},
|
||||
&fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{42: true}})
|
||||
defer missingCleanup()
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, missingLoc, healthyLoc)
|
||||
|
||||
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified {
|
||||
t.Error("a replica missing the needle must fail verification")
|
||||
}
|
||||
if len(missing) != 0 {
|
||||
t.Error("needle present somewhere must not be prunable")
|
||||
}
|
||||
})
|
||||
@@ -235,13 +252,35 @@ func TestFsVerifyVerifyEntryPrunability(t *testing.T) {
|
||||
concurrency := 2
|
||||
c.concurrency = &concurrency
|
||||
|
||||
verified, prunable := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified || !prunable {
|
||||
t.Errorf("concurrent verification = (%v, %v), want (false, true)", verified, prunable)
|
||||
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified || len(missing) != 1 {
|
||||
t.Errorf("concurrent verification = (%v, %d missing), want (false, 1)", verified, len(missing))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// With a restore source, a chunk on a volume the cluster does not know does
|
||||
// not hide a later missing chunk that may be restorable.
|
||||
func TestFsVerifyRestoreChecksChunksPastAnUnknownVolume(t *testing.T) {
|
||||
unknown := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 99, FileKey: 1}}
|
||||
lost := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: 42}}
|
||||
commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t,
|
||||
&fsVerifyTestFilerServer{},
|
||||
&fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{42: true}})
|
||||
defer cleanup()
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
|
||||
|
||||
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{unknown, lost}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified || len(missing) != 0 {
|
||||
t.Fatalf("without a restore source: verified=%v missing=%d, want the scan to stop", verified, len(missing))
|
||||
}
|
||||
c.restore = &restoreSource{}
|
||||
verified, missing = c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{unknown, lost}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified || len(missing) != 1 || missing[0] != lost {
|
||||
t.Fatalf("with a restore source: verified=%v missing=%v, want the lost chunk", verified, missing)
|
||||
}
|
||||
}
|
||||
|
||||
// Pruning must only delete the entry when it did not change since the
|
||||
// verification pass — a re-upload fixes the file and must survive.
|
||||
func TestFsVerifyPruneEntryGuards(t *testing.T) {
|
||||
@@ -368,12 +407,12 @@ func TestFsVerifyManifestResolutionFailure(t *testing.T) {
|
||||
defer cleanup()
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
|
||||
|
||||
verified, hasMissing := c.resolveAndVerify("/buckets/b/file",
|
||||
verified, missing := c.resolveAndVerify("/buckets/b/file",
|
||||
[]*filer_pb.FileChunk{manifestChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified {
|
||||
t.Error("entry with an unresolvable manifest must not count as verified")
|
||||
}
|
||||
if hasMissing {
|
||||
if len(missing) != 0 {
|
||||
t.Error("healthy raw manifest needle must not be classified as missing")
|
||||
}
|
||||
})
|
||||
@@ -392,12 +431,12 @@ func TestFsVerifyManifestResolutionFailure(t *testing.T) {
|
||||
defer cleanup()
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
|
||||
|
||||
verified, hasMissing := c.resolveAndVerify("/buckets/b/file",
|
||||
verified, missing := c.resolveAndVerify("/buckets/b/file",
|
||||
[]*filer_pb.FileChunk{manifestChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified {
|
||||
t.Error("entry with a missing manifest needle must not count as verified")
|
||||
}
|
||||
if !hasMissing {
|
||||
if len(missing) != 1 {
|
||||
t.Error("missing manifest needle must be classified as prunable")
|
||||
}
|
||||
})
|
||||
@@ -418,9 +457,33 @@ func TestFsVerifyIgnoresChunksPastAManifestSpan(t *testing.T) {
|
||||
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
|
||||
|
||||
verified, hasMissing := c.resolveAndVerify("/buckets/b/file",
|
||||
verified, missing := c.resolveAndVerify("/buckets/b/file",
|
||||
[]*filer_pb.FileChunk{shortened}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if !verified || hasMissing {
|
||||
t.Fatalf("verified=%v hasMissing=%v, want the needle past the span ignored", verified, hasMissing)
|
||||
if !verified || len(missing) != 0 {
|
||||
t.Fatalf("verified=%v missing=%d, want the needle past the span ignored", verified, len(missing))
|
||||
}
|
||||
}
|
||||
|
||||
// A missing manifest under a readable one fails the whole resolution, so the
|
||||
// readable levels are walked and the missing manifest is reported like any
|
||||
// other lost needle; a chunk past the parent's span is still ignored.
|
||||
func TestFsVerifyFindsMissingNestedManifest(t *testing.T) {
|
||||
chunk := func(key uint64, offset int64) *filer_pb.FileChunk {
|
||||
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: key, Cookie: 1}, Offset: offset, Size: 100}
|
||||
}
|
||||
nested := chunk(3, 100)
|
||||
nested.IsChunkManifest = true
|
||||
parent := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: 1, Cookie: 1}, Size: 200, IsChunkManifest: true}
|
||||
filerServer := &stubFilerServer{volumeUrls: map[string]string{"7": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{
|
||||
parent: {chunk(2, 0), nested, chunk(4, 200)},
|
||||
})}}
|
||||
commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t, filerServer, &fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{3: true, 4: true}})
|
||||
defer cleanup()
|
||||
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
|
||||
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
|
||||
|
||||
verified, missing := c.resolveAndVerify("/buckets/b/file", []*filer_pb.FileChunk{parent}, atomic.NewUint64(0), &sync.WaitGroup{})
|
||||
if verified || len(missing) != 1 || missing[0].GetFileIdString() != nested.GetFileIdString() {
|
||||
t.Fatalf("verified=%v missing=%v, want only the nested manifest missing", verified, missing)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user