mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
With -restoreFrom and -pruneEntries, a missing needle the source could not be read for (an unreadable .idx or a .dat read error), or held intact but skipped (a cipher-key chunk, a volume-level manifest), let the entry be pruned, deleting the file whose bytes were on hand. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
411 lines
14 KiB
Go
411 lines
14 KiB
Go
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 {
|
|
fileId string
|
|
needle *needle.Needle
|
|
collection string
|
|
manifest bool
|
|
}
|
|
|
|
// 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
|
|
n, 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{fileId: fileId, needle: n, collection: collection, manifest: chunk.IsChunkManifest})
|
|
}
|
|
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()
|
|
newFileIds := make(map[string]string)
|
|
var uploaded []orphanedNeedle
|
|
for _, r := range ready {
|
|
fileId, err := c.uploadRestored(restoreTarget{path, r.collection, ttlSec}, r.needle.Data, r.needle.IsCompressed(), restoreMimeType(r.needle))
|
|
if err != nil {
|
|
fmt.Fprintf(c.writer, "not restored %s chunk %s: %v\n", path, r.fileId, err)
|
|
continue
|
|
}
|
|
newFileIds[r.fileId] = 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
|
|
}
|
|
}
|
|
if len(applied) < len(newFileIds) {
|
|
// the others are held inside manifests
|
|
for i, chunk := range updated.Chunks {
|
|
if !chunk.IsChunkManifest || applied[chunk.GetFileIdString()] != "" {
|
|
continue
|
|
}
|
|
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, chunk.GetFileIdString(), 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 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.fileId]; found && r.manifest {
|
|
fmt.Fprintf(c.writer, "restored %s manifest %s: run fs.verify again to check the chunks it holds\n", path, r.fileId)
|
|
}
|
|
}
|
|
return true, true
|
|
}
|
|
|
|
// 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) {
|
|
return fmt.Errorf("content does not match chunk etag %s", chunk.ETag)
|
|
}
|
|
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 {
|
|
return fail(err)
|
|
}
|
|
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 ""
|
|
}
|