mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
* filer: keep a PUT under /etc inline like a POST The write handler marks /etc paths (and saveInside=true) to be stored as inline content, but only the multipart POST path honoured it. A plain PUT went through the chunk uploader, which keeps content inline only below saveToFilerLimit, 0 by default, so `curl -T x.json http://filer/etc/...` stored chunks and the loaders that read /etc files from inline content saw nothing. Both paths now share one saveInside write: read the body, check Content-Md5, store it as the entry's content. An append to a chunked file is refused for PUT as it already was for POST, and an offset write is refused for both instead of being treated as a whole-file write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: skip the saveInside PUT digest checks under fips140=only GODEBUG=fips140=only refuses MD5: the filer neither checks Content-Md5 nor reports Content-MD5, and crypto/md5 panics. The bad-digest test is skipped there, and the inline-store test checks the digest only when MD5 is available while always checking the content is inline with no chunks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: answer a malformed write offset with 400 A negative, non-numeric or overflowing ?offset, and an offset with op=append, were plain errors that the write handler answered with 500, while a positive offset to inline content got 400. Both the inline and the chunk path now parse it through one helper whose error carries the ErrMsgInvalidOffset prefix, mapped to 400. offset=0 stays a whole write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: charge a saveInside PUT its whole body like a POST A PUT stored inside the entry is now buffered whole by saveInsideEntry, but uploadCharge still charged it by chunks, so -concurrentUploadLimitMB no longer bounded the memory it holds. It is charged as the POST is: its declared length, at most the whole budget, or the whole budget when the length is unknown. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: bound a body stored inside the entry at 16 MiB A saveInside or /etc upload is read into memory whole, and nothing capped it: one PUT or POST could grow the filer's memory without bound, as the upload charge limits concurrency rather than bytes. The read now stops at 16 MiB, far above any config file, and a larger body is answered 413 with nothing stored, whether or not its length was declared. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: keep inline storage to entries inside /etc/ The /etc check was a bare string prefix, so a PUT to /etcd-backup/snap.db or /etcetera took the saveInside path and a large body was refused with 413 instead of chunked. Match /etc/ as a directory for the write, upload charge and zip extract paths. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: bound a zip member kept inline like a saveInside upload A zip member extracted under /etc/ (or with saveInside=true) is read into memory whole, but was bounded only by the 1 TiB archive limit. Refuse a member over saveInsideMaxBytes, as a PUT or POST body is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: keep a multipart POST to the bare /etc directory inline A POST to /etc with a file name lands the file inside the /etc directory, but the /etc/ prefix check missed the bare path and stored it as chunks. Match /etc itself as well as entries under it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
820 lines
28 KiB
Go
820 lines
28 KiB
Go
package weed_server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"hash"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/operation"
|
|
"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/util"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/constants"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, contentLength int64, so *operation.StorageOption) {
|
|
|
|
// autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
|
|
query := r.URL.Query()
|
|
|
|
chunkSize := fs.requestChunkSize(query)
|
|
|
|
var reply *FilerPostResult
|
|
var err error
|
|
var md5bytes []byte
|
|
if r.Method == http.MethodPost {
|
|
if r.Header.Get("Content-Type") == "" && strings.HasSuffix(r.URL.Path, "/") {
|
|
reply, err = fs.mkdir(ctx, w, r, so)
|
|
} else {
|
|
reply, md5bytes, err = fs.doPostAutoChunk(ctx, w, r, chunkSize, contentLength, so)
|
|
}
|
|
} else {
|
|
reply, md5bytes, err = fs.doPutAutoChunk(ctx, w, r, chunkSize, contentLength, so)
|
|
}
|
|
if err != nil {
|
|
errStr := err.Error()
|
|
switch {
|
|
case errors.Is(err, ErrReadOnly):
|
|
writeJsonError(w, r, http.StatusInsufficientStorage, err)
|
|
case errStr == constants.ErrMsgOperationNotPermitted:
|
|
writeJsonError(w, r, http.StatusForbidden, err)
|
|
case strings.HasPrefix(errStr, "read input:") || errStr == io.ErrUnexpectedEOF.Error():
|
|
writeJsonError(w, r, util.HttpStatusCancelled, err)
|
|
case strings.HasSuffix(errStr, "is a file") || strings.HasSuffix(errStr, "already exists"):
|
|
writeJsonError(w, r, http.StatusConflict, err)
|
|
case strings.HasPrefix(errStr, constants.ErrMsgSaveInsideTooLarge):
|
|
writeJsonError(w, r, http.StatusRequestEntityTooLarge, err)
|
|
case strings.HasPrefix(errStr, constants.ErrMsgInvalidOffset),
|
|
errStr == constants.ErrMsgBadDigest,
|
|
errStr == constants.ErrMsgAppendSaveInsideChunked,
|
|
errStr == constants.ErrMsgAppendInlineMode,
|
|
errStr == constants.ErrMsgOffsetWriteInline,
|
|
errStr == constants.ErrMsgPartialWriteRemoteOnly:
|
|
writeJsonError(w, r, http.StatusBadRequest, err)
|
|
default:
|
|
writeJsonError(w, r, http.StatusInternalServerError, err)
|
|
}
|
|
} else if reply != nil {
|
|
if len(md5bytes) > 0 && !util.DigestIsSha256() {
|
|
md5InBase64 := util.Base64Encode(md5bytes)
|
|
w.Header().Set("Content-MD5", md5InBase64)
|
|
}
|
|
writeJsonQuiet(w, r, http.StatusCreated, reply)
|
|
}
|
|
}
|
|
|
|
func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, contentLength int64, so *operation.StorageOption) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
|
|
multipartReader, multipartReaderErr := r.MultipartReader()
|
|
if multipartReaderErr != nil {
|
|
return nil, nil, multipartReaderErr
|
|
}
|
|
|
|
part1, part1Err := multipartReader.NextPart()
|
|
if part1Err != nil {
|
|
return nil, nil, part1Err
|
|
}
|
|
|
|
fileName := part1.FileName()
|
|
if fileName != "" {
|
|
fileName = path.Base(fileName)
|
|
}
|
|
contentType := part1.Header.Get("Content-Type")
|
|
if contentType == "application/octet-stream" {
|
|
contentType = ""
|
|
}
|
|
|
|
if err := fs.checkPermissions(ctx, r, fileName); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
if so.SaveInside {
|
|
return fs.saveInsideEntry(ctx, r, part1, fileName, contentType, so, chunkSize)
|
|
}
|
|
|
|
fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks(ctx, w, r, part1, chunkSize, fileName, contentType, contentLength, so)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
md5bytes = md5Hash.Sum(nil)
|
|
if contentMd5Mismatch(uploadBodyMd5(md5bytes, md5Hash), r.Header.Get("Content-Md5")) {
|
|
fs.filer.DeleteUncommittedChunks(ctx, fileChunks)
|
|
return nil, nil, errors.New(constants.ErrMsgBadDigest)
|
|
}
|
|
var uncommittedChunks []*filer_pb.FileChunk
|
|
filerResult, replyerr, uncommittedChunks = fs.saveMetaData(ctx, r, fileName, contentType, so, chunkSize, md5bytes, fileChunks, chunkOffset, smallContent)
|
|
if replyerr != nil {
|
|
fs.filer.DeleteUncommittedChunks(ctx, uncommittedChunks)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter, r *http.Request, chunkSize int32, contentLength int64, so *operation.StorageOption) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
|
|
|
|
fileName := path.Base(r.URL.Path)
|
|
contentType := r.Header.Get("Content-Type")
|
|
if contentType == "application/octet-stream" {
|
|
contentType = ""
|
|
}
|
|
|
|
if err := fs.checkPermissions(ctx, r, fileName); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
if so.SaveInside {
|
|
return fs.saveInsideEntry(ctx, r, r.Body, fileName, contentType, so, chunkSize)
|
|
}
|
|
|
|
fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks(ctx, w, r, r.Body, chunkSize, fileName, contentType, contentLength, so)
|
|
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
md5bytes = md5Hash.Sum(nil)
|
|
if contentMd5Mismatch(uploadBodyMd5(md5bytes, md5Hash), r.Header.Get("Content-Md5")) {
|
|
fs.filer.DeleteUncommittedChunks(ctx, fileChunks)
|
|
return nil, nil, errors.New(constants.ErrMsgBadDigest)
|
|
}
|
|
var uncommittedChunks []*filer_pb.FileChunk
|
|
filerResult, replyerr, uncommittedChunks = fs.saveMetaData(ctx, r, fileName, contentType, so, chunkSize, md5bytes, fileChunks, chunkOffset, smallContent)
|
|
if replyerr != nil {
|
|
fs.filer.DeleteUncommittedChunks(ctx, uncommittedChunks)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// saveInsideMaxBytes bounds a body stored as inline content, which is held in
|
|
// memory whole; config files are far smaller.
|
|
const saveInsideMaxBytes = 16 << 20
|
|
|
|
// saveInsideEntry stores the whole body as the entry's inline content, as
|
|
// /etc files and saveInside=true uploads are kept, with no chunks.
|
|
func (fs *FilerServer) saveInsideEntry(ctx context.Context, r *http.Request, body io.Reader, fileName, contentType string, so *operation.StorageOption, chunkSize int32) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) {
|
|
// Inline content is always written whole, so an offset into it cannot be honoured.
|
|
if offset, err := requestOffset(r); err != nil {
|
|
return nil, nil, err
|
|
} else if offset > 0 {
|
|
return nil, nil, errors.New(constants.ErrMsgOffsetWriteInline)
|
|
}
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
buf.Reset()
|
|
defer bufPool.Put(buf)
|
|
if _, err := buf.ReadFrom(io.LimitReader(body, saveInsideMaxBytes+1)); err != nil {
|
|
return nil, nil, fmt.Errorf("read input: %w", err)
|
|
}
|
|
if buf.Len() > saveInsideMaxBytes {
|
|
return nil, nil, fmt.Errorf("%s: over %d bytes", constants.ErrMsgSaveInsideTooLarge, saveInsideMaxBytes)
|
|
}
|
|
md5bytes = util.Md5(buf.Bytes())
|
|
if contentMd5Mismatch(util.BodyMd5Of(md5bytes, buf.Bytes()), r.Header.Get("Content-Md5")) {
|
|
return nil, nil, errors.New(constants.ErrMsgBadDigest)
|
|
}
|
|
filerResult, replyerr, _ = fs.saveMetaData(ctx, r, fileName, contentType, so, chunkSize, md5bytes, nil, int64(buf.Len()), buf.Bytes())
|
|
return
|
|
}
|
|
|
|
// requestOffset parses ?offset, which when present must be a non-negative integer.
|
|
func requestOffset(r *http.Request) (int64, error) {
|
|
query := r.URL.Query()
|
|
if !query.Has("offset") {
|
|
return 0, nil
|
|
}
|
|
offset := query.Get("offset")
|
|
n, err := strconv.ParseInt(offset, 10, 64)
|
|
if err != nil || n < 0 {
|
|
return 0, fmt.Errorf("%s: '%s'", constants.ErrMsgInvalidOffset, offset)
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
func isAppend(r *http.Request) bool {
|
|
return r.URL.Query().Get("op") == "append"
|
|
}
|
|
|
|
func skipCheckParentDirEntry(r *http.Request) bool {
|
|
return r.URL.Query().Get("skipCheckParentDir") == "true"
|
|
}
|
|
|
|
// requestChunkSize resolves the auto-chunking size from the maxMB query param
|
|
// or the server default, clamped so the int32 chunk size cannot overflow into
|
|
// a non-positive value that would drop the upload's contents.
|
|
func (fs *FilerServer) requestChunkSize(query url.Values) int32 {
|
|
parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
|
|
maxMB := parsedMaxMB
|
|
if maxMB <= 0 {
|
|
maxMB = int64(fs.option.MaxMB)
|
|
}
|
|
const maxChunkSizeMB = math.MaxInt32 / (1024 * 1024) // 2047
|
|
if maxMB > maxChunkSizeMB {
|
|
maxMB = maxChunkSizeMB
|
|
}
|
|
return int32(maxMB) * 1024 * 1024
|
|
}
|
|
|
|
func (fs *FilerServer) checkPermissions(ctx context.Context, r *http.Request, fileName string) error {
|
|
fullPath := fs.fixFilePath(ctx, r, fileName)
|
|
if fs.filer.FilerConf.MatchStorageRule(fullPath).ReadOnly {
|
|
return fmt.Errorf("%w: %s", ErrReadOnly, fullPath)
|
|
}
|
|
enforced, err := fs.wormEnforcedForEntry(ctx, fullPath)
|
|
if err != nil {
|
|
return err
|
|
} else if enforced {
|
|
// you cannot change a worm file
|
|
return errors.New(constants.ErrMsgOperationNotPermitted)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (fs *FilerServer) wormEnforcedForEntry(ctx context.Context, fullPath string) (bool, error) {
|
|
conf := fs.filer.FilerConf
|
|
if !conf.MatchStorageRule(fullPath).GetWorm() {
|
|
return false, nil
|
|
}
|
|
|
|
entry, err := fs.filer.FindEntry(ctx, util.FullPath(fullPath))
|
|
if err != nil {
|
|
if errors.Is(err, filer_pb.ErrNotFound) {
|
|
return false, nil
|
|
}
|
|
|
|
return false, err
|
|
}
|
|
|
|
return conf.WormEnforced(fullPath, entry.WORMEnforcedAtTsNs), nil
|
|
}
|
|
|
|
func (fs *FilerServer) fixFilePath(ctx context.Context, r *http.Request, fileName string) string {
|
|
// fix the path
|
|
fullPath := r.URL.Path
|
|
if strings.HasSuffix(fullPath, "/") {
|
|
if fileName != "" {
|
|
fullPath += fileName
|
|
}
|
|
} else {
|
|
if fileName != "" {
|
|
if possibleDirEntry, findDirErr := fs.filer.FindEntry(ctx, util.FullPath(fullPath)); findDirErr == nil {
|
|
if possibleDirEntry.IsDirectory() {
|
|
fullPath += "/" + fileName
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return fullPath
|
|
}
|
|
|
|
func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileName string, contentType string, so *operation.StorageOption, chunkSize int32, md5bytes []byte, fileChunks []*filer_pb.FileChunk, chunkOffset int64, content []byte) (filerResult *FilerPostResult, replyerr error, uncommittedChunks []*filer_pb.FileChunk) {
|
|
uncommittedChunks = fileChunks
|
|
|
|
// detect file mode
|
|
modeStr := r.URL.Query().Get("mode")
|
|
if modeStr == "" {
|
|
modeStr = "0660"
|
|
}
|
|
mode, err := strconv.ParseUint(modeStr, 8, 32)
|
|
if err != nil {
|
|
glog.ErrorfCtx(ctx, "Invalid mode format: %s, use 0660 by default", modeStr)
|
|
mode = 0660
|
|
}
|
|
|
|
// fix the path
|
|
path := fs.fixFilePath(ctx, r, fileName)
|
|
if fs.filer.FilerConf.MatchStorageRule(path).ReadOnly {
|
|
replyerr = fmt.Errorf("%w: %s", ErrReadOnly, path)
|
|
return
|
|
}
|
|
|
|
var entry *filer.Entry
|
|
var newChunks []*filer_pb.FileChunk
|
|
var mergedChunks []*filer_pb.FileChunk
|
|
|
|
isAppend := isAppend(r)
|
|
isOffsetWrite := len(fileChunks) > 0 && fileChunks[0].Offset > 0
|
|
var existingEntry *filer.Entry
|
|
var existingSnapshot *filer_pb.Entry
|
|
var distributedLock *cluster.LiveLock
|
|
// when it is an append
|
|
if isAppend || isOffsetWrite {
|
|
if fs.filer.Dlm != nil && len(fs.filer.Dlm.LockRing.GetSnapshot()) > 1 {
|
|
lockClient := fs.newLockClient()
|
|
distributedLock = lockClient.NewBlockingLongLivedLock(path, string(fs.option.Host), 0)
|
|
if distributedLock == nil {
|
|
replyerr = fmt.Errorf("failed to acquire lock for %s; retry the request", path)
|
|
return
|
|
}
|
|
defer distributedLock.Stop()
|
|
}
|
|
if fs.entryLockTable != nil {
|
|
pathLock := fs.entryLockTable.AcquireLock("appendEntry", util.FullPath(path), util.ExclusiveLock)
|
|
defer fs.entryLockTable.ReleaseLock(util.FullPath(path), pathLock)
|
|
}
|
|
var findErr error
|
|
existingEntry, findErr = fs.filer.FindEntry(ctx, util.FullPath(path))
|
|
if findErr != nil && !errors.Is(findErr, filer_pb.ErrNotFound) {
|
|
glog.V(0).InfofCtx(ctx, "failing to find %s: %v", path, findErr)
|
|
replyerr = fmt.Errorf("find entry %q: %w", path, findErr)
|
|
return
|
|
}
|
|
if existingEntry != nil {
|
|
if existingEntry.IsInRemoteOnly() && (len(fileChunks) > 0 || len(content) > 0) {
|
|
replyerr = errors.New(constants.ErrMsgPartialWriteRemoteOnly)
|
|
return
|
|
}
|
|
existingSnapshot = existingEntry.ToProtoEntry()
|
|
entry = cloneEntryForAppend(existingEntry)
|
|
}
|
|
}
|
|
|
|
inlineAppendHandled := false
|
|
inlineAppendConverted := false
|
|
if entry != nil {
|
|
inlineCandidate := len(entry.Content) > 0 ||
|
|
(isAppend && entry.FileSize == 0 && entry.Remote == nil && len(entry.HardLinkId) == 0 && len(entry.GetChunks()) == 0)
|
|
if isAppend && content != nil && !inlineCandidate {
|
|
if so.SaveInside {
|
|
replyerr = errors.New(constants.ErrMsgAppendSaveInsideChunked)
|
|
return
|
|
}
|
|
replyerr = fmt.Errorf("inline file changed while preparing append; retry the request")
|
|
return
|
|
}
|
|
|
|
if inlineCandidate {
|
|
if isOffsetWrite {
|
|
// TODO: support inline offset writes separately from append semantics.
|
|
replyerr = errors.New(constants.ErrMsgOffsetWriteInline)
|
|
return
|
|
}
|
|
if !isAppend || so.SaveInside || entry.Remote != nil || len(entry.HardLinkId) != 0 || len(entry.GetChunks()) != 0 {
|
|
replyerr = errors.New(constants.ErrMsgAppendInlineMode)
|
|
return
|
|
}
|
|
if entry.FileSize > uint64(len(entry.Content)) {
|
|
replyerr = fmt.Errorf("inline file %q has inconsistent size: metadata=%d content=%d", path, entry.FileSize, len(entry.Content))
|
|
return
|
|
}
|
|
|
|
entry.Mtime = time.Now()
|
|
entry.Md5 = nil
|
|
oldContentSize := int64(len(entry.Content))
|
|
|
|
switch {
|
|
case content != nil:
|
|
if int64(len(content)) != chunkOffset || len(fileChunks) != 0 {
|
|
replyerr = fmt.Errorf("invalid buffered inline append: size=%d offset=%d chunks=%d", len(content), chunkOffset, len(fileChunks))
|
|
return
|
|
}
|
|
combinedSize := oldContentSize + int64(len(content))
|
|
if len(content) == 0 || (fs.option.SaveToFilerLimit > 0 && combinedSize < fs.option.SaveToFilerLimit) {
|
|
combinedContent := make([]byte, 0, combinedSize)
|
|
combinedContent = append(combinedContent, entry.Content...)
|
|
combinedContent = append(combinedContent, content...)
|
|
entry.Content = combinedContent
|
|
entry.Chunks = nil
|
|
entry.FileSize = uint64(combinedSize)
|
|
entry.Md5 = util.Md5(combinedContent)
|
|
newChunks = nil
|
|
inlineAppendHandled = true
|
|
} else {
|
|
// The file grew after the upload path chose inline buffering. Promote
|
|
// the complete current file and this append as one chunk stream.
|
|
combinedContent := make([]byte, 0, combinedSize)
|
|
combinedContent = append(combinedContent, entry.Content...)
|
|
combinedContent = append(combinedContent, content...)
|
|
fileChunks, _, chunkOffset, replyerr, _ = fs.uploadReaderToChunks(ctx, r, bytes.NewReader(combinedContent), 0, chunkSize, fileName, contentType, true, so)
|
|
if replyerr != nil {
|
|
return
|
|
}
|
|
if chunkOffset != combinedSize {
|
|
uncommittedChunks = fileChunks
|
|
replyerr = fmt.Errorf("promoted inline append size mismatch: uploaded=%d expected=%d", chunkOffset, combinedSize)
|
|
return
|
|
}
|
|
entry.Content = nil
|
|
entry.FileSize = uint64(chunkOffset)
|
|
newChunks = fileChunks
|
|
uncommittedChunks = fileChunks
|
|
inlineAppendHandled = true
|
|
inlineAppendConverted = true
|
|
}
|
|
case len(fileChunks) > 0:
|
|
prefixChunks, _, prefixOffset, uploadErr, _ := fs.uploadReaderToChunks(ctx, r, bytes.NewReader(entry.Content), 0, chunkSize, fileName, contentType, true, so)
|
|
if uploadErr != nil {
|
|
replyerr = uploadErr
|
|
return
|
|
}
|
|
uncommittedChunks = append(append([]*filer_pb.FileChunk(nil), fileChunks...), prefixChunks...)
|
|
if prefixOffset != oldContentSize {
|
|
replyerr = fmt.Errorf("converted inline content size mismatch: uploaded=%d expected=%d", prefixOffset, oldContentSize)
|
|
return
|
|
}
|
|
for _, chunk := range fileChunks {
|
|
chunk.Offset += oldContentSize
|
|
}
|
|
newChunks = append(append([]*filer_pb.FileChunk(nil), prefixChunks...), fileChunks...)
|
|
entry.Content = nil
|
|
entry.FileSize = uint64(oldContentSize) + uint64(chunkOffset)
|
|
inlineAppendHandled = true
|
|
inlineAppendConverted = true
|
|
uncommittedChunks = newChunks
|
|
case chunkOffset == 0:
|
|
// An empty append must not migrate an inline file, even if the
|
|
// current threshold is disabled or lower than the file's size.
|
|
entry.FileSize = uint64(oldContentSize)
|
|
entry.Md5 = util.Md5(entry.Content)
|
|
newChunks = nil
|
|
inlineAppendHandled = true
|
|
default:
|
|
replyerr = fmt.Errorf("inline append has no content or uploaded chunks")
|
|
return
|
|
}
|
|
}
|
|
|
|
if !inlineAppendHandled {
|
|
entry.Mtime = time.Now()
|
|
entry.Md5 = nil
|
|
// New request chunks start at offset zero; append them after the
|
|
// existing chunk-backed file.
|
|
if isAppend {
|
|
entry.FileSize = entry.Size()
|
|
for _, chunk := range fileChunks {
|
|
chunk.Offset += int64(entry.FileSize)
|
|
}
|
|
entry.FileSize += uint64(chunkOffset)
|
|
}
|
|
newChunks = append(append([]*filer_pb.FileChunk(nil), entry.GetChunks()...), fileChunks...)
|
|
}
|
|
|
|
} else {
|
|
if isAppend && !so.SaveInside && content != nil {
|
|
replyerr = fmt.Errorf("inline append target disappeared while uploading; retry the request")
|
|
return
|
|
}
|
|
glog.V(4).InfolnCtx(ctx, "saving", path)
|
|
newChunks = fileChunks
|
|
entry = &filer.Entry{
|
|
FullPath: util.FullPath(path),
|
|
Attr: filer.Attr{
|
|
Mtime: time.Now(),
|
|
Crtime: time.Now(),
|
|
Mode: os.FileMode(mode),
|
|
Uid: OS_UID,
|
|
Gid: OS_GID,
|
|
TtlSec: so.TtlSeconds,
|
|
Mime: contentType,
|
|
Md5: md5bytes,
|
|
FileSize: uint64(chunkOffset),
|
|
},
|
|
Content: content,
|
|
}
|
|
}
|
|
|
|
// maybe concatenate small chunks into one whole chunk
|
|
mergedChunks, replyerr = fs.maybeMergeChunks(ctx, so, newChunks)
|
|
if replyerr != nil {
|
|
glog.V(0).InfofCtx(ctx, "merge chunks %s: %v", r.RequestURI, replyerr)
|
|
mergedChunks = newChunks
|
|
}
|
|
if inlineAppendConverted {
|
|
uncommittedChunks = mergedChunks
|
|
}
|
|
|
|
// maybe compact entry chunks
|
|
unmanifested := mergedChunks
|
|
mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(ctx, so), fs.filer.DeleteChunksNotRecursive, mergedChunks)
|
|
if replyerr != nil {
|
|
glog.V(0).InfofCtx(ctx, "manifestize %s: %v", r.RequestURI, replyerr)
|
|
if inlineAppendConverted {
|
|
uncommittedChunks = mergedChunks
|
|
}
|
|
return
|
|
}
|
|
if inlineAppendConverted {
|
|
uncommittedChunks = mergedChunks
|
|
}
|
|
entry.Chunks = mergedChunks
|
|
if isOffsetWrite {
|
|
entry.Md5 = nil
|
|
entry.FileSize = entry.Size()
|
|
}
|
|
|
|
filerResult = &FilerPostResult{
|
|
Name: fileName,
|
|
Size: int64(entry.FileSize),
|
|
}
|
|
|
|
// Save standard HTTP headers as extended attributes
|
|
// Note: S3 API now writes directly to volume servers and saves metadata via gRPC
|
|
// This handler is for non-S3 clients (WebDAV, SFTP, mount, curl, etc.)
|
|
if entry.Extended == nil {
|
|
entry.Extended = make(map[string][]byte)
|
|
}
|
|
for k, v := range r.Header {
|
|
if len(v) > 0 && len(v[0]) > 0 {
|
|
if k == filer.ExtRemoteRenameSourceKey {
|
|
continue // set by the filer only: it picks the remote key reads serve
|
|
}
|
|
if strings.HasPrefix(k, needle.PairNamePrefix) || k == "Cache-Control" || k == "Expires" || k == "Content-Disposition" {
|
|
entry.Extended[k] = []byte(v[0])
|
|
}
|
|
if k == "Response-Content-Disposition" {
|
|
entry.Extended["Content-Disposition"] = []byte(v[0])
|
|
}
|
|
}
|
|
}
|
|
|
|
// The recheck below reads the path; handing it to the create saves that a
|
|
// third lookup of the same entry follows.
|
|
var existingForWrite *filer.Entry
|
|
if isAppend || isOffsetWrite {
|
|
if distributedLock != nil && !distributedLock.IsLocked() {
|
|
replyerr = fmt.Errorf("lost distributed lock for %s; retry the request", path)
|
|
return
|
|
}
|
|
freshEntry, freshErr := fs.filer.FindEntry(ctx, util.FullPath(path))
|
|
if freshErr != nil && !errors.Is(freshErr, filer_pb.ErrNotFound) {
|
|
replyerr = fmt.Errorf("failed to recheck entry %q before write: %w", path, freshErr)
|
|
return
|
|
}
|
|
sameEntry := freshEntry == nil && existingSnapshot == nil ||
|
|
freshEntry != nil && existingSnapshot != nil &&
|
|
proto.Equal(existingSnapshot, freshEntry.ToProtoEntry())
|
|
if !sameEntry {
|
|
replyerr = fmt.Errorf("entry %s changed during append; retry the request", path)
|
|
return
|
|
}
|
|
existingForWrite = freshEntry
|
|
} else if fs.entryLockTable != nil {
|
|
// CreateEntry deletes the chunks of the entry it replaces, so concurrent
|
|
// overwrites must not both replace the same entry.
|
|
pathLock := fs.entryLockTable.AcquireLock("CreateEntry", util.FullPath(path), util.ExclusiveLock)
|
|
defer fs.entryLockTable.ReleaseLock(util.FullPath(path), pathLock)
|
|
}
|
|
|
|
var dbErr error
|
|
routed := false
|
|
if isAppend || isOffsetWrite {
|
|
routed, dbErr = fs.forwardToWriteOwner(ctx, entryRouteKey(util.FullPath(path)), func(owner pb.ServerAddress) error {
|
|
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
|
dir, _ := entry.FullPath.DirAndName()
|
|
forwardCtx := fs.withHTTPForwardAuthContext(context.WithoutCancel(ctx), r)
|
|
return filer_pb.CreateEntry(forwardCtx, client, &filer_pb.CreateEntryRequest{
|
|
Directory: dir,
|
|
Entry: entry.ToProtoEntry(),
|
|
IsMoved: true,
|
|
SkipCheckParentDirectory: skipCheckParentDirEntry(r),
|
|
Fsync: filer.SyncWrite(ctx),
|
|
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{
|
|
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
|
|
ExpectedEntry: existingSnapshot,
|
|
}}},
|
|
})
|
|
})
|
|
})
|
|
}
|
|
if !routed {
|
|
dbErr = fs.filer.CreateEntry(context.WithoutCancel(ctx), entry, existingForWrite, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength)
|
|
}
|
|
if dbErr != nil {
|
|
replyerr = dbErr
|
|
filerResult.Error = dbErr.Error()
|
|
glog.V(0).InfofCtx(ctx, "failing to write %s to filer server : %v", path, dbErr)
|
|
switch {
|
|
case routed && errors.Is(dbErr, filer_pb.ErrPreconditionFailed):
|
|
replyerr = fmt.Errorf("entry %s changed during append; retry the request", path)
|
|
case routed && status.Code(dbErr) == codes.Unauthenticated:
|
|
// The owner refused the call before running it. A new manifest can
|
|
// list committed chunks, so only its own blob is deleted.
|
|
if !inlineAppendConverted {
|
|
fs.filer.DeleteChunksNotRecursive(filer.DoMinusChunks(mergedChunks, unmanifested))
|
|
}
|
|
case routed:
|
|
// The owner may have committed before the reply was lost, and a
|
|
// separate local store may not hold that commit yet.
|
|
uncommittedChunks = nil
|
|
case inlineAppendConverted:
|
|
uncommittedChunks = fs.inlineAppendChunksNotReferenced(ctx, util.FullPath(path), mergedChunks)
|
|
}
|
|
} else {
|
|
uncommittedChunks = nil
|
|
}
|
|
return
|
|
}
|
|
|
|
func cloneEntryForAppend(entry *filer.Entry) *filer.Entry {
|
|
cloned := entry.ShallowClone()
|
|
cloned.Attr.Md5 = append([]byte(nil), entry.Md5...)
|
|
cloned.Attr.GroupNames = append([]string(nil), entry.GroupNames...)
|
|
cloned.Chunks = append([]*filer_pb.FileChunk(nil), entry.GetChunks()...)
|
|
cloned.Content = append([]byte(nil), entry.Content...)
|
|
cloned.WORMEnforcedAtTsNs = entry.WORMEnforcedAtTsNs
|
|
if entry.Extended != nil {
|
|
cloned.Extended = make(map[string][]byte, len(entry.Extended))
|
|
for key, value := range entry.Extended {
|
|
cloned.Extended[key] = append([]byte(nil), value...)
|
|
}
|
|
}
|
|
return cloned
|
|
}
|
|
|
|
func (fs *FilerServer) inlineAppendChunksNotReferenced(ctx context.Context, path util.FullPath, chunks []*filer_pb.FileChunk) []*filer_pb.FileChunk {
|
|
verifyCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
|
defer cancel()
|
|
|
|
entry, err := fs.filer.FindEntry(verifyCtx, path)
|
|
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
|
glog.V(0).InfofCtx(verifyCtx, "cannot verify inline append chunks for %s after metadata write failure: %v; retaining them", path, err)
|
|
return nil
|
|
}
|
|
|
|
referenced := make(map[string]struct{})
|
|
if entry != nil {
|
|
for _, chunk := range entry.GetChunks() {
|
|
referenced[chunk.GetFileIdString()] = struct{}{}
|
|
}
|
|
}
|
|
|
|
var unreferenced []*filer_pb.FileChunk
|
|
for _, chunk := range chunks {
|
|
if _, found := referenced[chunk.GetFileIdString()]; !found {
|
|
unreferenced = append(unreferenced, chunk)
|
|
}
|
|
}
|
|
return unreferenced
|
|
}
|
|
|
|
func (fs *FilerServer) saveAsChunk(ctx context.Context, so *operation.StorageOption) filer.SaveDataAsChunkFunctionType {
|
|
|
|
return func(reader io.Reader, name string, offset int64, tsNs int64, expectedDataSize uint64) (*filer_pb.FileChunk, error) {
|
|
var fileId string
|
|
var uploadResult *operation.UploadResult
|
|
|
|
err := util.Retry("saveAsChunk", func() error {
|
|
// assign one file id for one chunk
|
|
assignedFileId, urlLocation, auth, assignErr := fs.assignNewFileInfo(ctx, so, expectedDataSize)
|
|
if assignErr != nil {
|
|
return assignErr
|
|
}
|
|
|
|
fileId = assignedFileId
|
|
|
|
// upload the chunk to the volume server
|
|
uploadOption := &operation.UploadOption{
|
|
UploadUrl: urlLocation,
|
|
Filename: name,
|
|
Cipher: fs.option.Cipher,
|
|
IsInputCompressed: false,
|
|
MimeType: "",
|
|
PairMap: nil,
|
|
Jwt: auth,
|
|
}
|
|
|
|
uploader, uploaderErr := operation.NewUploader()
|
|
if uploaderErr != nil {
|
|
return uploaderErr
|
|
}
|
|
|
|
var uploadErr error
|
|
uploadCtx := context.WithoutCancel(ctx)
|
|
uploadResult, uploadErr, _ = uploader.Upload(uploadCtx, reader, uploadOption)
|
|
if uploadErr != nil {
|
|
return uploadErr
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return uploadResult.ToPbFileChunk(fileId, offset, tsNs), nil
|
|
}
|
|
}
|
|
|
|
func (fs *FilerServer) mkdir(ctx context.Context, w http.ResponseWriter, r *http.Request, so *operation.StorageOption) (filerResult *FilerPostResult, replyerr error) {
|
|
|
|
// detect file mode
|
|
modeStr := r.URL.Query().Get("mode")
|
|
if modeStr == "" {
|
|
modeStr = "0660"
|
|
}
|
|
mode, err := strconv.ParseUint(modeStr, 8, 32)
|
|
if err != nil {
|
|
glog.ErrorfCtx(ctx, "Invalid mode format: %s, use 0660 by default", modeStr)
|
|
mode = 0660
|
|
}
|
|
|
|
// fix the path
|
|
path := r.URL.Path
|
|
if strings.HasSuffix(path, "/") {
|
|
path = path[:len(path)-1]
|
|
}
|
|
|
|
existingEntry, err := fs.filer.FindEntry(ctx, util.FullPath(path))
|
|
if err == nil && existingEntry != nil {
|
|
replyerr = fmt.Errorf("dir %s already exists", path)
|
|
return
|
|
}
|
|
|
|
glog.V(4).InfolnCtx(ctx, "mkdir", path)
|
|
entry := &filer.Entry{
|
|
FullPath: util.FullPath(path),
|
|
Attr: filer.Attr{
|
|
Mtime: time.Now(),
|
|
Crtime: time.Now(),
|
|
Mode: os.FileMode(mode) | os.ModeDir,
|
|
Uid: OS_UID,
|
|
Gid: OS_GID,
|
|
TtlSec: so.TtlSeconds,
|
|
},
|
|
}
|
|
|
|
filerResult = &FilerPostResult{
|
|
Name: util.FullPath(path).Name(),
|
|
}
|
|
|
|
if dbErr := fs.filer.CreateEntry(context.WithoutCancel(ctx), entry, nil, false, false, nil, false, so.MaxFileNameLength); dbErr != nil {
|
|
replyerr = dbErr
|
|
filerResult.Error = dbErr.Error()
|
|
glog.V(0).InfofCtx(ctx, "failing to create dir %s on filer server : %v", path, dbErr)
|
|
}
|
|
return filerResult, replyerr
|
|
}
|
|
|
|
// contentMd5Mismatch compares the body's MD5, from util.BodyMd5, with the
|
|
// client's Content-MD5, base64 or hex. bodyMd5 is nil only under fips140=only
|
|
// with digest sha256, where no MD5 can be computed, and Content-MD5 then goes
|
|
// unchecked.
|
|
func contentMd5Mismatch(bodyMd5 []byte, headerMd5 string) bool {
|
|
if headerMd5 == "" || bodyMd5 == nil {
|
|
return false
|
|
}
|
|
return util.Base64Encode(bodyMd5) != headerMd5 && fmt.Sprintf("%x", bodyMd5) != headerMd5
|
|
}
|
|
|
|
// uploadHash is the content digest of an upload, which also feeds a separate
|
|
// MD5 of the body for the client's Content-MD5.
|
|
type uploadHash struct {
|
|
hash.Hash
|
|
contentMd5 hash.Hash
|
|
}
|
|
|
|
// newUploadHash returns the content digest hash for an upload of r's body. It
|
|
// is an uploadHash when r carries Content-MD5 and the content digest is not
|
|
// itself an MD5 (see util.NewContentMd5), else the plain digest; r may be nil.
|
|
// The MD5 rides on the digest hash rather than on the body reader, so the
|
|
// body's path through the upload stays as it is in every digest mode.
|
|
func newUploadHash(r *http.Request) hash.Hash {
|
|
digest := util.NewMd5()
|
|
if r == nil || r.Header.Get("Content-Md5") == "" {
|
|
return digest
|
|
}
|
|
contentMd5 := util.NewContentMd5()
|
|
if contentMd5 == nil {
|
|
return digest
|
|
}
|
|
return &uploadHash{Hash: digest, contentMd5: contentMd5}
|
|
}
|
|
|
|
func (h *uploadHash) Write(p []byte) (int, error) {
|
|
h.contentMd5.Write(p)
|
|
return h.Hash.Write(p)
|
|
}
|
|
|
|
func (h *uploadHash) Reset() {
|
|
h.Hash.Reset()
|
|
h.contentMd5.Reset()
|
|
}
|
|
|
|
// uploadBodyMd5 returns the body's MD5 for a Content-MD5 check, as
|
|
// util.BodyMd5 does, given the content digest and the hash from newUploadHash.
|
|
func uploadBodyMd5(contentDigest []byte, md5Hash hash.Hash) []byte {
|
|
var contentMd5 hash.Hash
|
|
if h, ok := md5Hash.(*uploadHash); ok {
|
|
contentMd5 = h.contentMd5
|
|
}
|
|
return util.BodyMd5(contentDigest, contentMd5)
|
|
}
|