diff --git a/weed/filer/gateway_upload.go b/weed/filer/gateway_upload.go index 7b6da4a25c..6edcd2ec00 100644 --- a/weed/filer/gateway_upload.go +++ b/weed/filer/gateway_upload.go @@ -117,6 +117,7 @@ func SaveGatewayDataAsChunk(req GatewayChunkUploadRequest) (*filer_pb.FileChunk, IsInputCompressed: false, MimeType: req.MimeType, PairMap: req.PairMap, + WantMd5: true, } if req.VolumeServerAccess == "filerProxy" && req.FilerHTTPAddress != "" { diff --git a/weed/filer/gateway_upload_test.go b/weed/filer/gateway_upload_test.go new file mode 100644 index 0000000000..a4d05813f3 --- /dev/null +++ b/weed/filer/gateway_upload_test.go @@ -0,0 +1,40 @@ +package filer + +import ( + "io" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/operation" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +type recordingUploader struct { + option *operation.UploadOption +} + +func (u *recordingUploader) UploadWithRetry(_ filer_pb.FilerClient, _ *filer_pb.AssignVolumeRequest, option *operation.UploadOption, reader io.Reader) (string, *operation.UploadResult, error, []byte) { + u.option = option + data, _ := io.ReadAll(reader) + return "1,01", &operation.UploadResult{Size: uint32(len(data))}, nil, data +} + +type nopFilerClient struct{ filer_pb.FilerClient } + +// Without the chunk md5 the file ETag is the md5 of empty digests, so an +// overwrite keeps the same ETag. +func TestSaveGatewayDataAsChunkAsksForMd5(t *testing.T) { + uploader := &recordingUploader{} + _, err := SaveGatewayDataAsChunk(GatewayChunkUploadRequest{ + FilerClient: nopFilerClient{}, + Uploader: uploader, + Reader: strings.NewReader("hello"), + FullPath: "/buckets/b/x.txt", + }) + if err != nil { + t.Fatal(err) + } + if !uploader.option.WantMd5 { + t.Fatal("WantMd5 is false; the chunk gets no ETag") + } +} diff --git a/weed/server/webdav_server.go b/weed/server/webdav_server.go index 8d0284af92..1c2d89eca6 100644 --- a/weed/server/webdav_server.go +++ b/weed/server/webdav_server.go @@ -110,20 +110,36 @@ func (h basicAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.next.ServeHTTP(w, r) } -// putOutcomeKey carries the flag WebDavFileSystem.OpenFile sets when a PUT -// replaced an existing entry, so the PUT can answer 204 instead of 201 +// putOutcomeKey carries the putOutcome a PUT's WebDavFileSystem calls fill type putOutcomeKey struct{} -// putOutcomeWriter turns the 201 of a PUT that replaced a file into 204 -// and swallows the status text webdav.Handler writes after it +// putOutcome records whether OpenFile replaced an existing entry, so the PUT +// can answer 204 instead of 201, and the ETag of what Close committed: +// webdav.Handler takes the ETag from a Stat made before Close +type putOutcome struct { + replaced bool + committed bool + etag string +} + +// putOutcomeWriter turns the 201 of a PUT that replaced a file into 204, +// swallows the status text webdav.Handler writes after it, and sends the +// committed content's ETag type putOutcomeWriter struct { http.ResponseWriter - replaced *bool + outcome *putOutcome noContent bool } func (w *putOutcomeWriter) WriteHeader(code int) { - if code == http.StatusCreated && *w.replaced { + if code == http.StatusCreated && w.outcome.committed { + if w.outcome.etag != "" { + w.Header().Set("ETag", `"`+w.outcome.etag+`"`) + } else { + w.Header().Del("ETag") + } + } + if code == http.StatusCreated && w.outcome.replaced { code = http.StatusNoContent w.noContent = true } @@ -271,9 +287,9 @@ func (h copyMoveGuardHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) // always answers 201, so OpenFile reports a replace on the request // context and the writer rewrites the status it sends if r.Method == "PUT" { - replaced := new(bool) - w = &putOutcomeWriter{ResponseWriter: w, replaced: replaced} - r = r.WithContext(context.WithValue(r.Context(), putOutcomeKey{}, replaced)) + outcome := &putOutcome{} + w = &putOutcomeWriter{ResponseWriter: w, outcome: outcome} + r = r.WithContext(context.WithValue(r.Context(), putOutcomeKey{}, outcome)) } // RFC 4918 10.6: a missing Overwrite header means T, but webdav.Handler // only overwrites on MOVE when it is set (golang/go#66059) @@ -376,7 +392,7 @@ func (fi *FileInfo) ETag(ctx context.Context) (string, error) { // an empty DAV:getetag is not a valid entity-tag; let webdav derive one return "", webdav.ErrNotImplemented } - return fi.etag, nil + return `"` + fi.etag + `"`, nil } type WebDavFile struct { @@ -566,8 +582,8 @@ func (fs *WebDavFileSystem) OpenFile(ctx context.Context, fullFilePath string, f // outcome matches what the write did even against racing writers: a // PUT that landed on an entry answers 204, a fresh create answers 201 if resp.GetMetadataEvent().GetEventNotification().GetOldEntry() != nil { - if replaced, ok := ctx.Value(putOutcomeKey{}).(*bool); ok { - *replaced = true + if outcome, ok := ctx.Value(putOutcomeKey{}).(*putOutcome); ok { + outcome.replaced = true } } return &WebDavFile{ @@ -736,6 +752,34 @@ func (fs *WebDavFileSystem) stat(ctx context.Context, fullFilePath string) (os.F return toFileInfo(fullpath, entry), nil } +// contentETag is the filer ETag when it tells contents apart: one built from +// chunks stored without a digest is shared by every file with as many chunks, +// and one for inline content by every inline file, so those are tagged by the +// inline bytes or by where the chunks are stored. +func contentETag(entry *filer_pb.Entry) string { + if entry.Attributes == nil || entry.Attributes.Md5 == nil { + if len(entry.Content) > 0 { + return util.Md5String(entry.Content) + } + for _, chunk := range entry.GetChunks() { + if chunk.ETag == "" { + return chunkLayoutETag(entry.GetChunks()) + } + } + } + return filer.ETag(entry) +} + +// chunkLayoutETag tags chunks by their file ids and placement: rewritten +// content is stored in new chunks, and entries sharing chunks share content. +func chunkLayoutETag(chunks []*filer_pb.FileChunk) string { + h := util.NewMd5() + for _, chunk := range chunks { + fmt.Fprintf(h, "%s,%d,%d,%d;", chunk.GetFileIdString(), chunk.Offset, chunk.Size, chunk.ModifiedTsNs) + } + return fmt.Sprintf("%x", h.Sum(nil)) +} + func toFileInfo(fullpath util.FullPath, entry *filer_pb.Entry) *FileInfo { // Name is what WebDAV publishes as DAV:displayname; clients that build a // child URL from it reach nothing when it carries the whole path. @@ -745,7 +789,7 @@ func toFileInfo(fullpath util.FullPath, entry *filer_pb.Entry) *FileInfo { name: fp.Name(), mode: os.FileMode(entry.Attributes.FileMode), modifiedTime: time.Unix(entry.Attributes.Mtime, 0), - etag: filer.ETag(entry), + etag: contentETag(entry), isDirectory: entry.IsDirectory, } @@ -881,6 +925,10 @@ func (f *WebDavFile) Close() error { err := f.bufWriter.Close() if f.entry != nil { + if outcome, ok := f.requestContext().Value(putOutcomeKey{}).(*putOutcome); ok && err == nil { + outcome.committed = true + outcome.etag = contentETag(f.entry) + } f.entry = nil f.visibleIntervals = nil } diff --git a/weed/server/webdav_server_test.go b/weed/server/webdav_server_test.go index a54a302910..b5319b9a53 100644 --- a/weed/server/webdav_server_test.go +++ b/weed/server/webdav_server_test.go @@ -11,15 +11,18 @@ import ( "path" "strings" "testing" + "time" "golang.org/x/net/webdav" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" + "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/security" "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/seaweedfs/seaweedfs/weed/util/buffered_writer" "github.com/seaweedfs/seaweedfs/weed/wdclient" "github.com/stretchr/testify/assert" ) @@ -52,14 +55,90 @@ func TestToFileInfoRootIsDirectory(t *testing.T) { } } +func TestToFileInfoETag(t *testing.T) { + file := func(etags ...string) *filer_pb.Entry { + entry := &filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{}} + for i, etag := range etags { + entry.Chunks = append(entry.Chunks, &filer_pb.FileChunk{FileId: fmt.Sprintf("1,%x", i+1), ETag: etag}) + } + return entry + } + + digestless := toFileInfo("/f", file("", "")).etag + if digestless == "" || digestless == filer.ETagChunks(file("", "").Chunks) { + t.Errorf("chunks without digests got etag %q; every 2-chunk file would share it", digestless) + } + moved := file("", "") + moved.Chunks[1].FileId = "2,03" + if etag := toFileInfo("/f", moved).etag; etag == digestless { + t.Errorf("chunks without digests in other needles got the same etag %q", etag) + } + if etag := toFileInfo("/f", file("XUFAKrxLKna5cZ2REBfFkg==", "XUFAKrxLKna5cZ2REBfFkg==")).etag; etag == "" { + t.Error("chunks with digests got no etag") + } + inline := func(content string) string { + entry := file() + entry.Content = []byte(content) + entry.Attributes.Mtime = 1700000000 + return toFileInfo("/f", entry).etag + } + if hello, world := inline("hello"), inline("world"); hello == "" || hello == world { + t.Errorf("inline contents of one size and mtime got etags %q and %q; a replace would answer 304", hello, world) + } + withMd5 := file("") + withMd5.Attributes.Md5 = []byte{0xab} + if etag := toFileInfo("/f", withMd5).etag; etag != "ab" { + t.Errorf("entry md5 etag = %q, want ab", etag) + } +} + +func TestPutAnswersCommittedETag(t *testing.T) { + outcome := &putOutcome{} + f := &WebDavFile{ + bufWriter: buffered_writer.NewBufferedWriteCloser(1024), + entry: &filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{}}, + ctx: context.WithValue(context.Background(), putOutcomeKey{}, outcome), + } + // the last chunk is only uploaded by Close + f.bufWriter.FlushFunc = func(data []byte, offset int64) error { + f.entry.Chunks = append(f.entry.Chunks, &filer_pb.FileChunk{FileId: "1,01", ETag: "XUFAKrxLKna5cZ2REBfFkg=="}) + return nil + } + if _, err := f.bufWriter.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + // webdav.Handler sets the ETag from a Stat made before Close committed + rec.Header().Set("ETag", `"d41d8cd98f00b204e9800998ecf8427e-0"`) + (&putOutcomeWriter{ResponseWriter: rec, outcome: outcome}).WriteHeader(http.StatusCreated) + if got, want := rec.Header().Get("ETag"), `"5d41402abc4b2a76b9719d911017c592"`; got != want { + t.Errorf("PUT ETag = %s, want the committed %s", got, want) + } +} + func TestFileInfoETag(t *testing.T) { ctx := context.Background() if _, err := (&FileInfo{}).ETag(ctx); err != webdav.ErrNotImplemented { t.Errorf("empty etag returned %v, want ErrNotImplemented so webdav derives one", err) } - if etag, err := (&FileInfo{etag: "abc"}).ETag(ctx); err != nil || etag != "abc" { - t.Errorf("ETag() = %q, %v, want \"abc\", nil", etag, err) + etag, err := (&FileInfo{etag: "abc"}).ETag(ctx) + if err != nil || etag != `"abc"` { + t.Fatalf("ETag() = %q, %v, want %q, nil", etag, err, `"abc"`) + } + + // webdav hands the tag to http.ServeContent, which only matches quoted tags. + req := httptest.NewRequest(http.MethodGet, "/f", nil) + req.Header.Set("If-None-Match", etag) + rec := httptest.NewRecorder() + rec.Header().Set("ETag", etag) + http.ServeContent(rec, req, "f", time.Time{}, strings.NewReader("hello")) + if rec.Code != http.StatusNotModified { + t.Errorf("If-None-Match with the served ETag got %d, want 304", rec.Code) } } @@ -880,8 +959,8 @@ type putOutcomeFS struct { func (f putOutcomeFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) { if flag&os.O_CREATE != 0 { if _, err := f.FileSystem.Stat(ctx, name); err == nil { - if replaced, ok := ctx.Value(putOutcomeKey{}).(*bool); ok { - *replaced = true + if outcome, ok := ctx.Value(putOutcomeKey{}).(*putOutcome); ok { + outcome.replaced = true } } } @@ -917,14 +996,14 @@ func TestWebDavFileSystem_OpenFile_PutOutcomeFlag(t *testing.T) { }} open := func(name string) bool { - replaced := new(bool) - ctx := context.WithValue(context.Background(), putOutcomeKey{}, replaced) + outcome := &putOutcome{} + ctx := context.WithValue(context.Background(), putOutcomeKey{}, outcome) f, err := fs.OpenFile(ctx, name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) assert.NoError(t, err) if f != nil { assert.NoError(t, f.Close()) } - return *replaced + return outcome.replaced } assert.True(t, open("/old.txt"))