mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
489563ca42 | ||
|
|
ed75a61fb0 | ||
|
|
9575032b4c | ||
|
|
1354b58675 | ||
|
|
68a23a4b3c |
No files matched your search
@@ -0,0 +1,186 @@
|
||||
# Design: Keying the mount's inode table on parent and name
|
||||
|
||||
Issue #10020 — a mount over 32.7M files sits at 2.1GB RSS after the readdir fixes.
|
||||
Its heap profile is 94% one structure: `InodeToPath`.
|
||||
|
||||
## Where the bytes are
|
||||
|
||||
Measured by populating the table with 1M children and reading `HeapAlloc` around
|
||||
it, after the two cheap wins already landed:
|
||||
|
||||
221.5 B/inode at 85-character paths
|
||||
285.6 B/inode at 148-character paths
|
||||
|
||||
so roughly **125 B fixed plus the full path rounded to a Go size class**. The
|
||||
fixed part is `InodeEntry` (32) and the two maps (~93). Reading the reporter's
|
||||
profile against that model — `Lookup` flat / 125 — gives ~5.6M live inodes at
|
||||
~200-character paths, ~350 B each, which is the 2.0GB.
|
||||
|
||||
The path is the larger half and it grows with directory depth. It is stored once
|
||||
and referenced twice: as the `path2inode` key and as `InodeEntry.path`.
|
||||
|
||||
## Shape
|
||||
|
||||
Directories keep a materialized full path. Files keep only their parent's inode
|
||||
and their own name. There are orders of magnitude fewer directories than files,
|
||||
so the full paths that remain are a rounding error, and no operation has to walk
|
||||
a parent chain: a file's path is one concat off its parent's.
|
||||
|
||||
type childKey struct {
|
||||
parent uint64
|
||||
name string
|
||||
}
|
||||
|
||||
type InodeEntry struct { // 32 bytes, one object, no allocation of its own
|
||||
parent uint64
|
||||
name string
|
||||
nlookup uint64
|
||||
}
|
||||
|
||||
inodes map[uint64]*InodeEntry // every inode
|
||||
children map[childKey]uint64 // (parent, name) -> inode
|
||||
dirs map[uint64]*dirState // directories only; carries the path
|
||||
dirPaths map[util.FullPath]uint64 // directories only
|
||||
extraLinks map[uint64][]childKey // hard-linked inodes only
|
||||
|
||||
`InodeEntry.name` shares its bytes with the `children` key, exactly as the path
|
||||
does with `path2inode` today.
|
||||
|
||||
The name has to be copied on the way in. Every name the mount has to hand is a
|
||||
slice of something longer — `FullPath.Name()` slices the full path, and a
|
||||
readdir's `dirEntry.Name` slices the listed entry's — and a Go string slice
|
||||
keeps its whole backing array alive. Storing one as-is would pin the ~200-byte
|
||||
path it came from per inode and leave the table costing what it costs today.
|
||||
`strings.Clone` at the point of storage; it is one small allocation per new
|
||||
inode, which is what building the child path costs already.
|
||||
|
||||
Per inode: entry 32, name bytes ~32, `children` ~51, `inodes` ~26 — about
|
||||
**141 B, independent of path length**, against ~350 at the reporter's depth. At
|
||||
5.6M inodes that is 2.0GB down to 0.8GB.
|
||||
|
||||
## What each operation becomes
|
||||
|
||||
`GetPath(inode)` — root is 1; a directory returns `dirs[inode].path`; anything
|
||||
else is `dirs[e.parent].path.Child(e.name)`. O(1), one allocation. Today it
|
||||
returns an existing string and allocates nothing, so this is the trade: one
|
||||
~200-byte allocation on an op that is already about to talk to a filer. It is
|
||||
per FUSE op, not per readdir entry.
|
||||
|
||||
`GetInode(path)` — `dirPaths[path]`, else split and hit `children`. Two map
|
||||
lookups, no walk. It keeps taking a path, so its thirteen callers are untouched
|
||||
by any of this; only its body changes.
|
||||
|
||||
`Lookup` — the signature changes from a full path to `(parentInode, name)`. All
|
||||
nine call sites already hold the parent nodeid; the readdir loop stops building
|
||||
a child path per entry entirely. Only the key shape changes: reusing the inode
|
||||
already at that key, honouring `possibleInode`, probing past a collision for
|
||||
anything that is not a hard link, and counting `nlookup` only when `isLookup`
|
||||
all have to survive intact, and want tests of their own before the switch.
|
||||
|
||||
The directory-state methods (`InvalidateChildrenCache`, `TouchDirectory`,
|
||||
`MarkChildrenCached`, `AdjustSubdirCount`, ~30 call sites between them) resolve a
|
||||
directory by path and stay exactly as they are, against `dirPaths`.
|
||||
|
||||
`Forget` — unchanged in how it counts: it subtracts the request's count from
|
||||
`nlookup`, keeps every mapping while that stays above zero, and clamps a kernel
|
||||
over-decrement the way it does today. At zero it drops every one of the inode's
|
||||
child keys, not just the primary:
|
||||
`children[{parent,name}]` plus each key in `extraLinks`, then `inodes`, and for
|
||||
a directory `dirs` and `dirPaths`. Unlinking one link of a hard-linked file
|
||||
promotes a surviving key into `InodeEntry`, the same shape `removeOnePath` has
|
||||
today, so `GetPath` never answers with a name that is gone.
|
||||
|
||||
A directory has to outlive its children, since that is what resolves them.
|
||||
`dirState` carries a child count, incremented as `children` gains a key under
|
||||
that parent and decremented as one goes; `Forget` releases a directory only at
|
||||
nlookup 0 **and** count 0, and re-checks on the last child's release. Linux
|
||||
evicts dentries bottom-up so this should never fire, which is the reason to
|
||||
assert it rather than assume it.
|
||||
|
||||
## What it does to rename
|
||||
|
||||
Renaming a directory today is repaired entry by entry. The filer moves every
|
||||
descendant and emits an event for each, and the mount turns each one into a
|
||||
`MovePath`, because every cached path under the directory holds the old prefix
|
||||
as literal bytes. A rename of a directory with a million cached children is a
|
||||
million table mutations, and the table is only correct as long as every one of
|
||||
those events arrives and is applied.
|
||||
|
||||
Keyed on the parent, files under a renamed directory need nothing at all — their
|
||||
key never mentioned the prefix. Only descendant *directories* have to have their
|
||||
materialized path re-prefixed, and there are few of those.
|
||||
|
||||
`MovePath` today moves the renamed entry and nothing under it, which is visible
|
||||
directly against the table (this is current behavior, not the target):
|
||||
|
||||
itp := NewInodeToPath("/", 0)
|
||||
dirInode := itp.Lookup("/a", now, true, false, 0, true)
|
||||
childInode := itp.Lookup("/a/f.txt", now, false, false, 0, true)
|
||||
itp.MovePath("/a", "/b")
|
||||
itp.GetPath(childInode) // "/a/f.txt"
|
||||
|
||||
The per-descendant events are what keep that from being reachable in practice.
|
||||
|
||||
## Phases
|
||||
|
||||
Each is its own commit, and the table's behavior is unchanged until the second.
|
||||
|
||||
1. Materialize the directory path in `dirState`, add `dirPaths`, serve directory
|
||||
`GetPath` from it. Establishes the invariant and its tests with the file half
|
||||
untouched.
|
||||
2. `InodeEntry` becomes `(parent, name)` and `extraLinks` arrives with it;
|
||||
`path2inode` becomes `children`; `GetPath` and `GetInode` take their new
|
||||
form, and `MovePath` re-prefixes the materialized path of every descendant
|
||||
directory, with a regression test that walks a nested tree through both a
|
||||
local and a subscription-driven rename. The load-bearing commit. A
|
||||
hard-linked file has to keep every one of its names from this commit on, not
|
||||
from phase 4 — a phase that is individually correct cannot park them
|
||||
somewhere in between.
|
||||
3. Convert `Lookup` and its nine callers to `(parentInode, name)`. It keeps its
|
||||
path signature through phase 2, so that commit does not have to move both
|
||||
halves at once.
|
||||
4. Tighten `InodeEntry` back to the 32-byte size class and assert it.
|
||||
5. Shed entries the mount no longer wants to hold. See below.
|
||||
|
||||
## Bounding the table
|
||||
|
||||
Everything above lowers the constant. Growth is still unbounded, because the
|
||||
only thing that ever removes an entry is a kernel FORGET, which arrives when the
|
||||
kernel evicts the dentry — under dcache pressure, on unlink, or at unmount. A
|
||||
machine with memory to spare never sends one.
|
||||
|
||||
Two halves to that, and only one is ours to refuse. A readdirplus reference is
|
||||
speculative: the mount hands the kernel attributes for every name it lists,
|
||||
whether or not the client ever looks at them. That one can be declined by
|
||||
leaving the `EntryOut` zeroed — Linux reads a zero nodeid in a READDIRPLUS reply
|
||||
as "no attributes for this entry" (`fuse_direntplus_link`) and takes no
|
||||
reference. A LOOKUP reference cannot be declined: a zero nodeid there means
|
||||
ENOENT, which would be a lie about the file existing.
|
||||
|
||||
So a cap on its own only stops the mount paying for attributes nobody asked for,
|
||||
and never shrinks anything. Actually shedding entries means asking the kernel to
|
||||
drop the dentry with `EntryNotify(parent, name)`, from the invalidation worker
|
||||
and never from a request handler — the deadlock `invalidateKernelDirListing`
|
||||
already documents. That call wants exactly the pair phase 2 makes the table's
|
||||
key, which is why this comes last: an eviction sweep is cheap to write against
|
||||
`children` and awkward against a map of full paths. It names one dentry, so a
|
||||
hard-linked inode needs one call per name — the primary and every key in
|
||||
`extraLinks` — before the entry goes, or the kernel keeps the aliases it was
|
||||
never told about.
|
||||
|
||||
## Risks
|
||||
|
||||
A child must never outlive its parent in the table, or its path is
|
||||
unresolvable. Linux evicts dentries bottom-up so FORGET arrives child-first, but
|
||||
the table should refuse to release a directory that still has children rather
|
||||
than trust it.
|
||||
|
||||
Every rename path has to keep `dirs`/`dirPaths` in step, including the ones that
|
||||
arrive from the metadata subscription rather than from a local syscall.
|
||||
|
||||
A rename this mount never sees — a subscription gap across a reconnect — strands
|
||||
a stale path either way. Fewer entries hold one, since a file's key never
|
||||
mentioned the prefix, but that buys nothing at resolution time: a file resolves
|
||||
through `dirs[e.parent].path`, so one stale directory path is enough to make
|
||||
every file under it resolve stale too. The exposure is the same shape as today's
|
||||
and reconciling the table against the filer after a gap is separate work.
|
||||
@@ -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)
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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"))
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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!")
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user