filer: keep a PUT under /etc inline like a POST (#13241)

* 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>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-12-01 16:46:59 -08:00
1 parent d715c4e28f
commit a8f13e7db2
9 files changed
+381 -54

No files matched your search

+5 -6
View File
@@ -148,13 +148,12 @@ const (
// -maxMB, as requestChunkSize resolves it, and the filer default when neither is
// positive, so the charge never collapses to 0.
//
// A POST stored inside the filer entry (?saveInside=true, or under /etc) is
// read into memory whole (doPostAutoChunk), so with a limit set it is charged
// A POST or PUT stored inside the filer entry (?saveInside=true, or under /etc)
// is read into memory whole (saveInsideEntry), so with a limit set it is charged
// its whole declared length, at most the whole budget, and an unknown length is
// charged the whole budget: it then runs only on an idle filer, the one place a
// body of any size can be buffered without overshooting. A PUT there still goes
// through the chunk loop and is charged by chunks. With no limit the charge
// only feeds the gauge, so the chunk-based one is kept.
// body of any size can be buffered without overshooting. With no limit the
// charge only feeds the gauge, so the chunk-based one is kept.
func (fs *FilerServer) uploadCharge(r *http.Request) int64 {
limit := fs.option.ConcurrentUploadLimit
query := r.URL.Query()
@@ -163,7 +162,7 @@ func (fs *FilerServer) uploadCharge(r *http.Request) int64 {
chunk = filerDefaultChunkSizeMB << 20
}
chunk = min(chunk, filerMaxChunkSizeMB<<20)
if limit > 0 && r.Method == http.MethodPost && (query.Get("saveInside") == "true" || strings.HasPrefix(r.URL.Path, "/etc")) {
if limit > 0 && (r.Method == http.MethodPost || r.Method == http.MethodPut) && (query.Get("saveInside") == "true" || util.IsEqualOrUnder(r.URL.Path, filer.DirectoryEtcRoot)) {
if r.ContentLength >= 0 {
return min(r.ContentLength, limit)
}
+2 -2
View File
@@ -126,7 +126,7 @@ func (fs *FilerServer) extractZipArchive(ctx context.Context, w http.ResponseWri
if memberSO.DiskType == "" {
memberSO.DiskType = fs.option.DiskType
}
if strings.HasPrefix(writePath, "/etc") {
if util.IsEqualOrUnder(writePath, filer.DirectoryEtcRoot) {
memberSO.SaveInside = true
}
return memberSO, nil
@@ -266,7 +266,7 @@ func (fs *FilerServer) saveExtractedEntry(ctx context.Context, destPath string,
// multipart upload; the declared size keeps a corrupt archive from
// buffering more than it advertised.
if so.SaveInside {
if memberSize < 0 || memberSize > filer.ZipExtractMaxBytes {
if memberSize < 0 || memberSize > saveInsideMaxBytes {
return nil, fmt.Errorf("zip member %s size %d out of bounds", fileName, memberSize)
}
var buf bytes.Buffer
@@ -4,13 +4,16 @@ import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -316,3 +319,35 @@ func multipartWriter(t *testing.T, buf *bytes.Buffer, fileName string, data []by
}
return mw.FormDataContentType()
}
// A member kept inline under /etc/ is held in memory whole, so it gets the
// same bound as an upload saved inside the entry.
func TestExtractZipArchiveInlineMemberIsBounded(t *testing.T) {
fs, f := newExtractTestServer(t)
zipBytes := buildTestZip(t, map[string]string{
"big.json": strings.Repeat("z", saveInsideMaxBytes+1),
"small.json": "{}",
}, nil, nil)
r := httptest.NewRequest(http.MethodPut, "/etc/pack.zip?extract=zip", bytes.NewReader(zipBytes))
w := httptest.NewRecorder()
fs.PostHandler(w, r, int64(len(zipBytes)))
if w.Code != http.StatusCreated {
t.Fatalf("status = %d, body: %s", w.Code, w.Body.String())
}
var result FilerExtractResult
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatalf("decode result: %v", err)
}
if len(result.Errors) != 1 || !strings.Contains(result.Errors[0], "big.json") {
t.Fatalf("member errors = %v, want big.json refused", result.Errors)
}
if _, err := f.FindEntry(r.Context(), "/etc/big.json"); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("oversized member stored: %v", err)
}
small, err := f.FindEntry(r.Context(), "/etc/small.json")
if err != nil || string(small.Content) != "{}" || len(small.GetChunks()) != 0 {
t.Fatalf("small member: %v, want inline {}", err)
}
}
@@ -195,10 +195,16 @@ func TestFilerUploadChargeFollowsRequestMaxMB(t *testing.T) {
// side by side.
func TestFilerUploadChargeCoversInlineUploads(t *testing.T) {
const limit = 64 << 20
for _, target := range []string{"/dir/file?saveInside=true", "/etc/config.toml"} {
t.Run(target, func(t *testing.T) {
for _, tc := range []struct{ method, target string }{
{http.MethodPost, "/dir/file?saveInside=true"},
{http.MethodPost, "/etc/config.toml"},
{http.MethodPut, "/dir/file?saveInside=true"},
{http.MethodPut, "/etc/config.toml"},
} {
method, target := tc.method, tc.target
t.Run(method+" "+target, func(t *testing.T) {
fs := newLimitedFiler(limit, 0)
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader("data"))
req := httptest.NewRequest(method, target, strings.NewReader("data"))
req.ContentLength = 80 << 20
// The whole body, capped at the whole budget: over the budget it
// runs only on an idle filer either way.
@@ -214,7 +220,7 @@ func TestFilerUploadChargeCoversInlineUploads(t *testing.T) {
if !fs.waitForUploadSlot(httptest.NewRecorder(), req, fs.uploadCharge(req)) {
t.Fatal("an oversized inline upload was refused on an idle filer")
}
second := httptest.NewRequest(http.MethodPost, target, strings.NewReader("data"))
second := httptest.NewRequest(method, target, strings.NewReader("data"))
second.ContentLength = 80 << 20
if fs.waitForUploadSlot(httptest.NewRecorder(), second, fs.uploadCharge(second)) {
t.Fatal("a second 80 MiB inline upload was admitted beside the first")
@@ -233,14 +239,3 @@ func TestFilerUploadChargeCoversInlineUploads(t *testing.T) {
})
}
}
// A PUT to an inline path still goes through the chunk loop, so it is charged by
// chunks: charged its whole body it would only run on an idle filer.
func TestFilerUploadChargeKeepsChunksForInlinePut(t *testing.T) {
fs := newLimitedFiler(64<<20, 0)
req := httptest.NewRequest(http.MethodPut, "/etc/config.toml", strings.NewReader("data"))
req.ContentLength = 1 << 30
if got := fs.uploadCharge(req); got != 4*4<<20 {
t.Fatalf("1 GiB PUT under /etc: charge %d, want four 4 MiB chunks", got)
}
}
+1 -1
View File
@@ -138,7 +138,7 @@ func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request, conte
so.DiskType = fs.option.DiskType
}
if strings.HasPrefix(r.URL.Path, "/etc") {
if util.IsEqualOrUnder(r.URL.Path, filer.DirectoryEtcRoot) {
so.SaveInside = true
}
@@ -60,7 +60,10 @@ func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *
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 errStr == constants.ErrMsgBadDigest,
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,
@@ -103,20 +106,7 @@ func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWrite
}
if so.SaveInside {
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
if _, err := buf.ReadFrom(part1); err != nil {
bufPool.Put(buf)
return nil, nil, fmt.Errorf("read input: %w", err)
}
md5bytes = util.Md5(buf.Bytes())
if contentMd5Mismatch(util.BodyMd5Of(md5bytes, buf.Bytes()), r.Header.Get("Content-Md5")) {
bufPool.Put(buf)
return nil, nil, errors.New(constants.ErrMsgBadDigest)
}
filerResult, replyerr, _ = fs.saveMetaData(ctx, r, fileName, contentType, so, chunkSize, md5bytes, nil, int64(buf.Len()), buf.Bytes())
bufPool.Put(buf)
return
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)
@@ -150,6 +140,10 @@ func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter
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 {
@@ -170,6 +164,50 @@ func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter
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"
}
@@ -0,0 +1,263 @@
package weed_server
import (
"bytes"
"context"
"crypto/fips140"
"errors"
"net/http"
"net/http/httptest"
"path"
"strings"
"testing"
"time"
"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/util"
"github.com/seaweedfs/seaweedfs/weed/util/constants"
)
func TestFilerSaveInsidePutStoresInlineContent(t *testing.T) {
ctx := context.Background()
const filePath = "/etc/targets.json"
content := []byte(`{"targets":[]}`)
f := newRenameTestFiler(t, newRenameTestStore())
fs, uploaded := newInlineAppendUploadServer(t, f, 0, 1)
// GODEBUG=fips140=only refuses MD5, so the server neither checks nor reports one.
md5Checked := !fips140.Enforced()
wantMD5 := util.Md5(content)
r := httptest.NewRequest(http.MethodPut, filePath, bytes.NewReader(content))
if md5Checked {
r.Header.Set("Content-Md5", util.Base64Encode(wantMD5))
}
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true})
if recorder.Code != http.StatusCreated {
t.Fatalf("PUT status = %d, body %s", recorder.Code, recorder.Body.String())
}
if got := recorder.Header().Get("Content-MD5"); md5Checked && got != util.Base64Encode(wantMD5) {
t.Fatalf("Content-MD5 = %q, want %q", got, util.Base64Encode(wantMD5))
}
if uploaded.count() != 0 {
t.Fatalf("saveInside PUT uploaded %d chunks", uploaded.count())
}
saved, err := f.FindEntry(ctx, filePath)
if err != nil {
t.Fatalf("find saved entry: %v", err)
}
if !bytes.Equal(saved.Content, content) || len(saved.GetChunks()) != 0 || saved.FileSize != uint64(len(content)) {
t.Fatalf("saved entry: content=%q chunks=%d size=%d, want inline %q", saved.Content, len(saved.GetChunks()), saved.FileSize, content)
}
if md5Checked && !bytes.Equal(saved.Md5, wantMD5) {
t.Fatalf("saved MD5 = %x, want %x", saved.Md5, wantMD5)
}
}
func TestFilerPutOutsideSaveInsideStillChunks(t *testing.T) {
ctx := context.Background()
const filePath = "/data/targets.json"
content := []byte(`{"targets":[]}`)
f := newRenameTestFiler(t, newRenameTestStore())
fs, uploaded := newInlineAppendUploadServer(t, f, 0, 1)
r := httptest.NewRequest(http.MethodPut, filePath, bytes.NewReader(content))
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{})
if recorder.Code != http.StatusCreated {
t.Fatalf("PUT status = %d, body %s", recorder.Code, recorder.Body.String())
}
saved, err := f.FindEntry(ctx, filePath)
if err != nil {
t.Fatalf("find saved entry: %v", err)
}
if len(saved.Content) != 0 || len(saved.GetChunks()) != 1 || uploaded.count() != 1 {
t.Fatalf("saved entry: content=%q chunks=%d uploaded=%d, want one chunk", saved.Content, len(saved.GetChunks()), uploaded.count())
}
}
func TestFilerSaveInsidePutRejectsBadDigest(t *testing.T) {
if fips140.Enforced() {
t.Skip("GODEBUG=fips140=only refuses MD5")
}
ctx := context.Background()
const filePath = "/etc/targets.json"
f := newRenameTestFiler(t, newRenameTestStore())
fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}}
r := httptest.NewRequest(http.MethodPut, filePath, bytes.NewReader([]byte(`{"targets":[]}`)))
r.Header.Set("Content-Md5", util.Base64Encode([]byte("not the digest")))
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true})
if recorder.Code != http.StatusBadRequest {
t.Fatalf("bad digest status = %d, want %d", recorder.Code, http.StatusBadRequest)
}
if _, err := f.FindEntry(ctx, filePath); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("bad digest still saved the entry: %v", err)
}
}
// A saveInside PUT rejects what a saveInside POST rejects: appending to a
// chunked file, and an offset into content that is always written whole.
func TestFilerSaveInsidePutPartialWritesRejected(t *testing.T) {
ctx := context.Background()
const filePath = "/etc/chunked.json"
store := newRenameTestStore()
f := newRenameTestFiler(t, store)
if err := store.InsertEntry(ctx, &filer.Entry{
FullPath: util.FullPath(filePath),
Attr: filer.Attr{Mtime: time.Unix(1, 0), Crtime: time.Unix(1, 0), FileSize: 4},
Chunks: []*filer_pb.FileChunk{{FileId: "1,00000001", Offset: 0, Size: 4}},
}); err != nil {
t.Fatalf("insert chunk-backed entry: %v", err)
}
fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}}
for _, query := range []string{"?op=append", "?offset=2"} {
r := httptest.NewRequest(http.MethodPut, filePath+query, bytes.NewReader([]byte("new")))
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true})
if recorder.Code != http.StatusBadRequest {
t.Fatalf("%s status = %d, want %d: %s", query, recorder.Code, http.StatusBadRequest, recorder.Body.String())
}
unchanged, err := f.FindEntry(ctx, filePath)
if err != nil {
t.Fatalf("find entry: %v", err)
}
if unchanged.FileSize != 4 || len(unchanged.GetChunks()) != 1 || len(unchanged.Content) != 0 {
t.Fatalf("%s changed the entry: size=%d chunks=%d content=%q", query, unchanged.FileSize, len(unchanged.GetChunks()), unchanged.Content)
}
}
}
// A malformed ?offset is the client's mistake on both the inline and the chunk
// path, answered 400 before anything is read or stored.
func TestFilerPutInvalidOffsetIsBadRequest(t *testing.T) {
ctx := context.Background()
f := newRenameTestFiler(t, newRenameTestStore())
fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}}
cases := []struct {
target string
saveInside bool
}{
{"/etc/a.json?offset=-1", true},
{"/etc/a.json?offset=abc", true},
{"/etc/a.json?offset=99999999999999999999", true},
{"/etc/a.json?offset=", true},
{"/data/a.bin?offset=-1", false},
{"/data/a.bin?offset=abc", false},
{"/data/a.bin?offset=99999999999999999999", false},
{"/data/a.bin?op=append&offset=5", false},
}
for _, tc := range cases {
r := httptest.NewRequest(http.MethodPut, tc.target, bytes.NewReader([]byte("x")))
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: tc.saveInside})
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), constants.ErrMsgInvalidOffset) {
t.Fatalf("%s: status %d body %s, want 400 invalid offset", tc.target, recorder.Code, recorder.Body.String())
}
}
r := httptest.NewRequest(http.MethodPut, "/etc/a.json?offset=0", bytes.NewReader([]byte("x")))
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true})
if recorder.Code != http.StatusCreated {
t.Fatalf("offset=0: status %d body %s, want 201", recorder.Code, recorder.Body.String())
}
saved, err := f.FindEntry(ctx, "/etc/a.json")
if err != nil || !bytes.Equal(saved.Content, []byte("x")) {
t.Fatalf("offset=0 entry = %v, %v; want inline content", saved, err)
}
}
// A body stored inline is held in memory whole, so it is bounded: at the bound
// it is stored, one byte over it is refused with 413 whether or not its length
// was declared, and nothing is stored.
func TestFilerSaveInsideBodyIsBounded(t *testing.T) {
ctx := context.Background()
f := newRenameTestFiler(t, newRenameTestStore())
fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}}
atLimit := bytes.Repeat([]byte("a"), saveInsideMaxBytes)
overLimit := append(atLimit, 'b')
r := httptest.NewRequest(http.MethodPut, "/etc/at-limit.json", bytes.NewReader(atLimit))
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true})
if recorder.Code != http.StatusCreated {
t.Fatalf("PUT at the bound: status %d, want 201", recorder.Code)
}
if saved, err := f.FindEntry(ctx, "/etc/at-limit.json"); err != nil || len(saved.Content) != saveInsideMaxBytes || len(saved.GetChunks()) != 0 {
t.Fatalf("PUT at the bound was not stored inline: %v", err)
}
for _, tc := range []struct {
name string
request func() *http.Request
}{
{"declared length", func() *http.Request {
return httptest.NewRequest(http.MethodPut, "/etc/over.json", bytes.NewReader(overLimit))
}},
{"unknown length", func() *http.Request {
r := httptest.NewRequest(http.MethodPut, "/etc/over.json", bytes.NewReader(overLimit))
r.ContentLength = -1
return r
}},
{"multipart POST", func() *http.Request {
return saveInsideMultipartRequest(t, "/etc/", "over.json", overLimit)
}},
} {
r := tc.request()
recorder := httptest.NewRecorder()
fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true})
if recorder.Code != http.StatusRequestEntityTooLarge || !strings.Contains(recorder.Body.String(), constants.ErrMsgSaveInsideTooLarge) {
t.Fatalf("%s over the bound: status %d body %.200s, want 413", tc.name, recorder.Code, recorder.Body.String())
}
if _, err := f.FindEntry(ctx, "/etc/over.json"); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("%s over the bound stored an entry: %v", tc.name, err)
}
}
}
// Only entries in /etc are kept inline: a sibling such as /etcd-backup/ holds
// ordinary data and keeps the chunk path, while a multipart POST to the /etc
// directory itself lands a file inside it.
func TestFilerPutUnderEtcSiblingStillChunks(t *testing.T) {
ctx := context.Background()
content := []byte("snapshot")
f := newRenameTestFiler(t, newRenameTestStore())
fs, uploaded := newInlineAppendUploadServer(t, f, 0, 1)
for _, tc := range []struct {
target, saved string
inline bool
}{
{"/etc/targets.json", "/etc/targets.json", true},
{"/etc", "/etc/posted.json", true},
{"/etcd-backup/snap.db", "/etcd-backup/snap.db", false},
{"/etcetera", "/etcetera", false},
} {
before := uploaded.count()
r := httptest.NewRequest(http.MethodPut, tc.target, bytes.NewReader(content))
if tc.target != tc.saved {
r = saveInsideMultipartRequest(t, tc.target, path.Base(tc.saved), content)
}
recorder := httptest.NewRecorder()
fs.PostHandler(recorder, r, r.ContentLength)
if recorder.Code != http.StatusCreated {
t.Fatalf("%s %s status = %d, body %s", r.Method, tc.target, recorder.Code, recorder.Body.String())
}
saved, err := f.FindEntry(ctx, util.FullPath(tc.saved))
if err != nil {
t.Fatalf("find %s: %v", tc.saved, err)
}
chunks := uploaded.count() - before
if tc.inline && (!bytes.Equal(saved.Content, content) || len(saved.GetChunks()) != 0 || chunks != 0) {
t.Fatalf("%s %s: content=%q chunks=%d uploaded=%d, want inline", r.Method, tc.target, saved.Content, len(saved.GetChunks()), chunks)
}
if !tc.inline && (len(saved.Content) != 0 || len(saved.GetChunks()) != 1 || chunks != 1) {
t.Fatalf("%s %s: content=%q chunks=%d uploaded=%d, want one chunk", r.Method, tc.target, saved.Content, len(saved.GetChunks()), chunks)
}
}
}
@@ -9,7 +9,6 @@ import (
"hash"
"io"
"net/http"
"strconv"
"sync"
"time"
@@ -21,6 +20,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/constants"
)
var bufPool = sync.Pool{
@@ -30,22 +30,15 @@ var bufPool = sync.Pool{
}
func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.ResponseWriter, r *http.Request, reader io.Reader, chunkSize int32, fileName, contentType string, contentLength int64, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) {
query := r.URL.Query()
isAppend := isAppend(r)
if query.Has("offset") {
offset := query.Get("offset")
offsetInt, err := strconv.ParseInt(offset, 10, 64)
if err != nil || offsetInt < 0 {
err = fmt.Errorf("invalid 'offset': '%s'", offset)
return nil, nil, 0, err, nil
}
if isAppend && offsetInt > 0 {
err = fmt.Errorf("cannot set offset when op=append")
return nil, nil, 0, err, nil
}
chunkOffset = offsetInt
offset, err := requestOffset(r)
if err != nil {
return nil, nil, 0, err, nil
}
if isAppend && offset > 0 {
return nil, nil, 0, fmt.Errorf("%s: cannot set offset when op=append", constants.ErrMsgInvalidOffset), nil
}
chunkOffset = offset
if isAppend && !so.SaveInside {
fullPath := fs.fixFilePath(ctx, r, fileName)
+4
View File
@@ -12,6 +12,10 @@ const (
ErrMsgAppendInlineMode = "append to inline content with this storage mode is not supported"
ErrMsgOffsetWriteInline = "offset write to inline small file is not supported yet"
ErrMsgPartialWriteRemoteOnly = "append or offset write to a remote-only entry is not supported; cache it first"
// Prefix of the error for a malformed or disallowed ?offset.
ErrMsgInvalidOffset = "invalid 'offset'"
// Prefix of the error for a saveInside body over the inline size bound.
ErrMsgSaveInsideTooLarge = "content saved inside the entry is too large"
// Suffix appended to a path, e.g. "/buckets/b/foo/bar is a file"
ErrMsgIsAFile = " is a file"
// Prefix + suffix, e.g. "existing /buckets/b/foo is a directory"