Compare commits

...
Author SHA1 Message Date
Chris Lu bd3b75b534 mount: let a readdirplus stop taking references at a cap
The inode table only shrinks when the kernel returns a reference, so a walk
over a large tree grows it with every child it touches and nothing gives any
of it back until the kernel reclaims dentries. On a mount with tens of
millions of files that is most of the process's heap.

-maxInodeEntries stops the speculative half of that. Past the cap a
readdirplus still reports every name, but leaves the EntryOut zeroed: Linux
reads a zero nodeid as 'no attributes for this entry', takes no reference, and
looks up the ones the client actually needs. A LOOKUP is never refused, so the
table can still grow past the cap by what a client really asks for, and
nothing here evicts. Default 0 keeps today's behavior.
2026-08-18 21:00:49 -07:00
Lars Lehtonen ed75a61fb0 fix(test/s3/versioning): dropped test error (#10813) 2026-08-18 17:26:51 -07:00
9575032b4c volume: forward fsync=true to replicas in ReplicatedWrite (#10805)
* volume: forward fsync=true to replicas in ReplicatedWrite

When a write request carries fsync=true, only the primary volume server
flushed to disk: the replica fan-out URL in ReplicatedWrite only carried
type/ttl/ts/cm, so replicas always wrote without fsync even when the
client explicitly requested a durable write.

Forward the fsync request parameter to the replica volume servers so a
durable write means every replica has flushed to disk, not just the
primary. Replicas without fsync are untouched (zero behavior change).

* storage: flush a durable write inline while stopping

The fsync flag on the write path really selects the async batch worker,
and it was switched off once the store is stopping. So a fsync=true write
landing during the pre-stop drain got acked without ever being flushed -
and now that ReplicatedWrite forwards fsync, that covers replicas too.

Flush it inline instead of queueing it. The drain keeps accepting writes,
which is the whole point of preStopSeconds, and the ack still means the
.dat is on disk. If the fsync fails, the append comes back off the .dat
and the needle map goes back to what it pointed at before, so nothing
resolves to an offset past the truncated end.

* storage: make the store's stopping flag atomic

SetStopping runs on the signal handler goroutine while the write and
vacuum paths read the flag, so every read of it was racy. Nothing about
the shutdown ordering changes; only the flag itself is now safe to read.

* topology: check the errors the replication test was dropping

The mock replica ignored its response write and the mock master ignored
whatever Serve returned, so a broken mock would have shown up as a
confusing timeout rather than a failure. Also drops the explicit listener
close: grpc.Server.Stop already closes the listener it was given.

---------

Co-authored-by: hzsunchao <hzsunchao@corp.netease.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-08-18 17:17:50 -07:00
Chris Lu 1354b58675 s3: stop unrouted bucket subresources from being answered with a listing (#10814)
* s3: answer GetBucketReplication, GetBucketWebsite and GetBucketNotificationConfiguration

None of the three had a route, so they reached the unconstrained ListObjectsV1
catch-all and a client asking for a bucket's replication config got 200 and a
<ListBucketResult> back. Replication and website report their configuration as
absent the way AWS does; notification returns the empty configuration AWS
returns for a bucket with no events wired up.

* s3: stop an unrouted bucket subresource from being answered with a listing

ListObjectsV1 is the catch-all GET on a bucket, so every subresource without a
route of its own - ?torrent today, whatever AWS adds next - came back 200 with a
<ListBucketResult>. A client that asked for a configuration and got a listing
either fails its XML decode in a way that reads like corruption, or worse,
tolerantly parses it. Refuse the request instead.

The allow-list is the ListObjects parameters rather than the subresources,
so a new one fails closed. Presigned URLs sign their credentials into the
query string, so X-Amz-* and the SigV2 trio have to stay listable.
2026-08-18 16:03:08 -07:00
Da.SanchezandChris Lu 68a23a4b3c filer: stop remote.unmount from deleting the remote objects (#10811)
* filer: add filer.options.disable_remote_storage_deletion for cache-only deletes

Deleting a filer entry under a remote.mount path also deletes the backing
object from the remote store (maybeDeleteFromRemote). Deployments that use a
remote mount as a read-through cache in front of an authoritative,
externally-managed object store cannot allow this: the filer typically holds
read-only credentials, so the remote delete fails and the entire delete
errors out; and even where it would succeed, it destroys data the filer does
not own.

Add filer.options.disable_remote_storage_deletion (default false, so existing
behaviour is unchanged). When enabled, maybeDeleteFromRemote is skipped for
both single-entry and recursive folder deletes: local metadata and cached
chunks are still removed, but the remote object is left intact.

* filer: assert local removal in cache-only recursive delete test

The recursive cache-only delete test only checked that no remote delete
happened; it did not verify the local child and directory entries were
removed. Add FindEntry assertions so a regression that skips local
recursive deletion is caught.

* filer: reload the remote mount mapping when /etc/remote changes

The mapping was only read at startup, so remote.unmount left the mount live
in the filer: the purge that follows the mapping delete then went to the
remote store and wiped every object under the mount.

Rebuild the rules trie and the conf map from scratch on each load, since
ptrie cannot drop a key, and swap them under a lock.

* filer: drop the filer-wide remote deletion switch

With the mapping reloaded on unmount, the purge no longer reaches the remote
store, so there is nothing left for the switch to protect against.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-08-18 15:38:02 -07:00
34 changed files with 663 additions and 68 deletions

No files matched your search

@@ -186,6 +186,7 @@ func TestVersioningPaginationOver1000Versions(t *testing.T) {
buf := make([]byte, len(expectedContent))
_, err = getResp.Body.Read(buf)
require.NoError(t, err)
getResp.Body.Close()
assert.Equal(t, expectedContent, string(buf), "Content mismatch for version %d", idx+1)
+2
View File
@@ -21,6 +21,7 @@ type MountOptions struct {
concurrentReaders *int
cacheMetaTtlSec *int
cacheDirMaxEntries *int
maxInodeEntries *int
cacheDirForRead *string
cacheDirForWrite *string
cacheSizeMBForRead *int64
@@ -116,6 +117,7 @@ func init() {
mountOptions.writeBufferSizeMB = cmdMount.Flag.Int64("writeBufferSizeMB", 0, "global cap on the per-mount write buffer (memory + swap) in MB, 0 means unlimited. Bounds /tmp growth when volume uploads stall")
mountOptions.cacheMetaTtlSec = cmdMount.Flag.Int("cacheMetaTtlSec", 60, "metadata cache validity seconds")
mountOptions.cacheDirMaxEntries = cmdMount.Flag.Int("cacheDirMaxEntries", 100000, "a directory with more children than this is not cached locally but read directly from the filer; 0 caches everything")
mountOptions.maxInodeEntries = cmdMount.Flag.Int("maxInodeEntries", 0, "stop handing the kernel references from readdirplus once this many inodes are tracked; listings stay complete and the kernel looks up what it needs. Does not evict - the table shrinks only as the kernel returns references. 0 is unlimited")
mountOptions.dataCenter = cmdMount.Flag.String("dataCenter", "", "prefer to write to the data center")
mountOptions.allowOthers = cmdMount.Flag.Bool("allowOthers", true, "allows other users to access the file system")
mountOptions.defaultPermissions = cmdMount.Flag.Bool("defaultPermissions", true, "enforce permissions by the operating system")
+1
View File
@@ -204,6 +204,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
WriteBufferSizeMB: *option.writeBufferSizeMB,
CacheMetaTTlSec: *option.cacheMetaTtlSec,
CacheDirMaxEntries: *option.cacheDirMaxEntries,
MaxInodeEntries: *option.maxInodeEntries,
DataCenter: *option.dataCenter,
Quota: int64(*option.collectionQuota) * 1024 * 1024,
LogicalDiskUsage: *option.logicalDiskUsage,
+64
View File
@@ -300,6 +300,19 @@ func registerStubMaker(t *testing.T, storageType string, client remote_storage.R
}
}
// putConfigEntry stores a filer entry whose content is a serialized configuration.
func putConfigEntry(store *stubFilerStore, path string, content []byte) {
store.entries[path] = &Entry{
FullPath: util.FullPath(path),
Attr: Attr{
Mtime: time.Unix(1700000000, 0),
Crtime: time.Unix(1700000000, 0),
Mode: 0644,
},
Content: content,
}
}
// --- tests ---
func TestMaybeLazyFetchFromRemote_HitsRemoteAndPersists(t *testing.T) {
@@ -581,6 +594,57 @@ func TestDeleteEntryMetaAndData_IsFromOtherClusterSkipsRemoteDelete(t *testing.T
require.Len(t, stub.removeCalls, 0)
}
func TestDeleteEntryMetaAndData_UnmountedDirectorySkipsRemoteDelete(t *testing.T) {
const storageType = "stub_lazy_unmounted"
stub := &stubRemoteClient{}
defer registerStubMaker(t, storageType, stub)()
store := newStubFilerStore()
confContent, err := proto.Marshal(&remote_pb.RemoteConf{Name: "cloud1", Type: storageType})
require.NoError(t, err)
putConfigEntry(store, DirectoryEtcRemote+"/cloud1"+REMOTE_STORAGE_CONF_SUFFIX, confContent)
mountedContent, err := proto.Marshal(&remote_pb.RemoteStorageMapping{
Mappings: map[string]*remote_pb.RemoteStorageLocation{
"/buckets/mybucket": {Name: "cloud1", Bucket: "mybucket", Path: "/"},
},
})
require.NoError(t, err)
putConfigEntry(store, DirectoryEtcRemote+"/"+REMOTE_STORAGE_MOUNT_FILE, mountedContent)
filePath := util.FullPath("/buckets/mybucket/cached.txt")
store.entries[string(filePath)] = &Entry{
FullPath: filePath,
Attr: Attr{
Mtime: time.Unix(1700000000, 0),
Crtime: time.Unix(1700000000, 0),
Mode: 0644,
FileSize: 64,
},
Remote: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 64},
}
f := newTestFiler(t, store, NewFilerRemoteStorage())
f.LoadRemoteStorageConfAndMapping()
_, remoteLoc := f.RemoteStorage.FindMountDirectory(filePath)
require.NotNil(t, remoteLoc)
unmountedContent, err := proto.Marshal(&remote_pb.RemoteStorageMapping{})
require.NoError(t, err)
putConfigEntry(store, DirectoryEtcRemote+"/"+REMOTE_STORAGE_MOUNT_FILE, unmountedContent)
f.onMetadataChangeEvent(&filer_pb.SubscribeMetadataResponse{
Directory: DirectoryEtcRemote,
EventNotification: &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{Name: REMOTE_STORAGE_MOUNT_FILE, Content: unmountedContent},
},
})
_, remoteLoc = f.RemoteStorage.FindMountDirectory(filePath)
require.Nil(t, remoteLoc)
require.NoError(t, f.DeleteEntryMetaAndData(context.Background(), filePath, false, false, true, false, nil, 0))
require.Len(t, stub.deleteCalls, 0)
require.Len(t, stub.removeCalls, 0)
}
func TestDeleteEntryMetaAndData_RemoteOnlyFileNotUnderMountSkipsRemoteDelete(t *testing.T) {
const storageType = "stub_lazy_delete_not_under_mount"
stub := &stubRemoteClient{}
+7 -1
View File
@@ -136,5 +136,11 @@ func (f *Filer) LoadRemoteStorageConfAndMapping() {
}
}
func (f *Filer) maybeReloadRemoteStorageConfigurationAndMapping(event *filer_pb.SubscribeMetadataResponse) {
// FIXME add reloading
if !filer_pb.MetadataEventTouchesDirectory(event, DirectoryEtcRemote) {
return
}
// a mount left behind after remote.unmount would still send deletes to a
// remote the filer no longer owns
f.LoadRemoteStorageConfAndMapping()
}
+32 -14
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"math"
"strings"
"sync"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
@@ -22,6 +23,9 @@ const REMOTE_STORAGE_CONF_SUFFIX = ".conf"
const REMOTE_STORAGE_MOUNT_FILE = "mount.mapping"
type FilerRemoteStorage struct {
// guards rules and storageNameToConf, which are replaced wholesale
// whenever /etc/remote changes
mu sync.RWMutex
rules ptrie.Trie[*remote_pb.RemoteStorageLocation]
storageNameToConf map[string]*remote_pb.RemoteConf
}
@@ -48,44 +52,62 @@ func (rs *FilerRemoteStorage) LoadRemoteStorageConfigurationsAndMapping(filer *F
return
}
// build into fresh containers so an unmounted directory disappears instead
// of lingering in the trie, which has no way to drop a key
rules := ptrie.New[*remote_pb.RemoteStorageLocation]()
storageNameToConf := make(map[string]*remote_pb.RemoteConf)
for _, entry := range entries {
if entry.Name() == REMOTE_STORAGE_MOUNT_FILE {
if err := rs.loadRemoteStorageMountMapping(entry.Content); err != nil {
if err := loadRemoteStorageMountMapping(rules, entry.Content); err != nil {
return err
}
continue
}
if !strings.HasSuffix(entry.Name(), REMOTE_STORAGE_CONF_SUFFIX) {
return nil
continue
}
conf := &remote_pb.RemoteConf{}
if err := proto.Unmarshal(entry.Content, conf); err != nil {
return fmt.Errorf("unmarshal %s/%s: %v", DirectoryEtcRemote, entry.Name(), err)
}
rs.storageNameToConf[conf.Name] = conf
storageNameToConf[conf.Name] = conf
}
rs.mu.Lock()
rs.rules, rs.storageNameToConf = rules, storageNameToConf
rs.mu.Unlock()
return nil
}
func (rs *FilerRemoteStorage) loadRemoteStorageMountMapping(data []byte) (err error) {
func loadRemoteStorageMountMapping(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], data []byte) (err error) {
mappings := &remote_pb.RemoteStorageMapping{}
if err := proto.Unmarshal(data, mappings); err != nil {
return fmt.Errorf("unmarshal %s/%s: %v", DirectoryEtcRemote, REMOTE_STORAGE_MOUNT_FILE, err)
}
for dir, storageLocation := range mappings.Mappings {
rs.mapDirectoryToRemoteStorage(util.FullPath(dir), storageLocation)
putDirectoryToRemoteStorage(rules, util.FullPath(dir), storageLocation)
}
return nil
}
func (rs *FilerRemoteStorage) mapDirectoryToRemoteStorage(dir util.FullPath, loc *remote_pb.RemoteStorageLocation) {
rs.rules.Put([]byte(dir+"/"), loc)
rs.mu.Lock()
defer rs.mu.Unlock()
putDirectoryToRemoteStorage(rs.rules, dir, loc)
}
func putDirectoryToRemoteStorage(rules ptrie.Trie[*remote_pb.RemoteStorageLocation], dir util.FullPath, loc *remote_pb.RemoteStorageLocation) {
rules.Put([]byte(dir+"/"), loc)
}
// FindMountDirectory returns the mount directory and location for p. When multiple
// mounts match (e.g. /buckets/b and /buckets/b/prefix), ptrie MatchPrefix visits
// shorter prefixes first, so the last match is the longest prefix.
func (rs *FilerRemoteStorage) FindMountDirectory(p util.FullPath) (mountDir util.FullPath, remoteLocation *remote_pb.RemoteStorageLocation) {
rs.mu.RLock()
defer rs.mu.RUnlock()
rs.rules.MatchPrefix([]byte(p), func(key []byte, value *remote_pb.RemoteStorageLocation) bool {
mountDir = util.FullPath(string(key[:len(key)-1]))
remoteLocation = value
@@ -95,22 +117,18 @@ func (rs *FilerRemoteStorage) FindMountDirectory(p util.FullPath) (mountDir util
}
func (rs *FilerRemoteStorage) FindRemoteStorageClient(p util.FullPath) (client remote_storage.RemoteStorageClient, remoteConf *remote_pb.RemoteConf, found bool) {
var storageLocation *remote_pb.RemoteStorageLocation
rs.rules.MatchPrefix([]byte(p), func(key []byte, value *remote_pb.RemoteStorageLocation) bool {
storageLocation = value
return true
})
_, storageLocation := rs.FindMountDirectory(p)
if storageLocation == nil {
found = false
return
return nil, nil, false
}
return rs.GetRemoteStorageClient(storageLocation.Name)
}
func (rs *FilerRemoteStorage) GetRemoteStorageClient(storageName string) (client remote_storage.RemoteStorageClient, remoteConf *remote_pb.RemoteConf, found bool) {
rs.mu.RLock()
remoteConf, found = rs.storageNameToConf[storageName]
rs.mu.RUnlock()
if !found {
return
}
+6
View File
@@ -214,6 +214,12 @@ func (i *InodeToPath) GetAllPaths(inode uint64) []util.FullPath {
return out
}
func (i *InodeToPath) Len() int {
i.RLock()
defer i.RUnlock()
return len(i.inode2path)
}
func (i *InodeToPath) HasPath(path util.FullPath) bool {
i.RLock()
defer i.RUnlock()
+5
View File
@@ -60,6 +60,11 @@ type Option struct {
DisableXAttr bool
IsMacOs bool
// MaxInodeEntries bounds what readdirplus adds, not the table itself: only
// a kernel FORGET releases an entry, and LOOKUP is never refused.
// 0 is unlimited.
MaxInodeEntries int
// LogicalDiskUsage reports data sizes rather than the space they occupy,
// for both df and the quota. See WFS.diskSizes.
LogicalDiskUsage bool
+10
View File
@@ -214,6 +214,13 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
// Only a reference makes a child worth entering in the inode table: without
// one nothing ever arrives to take the entry back out again.
takesLookupRef := isPlusMode && out.TakesLookupRef()
// A zeroed EntryOut reads to the kernel as "no attributes for this entry":
// the name is still listed, but no reference is taken and none is owed back.
atInodeCap := takesLookupRef && wfs.option.MaxInodeEntries > 0 &&
wfs.inodeToPath.Len() >= wfs.option.MaxInodeEntries
if atInodeCap {
takesLookupRef = false
}
// index is the position in entryStream, used to calculate the offset for next readdir
processEachEntryFn := func(entry *filer.Entry, index int64) bool {
@@ -240,6 +247,9 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
if entryOut == nil {
return false
}
if atInodeCap {
return true
}
if fh, found := wfs.fhMap.FindFileHandle(inode); found {
glog.V(4).Infof("readdir opened file %s", childPath)
entry = filer.FromPbEntry(string(dirPath), fh.GetEntry().GetEntry())
+1 -7
View File
@@ -62,12 +62,6 @@ func (s *benchSink) AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut {
func (s *benchSink) TakesLookupRef() bool { return s.takesRef }
func inodeTableSize(i *InodeToPath) int {
i.RLock()
defer i.RUnlock()
return len(i.inode2path)
}
func newBenchWFS(tb testing.TB, dir util.FullPath, n int) *WFS {
tb.Helper()
@@ -227,7 +221,7 @@ func BenchmarkReadDirectory(b *testing.B) {
b.StopTimer()
// What the listing left in the inode table, over the root and the
// directory itself.
b.ReportMetric(float64(inodeTableSize(wfs.inodeToPath)), "inodes_left")
b.ReportMetric(float64(wfs.inodeToPath.Len()), "inodes_left")
})
}
}
@@ -0,0 +1,50 @@
package mount
import (
"fmt"
"testing"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// Past the cap the listing is still complete, but takes no more references.
func TestReadDirPlusStopsAtInodeCap(t *testing.T) {
dir := util.FullPath("/images")
names := make([]string, 40)
for i := range names {
names[i] = fmt.Sprintf("f%03d.jpg", i)
}
wfs := newPagingWFS(t, dir, names, 0)
wfs.option.MaxInodeEntries = 10
dirInode, _ := wfs.inodeToPath.GetInode(dir)
sink := &benchSink{plus: true, takesRef: true, sinkLimit: 8}
if got := walkOnce(t, wfs, dirInode, sink, false); got != len(names)+2 {
t.Fatalf("listed %d entries, want %d", got, len(names)+2)
}
if got := wfs.inodeToPath.Len(); got >= len(names) {
t.Fatalf("inode table holds %d, want it capped well under %d", got, len(names))
}
// Starting at the cap, nothing gets attributes.
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink.reset()
status := wfs.doReadDirectory(&fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Size: 1 << 20,
}, sink, true)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if sink.count == 0 {
t.Fatal("listed nothing")
}
for i := range sink.attrs {
if sink.attrs[i].NodeId != 0 {
t.Fatalf("entry %d took a reference past the cap", i)
}
}
}
+65
View File
@@ -5,6 +5,7 @@ import (
"errors"
"io"
"net/http"
"strings"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
@@ -30,6 +31,10 @@ type bucketLoggingStatusResponse struct {
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ BucketLoggingStatus"`
}
type notificationConfigurationResponse struct {
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ NotificationConfiguration"`
}
// GetBucketPolicyStatusHandler reports whether the bucket policy grants public access.
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketPolicyStatus.html
func (s3a *S3ApiServer) GetBucketPolicyStatusHandler(w http.ResponseWriter, r *http.Request) {
@@ -130,3 +135,63 @@ func (s3a *S3ApiServer) GetBucketLoggingHandler(w http.ResponseWriter, r *http.R
}
writeSuccessResponseXML(w, r, bucketLoggingStatusResponse{})
}
// GetBucketNotificationConfigurationHandler returns an empty configuration; SeaweedFS
// has no bucket event notifications, and AWS answers an unconfigured bucket the same way.
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketNotificationConfiguration.html
func (s3a *S3ApiServer) GetBucketNotificationConfigurationHandler(w http.ResponseWriter, r *http.Request) {
bucket, _ := s3_constants.GetBucketAndObject(r)
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, err)
return
}
writeSuccessResponseXML(w, r, notificationConfigurationResponse{})
}
// GetBucketReplicationHandler reports that no replication configuration exists.
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketReplication.html
func (s3a *S3ApiServer) GetBucketReplicationHandler(w http.ResponseWriter, r *http.Request) {
bucket, _ := s3_constants.GetBucketAndObject(r)
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, err)
return
}
s3err.WriteErrorResponse(w, r, s3err.ErrReplicationConfigurationNotFound)
}
// GetBucketWebsiteHandler reports that no website configuration exists.
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketWebsite.html
func (s3a *S3ApiServer) GetBucketWebsiteHandler(w http.ResponseWriter, r *http.Request) {
bucket, _ := s3_constants.GetBucketAndObject(r)
if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, err)
return
}
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchWebsiteConfiguration)
}
// listObjectsQueryParams are the query keys a ListObjects/ListObjectsV2 request may
// carry. x-id is stamped by the AWS SDKs and carries no meaning for the server; the
// rest of the non-listing keys are what a presigned URL signs into the query string.
var listObjectsQueryParams = map[string]bool{
"prefix": true, "delimiter": true, "marker": true, "max-keys": true,
"encoding-type": true, "list-type": true, "continuation-token": true,
"start-after": true, "fetch-owner": true, "expected-bucket-owner": true,
"x-id": true,
// SigV2 presigned URLs.
"AWSAccessKeyId": true, "Signature": true, "Expires": true,
}
// unroutedBucketSubresource names a query key on a bucket GET that no route claimed.
// Everything SeaweedFS implements is matched by its own route before the ListObjects
// catch-all, so anything left is a subresource it does not implement - and answering
// it with a bucket listing is worse than saying so.
func unroutedBucketSubresource(r *http.Request) (string, bool) {
for key := range r.URL.Query() {
if listObjectsQueryParams[key] || strings.HasPrefix(key, "X-Amz-") {
continue
}
return key, true
}
return "", false
}
@@ -0,0 +1,34 @@
package s3api
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
// TestUnroutedBucketSubresource guards the rule that keeps a bucket GET carrying an
// unimplemented subresource from being answered with a bucket listing: everything
// SeaweedFS implements is matched by its own route before the ListObjects catch-all,
// so anything left over that is not a listing parameter is a subresource.
func TestUnroutedBucketSubresource(t *testing.T) {
for _, query := range []string{
"",
"prefix=a&max-keys=10",
"list-type=2&continuation-token=x",
"delimiter=/&encoding-type=url",
"x-id=ListObjectsV2",
"prefix=a&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=deadbeef&X-Amz-Expires=900",
"AWSAccessKeyId=key&Signature=sig&Expires=1700000000",
} {
req, _ := http.NewRequest("GET", "http://localhost/bucket?"+query, nil)
name, found := unroutedBucketSubresource(req)
assert.False(t, found, "%q is a listing request, got %q", query, name)
}
for _, query := range []string{"torrent=", "replication=", "prefix=a&torrent="} {
req, _ := http.NewRequest("GET", "http://localhost/bucket?"+query, nil)
_, found := unroutedBucketSubresource(req)
assert.True(t, found, "%q should be reported as a subresource", query)
}
}
+13 -1
View File
@@ -923,6 +923,12 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketAccelerateConfigurationHandler, ACTION_READ)), "GET")).Queries("accelerate", "")
// GetBucketLogging
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLoggingHandler, ACTION_READ)), "GET")).Queries("logging", "")
// GetBucketNotificationConfiguration
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketNotificationConfigurationHandler, ACTION_READ)), "GET")).Queries("notification", "")
// GetBucketReplication
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketReplicationHandler, ACTION_READ)), "GET")).Queries("replication", "")
// GetBucketWebsite
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketWebsiteHandler, ACTION_READ)), "GET")).Queries("website", "")
// GetBucketVersioning
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketVersioningHandler, ACTION_READ)), "GET")).Queries("versioning", "")
@@ -993,8 +999,14 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
// DeleteBucket
bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketHandler, ACTION_DELETE_BUCKET)), "DELETE"))
// ListObjectsV1 (Legacy)
// ListObjectsV1 (Legacy). This is the catch-all GET on a bucket, so a
// subresource with no route of its own would be answered with a listing.
bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.AuthWithPublicRead(func(w http.ResponseWriter, r *http.Request) {
if subresource, found := unroutedBucketSubresource(r); found {
glog.V(1).Infof("unimplemented bucket subresource ?%s", subresource)
s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
return
}
limitedHandler, _ := s3a.cb.Limit(s3a.ListObjectsV1Handler, ACTION_LIST)
limitedHandler(w, r)
}, ACTION_LIST), "LIST"))
+12
View File
@@ -56,6 +56,8 @@ const (
ErrNoSuchBucketPolicy
ErrNoSuchCORSConfiguration
ErrNoSuchLifecycleConfiguration
ErrNoSuchWebsiteConfiguration
ErrReplicationConfigurationNotFound
ErrNoSuchKey
ErrNoSuchVersion
ErrNoSuchUpload
@@ -298,6 +300,16 @@ var errorCodeResponse = map[ErrorCode]APIError{
Description: "The lifecycle configuration does not exist",
HTTPStatusCode: http.StatusNotFound,
},
ErrNoSuchWebsiteConfiguration: {
Code: "NoSuchWebsiteConfiguration",
Description: "The specified bucket does not have a website configuration",
HTTPStatusCode: http.StatusNotFound,
},
ErrReplicationConfigurationNotFound: {
Code: "ReplicationConfigurationNotFoundError",
Description: "The replication configuration was not found",
HTTPStatusCode: http.StatusNotFound,
},
ErrNoSuchKey: {
Code: "NoSuchKey",
Description: "The specified key does not exist.",
+2 -1
View File
@@ -65,7 +65,8 @@ func (c *commandRemoteUnmount) Do(args []string, commandEnv *CommandEnv, writer
return fmt.Errorf("directory %s is not mounted", *dir)
}
// store a mount configuration in filer
// delete the mount mapping first: the filer reloads it on the spot, so the
// purge below stays local instead of deleting the remote objects
fmt.Fprintf(writer, "deleting mount for %s ...\n", *dir)
if err = filer.DeleteMountMapping(commandEnv, *dir); err != nil {
return fmt.Errorf("delete mount mapping: %w", err)
+1 -1
View File
@@ -186,7 +186,7 @@ func tierUpVolumeLive(t *testing.T, dir string, vid needle.VolumeId, b *localDir
require.NoError(t, err)
for i := 1; i <= 5; i++ {
_, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false)
_, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false)
require.NoError(t, err)
}
+4 -4
View File
@@ -80,7 +80,7 @@ type Store struct {
DeletedVolumesChan chan *master_pb.VolumeShortInformationMessage
NewEcShardsChan chan *master_pb.VolumeEcShardInformationMessage
DeletedEcShardsChan chan *master_pb.VolumeEcShardInformationMessage
isStopping bool
isStopping atomic.Bool
volumeReport volumeReportState
}
@@ -732,14 +732,14 @@ func (s *Store) deleteExpiredEcVolumes() (ecShards, deleted []*master_pb.VolumeE
}
func (s *Store) SetStopping() {
s.isStopping = true
s.isStopping.Store(true)
for _, location := range s.Locations {
location.SetStopping()
}
}
func (s *Store) IsStopping() bool {
return s.isStopping
return s.isStopping.Load()
}
func (s *Store) LoadNewVolumes() {
@@ -760,7 +760,7 @@ func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, checkCook
err = fmt.Errorf("volume %d is read only", i)
return
}
_, _, isUnchanged, err = v.writeNeedle2(n, checkCookie, fsync && !s.isStopping)
_, _, isUnchanged, err = v.writeNeedle2(n, checkCookie, fsync, s.isStopping.Load())
return
}
glog.V(0).Infoln("volume", i, "not found!")
+1 -1
View File
@@ -93,7 +93,7 @@ func TestConsolidateVolumeIndexMovesIdxToIdxDir(t *testing.T) {
require.NotNil(t, mounted)
n := &needle.Needle{Id: types.Uint64ToNeedleId(42), Data: []byte("payload-across-relocate")}
n.Checksum = needle.NewCRC(n.Data)
_, _, _, err = mounted.writeNeedle2(n, true, false)
_, _, _, err = mounted.writeNeedle2(n, true, false, false)
require.NoError(t, err)
require.NoError(t, store.ConsolidateVolumeIndex(vid))
+1 -1
View File
@@ -20,7 +20,7 @@ func TestCollectStatForOneVolumeModifiedAtSecond(t *testing.T) {
defer v.Close()
v.location = &DiskLocation{Directory: dir, DiskType: types.HardDriveType}
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
t.Fatalf("write: %v", err)
}
+1 -1
View File
@@ -32,7 +32,7 @@ func (s *Store) CompactVolume(vid needle.VolumeId, preallocate int64, compaction
}
func (s *Store) CommitCompactVolume(vid needle.VolumeId) (bool, int64, error) {
if s.isStopping {
if s.isStopping.Load() {
return false, 0, fmt.Errorf("volume id %d skips compact because volume is stopping", vid)
}
if v := s.findVolume(vid); v != nil {
+7 -7
View File
@@ -142,7 +142,7 @@ func TestScrubVolumeData_IgnoresOffset0Tombstone(t *testing.T) {
}
defer v.Close()
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
t.Fatalf("write needle: %v", err)
}
if err := v.DataBackend.Sync(); err != nil {
@@ -197,7 +197,7 @@ func TestCheckVolumeDataIntegrityWithDeletionTombstone(t *testing.T) {
for i := 1; i <= 3; i++ {
n := newRandomNeedle(uint64(i))
if _, _, _, err := v.writeNeedle2(n, true, false); err != nil {
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
}
@@ -251,7 +251,7 @@ func TestCheckVolumeDataIntegritySortedIndex(t *testing.T) {
// Write keys in descending order so the highest key lands at the lowest
// .dat offset; the last-written needle (lowest key) sits at the tail.
for _, id := range []uint64{30, 20, 10} {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
t.Fatalf("write needle %d: %v", id, err)
}
}
@@ -291,7 +291,7 @@ func TestCheckVolumeDataIntegrityVerifiesDeletionTail(t *testing.T) {
defer v.Close()
for i := 1; i <= 3; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false); err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
}
@@ -341,7 +341,7 @@ func TestVolumeLoadStaysWritableWithKeySortedIndex(t *testing.T) {
}
wanted := newRandomNeedle(10)
for _, n := range []*needle.Needle{newRandomNeedle(30), newRandomNeedle(20), wanted} {
if _, _, _, err := v.writeNeedle2(n, true, false); err != nil {
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write needle %d: %v", n.Id, err)
}
}
@@ -369,7 +369,7 @@ func TestVolumeLoadStaysWritableWithKeySortedIndex(t *testing.T) {
if _, err := reloaded.readNeedle(rn, nil, nil); err != nil {
t.Fatalf("read surviving needle after reload: %v", err)
}
if _, _, _, err := reloaded.writeNeedle2(newRandomNeedle(40), true, false); err != nil {
if _, _, _, err := reloaded.writeNeedle2(newRandomNeedle(40), true, false, false); err != nil {
t.Fatalf("write after reload should succeed: %v", err)
}
}
@@ -431,7 +431,7 @@ func TestMaxNeedleEnd(t *testing.T) {
// A handful of healthy needles establishes a baseline .dat/.idx.
for i := 1; i <= 4; i++ {
n := newRandomNeedle(uint64(i))
if _, _, _, err := v.writeNeedle2(n, true, false); err != nil {
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
}
+2 -2
View File
@@ -22,7 +22,7 @@ func TestDestroyKeepsVifWhenEcCoexists(t *testing.T) {
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
require.NoError(t, err)
v.location = newTestDiskLocation(dir)
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false)
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false, false)
require.NoError(t, err)
base := VolumeFileName(dir, "", 1)
@@ -47,7 +47,7 @@ func TestDestroyRemovesVifWhenNoEc(t *testing.T) {
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
require.NoError(t, err)
v.location = newTestDiskLocation(dir)
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false)
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false, false)
require.NoError(t, err)
base := VolumeFileName(dir, "", 1)
+1 -1
View File
@@ -40,7 +40,7 @@ func writeTestVolume(t *testing.T, dir string, needleCount int) map[uint64]*need
written := make(map[uint64]*needle.Needle)
for i := 1; i <= needleCount; i++ {
n := newRandomNeedle(uint64(i))
if _, _, _, err := v.writeNeedle2(n, true, false); err != nil {
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
v.Close()
t.Fatalf("write needle %d: %v", i, err)
}
@@ -17,7 +17,7 @@ func TestLoad_CorruptIdx_NoSegfault(t *testing.T) {
if err != nil {
t.Fatalf("create volume: %v", err)
}
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
t.Fatalf("seed write: %v", err)
}
v.PersistReadOnly(true, false) // reload goes through SortedFileNeedleMap
+3 -3
View File
@@ -21,7 +21,7 @@ func TestMarkVolumeWritable_ReopensPersistedReadOnly(t *testing.T) {
t.Fatalf("create volume: %v", err)
}
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
t.Fatalf("initial write: %v", err)
}
@@ -47,7 +47,7 @@ func TestMarkVolumeWritable_ReopensPersistedReadOnly(t *testing.T) {
// once noWriteOrDelete is cleared. Confirm the failure mode the issue
// describes — flipping only the flag is not enough.
v2.noWriteOrDelete = false
_, _, _, writeErr := v2.writeNeedle2(newRandomNeedle(2), true, false)
_, _, _, writeErr := v2.writeNeedle2(newRandomNeedle(2), true, false, false)
if !errors.Is(writeErr, os.ErrInvalid) {
t.Fatalf("expected write through SortedFileNeedleMap to fail with os.ErrInvalid, got %v", writeErr)
}
@@ -61,7 +61,7 @@ func TestMarkVolumeWritable_ReopensPersistedReadOnly(t *testing.T) {
}
v2.noWriteOrDelete = false
if _, _, _, err := v2.writeNeedle2(newRandomNeedle(3), true, false); err != nil {
if _, _, _, err := v2.writeNeedle2(newRandomNeedle(3), true, false, false); err != nil {
t.Fatalf("write after reopen: %v", err)
}
}
+2 -2
View File
@@ -59,7 +59,7 @@ func TestReadNeedMetaWithWritesAndUpdates(t *testing.T) {
n.Flags = 0x08
n.LastModified = mockLastUpdateTime
mockLastUpdateTime += 2000
offset, _, _, err := v.writeNeedle2(n, true, false)
offset, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
@@ -98,7 +98,7 @@ func TestReadNeedMetaWithDeletesThenWrites(t *testing.T) {
n.Flags = 0x08
n.LastModified = mockLastUpdateTime
mockLastUpdateTime += 2000
offset, _, _, err := v.writeNeedle2(n, true, false)
offset, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
@@ -42,7 +42,7 @@ func TestReconcileRollForwardMarkerOnly(t *testing.T) {
const liveCount = 6
for i := uint64(1); i <= liveCount; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
@@ -117,7 +117,7 @@ func TestReconcileRollForwardPartialRename(t *testing.T) {
}
const liveCount = 6
for i := uint64(1); i <= liveCount; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
@@ -182,7 +182,7 @@ func TestReconcileRollBackNoMarker(t *testing.T) {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 4; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
@@ -228,7 +228,7 @@ func TestReconcileSkipsLoadedVolumeMidVacuum(t *testing.T) {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 4; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
@@ -270,7 +270,7 @@ func TestApplyCompactSwapMissingTempFilesPreservesLive(t *testing.T) {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 3; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
@@ -305,7 +305,7 @@ func TestDestroyRemovesCommitMarker(t *testing.T) {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 3; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
+3 -3
View File
@@ -166,7 +166,7 @@ func TestCommitCompactDeletionTailKeepsWritable(t *testing.T) {
}
for i := uint64(1); i <= 5; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false); err != nil {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
@@ -299,7 +299,7 @@ func TestCompactByIndex_DropsDanglingNeedle(t *testing.T) {
infos := make([]*needleInfo, goodNeedleCount)
for i := 1; i <= goodNeedleCount; i++ {
n := newRandomNeedle(uint64(i))
_, size, _, err := v.writeNeedle2(n, true, false)
_, size, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
@@ -369,7 +369,7 @@ func TestCompactByIndex_DropsDanglingNeedle(t *testing.T) {
func doSomeWritesDeletes(i int, v *Volume, t *testing.T, infos []*needleInfo) {
n := newRandomNeedle(uint64(i))
_, size, _, err := v.writeNeedle2(n, true, false)
_, size, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write file %d: %v", i, err)
}
+56 -5
View File
@@ -156,23 +156,74 @@ func (v *Volume) asyncRequestAppend(request *needle.AsyncRequest) {
v.asyncRequestsChan <- request
}
func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool) (offset uint64, size Size, isUnchanged bool, err error) {
func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
// glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
return v.doWriteRequest(n, checkCookie)
if !fsync {
return v.doWriteRequest(n, checkCookie)
}
end, _, statErr := v.DataBackend.GetStat()
if statErr != nil {
return 0, 0, false, fmt.Errorf("cannot read current volume position: %v", statErr)
}
priorOffset, priorSize, hasPrior := Offset{}, Size(0), false
if nv, found := v.nm.Get(n.Id); found {
priorOffset, priorSize, hasPrior = nv.Offset, nv.Size, true
}
offset, size, isUnchanged, err = v.doWriteRequest(n, checkCookie)
if err != nil {
return
}
if syncErr := v.DataBackend.Sync(); syncErr != nil {
v.checkReadWriteError(syncErr)
if !isUnchanged {
v.rollbackUnflushedWrite(n, offset, end, priorOffset, priorSize, hasPrior)
}
return 0, 0, false, syncErr
}
return
}
func (v *Volume) writeNeedle2(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
// rollbackUnflushedWrite undoes an append whose fsync failed: the bytes are not
// data we can vouch for, so they come back off the .dat and the needle map goes
// back to what it pointed at before, rather than at an offset past the new end.
func (v *Volume) rollbackUnflushedWrite(n *needle.Needle, offset uint64, end int64, priorOffset Offset, priorSize Size, hasPrior bool) {
if te := v.DataBackend.Truncate(end); te != nil {
glog.V(0).Infof("Failed to truncate %s back to %d with error: %v", v.DataBackend.Name(), end, te)
}
current, found := v.nm.Get(n.Id)
if !found || current.Offset.ToActualOffset() != int64(offset) {
// doWriteRequest kept an existing mapping at a higher offset
return
}
var err error
if hasPrior {
err = v.nm.Put(n.Id, priorOffset, priorSize)
} else {
err = v.nm.Delete(n.Id, ToOffset(int64(offset)))
}
if err != nil {
glog.V(0).Infof("Failed to roll back the index of needle %d in volume %d: %v", n.Id, v.Id, err)
}
}
// writeNeedle2 appends a needle. A durable write normally goes through the
// async batch worker, which fsyncs once for the whole batch; while the server
// is stopping the worker is winding down, so it is flushed inline instead. Both
// paths only return once the .dat is on disk.
func (v *Volume) writeNeedle2(n *needle.Needle, checkCookie bool, fsync bool, isStopping bool) (offset uint64, size Size, isUnchanged bool, err error) {
// glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
if n.Ttl == needle.EMPTY_TTL && v.Ttl != needle.EMPTY_TTL {
n.SetHasTtl()
n.Ttl = v.Ttl
}
if !fsync {
return v.syncWrite(n, checkCookie)
if !fsync || isStopping {
return v.syncWrite(n, checkCookie, fsync)
} else {
asyncRequest := needle.NewAsyncRequest(n, true)
// using len(n.Data) here instead of n.Size before n.Size is populated in n.Append()
+142
View File
@@ -0,0 +1,142 @@
package storage
import (
"errors"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/stretchr/testify/require"
)
// countingBackend counts Sync calls and can be made to fail them.
type countingBackend struct {
backend.BackendStorageFile
syncCount int
syncErr error
}
func (b *countingBackend) Sync() error {
b.syncCount++
if b.syncErr != nil {
return b.syncErr
}
return b.BackendStorageFile.Sync()
}
func newCountingVolume(t *testing.T) (*Volume, *countingBackend) {
t.Helper()
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
require.NoError(t, err)
t.Cleanup(v.Close)
counting := &countingBackend{BackendStorageFile: v.DataBackend}
v.DataBackend = counting
return v, counting
}
// A durable write reaching a stopping server used to silently drop its fsync,
// so the ack promised durability the .dat did not have. It now flushes inline
// instead of queueing on the batch worker that is winding down.
func TestWriteNeedle2FsyncsInlineWhileStopping(t *testing.T) {
v, counting := newCountingVolume(t)
_, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, true, true)
require.NoError(t, err, "a durable write must still be accepted while stopping")
require.Equal(t, 1, counting.syncCount, "the write should have been flushed inline")
// A non-durable write keeps the drain cheap: still accepted, still no fsync.
_, _, _, err = v.writeNeedle2(newRandomNeedle(2), true, false, true)
require.NoError(t, err)
require.Equal(t, 1, counting.syncCount, "a write that did not ask for fsync must not pay for one")
}
func fixedNeedle(id uint64, data string) *needle.Needle {
n := new(needle.Needle)
n.Data = []byte(data)
n.Checksum = needle.NewCRC(n.Data)
n.Id = types.Uint64ToNeedleId(id)
return n
}
// An append we could not flush is not data to vouch for: the inline path takes
// it back off the .dat and fails the write. The needle map has to come back
// with it, or it would resolve to an offset past the truncated end.
func TestWriteNeedle2TruncatesWhenInlineFsyncFails(t *testing.T) {
v, counting := newCountingVolume(t)
kept := fixedNeedle(1, "first-copy")
_, _, _, err := v.writeNeedle2(kept, true, true, true)
require.NoError(t, err)
keptEntry, found := v.nm.Get(kept.Id)
require.True(t, found)
keptOffset, keptSize := keptEntry.Offset, keptEntry.Size
before, _, err := v.DataBackend.GetStat()
require.NoError(t, err)
counting.syncErr = errors.New("disk went away")
_, _, _, err = v.writeNeedle2(fixedNeedle(1, "second-copy"), true, true, true)
require.Error(t, err, "a write whose fsync failed must not be acked")
after, _, err := v.DataBackend.GetStat()
require.NoError(t, err)
require.Equal(t, before, after, "the unflushed append should have been truncated away")
now, found := v.nm.Get(kept.Id)
require.True(t, found, "the mapping the failed write replaced should be back")
require.Equal(t, keptOffset, now.Offset, "the index must not point past the truncated end")
require.Equal(t, keptSize, now.Size)
counting.syncErr = nil
readBack := new(needle.Needle)
readBack.Id = kept.Id
_, err = v.readNeedle(readBack, nil, nil)
require.NoError(t, err, "the surviving needle must still be readable")
require.Equal(t, []byte("first-copy"), readBack.Data)
}
// Same rollback for a needle the failed write introduced: with nothing to go
// back to, the mapping goes away rather than pointing past the end.
func TestWriteNeedle2DropsIndexOfUnflushedNewNeedle(t *testing.T) {
v, counting := newCountingVolume(t)
counting.syncErr = errors.New("disk went away")
fresh := fixedNeedle(7, "never-landed")
_, _, _, err := v.writeNeedle2(fresh, true, true, true)
require.Error(t, err)
if entry, found := v.nm.Get(fresh.Id); found {
require.True(t, entry.Size.IsDeleted(), "a needle that never reached the disk must not resolve")
}
counting.syncErr = nil
readBack := new(needle.Needle)
readBack.Id = fresh.Id
_, err = v.readNeedle(readBack, nil, nil)
require.Error(t, err, "reading the rolled-back needle should fail cleanly, not read past the end")
}
// The pre-stop drain exists so writes already assigned to this server land.
// Refusing them once stopping would turn every rolling restart into client
// write failures for the length of the drain.
func TestStoreWriteVolumeNeedleStaysDurableWhileStopping(t *testing.T) {
dir := t.TempDir()
store := newIdxSplitStore(t, dir, dir)
const vid = needle.VolumeId(1)
require.NoError(t, store.AddVolume(vid, "", NeedleMapInMemory, "000", "", 0, needle.GetCurrentVersion(), 0, types.HardDriveType, 0))
v := store.findVolume(vid)
require.NotNil(t, v)
counting := &countingBackend{BackendStorageFile: v.DataBackend}
v.DataBackend = counting
store.SetStopping()
counting.syncCount = 0
isUnchanged, err := store.WriteVolumeNeedle(vid, newRandomNeedle(1), true, true)
require.NoError(t, err, "the drain must keep accepting durable writes")
require.False(t, isUnchanged)
require.Equal(t, 1, counting.syncCount, "the accepted write must actually be on disk")
}
+6 -6
View File
@@ -29,7 +29,7 @@ func TestSearchVolumesWithDeletedNeedles(t *testing.T) {
for i := 1; i < count; i++ {
n := newRandomNeedle(uint64(i))
_, _, _, err := v.writeNeedle2(n, true, false)
_, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle %d: %v", i, err)
}
@@ -126,7 +126,7 @@ func TestDestroyNonemptyVolumeWithOnlyEmpty(t *testing.T) {
path := v.DataBackend.Name()
// should return "volume not empty" error and do not delete file when Destroy non-empty volume
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false)
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false, false)
if err != nil {
t.Fatalf("write needle: %v", err)
}
@@ -138,7 +138,7 @@ func TestDestroyNonemptyVolumeWithOnlyEmpty(t *testing.T) {
assertFileExist(t, true, path)
// should keep working after "volume not empty"
_, _, _, err = v.writeNeedle2(newRandomNeedle(2), true, false)
_, _, _, err = v.writeNeedle2(newRandomNeedle(2), true, false, false)
if err != nil {
t.Fatalf("write needle: %v", err)
}
@@ -156,7 +156,7 @@ func TestDestroyNonemptyVolumeWithoutOnlyEmpty(t *testing.T) {
path := v.DataBackend.Name()
// should can Destroy non-empty volume without onlyEmpty
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false)
_, _, _, err = v.writeNeedle2(newRandomNeedle(1), true, false, false)
if err != nil {
t.Fatalf("write needle: %v", err)
}
@@ -179,7 +179,7 @@ func TestWriteNeedleBlobRejectedOnReadOnlyVolume(t *testing.T) {
t.Fatalf("volume creation: %v", err)
}
n := newRandomNeedle(1)
offset, _, _, err := v.writeNeedle2(n, true, false)
offset, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle: %v", err)
}
@@ -230,7 +230,7 @@ func TestWriteNeedleBlobRejectsSizeMismatch(t *testing.T) {
location.SetVolume(7, v)
n := newRandomNeedle(1)
offset, _, _, err := v.writeNeedle2(n, true, false)
offset, _, _, err := v.writeNeedle2(n, true, false, false)
if err != nil {
t.Fatalf("write needle: %v", err)
}
+3
View File
@@ -97,6 +97,9 @@ func ReplicatedWrite(ctx context.Context, masterFn operation.GetMasterFn, grpcDi
"type": {"replicate"},
"ttl": {n.Ttl.String()},
}
if fsync {
q.Set("fsync", "true")
}
if n.LastModified > 0 {
q.Set("ts", strconv.FormatUint(n.LastModified, 10))
}
+118
View File
@@ -3,10 +3,22 @@ package topology
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// TestDistributedOperationCancelsSiblingsOnFirstError verifies that once one
@@ -53,3 +65,109 @@ func TestDistributedOperationEmpty(t *testing.T) {
t.Fatalf("expected nil for no locations, got %v", err)
}
}
type mockMasterServer struct {
master_pb.UnimplementedSeaweedServer
locations []*master_pb.Location
}
func (m *mockMasterServer) LookupVolume(ctx context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
var vls []*master_pb.LookupVolumeResponse_VolumeIdLocation
for _, vid := range req.VolumeOrFileIds {
vls = append(vls, &master_pb.LookupVolumeResponse_VolumeIdLocation{
VolumeOrFileId: vid,
Locations: m.locations,
})
}
return &master_pb.LookupVolumeResponse{VolumeIdLocations: vls}, nil
}
// TestReplicatedWriteForwardsFsyncToReplicas verifies that the fsync=true
// request parameter is forwarded to replica volume servers in the fan-out
// request, so a durable write means every replica has flushed to disk.
func TestReplicatedWriteForwardsFsyncToReplicas(t *testing.T) {
replicaQueries := make(chan url.Values, 4)
replica := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
replicaQueries <- r.URL.Query()
w.WriteHeader(http.StatusCreated)
if _, err := w.Write([]byte(`{"size":1}`)); err != nil {
t.Errorf("replica write response: %v", err)
}
}))
defer replica.Close()
replicaHost := strings.TrimPrefix(replica.URL, "http://")
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
grpcServer := grpc.NewServer()
master_pb.RegisterSeaweedServer(grpcServer, &mockMasterServer{
locations: []*master_pb.Location{{Url: replicaHost}},
})
serveErr := make(chan error, 1)
go func() { serveErr <- grpcServer.Serve(lis) }()
// Stop closes the listener it was handed, so there is no separate close here
defer func() {
grpcServer.Stop()
if err := <-serveErr; err != nil && !errors.Is(err, grpc.ErrServerStopped) {
t.Errorf("mock master serve: %v", err)
}
}()
grpcPort := lis.Addr().(*net.TCPAddr).Port
masterFn := func(_ context.Context) pb.ServerAddress {
// ServerAddress.ToGrpcAddress treats "host:port" as an http address and
// adds 10000 to reach the grpc port, so hand it the "port.grpcPort"
// form to point straight at the mock listener.
return pb.NewServerAddressWithGrpcPort(fmt.Sprintf("127.0.0.1:%d", grpcPort), grpcPort)
}
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
store := &storage.Store{}
volumeId := needle.VolumeId(1)
for _, tc := range []struct {
name string
fsync string
wantFsync bool
}{
{name: "fsync requested", fsync: "true", wantFsync: true},
{name: "no fsync requested", fsync: "", wantFsync: false},
} {
t.Run(tc.name, func(t *testing.T) {
operation.InvalidateVolumeIdLocationCache(volumeId.String())
path := "http://127.0.0.1:8080/1,01637037d6"
if tc.fsync != "" {
path += "?fsync=" + tc.fsync
}
r := httptest.NewRequest(http.MethodPost, path, nil)
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
n := &needle.Needle{
Id: 1,
Data: []byte("test data"),
Ttl: needle.EMPTY_TTL,
}
if _, err := ReplicatedWrite(context.Background(), masterFn, dialOption, store, volumeId, n, r, ""); err != nil {
t.Fatalf("ReplicatedWrite: %v", err)
}
select {
case q := <-replicaQueries:
got := q.Get("fsync")
if tc.wantFsync && got != "true" {
t.Errorf("expected fsync=true in replica query, got %q (query: %v)", got, q)
}
if !tc.wantFsync && got != "" {
t.Errorf("expected no fsync in replica query, got %q (query: %v)", got, q)
}
case <-time.After(5 * time.Second):
t.Fatal("replica never received the fan-out request")
}
})
}
}