Compare commits

..
Author SHA1 Message Date
github-actions[bot] db42bb4975 4.39 2026-07-10 04:08:14 +00:00
Chris Lu 9a7cfaf371 admin: stop holding the shell admin lock across whole scheduler batches (#10290)
* admin: let waiting shell clients win the admin lock

The admin lock manager re-acquired the cluster shell lock immediately
after releasing it, while a waiting weed shell client only polls the
master once a second, so an operator could lose the race indefinitely.
Leave the lock free for slightly more than one poll interval before
re-acquiring, and once overlapping reference-counted holds have kept
the lock continuously held for over a minute, make new admin-side
acquires wait for a full release before piggybacking.

* admin/plugin: take the shell lock per detection and per job, not per batch

The default-lane scheduler acquired the cluster shell lock once and
held it across the whole pass: every due job type's detection plus all
of its dispatched jobs, each drained to completion. A manual weed
shell operation sharing that lock could stall behind the batch for up
to the extended execution window.

Hold the lock only while it protects something: around each detection
scan and around each dispatched job. Manual shell operations now wait
for at most one in-flight job. The admin UI detect+execute path stops
wrapping dispatch in an outer hold, since a nested acquire would
deadlock against the lock manager's fairness window; detection and
per-job dispatch take the lock themselves.

* admin/plugin: stop extending the dispatch window to the largest job estimate

When any proposal's estimated runtime exceeded the remaining
JobTypeMaxRuntime, the whole dispatch context was replaced with a
fresh one capped at eight hours, so a single balance backlog could
hold the default lane (and with it erasure_coding and vacuum
detection) for that long.

Keep the dispatch window at JobTypeMaxRuntime and instead detach each
started attempt onto its own estimated-runtime deadline. Large jobs
still get their full time once started; jobs not yet started when the
window closes are canceled and re-proposed by a later detection, so
sibling job types get a turn every window.

* worker/balance: re-check each planned move against the master before executing

A balance plan is computed at detection time, but the admin lock is
released between detection and execution, so a manual shell operation
can rearrange the volume in the gap. The task's own guards catch a
vanished source, but a target that gained a replica in the meantime
would be silently overwritten by VolumeCopy and the source delete
would then reduce the volume to a single copy.

Before executing each move, ask the master for the volume's current
locations (uncached) and skip the move if the volume has left the
source or the target already holds a replica. Skipped moves fail with
a stale-move error and the next detection replans them. Without master
addresses in the cluster context the check is skipped, preserving the
old behavior with older admins.

* admin: block re-acquire while the final lock release is in flight

Release dropped the manager mutex before calling ReleaseLock, so a
concurrent Acquire could see hold count zero and call RequestLock
while the locker still considered itself locked. That request no-ops,
leaving a hold with no live master lease. Track the in-flight release
and make Acquire wait for it.

Also normalize a nil release function from lock manager
implementations, and make the yield and fairness windows per-instance
fields so tests stop mutating globals.
2026-07-09 20:43:55 -07:00
Chris Lu 6fd82b7e6f fix: merge filer service annotations to avoid duplicate keys in Helm (#10293) 2026-07-09 18:25:34 -07:00
Lars Lehtonen 3a0021e144 fix(weed/worker/tasks/balance): dropped test error (#10291) 2026-07-09 18:20:14 -07:00
Chris Lu 6f816c955d volume.fsck: fix orphan purge against the rust volume server (#10289)
* rust volume: accept odd-length needle id hex in file ids

Go formats the needle id with strconv.FormatUint and parses it back with
strconv.ParseUint, neither of which pads to an even number of hex digits.
hex::decode rejected such file ids with "Odd number of digits", so
volume.fsck could not purge orphans from a rust volume server. Parse the
needle id and cookie with from_str_radix, matching Go's ParseNeedleId
and ParseCookie.

* storage: emit even-length needle id hex in NeedleId.FileId

volume.fsck and volume.check_disk build purge file ids here with unpadded
FormatUint hex, while every other fid formatter strips whole leading zero
bytes. Pad to even length so the output matches the canonical fid format
and strict hex parsers accept it.
2026-07-09 11:19:31 -07:00
Chris Lu e6b2849381 s3: verify SigV4 against each plausible reverse-proxy host (#10284)
* s3: verify SigV4 against each plausible reverse-proxy host

A portless X-Forwarded-Host leaves the client's true port ambiguous: a
proxy that kept the Host header makes the backend Host port right, one
that rewrote it makes X-Forwarded-Port right, and a client on the
scheme's default port signed no port at all. The verifier bet on the
backend Host port whenever the hostnames matched, so nginx-style
$host/$server_port forwarding got SignatureDoesNotMatch whenever the
proxy and backend share a hostname. Try each plausible host value in
likelihood order instead of guessing one.

* s3: unbracket IPv6 X-Forwarded-Host before matching the request host

net.SplitHostPort strips brackets from the request host, so a bracketed
portless X-Forwarded-Host like [::1] never matched and lost its port
candidate.

* s3: cover unbracketed IPv6 forwarded-host candidates; compare with slices.Equal
2026-07-09 02:34:13 -07:00
qzhello 95023af489 fix(shell): print markVolumeWritable/markVolumeReadonly based on the writable flag (#10283) 2026-07-09 00:30:21 -07:00
Chris Lu fd5a6ff427 log_buffer: cap the shared-snapshot race test's heap (#10281)
TestSharedSnapshotConcurrentIntegrity writes as fast as one core can
marshal for two seconds, so its transient heap scales with host speed.
On linux/386 a fast runner walks the heap into the 4GB address-space
ceiling and the run dies with out of memory. Set a 1GB memory limit for
the duration of the test so the GC paces the writer instead of the
address space; the seal-and-recycle race being tested is unaffected.
2026-07-09 00:29:17 -07:00
Chris Lu 399f8033f8 s3: keep listing when empty directories fill the listing window (#10280)
* s3: keep listing when empty directories fill the listing window

doListFilerEntries issued a single ListEntries request per directory with
Limit = maxKeys+2. Entries that emit nothing - empty directories, the
.uploads folder, the marker echo - consume that window without consuming
maxKeys, so a bucket whose first window held only empty directories was
reported empty and not truncated, and a subdirectory whose window filled
up silently dropped the entries behind it. Keep requesting from the last
received entry until the quota is filled or a short window shows the
directory is exhausted.

* s3: test listing across windows of empty directories

The test filer client now honors StartFromFileName so repeated windows
advance like the real filer.

* s3: propagate the request context into directory listing RPCs

A disconnected client now cancels the ListEntries streams instead of
letting the listing keep issuing requests against the filer.

* s3: group per-directory listing parameters into a request struct

doListFilerEntries took ten positional parameters; call sites read as
string and bool soup. Wrap the per-directory arguments in
listDirectoryRequest so recursions and tests name what they pass.

* s3: group list request parameters into a struct

listFilerEntries took eight positional parameters ending in two bare
booleans. Wrap them in listObjectsRequest so the V1 and V2 handlers
name what they pass.
2026-07-09 00:22:34 -07:00
Chris Lu 02b5b66a3f topology/balancer: share replica selection between shell and workers (#10276)
Move pickOneReplicaToCopyFrom, pickOneReplicaToDelete,
pickOneMisplacedVolume, and isMisplaced into weed/topology/balancer,
following satisfyReplicaPlacement. Selection functions take the shared
balancer.Replica shape and return indices, so the shell keeps its own
replica type; behavior is unchanged and covered by the existing shell
tests.
2026-07-08 20:06:15 -07:00
Chris Lu 78e428758b volume.fix.replication: parallelize under-replicated volume copies (#10275)
* volume.fix.replication: parallelize under-replicated volume copies

Fan out fixOneUnderReplicatedVolume up to -maxParallelization at a time.
Destination selection and free-slot accounting stay atomic behind a
scheduler mutex, so concurrent fixes see each other's reservations; a
failed copy returns its reserved slot. A per-server in-flight cap
(-maxParallelizationPerServer, default 1) keeps many simultaneous copies
from swamping a single destination server; when every eligible
destination is at the cap the fix waits for a slot instead of failing.

* volume.fix.replication: isolate the scheduler's location ordering

Clone allLocations before the per-volume fan-out so the scheduler's
re-sorting cannot alias the slice shared with the concurrent delete
phases, and make the test's per-iteration location copy explicit.
2026-07-08 20:03:01 -07:00
Chris Lu a9cfbd8d3a s3: tear down the emptied .versions directory on last-version delete; drain existing residue (#10278)
* s3: routed last-version delete removes the emptied .versions directory

The routed versioned delete (routedDeleteSpecificVersion) repoints the
latest pointer and deletes the version file, but unlike the lock-path
fallback (updateLatestVersionAfterDeletion) it never tears down the
.versions/ directory it just emptied. The residue keeps the key's read
path in the self-heal rescan loop: every GET of the deleted key logs
event=surfaced plus a GetObject error until the background
EmptyFolderCleaner gets to the directory — at least two minutes away on
its delay queue, and possibly never (the queue is in-memory, bounded,
and gated on the bucket's allow-empty-folders policy). Veeam's lock
arbitration probes deleted lock keys continuously, so those windows are
always open and the log spam is chronic.

ObjectMutation DELETE gains remove_empty_parent: after the child delete,
the filer best-effort removes the parent directory in the same locked
transaction. Non-recursive on purpose — a concurrent write that lands a
new version fails the removal instead of being lost with it. The routed
last-version delete sets it on the version-file DELETE, matching the
lock-path fallback's contract.

Claude-Session: https://claude.ai/code/session_014mMYAHXZySkCCUfpRFNtSv

* s3: drain empty .versions residue on read heal and in s3.versions.audit

Directories already stranded by pre-teardown deletes (or dropped from
the EmptyFolderCleaner's bounded in-memory queue) previously re-entered
the self-heal rescan on every GET forever: the heal only cleared the
pointer and nothing ever removed the directory, and s3.versions.audit
counted the state as clean.

When the heal rescan finds no remaining version, remove the directory
outright (non-recursive, so orphan children still block and fall back to
the pointer clear) and log event=healed mode=empty_dir_removed; the next
GET takes the clean not-found path. The audit gains an empty category so
the residue is visible, and -heal removes such directories in bulk.

Claude-Session: https://claude.ai/code/session_014mMYAHXZySkCCUfpRFNtSv
2026-07-08 18:50:54 -07:00
Chris Lu 11fd20e2b0 s3.bucket.list: measure quota usage by logical size (#10274)
Align the usage percentage with s3.bucket.quota.enforce and the admin
UI, which measure quota against the live data size (size minus
un-vacuumed deleted bytes). Also print the logical size so both the
raw and live views stay visible.
2026-07-08 14:32:04 -07:00
Chris Lu b43089f721 s3: keep empty-folder cleanup out of the multipart .uploads staging tree (#10273)
* s3: keep empty-folder cleanup out of the multipart .uploads staging tree

The async EmptyFolderCleaner deleted <bucket>/.uploads once it looked
empty. A concurrent CreateMultipartUpload inserting its marker between
the cleaner's emptiness check and the bulk child delete had its row
wiped, so the upload silently vanished: ListMultipartUploads then omits
it and the following part/complete/copy calls fail. Skip the .uploads
subtree in both the queue and the delete path (including the eager
parent cascade); the multipart upload lifecycle owns it.

* s3: slice the bucket-relative path instead of reallocating it
2026-07-08 14:30:57 -07:00
AlekseyandChris Lu cfb46ee19f volume.balance: rank by physical disk usage (#10271)
* volume.balance: rank by physical disk usage

* volume.balance: keep -byDiskUsage ranking on one scale across the fleet

A server that does not report disk bytes ranks at whole volume-equivalents
while reporting servers stay below 1.0, so during a rolling upgrade the
balancer drains nearly empty old-build servers onto physically fuller ones.
Decide the scale once: rank by physical used percent only when every server
reports disk bytes, otherwise fall back to the data-size ranking for all.
Normalizing the fallback by maxVolumeCount instead would reintroduce the
over-configured-maxVolumeCount distortion this flag exists to avoid.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-07-08 09:29:59 -07:00
Chris Lu 65f2f1488a iam: test that groups and roles claims reach request-time policy evaluation
Drives the full path: AssumeRoleWithWebIdentity embeds the claims in the
session JWT, AuthenticateJWT restores them, and AuthorizeAction evaluates
ForAnyValue:StringEquals on jwt:groups / jwt:roles per bucket. The mock
OIDC provider now carries token claims through and surfaces roles,
matching the real provider.
2026-07-08 01:53:37 -07:00
Chris Wydra 63db56ff7d iam: surface OIDC groups and roles into the STS session request context for resource-policy ABAC (#10263)
* iam: surface OIDC groups into STS session request context for resource-policy ABAC

The groups claim was added to ExternalIdentity.Groups but excluded from Attributes
(processedClaims), so it never reached the session RequestContext. As a result
group membership was usable only in role trust policies (assume-time), not in
resource/permission policies (request-time) - so a single role could not scope
access by the caller's groups (aggregate ABAC). Surface Groups as a []string in
the request context; the string-condition evaluator already handles multi-valued
context keys, and the S3 middleware exposes it as jwt:groups.

* iam: also surface OIDC roles into the STS request context (companion to groups)

The 'roles' claim is excluded from the OIDC attributes by the same processedClaims
set that excluded 'groups', so it never reached the session request context and was
usable only via provider-configured role mapping - not a raw token roles claim. Add
ExternalIdentity.Roles, populate it from the token's roles claim, and surface it as a
[]string in the request context so resource policies can gate on jwt:roles, exactly
as the previous commit did for jwt:groups.
2026-07-08 01:52:39 -07:00
Chris Lu e873e671b6 filer: share one log-buffer window snapshot across all subscriber reads (#10267)
* log_buffer: share one window snapshot across all subscriber reads

Every in-memory read handed each subscriber a private pooled copy of the
window it wanted, so N subscribers reading the same data cost N copies of
up to 8MB each -- and slow consumers (grpc send backpressure) held those
copies live for their whole iteration. With hundreds of mount subscribers
that multiplied into gigabytes of live heap on the filer.

Share the bytes instead of copying per reader:

- Sealed windows get a lazily created GC-owned snapshot, made once by the
  first reader and handed out zero-copy to the rest. The snapshot travels
  with its window when SealBuffer shifts slots, so recycling the sealed
  array never invalidates it.
- The current window keeps a shared snapshot of its append-only prefix
  buf[:pos], extended on demand; each byte is copied once per window
  (writer-rate-bound) instead of once per reader. At seal a fully
  extended prefix becomes the sealed window's snapshot.

ReadFromBuffer now reports whether the returned buffer is a pooled copy
(flush path) or a shared view that must not be released; the read loops
only recycle pooled buffers.

With 200 subscribers consuming at grpc pace over sealed and current
windows, peak live heap drops from 5.2GB to 178MB.

* log_buffer: clear released read buffer so a panic cannot double-free it

The read loops release the previous iteration's pooled buffer and then
call ReadFromBuffer. If that call panicked before reassigning bytesBuf,
the deferred cleanup would put the same buffer into the pool a second
time, letting two future readers share one backing array. Nil the
pointer at the release site so the defer sees nothing to free.
2026-07-08 01:50:51 -07:00
Chris Lu 24fb7e47f3 java client: fail cleanly when a chunk read returns short or empty data (#10269)
* java client: fail cleanly when a chunk read returns short or empty data

readChunkView copied chunkView.size bytes out of the fetched chunk without
checking the fetched length, so an empty body (seen transiently right after an
append) threw an opaque IndexOutOfBoundsException. Retry empty chunk fetches and
bound the copy to the data actually returned.

* overflow-safe bounds check and null guard on fetched chunk data
2026-07-08 01:50:42 -07:00
Chris Lu 0ae1fdcad2 volume: reload a remote-tiered volume without re-entering the data lock (#10266)
LoadRemoteFile now takes dataFileAccessLock (so a live tier upload does
not race the heartbeat's DataBackend read). But load() also runs it, and
CommitCompact calls load() while already holding that lock, so reloading
a remote-tiered volume during a compaction commit re-enters the
non-reentrant lock and deadlocks.

Split the locked bodies out: swapDataBackendLocked and loadRemoteFileLocked
assume the caller holds dataFileAccessLock. load() uses loadRemoteFileLocked;
the public LoadRemoteFile keeps taking the lock for the live tier-upload
handler that does not hold it.
2026-07-08 01:27:10 -07:00
jay a16194f5b4 refract: reduce mem alloc while building str (#10261)
Signed-off-by: jayl1e <jayl1e@outlook.com>
2026-07-08 01:24:45 -07:00
dependabot[bot] c000addfc9 build(deps): bump golang.org/x/crypto from 0.51.0 to 0.52.0 in /test/kafka/kafka-client-loadtest (#10265)
build(deps): bump golang.org/x/crypto

Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.51.0 to 0.52.0.
- [Commits](https://github.com/golang/crypto/compare/v0.51.0...v0.52.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.52.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-08 01:23:00 -07:00
Chris Lu 6413b774df filer: cut metadata-subscription allocation churn (issue #10253) (#10260)
* log_buffer: read only ts_ns during metadata-read binary search

readTs ran a full proto.Unmarshal of each LogEntry just to compare
timestamps during ReadFromBuffer's binary search, allocating fresh
slices for the data and key byte fields on every probe. Under
metadata-subscription fan-out this decode churn dominated allocations
and drove heavy GC, inflating filer RSS well past the live heap.

Scan the wire format for ts_ns (field 1) instead and skip the data/key
payloads without copying them. readTs is now zero-alloc; the binary
search no longer touches the event payloads at all.

* log_buffer: alias event payloads instead of copying them on delivery

The subscribe read loops decoded each LogEntry with a full proto.Unmarshal,
allocating fresh slices for the data and key byte fields on every entry
(protobuf consumeBytesNoZero). When many metadata subscribers each re-read
the in-memory log window under a reconnect storm, that per-entry copy was a
large share of allocation churn -- and for entries a subscriber filters out
by prefix, the copied payload was never even looked at.

Decode with a wire scan that points data/key at sub-slices of the source
buffer instead of copying. The aliased slices are valid only for the
duration of the eachLogEntryFn callback; every current subscriber either
re-decodes the event into its own struct or hands it to a synchronous grpc
Send, so none retain them. Per delivered entry the loop decode drops from
176 B / 2 allocs to zero.
2026-07-08 00:05:20 -07:00
github-actions[bot] 274a41fd26 java 4.38 2026-07-08 06:43:07 +00:00
Chris Lu 218f23fdf0 ci: bump wiki java client versions after publish 2026-07-07 23:41:58 -07:00
dependabot[bot] 1262147d9f build(deps): bump golang.org/x/crypto from 0.45.0 to 0.52.0 in /test/sftp (#10264)
build(deps): bump golang.org/x/crypto in /test/sftp

Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.45.0 to 0.52.0.
- [Commits](https://github.com/golang/crypto/compare/v0.45.0...v0.52.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.52.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-07 23:41:47 -07:00
Chris Lu 56fec510e4 ci: make java release version-bump push rebase-safe 2026-07-07 23:36:44 -07:00
Chris Lu 94078b6e3f ci: default java release dry_run to false 2026-07-07 23:32:15 -07:00
Chris Lu cc9549def8 ci: add java client release workflow 2026-07-07 23:26:01 -07:00
Chris Lu 60d9c7ef4c java: bump maven-gpg-plugin to 3.2.4 for headless signing 2026-07-07 23:26:01 -07:00
Chris Lu 254c2a1024 volume: clear remote flag when tiering a volume back to local (#10262)
VolumeTierMoveDatFromRemote downloads the .dat, trims the .vif, and swaps
the data backend to the local file, but left hasRemoteFile set. The
volume.tier.download command masks this by unmounting and remounting
right after, which reloads the flag from the trimmed .vif — but in the
window before the remount the in-memory flag is wrong: doDeleteRequest
would skip appending the tombstone to the freshly local .dat, and the
phantom-.dat guard stays disabled.

Give SwapDataBackend a hasRemoteFile argument so the backend swap and the
flag move together under one lock, and route both tier directions through
it: the tier-down download passes false, LoadRemoteFile passes true. The
flag can no longer disagree with the live backend.
2026-07-07 23:03:17 -07:00
Chris Lu 2d2fdeac3d volume: keep tier-uploaded volume reporting to master after volume.tier.upload (#10259)
volume: keep tier-uploaded volume reporting to master

A live volume.tier.upload removes the local .dat and swaps the data
backend to remote, but v.hasRemoteFile was only ever set when a volume
is loaded from disk, so the running volume kept it false. The phantom
.dat guard then saw fileCount>0, !HasRemoteFile, and a missing .dat, and
stopped reporting the volume to the master. The volume vanished from the
topology even though the upload succeeded and the data was in cloud
storage.

Set hasRemoteFile in LoadRemoteFile, the single point where a volume's
backend becomes remote, so it is true both on disk-scan load and after
an in-process tier upload. Route the backend reassignment through
SwapDataBackend so it happens under dataFileAccessLock, closing the old
backend and never racing the heartbeat's concurrent DataBackend read.
Make the field atomic since the heartbeat now reads it concurrently with
the tier-upload handler that writes it.
2026-07-07 23:00:22 -07:00
Chris Lu bcc528a517 java: HTTP Basic Auth for filer behind an Nginx reverse proxy (#10258)
* java: HTTP Basic Auth for filer behind an Nginx reverse proxy

Attach an "Authorization: Basic" header to the filer gRPC channel through a
ClientInterceptor and to the volume read/write HTTP requests, so the Java
client can reach SeaweedFS fronted by Nginx with auth_basic enabled.

Credentials come from a [basic_auth] section in security.toml or from
FilerSecurityContext.setBasicAuth(). On writes the volume JWT still owns the
Authorization header when present, since the two cannot share it.

* java: precompute Basic Auth header and warn on plaintext channel

Cache the Base64 Authorization value once instead of re-encoding on every
chunk read/write, and log a one-time warning when Basic Auth rides a
plaintext gRPC channel where the credentials would travel in cleartext.
2026-07-07 20:52:50 -07:00
78 changed files with 3551 additions and 699 deletions

No files matched your search

+71 -15
View File
@@ -10,20 +10,20 @@ name: "release: java clients"
# gpg --homedir <keyring> --armor --export-secret-keys <KEYID> > key.asc
# MAVEN_GPG_PASSPHRASE - passphrase for that key
#
# Run with dry_run on first (default) to exercise secrets, GPG signing, and the
# build without publishing. Uncheck dry_run for the real release to Central.
# A plain run publishes to Central. Check dry_run to exercise secrets, GPG
# signing, and the build without committing or publishing.
on:
workflow_dispatch:
inputs:
version:
description: "Java client version to publish, e.g. 4.39 (MAJOR.MINOR)"
description: "Version to publish, e.g. 4.39. Leave blank to use the current SeaweedFS version."
type: string
required: true
required: false
dry_run:
description: "Build and GPG-sign only; skip the version commit and the Central upload"
type: boolean
default: true
default: false
permissions:
contents: write
@@ -46,16 +46,31 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
# Full history so the version-bump commit can rebase onto a moved master.
fetch-depth: 0
- name: Validate version
# An explicit input wins; otherwise fall back to the current SeaweedFS
# version (MAJOR.MINOR) from constants.go, matching its %d.%02d formatting.
- name: Resolve version
id: resolve
env:
VERSION: ${{ inputs.version }}
INPUT_VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
VERSION="$INPUT_VERSION"
if [ -z "$VERSION" ]; then
CONST=weed/util/version/constants.go
MAJOR=$(grep -oP 'MAJOR_VERSION\s*=\s*int32\(\K[0-9]+' "$CONST")
MINOR=$(grep -oP 'MINOR_VERSION\s*=\s*int32\(\K[0-9]+' "$CONST")
VERSION=$(printf '%d.%02d' "$MAJOR" "$MINOR")
echo "No version given; using current SeaweedFS version ${VERSION}."
fi
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
echo "::error::version must be MAJOR.MINOR, e.g. 4.39 (got '$VERSION')"
exit 1
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Set up JDK 17
uses: actions/setup-java@v5
@@ -73,7 +88,7 @@ jobs:
# its seaweedfs-client dependency from the seaweedfs.client.version property.
- name: Set versions in poms
env:
VERSION: ${{ inputs.version }}
VERSION: ${{ steps.resolve.outputs.version }}
run: |
set -euo pipefail
V=org.codehaus.mojo:versions-maven-plugin:2.16.2
@@ -85,18 +100,27 @@ jobs:
- name: Commit version bump
if: ${{ !inputs.dry_run }}
env:
VERSION: ${{ inputs.version }}
VERSION: ${{ steps.resolve.outputs.version }}
run: |
set -euo pipefail
if git diff --quiet; then
echo "Poms already at ${VERSION}; nothing to commit."
else
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add other/java/client/pom.xml other/java/hdfs3/pom.xml
git commit -m "java ${VERSION}"
git push
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add other/java/client/pom.xml other/java/hdfs3/pom.xml
git commit -m "java ${VERSION}"
# Rebase and retry so a concurrent push to master doesn't lose the bump.
for attempt in 1 2 3 4 5; do
if git push origin HEAD:master; then
exit 0
fi
echo "push rejected (attempt ${attempt}); rebasing onto latest master"
git pull --rebase origin master
done
echo "::error::could not push version bump after retries"
exit 1
# Tests are skipped here: the integration tests need a live filer, and the
# offline unit tests already run on every push in java_unit_tests.yml.
@@ -125,3 +149,35 @@ jobs:
set -euo pipefail
[ "$DRY_RUN" = "true" ] && GOAL="clean install" || GOAL="clean deploy"
mvn -B -ntp $GOAL -DskipTests
# Bump every version the wiki quotes for the Java clients. Runs only after
# a successful real publish. Uses GITHUB_TOKEN; set a WIKI_TOKEN secret if
# the token can't push to the wiki.
- name: Update wiki client versions
if: ${{ !inputs.dry_run }}
env:
VERSION: ${{ steps.resolve.outputs.version }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WIKI_TOKEN: ${{ secrets.WIKI_TOKEN }}
run: |
set -euo pipefail
TOKEN="${WIKI_TOKEN:-$GH_TOKEN}"
git clone -q "https://x-access-token:${TOKEN}@github.com/${{ github.repository }}.wiki.git" wiki
cd wiki
for f in $(grep -rlE "seaweedfs-(client|hadoop3-client)" --include="*.md" .); do
NEWV="$VERSION" perl -0777 -i -pe '
my $v = $ENV{NEWV};
s{(<artifactId>seaweedfs-(?:client|hadoop3-client)</artifactId>\s*<version>)[0-9]+\.[0-9]+(</version>)}{$1$v$2}g;
s{(seaweedfs-(?:client|hadoop3-client):)[0-9]+\.[0-9]+}{$1$v}g;
s{(seaweedfs-(?:client|hadoop3-client)-)[0-9]+\.[0-9]+(\.jar)}{$1$v$2}g;
s{(seaweedfs-(?:client|hadoop3-client)/)[0-9]+\.[0-9]+(/)}{$1$v$2}g;
' "$f"
done
if git diff --quiet; then
echo "Wiki already references ${VERSION}."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -am "java clients ${VERSION}"
git push
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.38"
appVersion: "4.39"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.38.0
version: 4.39.0
@@ -2,8 +2,6 @@
apiVersion: v1
kind: Service
metadata:
annotations:
service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
name: {{ include "seaweedfs.componentName" (list . "filer") }}
namespace: {{ .Release.Namespace }}
labels:
@@ -12,8 +10,9 @@ metadata:
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: filer
{{- if .Values.filer.annotations }}
annotations:
service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
{{- if .Values.filer.annotations }}
{{- toYaml .Values.filer.annotations | nindent 4 }}
{{- end }}
spec:
+1 -1
View File
@@ -5,7 +5,7 @@
<groupId>com.seaweedfs</groupId>
<artifactId>seaweedfs-client</artifactId>
<version>4.00</version>
<version>4.38</version>
<name>SeaweedFS Java Client</name>
<description>A java client for SeaweedFS.</description>
@@ -0,0 +1,35 @@
package seaweedfs.client;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
// Adds an HTTP Basic Auth "Authorization" header to every gRPC call so the filer can be
// reached through an Nginx reverse proxy with auth_basic enabled.
public class BasicAuthInterceptor implements ClientInterceptor {
private static final Metadata.Key<String> AUTHORIZATION_KEY =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
private final String headerValue;
public BasicAuthInterceptor(String headerValue) {
this.headerValue = headerValue;
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
headers.put(AUTHORIZATION_KEY, headerValue);
super.start(responseListener, headers);
}
};
}
}
@@ -14,6 +14,7 @@ import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class FilerGrpcClient {
@@ -37,6 +38,8 @@ public class FilerGrpcClient {
public final Map<String, FilerProto.Locations> vidLocations = new HashMap<>();
protected int randomClientId;
private static final AtomicBoolean plaintextBasicAuthWarned = new AtomicBoolean(false);
// Connection pool to handle concurrent requests
private static final int CHANNEL_POOL_SIZE = 4;
private final List<ManagedChannel> channelPool;
@@ -99,6 +102,14 @@ public class FilerGrpcClient {
builder.overrideAuthority(cn);
}
}
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
if (sslContext == null && plaintextBasicAuthWarned.compareAndSet(false, true)) {
logger.warn("Basic Auth is enabled on a plaintext gRPC channel; credentials are sent in cleartext. Use TLS to the proxy.");
}
builder.intercept(new BasicAuthInterceptor(basicAuthHeader));
}
return builder;
}
@@ -13,10 +13,12 @@ import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Base64;
public abstract class FilerSecurityContext extends SslContext {
//extends Netty SslContext to access its protected static utility methods in
@@ -36,6 +38,11 @@ public abstract class FilerSecurityContext extends SslContext {
private static String httpClientCertChainFilePath;
private static String httpClientPrivateKeyFilePath;
// Optional HTTP Basic Auth for reaching SeaweedFS through an Nginx reverse proxy
// that has auth_basic enabled. Applied to both the filer gRPC channel and the
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
private static volatile String basicAuthHeaderValue;
static {
String securityFileName = "security.toml";
@@ -55,6 +62,9 @@ public abstract class FilerSecurityContext extends SslContext {
Toml toml = new Toml().read(securityFile);
logger.debug("reading ssl setup from {}", securityFile);
basicAuthHeaderValue = computeBasicAuthHeaderValue(
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
grpcClientCertChainFilePath = toml.getString("grpc.client.cert");
@@ -120,6 +130,30 @@ public abstract class FilerSecurityContext extends SslContext {
return httpSslContext;
}
// Configure HTTP Basic Auth programmatically instead of via security.toml. Must be
// called before constructing a FilerClient so the credentials reach the gRPC channel.
public static void setBasicAuth(String username, String password) {
basicAuthHeaderValue = computeBasicAuthHeaderValue(username, password);
}
public static boolean isBasicAuthEnabled() {
return basicAuthHeaderValue != null;
}
// Returns the "Basic <base64(user:password)>" Authorization header value, or null
// when no Basic Auth credentials are configured.
public static String getBasicAuthHeaderValue() {
return basicAuthHeaderValue;
}
private static String computeBasicAuthHeaderValue(String username, String password) {
if (Strings.isNullOrEmpty(username)) {
return null;
}
String credentials = username + ":" + (password == null ? "" : password);
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
}
private static SslContext buildGrpcSslContext() throws SSLException {
SslContextBuilder builder = GrpcSslContexts.forClient();
if (grpcTrustCertCollectionFilePath != null) {
@@ -111,10 +111,18 @@ public class SeaweedRead {
}
int len = (int) chunkView.size - (int) (startOffset - chunkView.logicOffset);
int srcOffset = (int) (startOffset - chunkView.logicOffset + chunkView.offset);
LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView.offset:{} chunkView[{};{}) startOffset:{}",
chunkView.fileId, chunkData.length, chunkView.offset, chunkView.logicOffset,
chunkView.logicOffset + chunkView.size, startOffset);
buf.put(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), len);
// The fetched chunk can be shorter than the view claims when a read briefly
// returns an empty body (seen right after an append). Fail clearly instead of
// letting ByteBuffer.put throw an opaque IndexOutOfBoundsException.
if (srcOffset < 0 || len < 0 || srcOffset > chunkData.length - len) {
throw new IOException("chunk " + chunkView.fileId + " returned " + chunkData.length
+ " bytes, need [" + srcOffset + "," + ((long) srcOffset + len) + ")");
}
buf.put(chunkData, srcOffset, len);
return len;
}
@@ -128,7 +136,15 @@ public class SeaweedRead {
for (FilerProto.Location location : locations.getLocationsList()) {
String url = filerClient.getChunkUrl(chunkView.fileId, location.getUrl(), location.getPublicUrl());
try {
data = doFetchOneFullChunkData(chunkView, url);
byte[] fetched = doFetchOneFullChunkData(chunkView, url);
// An empty (or null) body for a chunk we are reading from is never
// valid; treat it as a transient failure so the retry loop tries
// another location and backs off, rather than caching an empty chunk.
if (fetched == null || fetched.length == 0) {
lastException = new IOException("empty or null response for chunk " + chunkView.fileId + " from " + url);
continue;
}
data = fetched;
lastException = null;
break;
} catch (IOException ioe) {
@@ -161,6 +177,11 @@ public class SeaweedRead {
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
}
byte[] data = null;
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
@@ -179,7 +179,14 @@ public class SeaweedWrite {
HttpPost post = new HttpPost(targetUrl);
if (auth != null && auth.length() != 0) {
// Volume JWT and Basic Auth both use the Authorization header; the JWT wins
// when present. Front the volume with a JWT-free path to use Basic Auth here.
post.addHeader("Authorization", "BEARER " + auth);
} else {
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
post.addHeader("Authorization", basicAuthHeader);
}
}
post.addHeader("Content-MD5", Base64.getEncoder().encodeToString(md.digest()));
@@ -325,6 +325,7 @@ message ObjectMutation {
bool set_content = 10; // PATCH_EXTENDED: replace Entry.content with content
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
@@ -0,0 +1,95 @@
package seaweedfs.client;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import org.junit.After;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class BasicAuthTest {
@After
public void clearCredentials() {
FilerSecurityContext.setBasicAuth(null, null);
}
@Test
public void noCredentialsMeansNoHeader() {
FilerSecurityContext.setBasicAuth(null, null);
assertNull(FilerSecurityContext.getBasicAuthHeaderValue());
assertFalse(FilerSecurityContext.isBasicAuthEnabled());
FilerSecurityContext.setBasicAuth("", "ignored");
assertNull(FilerSecurityContext.getBasicAuthHeaderValue());
assertFalse(FilerSecurityContext.isBasicAuthEnabled());
}
@Test
public void encodesUserAndPassword() {
FilerSecurityContext.setBasicAuth("alice", "s3cret");
String expected = "Basic " + Base64.getEncoder()
.encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8));
assertEquals(expected, FilerSecurityContext.getBasicAuthHeaderValue());
assertTrue(FilerSecurityContext.isBasicAuthEnabled());
}
@Test
public void interceptorAddsAuthorizationHeader() {
String headerValue = "Basic dGVzdDp0ZXN0";
final Metadata[] captured = new Metadata[1];
Channel channel = new Channel() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
return new ClientCall<ReqT, RespT>() {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
captured[0] = headers;
}
@Override
public void request(int numMessages) {
}
@Override
public void cancel(String message, Throwable cause) {
}
@Override
public void halfClose() {
}
@Override
public void sendMessage(ReqT message) {
}
};
}
@Override
public String authority() {
return "test";
}
};
BasicAuthInterceptor interceptor = new BasicAuthInterceptor(headerValue);
ClientCall<Object, Object> call =
interceptor.interceptCall(null, CallOptions.DEFAULT, channel);
call.start(null, new Metadata());
Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
assertNotNull(captured[0]);
assertEquals(headerValue, captured[0].get(key));
}
}
@@ -4,12 +4,38 @@ import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SeaweedReadTest {
// A chunk fetch that briefly returns an empty body (observed right after an
// append) must not overrun the buffer with an opaque IndexOutOfBoundsException.
@Test
public void testReadChunkShorterThanViewFailsCleanly() throws IOException {
String fileId = "7,readchunkshort01";
SeaweedRead.volumeIdCache.setLocations("7",
FilerProto.Locations.newBuilder()
.addLocations(FilerProto.Location.newBuilder().setUrl("localhost:0").build())
.build());
// seed the chunk cache with an empty body so the fetch is skipped
SeaweedRead.chunkCache.setChunk(fileId, new byte[0]);
List<SeaweedRead.VisibleInterval> visibles = new ArrayList<>();
visibles.add(new SeaweedRead.VisibleInterval(0, 175, fileId, 1L, 0, true, null, false));
ByteBuffer buf = ByteBuffer.allocate(175);
try {
SeaweedRead.read(null, visibles, 0, buf, 175);
Assert.fail("expected IOException for a chunk shorter than its view");
} catch (IOException e) {
Assert.assertTrue(e.getMessage(), e.getMessage().contains(fileId));
Assert.assertTrue(e.getMessage(), e.getMessage().contains("[0,175)"));
}
}
@Test
public void testNonOverlappingVisibleIntervals() throws IOException {
List<FilerProto.FileChunk> chunks = new ArrayList<>();
+1 -1
View File
@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<properties>
<seaweedfs.client.version>4.00</seaweedfs.client.version>
<seaweedfs.client.version>4.38</seaweedfs.client.version>
<hadoop.version>3.4.0</hadoop.version>
</properties>
+22 -13
View File
@@ -743,19 +743,14 @@ pub fn parse_needle_id_cookie(s: &str) -> Result<(NeedleId, Cookie), String> {
let needle_id_hex = &hex_part[..split];
let cookie_hex = &hex_part[split..];
let needle_id_bytes = hex::decode(needle_id_hex).map_err(|e| format!("Parse needleId error: {}", e))?;
let cookie_bytes = hex::decode(cookie_hex).map_err(|e| format!("Parse cookie error: {}", e))?;
// Pad needle id to 8 bytes
let mut nid_buf = [0u8; 8];
if needle_id_bytes.len() > 8 {
return Err(format!("KeyHash is too long."));
}
let start = 8 - needle_id_bytes.len();
nid_buf[start..].copy_from_slice(&needle_id_bytes);
let mut key = NeedleId::from_bytes(&nid_buf[0..8]);
let cookie = Cookie::from_bytes(&cookie_bytes[0..4]);
// Go parses both with strconv.ParseUint, which accepts odd-length hex
let mut key = NeedleId(
u64::from_str_radix(needle_id_hex, 16)
.map_err(|e| format!("Parse needleId error: {}", e))?,
);
let cookie = Cookie(
u32::from_str_radix(cookie_hex, 16).map_err(|e| format!("Parse cookie error: {}", e))?,
);
// Apply delta if present (Go: n.Id += Uint64ToNeedleId(d))
if let Some(d) = delta {
@@ -941,4 +936,18 @@ mod tests {
assert_eq!(key, NeedleId(1));
assert_eq!(cookie, Cookie(0x12345678));
}
#[test]
fn test_parse_odd_length_needle_id() {
// Go's shell formats purge fids with strconv.FormatUint, which does not
// pad the needle id hex to an even length.
let (key, cookie) = parse_needle_id_cookie("100000000").unwrap();
assert_eq!(key, NeedleId(1));
assert_eq!(cookie, Cookie(0));
let fid = FileId::parse("3,12300000000").unwrap();
assert_eq!(fid.volume_id, VolumeId(3));
assert_eq!(fid.key, NeedleId(0x123));
assert_eq!(fid.cookie, Cookie(0));
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ require (
github.com/prometheus/procfs v0.16.1 // indirect
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sys v0.45.0 // indirect
)
+2 -2
View File
@@ -84,8 +84,8 @@ go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+3 -3
View File
@@ -1,17 +1,17 @@
module seaweedfs-sftp-tests
go 1.24.0
go 1.25.0
require (
github.com/pkg/sftp v1.13.7
github.com/stretchr/testify v1.10.0
golang.org/x/crypto v0.45.0
golang.org/x/crypto v0.52.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/sys v0.45.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+6 -6
View File
@@ -17,8 +17,8 @@ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5t
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -37,15 +37,15 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+52 -6
View File
@@ -14,16 +14,38 @@ const (
adminLockClientName = "admin-plugin"
)
const (
// A competing shell client polls the master once a second, while a local
// re-acquire would win immediately. Leave the lock free for slightly more
// than one poll interval so a waiting operator gets it first.
defaultAdminLockYieldWindow = 2 * time.Second
// After the lock has been held continuously for this long (overlapping
// reference-counted holds can keep it held indefinitely), new Acquire
// calls wait for a full release so shell clients are not starved.
defaultAdminLockFairnessWindow = time.Minute
)
// adminLocker is the subset of exclusive_locks.ExclusiveLocker the manager uses.
type adminLocker interface {
RequestLock(clientName string)
ReleaseLock()
SetMessage(message string)
}
// AdminLockManager coordinates exclusive admin locks with reference counting.
// It is safe for concurrent use.
type AdminLockManager struct {
locker *exclusive_locks.ExclusiveLocker
clientName string
locker adminLocker
clientName string
yieldWindow time.Duration
fairnessWindow time.Duration
mu sync.Mutex
cond *sync.Cond
acquiring bool
releasing bool
holdCount int
heldSince time.Time
lastAcquiredAt time.Time
lastReleasedAt time.Time
@@ -40,13 +62,19 @@ func NewAdminLockManager(masterClient *wdclient.MasterClient, clientName string)
clientName = adminLockClientName
}
manager := &AdminLockManager{
locker: exclusive_locks.NewExclusiveLocker(masterClient, adminLockName),
clientName: clientName,
locker: exclusive_locks.NewExclusiveLocker(masterClient, adminLockName),
clientName: clientName,
yieldWindow: defaultAdminLockYieldWindow,
fairnessWindow: defaultAdminLockFairnessWindow,
}
manager.cond = sync.NewCond(&manager.mu)
return manager
}
// Acquire takes the shared cluster lock, reference counted so overlapping
// admin-side holders piggyback on one lease. It must not be called while the
// caller's own call stack already holds the lock: once the fairness window
// makes new acquires wait for a full release, a nested Acquire deadlocks.
func (m *AdminLockManager) Acquire(reason string) (func(), error) {
if m == nil || m.locker == nil {
return func() {}, nil
@@ -57,18 +85,28 @@ func (m *AdminLockManager) Acquire(reason string) (func(), error) {
m.locker.SetMessage(reason)
m.currentReason = reason
}
for m.acquiring {
for m.acquiring || m.releasing || (m.holdCount > 0 && time.Since(m.heldSince) > m.fairnessWindow) {
m.cond.Wait()
}
if m.holdCount == 0 {
m.acquiring = true
m.waitingSince = time.Now().UTC()
m.waitingReason = reason
yield := time.Duration(0)
if !m.lastReleasedAt.IsZero() {
if since := time.Since(m.lastReleasedAt); since < m.yieldWindow {
yield = m.yieldWindow - since
}
}
m.mu.Unlock()
if yield > 0 {
time.Sleep(yield)
}
m.locker.RequestLock(m.clientName)
m.mu.Lock()
m.acquiring = false
m.holdCount = 1
m.heldSince = time.Now()
m.lastAcquiredAt = time.Now().UTC()
m.waitingSince = time.Time{}
m.waitingReason = ""
@@ -96,14 +134,22 @@ func (m *AdminLockManager) Release() {
}
m.holdCount--
shouldRelease := m.holdCount == 0
if shouldRelease {
// Block new acquires until ReleaseLock completes: a RequestLock
// issued while the locker still considers itself locked would no-op
// and leave a hold with no live lease.
m.releasing = true
}
m.mu.Unlock()
if shouldRelease {
m.locker.ReleaseLock()
m.mu.Lock()
m.releasing = false
m.lastReleasedAt = time.Now().UTC()
m.currentReason = ""
m.cond.Broadcast()
m.mu.Unlock()
m.locker.ReleaseLock()
}
}
+156
View File
@@ -0,0 +1,156 @@
package dash
import (
"sync"
"testing"
"time"
)
type fakeAdminLocker struct {
releaseDelay time.Duration
mu sync.Mutex
requests []time.Time
releases []time.Time // recorded when ReleaseLock returns
}
func (f *fakeAdminLocker) RequestLock(clientName string) {
f.mu.Lock()
f.requests = append(f.requests, time.Now())
f.mu.Unlock()
}
func (f *fakeAdminLocker) ReleaseLock() {
if f.releaseDelay > 0 {
time.Sleep(f.releaseDelay)
}
f.mu.Lock()
f.releases = append(f.releases, time.Now())
f.mu.Unlock()
}
func (f *fakeAdminLocker) SetMessage(message string) {}
func (f *fakeAdminLocker) counts() (int, int) {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.requests), len(f.releases)
}
func newTestLockManager(locker adminLocker, yieldWindow, fairnessWindow time.Duration) *AdminLockManager {
m := &AdminLockManager{
locker: locker,
clientName: "test",
yieldWindow: yieldWindow,
fairnessWindow: fairnessWindow,
}
m.cond = sync.NewCond(&m.mu)
return m
}
func TestAdminLockManagerRefCountsOverlappingHolds(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{}
m := newTestLockManager(locker, defaultAdminLockYieldWindow, defaultAdminLockFairnessWindow)
release1, _ := m.Acquire("a")
release2, _ := m.Acquire("b")
if requests, releases := locker.counts(); requests != 1 || releases != 0 {
t.Fatalf("expected one lease request while overlapping, got requests=%d releases=%d", requests, releases)
}
release1()
if _, releases := locker.counts(); releases != 0 {
t.Fatalf("lock released while still held by another caller")
}
release2()
if _, releases := locker.counts(); releases != 1 {
t.Fatalf("expected one release after last holder, got %d", releases)
}
}
func TestAdminLockManagerYieldsBeforeReacquire(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{}
m := newTestLockManager(locker, 100*time.Millisecond, defaultAdminLockFairnessWindow)
release, _ := m.Acquire("first")
release()
release, _ = m.Acquire("second")
release()
locker.mu.Lock()
gap := locker.requests[1].Sub(locker.releases[0])
locker.mu.Unlock()
if gap < 90*time.Millisecond {
t.Fatalf("re-acquire did not yield to competing clients: gap=%v", gap)
}
}
func TestAdminLockManagerFairnessWindowForcesFullRelease(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{}
m := newTestLockManager(locker, 20*time.Millisecond, 50*time.Millisecond)
release1, _ := m.Acquire("long-hold")
m.mu.Lock()
m.heldSince = time.Now().Add(-time.Second)
m.mu.Unlock()
acquired := make(chan func(), 1)
go func() {
release2, _ := m.Acquire("late-joiner")
acquired <- release2
}()
select {
case <-acquired:
t.Fatalf("late acquire joined a hold older than the fairness window")
case <-time.After(50 * time.Millisecond):
}
release1()
select {
case release2 := <-acquired:
release2()
case <-time.After(time.Second):
t.Fatalf("late acquire did not proceed after full release")
}
if requests, releases := locker.counts(); requests != 2 || releases != 2 {
t.Fatalf("expected a full release/re-acquire cycle, got requests=%d releases=%d", requests, releases)
}
}
func TestAdminLockManagerAcquireWaitsForReleaseInFlight(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{releaseDelay: 50 * time.Millisecond}
m := newTestLockManager(locker, time.Millisecond, defaultAdminLockFairnessWindow)
release1, _ := m.Acquire("first")
releaseDone := make(chan struct{})
go func() {
release1()
close(releaseDone)
}()
// Let the release enter the slow ReleaseLock before re-acquiring.
time.Sleep(10 * time.Millisecond)
release2, _ := m.Acquire("second")
<-releaseDone
release2()
locker.mu.Lock()
defer locker.mu.Unlock()
if len(locker.requests) != 2 || len(locker.releases) != 2 {
t.Fatalf("unexpected lease traffic: requests=%d releases=%d", len(locker.requests), len(locker.releases))
}
if locker.requests[1].Before(locker.releases[0]) {
t.Fatalf("RequestLock ran while ReleaseLock was still in flight")
}
}
+2 -2
View File
@@ -1459,8 +1459,8 @@ func (s *AdminServer) RunPluginDetectionWithReport(
// DispatchPluginProposals dispatches a batch of proposals using the same
// capacity-aware dispatch logic as the scheduler loop (executor reservation with
// backoff, per-job retry on transient errors). The plugin lock must already be
// held by the caller.
// backoff, per-job retry on transient errors). The dispatch takes the cluster
// admin lock around each job itself; callers must not hold it.
func (s *AdminServer) DispatchPluginProposals(
ctx context.Context,
jobType string,
+3 -8
View File
@@ -595,20 +595,15 @@ func (s *AdminServer) TriggerPluginDetectionAPI(w http.ResponseWriter, r *http.R
}
// RunPluginJobTypeAPI runs full workflow for one job type: detect then dispatch detected jobs.
// RunPluginDetection and the dispatch path take the cluster admin lock
// themselves (around detection and around each job), so no lock is held
// across the whole workflow here.
func (s *AdminServer) RunPluginJobTypeAPI(w http.ResponseWriter, r *http.Request) {
jobType := strings.TrimSpace(mux.Vars(r)["jobType"])
if jobType == "" {
writeJSONError(w, http.StatusBadRequest, "jobType is required")
return
}
releaseLock, err := s.acquirePluginLock(fmt.Sprintf("plugin detect+execute %s", jobType))
if err != nil {
writeJSONError(w, http.StatusInternalServerError, err.Error())
return
}
if releaseLock != nil {
defer releaseLock()
}
var req struct {
ClusterContext json.RawMessage `json:"cluster_context"`
+7 -1
View File
@@ -424,7 +424,13 @@ func (r *Plugin) acquireAdminLock(reason string) (func(), error) {
if r == nil || r.lockManager == nil {
return func() {}, nil
}
return r.lockManager.Acquire(reason)
release, err := r.lockManager.Acquire(reason)
if release == nil {
// Lock manager implementations may return a nil release when
// disabled; callers always invoke the release function.
release = func() {}
}
return release, err
}
// RunDetectionWithReport requests one detector worker and returns proposals with request metadata.
+90 -57
View File
@@ -98,9 +98,11 @@ func (r *Plugin) laneSchedulerLoop(ls *schedulerLaneState) {
// runLaneSchedulerIteration runs one scheduling pass for a single lane,
// processing only the job types assigned to that lane.
//
// For lanes that require a lock (e.g. LaneDefault), all job types are
// processed sequentially under one admin lock because their volume
// management operations share global state.
// For lanes that require a lock (e.g. LaneDefault), job types are processed
// sequentially because their volume management operations share global
// state, and the cluster admin lock is taken around each detection and each
// dispatched job rather than the whole pass, so manual shell operations
// sharing the same lock can interleave between jobs.
//
// For lanes that do not require a lock (e.g. LaneIceberg, LaneLifecycle),
// each job type runs independently in its own goroutine so they do not
@@ -122,7 +124,7 @@ func (r *Plugin) runLaneSchedulerIteration(ls *schedulerLaneState) bool {
}
if LaneRequiresLock(ls.lane) {
return r.runLaneSchedulerIterationLocked(ls, jobTypes)
return r.runLaneSchedulerIterationSequential(ls, jobTypes)
}
return r.runLaneSchedulerIterationConcurrent(ls, jobTypes)
}
@@ -162,21 +164,13 @@ func (r *Plugin) collectDueJobTypes(ls *schedulerLaneState, jobTypes []string) (
return active, due
}
// runLaneSchedulerIterationLocked processes job types sequentially under a
// single admin lock. Used by the default lane where volume management
// operations must be serialised.
func (r *Plugin) runLaneSchedulerIterationLocked(ls *schedulerLaneState, jobTypes []string) bool {
r.setLaneLoopState(ls, "", "waiting_for_lock")
lockName := fmt.Sprintf("plugin scheduler:%s", ls.lane)
releaseLock, err := r.acquireAdminLock(lockName)
if err != nil {
glog.Warningf("Plugin scheduler [%s] failed to acquire lock: %v", ls.lane, err)
r.setLaneLoopState(ls, "", "idle")
return false
}
if releaseLock != nil {
defer releaseLock()
}
// runLaneSchedulerIterationSequential processes job types one at a time.
// Used by the default lane where volume management operations must be
// serialised. The cluster admin lock is not held across the pass;
// runJobTypeIteration and dispatchScheduledProposals take it around each
// detection and each job.
func (r *Plugin) runLaneSchedulerIterationSequential(ls *schedulerLaneState, jobTypes []string) bool {
r.setLaneLoopState(ls, "", "busy")
active, due := r.collectDueJobTypes(ls, jobTypes)
hadJobs := false
@@ -288,6 +282,30 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
return false
}
// Detection plans against the live topology, so it runs under the shared
// cluster admin lock; the lock is released as soon as detection returns.
releaseDetectionLock := func() {}
if LaneRequiresLock(JobTypeLane(jobType)) {
r.setSchedulerLoopStateForJobType(jobType, "waiting_for_lock")
release, lockErr := r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s detection", jobType))
if lockErr != nil {
r.recordSchedulerDetectionError(jobType, lockErr)
r.appendActivity(JobActivity{
JobType: jobType,
Source: "admin_scheduler",
Message: fmt.Sprintf("scheduled detection aborted: %v", lockErr),
Stage: "failed",
OccurredAt: timeToPtr(time.Now().UTC()),
})
r.recordSchedulerRunComplete(jobType, "error")
return false
}
var releaseOnce sync.Once
releaseDetectionLock = func() { releaseOnce.Do(release) }
r.setSchedulerLoopStateForJobType(jobType, "detecting")
}
defer releaseDetectionLock()
detectionTimeout := policy.DetectionTimeout
remaining := time.Until(start.Add(maxRuntime))
if remaining <= 0 {
@@ -311,6 +329,7 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
detectCtx, cancelDetect := context.WithTimeout(jobCtx, detectionTimeout)
proposals, err := r.RunDetection(detectCtx, jobType, clusterContext, policy.MaxResults)
cancelDetect()
releaseDetectionLock()
if err != nil {
r.recordSchedulerDetectionError(jobType, err)
stage := "failed"
@@ -375,26 +394,6 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
r.setSchedulerLoopStateForJobType(jobType, "executing")
// Scan proposals for the maximum estimated_runtime_seconds so the
// execution phase gets enough time for large jobs (e.g. vacuum on
// big volumes). If any proposal needs more time than the remaining
// JobTypeMaxRuntime, extend the execution context accordingly.
var maxEstimatedRuntime time.Duration
for _, p := range filtered {
if p.Parameters != nil {
if est, ok := p.Parameters["estimated_runtime_seconds"]; ok {
if v := est.GetInt64Value(); v > 0 {
if d := time.Duration(v) * time.Second; d > maxEstimatedRuntime {
maxEstimatedRuntime = d
}
}
}
}
}
if maxEstimatedRuntime > maxEstimatedRuntimeCap {
maxEstimatedRuntime = maxEstimatedRuntimeCap
}
remaining = time.Until(start.Add(maxRuntime))
if remaining <= 0 {
r.appendActivity(JobActivity{
@@ -408,17 +407,6 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
return detected
}
// If the longest estimated job exceeds the remaining JobTypeMaxRuntime,
// create a new execution context with enough headroom instead of using
// jobCtx which would cancel too early.
execCtx := jobCtx
execCancel := context.CancelFunc(func() {})
if maxEstimatedRuntime > 0 && maxEstimatedRuntime > remaining {
execCtx, execCancel = context.WithTimeout(context.Background(), maxEstimatedRuntime)
remaining = maxEstimatedRuntime
}
defer execCancel()
execPolicy := policy
if execPolicy.ExecutionTimeout <= 0 {
execPolicy.ExecutionTimeout = defaultScheduledExecutionTimeout
@@ -427,10 +415,15 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
execPolicy.ExecutionTimeout = remaining
}
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(execCtx, jobType, filtered, clusterContext, execPolicy)
// jobCtx bounds how long this run keeps STARTING jobs; a started job
// runs on its own estimated-runtime deadline (see
// executeScheduledJobWithExecutor). Jobs still queued when the window
// closes are canceled and re-proposed by a later detection, so one large
// backlog cannot monopolise the lane for hours.
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(jobCtx, jobType, filtered, clusterContext, execPolicy)
status := "success"
if execCtx.Err() != nil {
if jobCtx.Err() != nil {
status = "timeout"
} else if errorCount > 0 || canceledCount > 0 {
status = "error"
@@ -818,6 +811,11 @@ func (r *Plugin) dispatchScheduledProposals(
ctx = context.Background()
}
// Volume management jobs mutate volume placement, so each one runs under
// the shared cluster admin lock. Taking it per job instead of around the
// whole dispatch lets manual shell operations interleave between jobs.
jobsRequireLock := LaneRequiresLock(JobTypeLane(jobType))
jobQueue := make(chan *plugin_pb.JobSpec, len(proposals))
for index, proposal := range proposals {
job := buildScheduledJobSpec(jobType, proposal, index)
@@ -900,7 +898,42 @@ func (r *Plugin) dispatchScheduledProposals(
break
}
var releaseJobLock func()
if jobsRequireLock {
var lockErr error
releaseJobLock, lockErr = r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s job %s", jobType, job.JobId))
if lockErr != nil {
release()
statsMu.Lock()
errorCount++
statsMu.Unlock()
r.appendActivity(JobActivity{
JobID: job.JobId,
JobType: job.JobType,
Source: "admin_scheduler",
Message: fmt.Sprintf("scheduled execution lock failed: %v", lockErr),
Stage: "failed",
OccurredAt: timeToPtr(time.Now().UTC()),
})
break
}
// The lock may have been held by an operator for a
// while; re-check the execution window.
if ctx.Err() != nil {
releaseJobLock()
release()
r.cancelQueuedJob(job, ctx.Err())
statsMu.Lock()
canceledCount++
statsMu.Unlock()
continue jobLoop
}
}
err := r.executeScheduledJobWithExecutor(ctx, executor, job, clusterContext, policy)
if releaseJobLock != nil {
releaseJobLock()
}
release()
if errors.Is(err, errExecutorAtCapacity) {
r.trackExecutionQueued(job)
@@ -1164,10 +1197,6 @@ func (r *Plugin) executeScheduledJobWithExecutor(
return ctx.Err()
}
parent := ctx
if parent == nil {
parent = context.Background()
}
// Use the job's estimated runtime if provided and larger than the
// default execution timeout. This lets handlers like vacuum scale
// the timeout based on volume size so large volumes are not killed.
@@ -1185,7 +1214,11 @@ func (r *Plugin) executeScheduledJobWithExecutor(
}
}
}
execCtx, cancel := context.WithTimeout(parent, timeout)
// The attempt runs against its own deadline, detached from the
// dispatch window (ctx): a job started near the end of the window
// may run to completion; the window only stops further jobs from
// starting.
execCtx, cancel := context.WithTimeout(context.Background(), timeout)
_, err := r.executeJobWithExecutor(execCtx, executor, job, clusterContext, int32(attempt))
cancel()
if err == nil {
@@ -664,6 +664,12 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
t.Fatalf("SaveJobTypeConfig: %v", err)
}
// Make the job type due immediately so the iteration reaches
// detection; the lock is only taken around due work now.
pluginSvc.schedulerMu.Lock()
pluginSvc.nextDetectionAt[tt.jobType] = time.Now().UTC().Add(-time.Second)
pluginSvc.schedulerMu.Unlock()
ls := pluginSvc.lanes[tt.lane]
pluginSvc.runLaneSchedulerIteration(ls)
@@ -674,6 +680,61 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
}
}
func TestDispatchScheduledProposalsLocksPerJob(t *testing.T) {
t.Parallel()
tests := []struct {
name string
jobType string
wantLocks int
}{
{"DefaultLaneLocksEachJob", "volume_balance", 3},
{"LifecycleLaneNeedsNoLock", "s3_lifecycle", 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
lm := &trackingLockManager{}
pluginSvc, err := New(Options{LockManager: lm})
if err != nil {
t.Fatalf("New: %v", err)
}
defer pluginSvc.Shutdown()
// The worker has capabilities but no connected session, so each
// job reserves capacity, fails to send, and moves on.
pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{
WorkerId: "worker-a",
Capabilities: []*plugin_pb.JobTypeCapability{
{JobType: tt.jobType, CanExecute: true, MaxExecutionConcurrency: 4},
},
})
policy := schedulerPolicy{
ExecutionConcurrency: 1,
PerWorkerConcurrency: 1,
ExecutionTimeout: time.Second,
ExecutorReserveBackoff: time.Millisecond,
}
proposals := []*plugin_pb.JobProposal{
{ProposalId: "p1", JobType: tt.jobType, DedupeKey: "k1"},
{ProposalId: "p2", JobType: tt.jobType, DedupeKey: "k2"},
{ProposalId: "p3", JobType: tt.jobType, DedupeKey: "k3"},
}
success, errors, canceled := pluginSvc.dispatchScheduledProposals(
context.Background(), tt.jobType, proposals, &plugin_pb.ClusterContext{}, policy)
if success != 0 || canceled != 0 || errors != 3 {
t.Fatalf("unexpected dispatch counts: success=%d errors=%d canceled=%d", success, errors, canceled)
}
if got := lm.count(); got != tt.wantLocks {
t.Fatalf("lock acquired %d times, want %d", got, tt.wantLocks)
}
})
}
}
// ---------- lane-scoped prune ----------
func TestPruneSchedulerState_DefaultLaneKeepsForeignLanesAndPrunesOwnStale(t *testing.T) {
+9 -7
View File
@@ -6,8 +6,8 @@ import (
)
// SchedulerLane identifies an independent scheduling track. Each lane runs
// its own goroutine, maintains its own detection timing, and acquires its
// own admin lock so that workloads in different lanes never block each other.
// its own goroutine and maintains its own detection timing so that
// workloads in different lanes never block each other.
type SchedulerLane string
const (
@@ -39,17 +39,19 @@ var laneIdleSleep = map[SchedulerLane]time.Duration{
}
// laneRequiresLock maps each lane to whether its job types must be
// serialised under a single admin lock. The default lane needs this
// because volume-management operations share global state. Other
// lanes run each job type independently.
// serialised and run under the shared cluster admin lock. The default
// lane needs this because volume-management operations share global
// state; the lock is taken around each detection and each job so manual
// shell operations can interleave. Other lanes run each job type
// independently without the lock.
var laneRequiresLock = map[SchedulerLane]bool{
LaneDefault: true,
LaneIceberg: false,
LaneLifecycle: false,
}
// LaneRequiresLock returns true if the given lane needs a single admin
// lock to serialise its job types. Unknown lanes default to true.
// LaneRequiresLock returns true if the given lane serialises its job types
// and runs them under the cluster admin lock. Unknown lanes default to true.
func LaneRequiresLock(lane SchedulerLane) bool {
if v, ok := laneRequiresLock[lane]; ok {
return v
@@ -128,6 +128,11 @@ func (efc *EmptyFolderCleaner) OnDeleteEvent(directory string, entryName string,
return
}
// Never queue the S3 multipart staging area; the upload lifecycle owns it.
if isMultipartUploadsPath(efc.bucketPath, directory) {
return
}
// Check if we own this folder
if !efc.ownsFolder(directory) {
glog.V(4).Infof("EmptyFolderCleaner: not owner of %s, skipping", directory)
@@ -239,6 +244,15 @@ func (efc *EmptyFolderCleaner) processCleanupQueue() {
// executeCleanup performs the actual cleanup of an empty folder
func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string) {
// The bucket-shared .uploads staging tree holds in-progress multipart uploads.
// Deleting <bucket>/.uploads (reached here directly or via the parent cascade
// below) races a concurrent CreateMultipartUpload: the new upload's marker row
// is inserted between the emptiness check and the folder delete, then wiped,
// so the upload silently vanishes. Leave this tree to the upload lifecycle.
if isMultipartUploadsPath(efc.bucketPath, folder) {
return
}
efc.mu.Lock()
// Quick check: if we have cached count and it's > 0, skip
@@ -422,6 +436,21 @@ func isUnderPath(child, parent string) bool {
return child[len(parent)] == '/'
}
// isMultipartUploadsPath reports whether directory is the S3 multipart staging
// root <bucket>/.uploads or anything beneath it.
func isMultipartUploadsPath(bucketPath, directory string) bool {
if bucketPath == "" {
return false
}
dir, ok := util.ExtractBucketPath(bucketPath, directory, true)
if !ok {
return false
}
// requireChild guarantees directory starts with dir + "/", so slice past it.
first, _, _ := strings.Cut(directory[len(dir)+1:], "/")
return first == s3_constants.MultipartUploadsFolder
}
// isUnderBucketPath checks if directory is inside a bucket (under /buckets/<bucket>/...)
// This ensures we only clean up folders inside buckets, not the buckets themselves
func isUnderBucketPath(directory, bucketPath string) bool {
@@ -104,6 +104,102 @@ func Test_isUnderBucketPath(t *testing.T) {
}
}
func Test_isMultipartUploadsPath(t *testing.T) {
uploads := s3_constants.MultipartUploadsFolder
tests := []struct {
name string
directory string
bucketPath string
expected bool
}{
{"staging root", "/buckets/mybucket/" + uploads, "/buckets", true},
{"upload marker dir", "/buckets/mybucket/" + uploads + "/abc123", "/buckets", true},
{"nested under staging", "/buckets/mybucket/" + uploads + "/abc123/hashstates", "/buckets", true},
{"normal folder", "/buckets/mybucket/folder", "/buckets", false},
{"registry own uploads dir", "/buckets/mybucket/docker/registry/v2/_uploads/x", "/buckets", false},
{"bucket itself", "/buckets/mybucket", "/buckets", false},
{"outside buckets", "/other/" + uploads, "/buckets", false},
{"empty bucket path", "/buckets/mybucket/" + uploads, "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isMultipartUploadsPath(tt.bucketPath, tt.directory); got != tt.expected {
t.Errorf("isMultipartUploadsPath(%q, %q) = %v, want %v", tt.bucketPath, tt.directory, got, tt.expected)
}
})
}
}
func TestEmptyFolderCleaner_OnDeleteEvent_skipsMultipartUploads(t *testing.T) {
lockRing := lock_manager.NewLockRing(5 * time.Second)
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"}, 0)
cleaner := &EmptyFolderCleaner{
lockRing: lockRing,
host: "filer1:8888",
bucketPath: "/buckets",
enabled: true,
folderCounts: make(map[string]*folderState),
cleanupQueue: NewCleanupQueue(1000, 10*time.Minute),
stopCh: make(chan struct{}),
}
now := time.Now()
uploads := "/buckets/mybucket/" + s3_constants.MultipartUploadsFolder
cleaner.OnDeleteEvent(uploads, "abc123", true, now)
cleaner.OnDeleteEvent(uploads+"/abc123", "0001.part", false, now)
if cleaner.GetPendingCleanupCount() != 0 {
t.Fatalf("multipart staging paths must not be queued, got %d pending", cleaner.GetPendingCleanupCount())
}
// A normal folder is still queued, proving the guard is scoped to .uploads.
cleaner.OnDeleteEvent("/buckets/mybucket/folder", "file.txt", false, now)
if cleaner.GetPendingCleanupCount() != 1 {
t.Fatalf("normal folder should be queued, got %d pending", cleaner.GetPendingCleanupCount())
}
cleaner.Stop()
}
func TestEmptyFolderCleaner_executeCleanup_skipsMultipartUploads(t *testing.T) {
lockRing := lock_manager.NewLockRing(5 * time.Second)
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"}, 0)
var deleted []string
mock := &mockFilerOps{
countFn: func(util.FullPath) (int, error) { return 0, nil },
deleteFn: func(p util.FullPath) error { deleted = append(deleted, string(p)); return nil },
}
cleaner := &EmptyFolderCleaner{
filer: mock,
lockRing: lockRing,
host: "filer1:8888",
bucketPath: "/buckets",
enabled: true,
maxCountCheck: DefaultMaxCountCheck,
cacheExpiry: DefaultCacheExpiry,
folderCounts: make(map[string]*folderState),
bucketCleanupPolicies: make(map[string]*bucketCleanupPolicyState),
cleanupQueue: NewCleanupQueue(1000, 10*time.Minute),
stopCh: make(chan struct{}),
}
uploads := "/buckets/mybucket/" + s3_constants.MultipartUploadsFolder
cleaner.executeCleanup(uploads, "abc123")
cleaner.executeCleanup(uploads+"/abc123", "0001.part")
if len(deleted) != 0 {
t.Fatalf("multipart staging paths must not be deleted, got %v", deleted)
}
// An empty normal folder is deleted, proving the guard did not disable cleanup.
cleaner.executeCleanup("/buckets/mybucket/folder", "file.txt")
if len(deleted) != 1 || deleted[0] != "/buckets/mybucket/folder" {
t.Fatalf("normal empty folder should be deleted, got %v", deleted)
}
}
func Test_autoRemoveEmptyFoldersEnabled(t *testing.T) {
tests := []struct {
name string
+16 -4
View File
@@ -59,12 +59,14 @@ func (m *MockOIDCProvider) Authenticate(ctx context.Context, token string) (*pro
email, _ := claims.GetClaimString("email")
displayName, _ := claims.GetClaimString("name")
groups, _ := claims.GetClaimStringSlice("groups")
rawRoles, _ := claims.GetClaimStringSlice("roles")
return &providers.ExternalIdentity{
UserID: claims.Subject,
Email: email,
DisplayName: displayName,
Groups: groups,
Roles: rawRoles,
Provider: m.name,
}, nil
}
@@ -107,16 +109,26 @@ func (m *MockOIDCProvider) ValidateToken(ctx context.Context, token string) (*pr
issuedAt = time.Unix(int64(iat), 0)
}
// Carry the token's claims through like the real provider, keeping
// the synthesized defaults for tests that rely on them
claimsMap := make(map[string]interface{}, len(jwtClaims)+2)
for k, v := range jwtClaims {
claimsMap[k] = v
}
if _, ok := claimsMap["email"]; !ok {
claimsMap["email"] = subject + "@test-domain.com"
}
if _, ok := claimsMap["name"]; !ok {
claimsMap["name"] = "Test User " + subject
}
return &providers.TokenClaims{
Subject: subject,
Issuer: issuer,
Audience: audience,
ExpiresAt: expiresAt,
IssuedAt: issuedAt,
Claims: map[string]interface{}{
"email": subject + "@test-domain.com",
"name": "Test User " + subject,
},
Claims: claimsMap,
}, nil
}
}
+5
View File
@@ -481,6 +481,10 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide
email, _ := claims.GetClaimString("email")
displayName, _ := claims.GetClaimString("name")
groups, _ := claims.GetClaimStringSlice("groups")
// The raw `roles` claim (e.g. from a Keycloak realm-role mapper). Surfaced into
// the STS request context below (see ExternalIdentity.Roles) so resource policies
// can gate on jwt:roles. Distinct from the provider-configured role mapping below.
rawRoles, _ := claims.GetClaimStringSlice("roles")
// Debug: Log available claims
glog.V(3).Infof("Available claims: %+v", claims.Claims)
@@ -535,6 +539,7 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide
Email: email,
DisplayName: displayName,
Groups: groups,
Roles: rawRoles,
Attributes: attributes,
Provider: p.name,
Issuer: claims.Issuer,
+7
View File
@@ -43,6 +43,13 @@ type ExternalIdentity struct {
// Groups are the groups the user belongs to
Groups []string `json:"groups,omitempty"`
// Roles are the roles the user holds (from the token's `roles` claim).
// Surfaced into the STS request context so resource policies can gate on
// jwt:roles - same rationale as Groups (the claim is otherwise excluded from
// attributes by the provider's processedClaims set, so it never reached the
// request context and was usable only via provider-configured role mapping).
Roles []string `json:"roles,omitempty"`
// Attributes are additional user attributes
Attributes map[string]string `json:"attributes,omitempty"`
+20
View File
@@ -640,6 +640,26 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
// Add sub as well since it's commonly used
requestContext["sub"] = externalIdentity.UserID
// Surface federated group memberships so resource (permission) policies can do
// group-based ABAC - not just role trust policies. Stored as a []string; the
// string-condition evaluator already handles multi-valued context keys, and the
// S3 middleware additionally exposes it as jwt:groups. Without this, "groups"
// was excluded from the OIDC attributes (see oidc_provider processedClaims) and
// so only usable at assume-time (trust policy), never at request-time - meaning
// a single role's permission policy could not scope access by the caller's
// groups (aggregate/ABAC).
if len(externalIdentity.Groups) > 0 {
requestContext["groups"] = externalIdentity.Groups
}
// Same for the caller's roles (the `roles` claim). Surfaced as a []string so a
// resource policy can gate on jwt:roles - the S3 middleware exposes it that way.
// Without this, "roles" was excluded from the OIDC attributes (processedClaims)
// and so unusable in a request-time permission policy.
if len(externalIdentity.Roles) > 0 {
requestContext["roles"] = externalIdentity.Roles
}
// Compute a stable parent-user hash from (sub, iss). Only this tuple is
// guaranteed stable across token refresh per OIDC Core 1.0, so this is the
// right key for any per-identity state (audit trail, future quotas).
+1
View File
@@ -325,6 +325,7 @@ message ObjectMutation {
bool set_content = 10; // PATCH_EXTENDED: replace Entry.content with content
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
+26 -17
View File
@@ -1476,21 +1476,22 @@ func (x *WriteCondition) GetClauses() []*WriteCondition_Clause {
// several RPCs. Data-bearing writes (entries with chunks) should be written
// before the transaction; mutations here are metadata-scoped.
type ObjectMutation struct {
state protoimpl.MessageState `protogen:"open.v1"`
Type ObjectMutation_Type `protobuf:"varint,1,opt,name=type,proto3,enum=filer_pb.ObjectMutation_Type" json:"type,omitempty"`
Directory string `protobuf:"bytes,2,opt,name=directory,proto3" json:"directory,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // entry name for DELETE / PATCH_EXTENDED / RECOMPUTE_LATEST (the pointer entry)
Entry *Entry `protobuf:"bytes,4,opt,name=entry,proto3" json:"entry,omitempty"` // full entry for PUT
SetExtended map[string][]byte `protobuf:"bytes,5,rep,name=set_extended,json=setExtended,proto3" json:"set_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // PATCH_EXTENDED: keys to set
DeleteExtended []string `protobuf:"bytes,6,rep,name=delete_extended,json=deleteExtended,proto3" json:"delete_extended,omitempty"` // PATCH_EXTENDED: keys to remove
IsDeleteData bool `protobuf:"varint,7,opt,name=is_delete_data,json=isDeleteData,proto3" json:"is_delete_data,omitempty"` // DELETE: also delete chunk data
IsRecursive bool `protobuf:"varint,8,opt,name=is_recursive,json=isRecursive,proto3" json:"is_recursive,omitempty"` // DELETE: recurse into a directory
Recompute *Recompute `protobuf:"bytes,9,opt,name=recompute,proto3" json:"recompute,omitempty"` // RECOMPUTE_LATEST parameters
SetContent bool `protobuf:"varint,10,opt,name=set_content,json=setContent,proto3" json:"set_content,omitempty"` // PATCH_EXTENDED: replace Entry.content with content
Content []byte `protobuf:"bytes,11,opt,name=content,proto3" json:"content,omitempty"` // PATCH_EXTENDED: new Entry.content when set_content
TouchMtime bool `protobuf:"varint,12,opt,name=touch_mtime,json=touchMtime,proto3" json:"touch_mtime,omitempty"` // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
Type ObjectMutation_Type `protobuf:"varint,1,opt,name=type,proto3,enum=filer_pb.ObjectMutation_Type" json:"type,omitempty"`
Directory string `protobuf:"bytes,2,opt,name=directory,proto3" json:"directory,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // entry name for DELETE / PATCH_EXTENDED / RECOMPUTE_LATEST (the pointer entry)
Entry *Entry `protobuf:"bytes,4,opt,name=entry,proto3" json:"entry,omitempty"` // full entry for PUT
SetExtended map[string][]byte `protobuf:"bytes,5,rep,name=set_extended,json=setExtended,proto3" json:"set_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // PATCH_EXTENDED: keys to set
DeleteExtended []string `protobuf:"bytes,6,rep,name=delete_extended,json=deleteExtended,proto3" json:"delete_extended,omitempty"` // PATCH_EXTENDED: keys to remove
IsDeleteData bool `protobuf:"varint,7,opt,name=is_delete_data,json=isDeleteData,proto3" json:"is_delete_data,omitempty"` // DELETE: also delete chunk data
IsRecursive bool `protobuf:"varint,8,opt,name=is_recursive,json=isRecursive,proto3" json:"is_recursive,omitempty"` // DELETE: recurse into a directory
Recompute *Recompute `protobuf:"bytes,9,opt,name=recompute,proto3" json:"recompute,omitempty"` // RECOMPUTE_LATEST parameters
SetContent bool `protobuf:"varint,10,opt,name=set_content,json=setContent,proto3" json:"set_content,omitempty"` // PATCH_EXTENDED: replace Entry.content with content
Content []byte `protobuf:"bytes,11,opt,name=content,proto3" json:"content,omitempty"` // PATCH_EXTENDED: new Entry.content when set_content
TouchMtime bool `protobuf:"varint,12,opt,name=touch_mtime,json=touchMtime,proto3" json:"touch_mtime,omitempty"` // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
RemoveEmptyParent bool `protobuf:"varint,13,opt,name=remove_empty_parent,json=removeEmptyParent,proto3" json:"remove_empty_parent,omitempty"` // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ObjectMutation) Reset() {
@@ -1607,6 +1608,13 @@ func (x *ObjectMutation) GetTouchMtime() bool {
return false
}
func (x *ObjectMutation) GetRemoveEmptyParent() bool {
if x != nil {
return x.RemoveEmptyParent
}
return false
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
// current contents of a scanned directory, atomically under the transaction's
// lock. It is mechanical: the filer picks the child that sorts first or last by
@@ -6928,7 +6936,7 @@ const file_filer_proto_rawDesc = "" +
"\x13IF_UNMODIFIED_SINCE\x10\x05\x12\x15\n" +
"\x11IF_MODIFIED_SINCE\x10\x06\x12\x19\n" +
"\x15IF_EXTENDED_NOT_EQUAL\x10\a\x12\x1c\n" +
"\x18IF_EXTENDED_TIME_ELAPSED\x10\b\"\xf2\x04\n" +
"\x18IF_EXTENDED_TIME_ELAPSED\x10\b\"\xa2\x05\n" +
"\x0eObjectMutation\x121\n" +
"\x04type\x18\x01 \x01(\x0e2\x1d.filer_pb.ObjectMutation.TypeR\x04type\x12\x1c\n" +
"\tdirectory\x18\x02 \x01(\tR\tdirectory\x12\x12\n" +
@@ -6944,7 +6952,8 @@ const file_filer_proto_rawDesc = "" +
"setContent\x12\x18\n" +
"\acontent\x18\v \x01(\fR\acontent\x12\x1f\n" +
"\vtouch_mtime\x18\f \x01(\bR\n" +
"touchMtime\x1a>\n" +
"touchMtime\x12.\n" +
"\x13remove_empty_parent\x18\r \x01(\bR\x11removeEmptyParent\x1a>\n" +
"\x10SetExtendedEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"E\n" +
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v6.33.4
// - protoc v7.35.0
// source: filer.proto
package filer_pb
+75
View File
@@ -0,0 +1,75 @@
package pluginworker
import (
"context"
"fmt"
"strconv"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"google.golang.org/grpc"
)
// LookupVolumeLocations asks the masters for the current registered locations
// of a volume, bypassing any client-side caches. Execution handlers use it to
// re-check a proposal against the live topology, since a proposal can go
// stale between detection and execution. Returns the location URLs
// (host:port) the master reports; an empty slice means the volume is not
// registered anywhere.
func LookupVolumeLocations(ctx context.Context, masterAddresses []string, grpcDialOption grpc.DialOption, volumeID uint32) ([]string, error) {
if grpcDialOption == nil {
return nil, fmt.Errorf("grpc dial option is not configured")
}
if len(masterAddresses) == 0 {
return nil, fmt.Errorf("no master addresses provided in cluster context")
}
vid := strconv.FormatUint(uint64(volumeID), 10)
var lastErr error
for _, address := range masterAddresses {
for _, candidate := range MasterAddressCandidates(address) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
dialCtx, cancelDial := context.WithTimeout(ctx, 5*time.Second)
conn, err := pb.GrpcDial(dialCtx, candidate, false, grpcDialOption)
cancelDial()
if err != nil {
lastErr = err
continue
}
client := master_pb.NewSeaweedClient(conn)
callCtx, cancelCall := context.WithTimeout(ctx, 10*time.Second)
resp, callErr := client.LookupVolume(callCtx, &master_pb.LookupVolumeRequest{
VolumeOrFileIds: []string{vid},
})
cancelCall()
_ = conn.Close()
if callErr != nil {
lastErr = callErr
continue
}
for _, vidLocation := range resp.VolumeIdLocations {
if vidLocation.VolumeOrFileId != vid {
continue
}
locations := make([]string, 0, len(vidLocation.Locations))
for _, location := range vidLocation.Locations {
locations = append(locations, location.Url)
}
return locations, nil
}
// The master answered but does not know the volume.
return nil, nil
}
}
if lastErr == nil {
lastErr = fmt.Errorf("no valid master address candidate")
}
return nil, lastErr
}
+37 -7
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
@@ -46,12 +47,13 @@ func TestReverseProxySignatureVerification(t *testing.T) {
}`
tests := []struct {
name string
externalUrl string // s3.externalUrl config for the backend
clientScheme string // scheme the client uses for signing
clientHost string // host the client signs against
proxyForwardsHost bool // whether proxy sets X-Forwarded-Host
expectSuccess bool
name string
externalUrl string // s3.externalUrl config for the backend
clientScheme string // scheme the client uses for signing
clientHost string // host the client signs against
proxyForwardsHost bool // whether proxy sets X-Forwarded-Host
portlessForwardedHost bool // nginx-style $host / $server_port: hostname in X-Forwarded-Host, port in X-Forwarded-Port
expectSuccess bool
}{
{
name: "non-standard port, externalUrl matches proxy address",
@@ -101,6 +103,26 @@ func TestReverseProxySignatureVerification(t *testing.T) {
proxyForwardsHost: false,
expectSuccess: false,
},
{
// The backend Host (127.0.0.1:ephemeral) shares the forwarded hostname, so the
// backend port must not shadow X-Forwarded-Port.
name: "nginx $host/$server_port forwarding, backend on same hostname",
externalUrl: "",
clientScheme: "http",
clientHost: "127.0.0.1:9000",
proxyForwardsHost: true,
portlessForwardedHost: true,
expectSuccess: true,
},
{
name: "portless X-Forwarded-Host on default port, backend on same hostname",
externalUrl: "",
clientScheme: "http",
clientHost: "127.0.0.1",
proxyForwardsHost: true,
portlessForwardedHost: true,
expectSuccess: true,
},
{
name: "proxy without X-Forwarded-Host, externalUrl saves the day",
externalUrl: "http://api.example.com:9000",
@@ -136,6 +158,7 @@ func TestReverseProxySignatureVerification(t *testing.T) {
proxy := httputil.NewSingleHostReverseProxy(backendURL)
forwardsHost := tt.proxyForwardsHost
portlessForwardedHost := tt.portlessForwardedHost
originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
originalHost := req.Host
@@ -148,7 +171,14 @@ func TestReverseProxySignatureVerification(t *testing.T) {
// (nginx proxy_pass and Kong both do this by default)
req.Host = backendURL.Host
if forwardsHost {
req.Header.Set("X-Forwarded-Host", originalHost)
forwardedHost := originalHost
if portlessForwardedHost {
if h, p, splitErr := net.SplitHostPort(originalHost); splitErr == nil {
forwardedHost = h
req.Header.Set("X-Forwarded-Port", p)
}
}
req.Header.Set("X-Forwarded-Host", forwardedHost)
req.Header.Set("X-Forwarded-Proto", originalScheme)
}
}
+83 -39
View File
@@ -29,6 +29,7 @@ import (
"net/http"
"net/url"
"regexp"
"slices"
"sort"
"strconv"
"strings"
@@ -314,36 +315,57 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
)
}
// 8. Verify the signature, trying with X-Forwarded-Prefix first
// 8. Verify the signature for each plausible host value: when X-Forwarded-Host carries
// no port, the client may have signed the Host header the proxy kept or the forwarded
// host and port, and the headers alone cannot tell which.
pathForSignature := r.URL.EscapedPath()
if pathForSignature == "" {
pathForSignature = r.URL.Path
}
if forwardedPrefix := r.Header.Get("X-Forwarded-Prefix"); forwardedPrefix != "" {
cleanedPath := buildPathWithForwardedPrefix(forwardedPrefix, pathForSignature)
calculatedSignature, errCode = verify(cleanedPath)
forwardedPrefix := r.Header.Get("X-Forwarded-Prefix")
for i, hostCandidate := range extractHostHeaderCandidates(r, iam.externalHost) {
if i > 0 && !replaceSignedHostHeader(extractedSignedHeaders, hostCandidate) {
break
}
// 9. Verify with the X-Forwarded-Prefix path first
if forwardedPrefix != "" {
cleanedPath := buildPathWithForwardedPrefix(forwardedPrefix, pathForSignature)
calculatedSignature, errCode = verify(cleanedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
}
// 10. Verify with the original path
calculatedSignature, errCode = verify(pathForSignature)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
}
// 9. Verify with the original path
calculatedSignature, errCode = verify(pathForSignature)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
// 10. Retry with decoded path if signature used raw path encoding
if decodedPath, decodeErr := url.PathUnescape(pathForSignature); decodeErr == nil && decodedPath != pathForSignature {
calculatedSignature, errCode = verify(decodedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
// 11. Retry with decoded path if signature used raw path encoding
if decodedPath, decodeErr := url.PathUnescape(pathForSignature); decodeErr == nil && decodedPath != pathForSignature {
calculatedSignature, errCode = verify(decodedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
}
}
return nil, nil, "", nil, errCode
}
func replaceSignedHostHeader(headers http.Header, host string) bool {
replaced := false
for name := range headers {
if strings.EqualFold(name, "host") {
headers[name] = []string{host}
replaced = true
}
}
return replaced
}
// validateSTSSessionToken validates an STS session token and extracts temporary credentials
func (iam *IdentityAccessManagement) validateSTSSessionToken(r *http.Request, sessionToken string, accessKey string) (*Identity, *Credential, s3err.ErrorCode) {
// Check if IAM integration is available
@@ -860,13 +882,20 @@ func extractSignedHeaders(signedHeaders []string, r *http.Request, externalHost
return extractedSignedHeaders, s3err.ErrNone
}
// extractHostHeader returns the value of host header to use for signature verification.
// When externalHost is set (from s3.externalUrl), it is returned directly.
// Otherwise, the host is reconstructed from X-Forwarded-* headers or the request Host,
// with default port stripping to match AWS SDK SanitizeHostForHeader behavior.
// extractHostHeader returns the most likely host header value for signature verification.
func extractHostHeader(r *http.Request, externalHost string) string {
return extractHostHeaderCandidates(r, externalHost)[0]
}
// extractHostHeaderCandidates returns the host values the client may have signed, most
// likely first. When externalHost is set (from s3.externalUrl), it is the only candidate.
// Otherwise, the host is reconstructed from X-Forwarded-* headers or the request Host.
// When X-Forwarded-Host carries no port, the true client port is ambiguous: a proxy that
// kept the Host header makes the r.Host port right, one that rewrote it makes
// X-Forwarded-Port right, and a client on the scheme's default port signed no port at all.
func extractHostHeaderCandidates(r *http.Request, externalHost string) []string {
if externalHost != "" {
return externalHost
return []string{externalHost}
}
forwardedHost := r.Header.Get("X-Forwarded-Host")
@@ -895,7 +924,8 @@ func extractHostHeader(r *http.Request, externalHost string) string {
scheme = forwardedProto
}
var host, port string
var host string
var ports []string
if forwardedHost != "" {
// X-Forwarded-Host can be a comma-separated list of hosts when there are multiple proxies.
// Use only the first host in the list and trim spaces for robustness.
@@ -908,14 +938,16 @@ func extractHostHeader(r *http.Request, externalHost string) string {
// If the host itself contains a port, it should take precedence
if h, p, err := net.SplitHostPort(host); err == nil {
host = h
port = p
ports = []string{p}
} else {
// If X-Forwarded-Host has no port, try to get port from r.Host if hostnames match
if rh, rp, err := net.SplitHostPort(r.Host); err == nil && rh == host {
port = rp
} else if forwardedPort != "" {
port = forwardedPort
// SplitHostPort unbrackets IPv6 hosts, so unbracket the forwarded host to match
if rh, rp, err := net.SplitHostPort(r.Host); err == nil && rh == strings.Trim(host, "[]") {
ports = append(ports, rp)
}
if forwardedPort != "" {
ports = append(ports, forwardedPort)
}
ports = append(ports, "")
}
} else {
host = r.Host
@@ -927,14 +959,29 @@ func extractHostHeader(r *http.Request, externalHost string) string {
// Otherwise, if X-Forwarded-Port is set, use it.
if h, p, err := net.SplitHostPort(host); err == nil {
host = h
port = p
} else if forwardedPort != "" {
port = forwardedPort
ports = []string{p}
} else {
if forwardedPort != "" {
ports = append(ports, forwardedPort)
}
ports = append(ports, "")
}
}
// Strip default ports based on scheme to match AWS SDK SanitizeHostForHeader behavior.
// The AWS SDK strips port 80 for HTTP and port 443 for HTTPS before signing.
var candidates []string
for _, port := range ports {
candidate := joinSignedHost(host, port, scheme)
if !slices.Contains(candidates, candidate) {
candidates = append(candidates, candidate)
}
}
return candidates
}
// joinSignedHost renders host:port the way AWS SDKs sign it: default ports are stripped
// to match SanitizeHostForHeader, and bare IPv6 addresses lose their brackets.
// Reference: https://github.com/aws/aws-sdk-go-v2/blob/main/aws/signer/internal/v4/host.go
func joinSignedHost(host, port, scheme string) string {
if port != "" && !isDefaultPort(scheme, port) {
// Strip existing brackets before calling JoinHostPort, which automatically adds
// brackets for IPv6 addresses. This prevents double-bracketing like [[::1]]:8080.
@@ -942,9 +989,6 @@ func extractHostHeader(r *http.Request, externalHost string) string {
return net.JoinHostPort(host, port)
}
// Default port was stripped, or no port present.
// For IPv6 addresses, strip brackets to match AWS SDK behavior.
// Reference: https://github.com/aws/aws-sdk-go-v2/blob/main/aws/signer/internal/v4/host.go
if strings.Contains(host, ":") {
return strings.Trim(host, "[]")
}
@@ -1123,9 +1167,9 @@ func encodePath(pathName string) string {
if runeLen < 0 {
return pathName
}
u := make([]byte, runeLen)
utf8.EncodeRune(u, s)
for _, r := range u {
var u [utf8.UTFMax]byte
utf8.EncodeRune(u[:], s)
for _, r := range u[:runeLen] {
buf.WriteByte('%')
buf.WriteByte(pathHexTable[r>>4])
buf.WriteByte(pathHexTable[r&0x0f])
+106
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"fmt"
"net/http"
"slices"
"testing"
"time"
@@ -521,6 +522,111 @@ func TestExtractHostHeader(t *testing.T) {
}
}
// TestExtractHostHeaderCandidates tests the alternate host values tried during verification
// when the true client-facing host is ambiguous behind a reverse proxy.
func TestExtractHostHeaderCandidates(t *testing.T) {
tests := []struct {
name string
hostHeader string
forwardedHost string
forwardedPort string
forwardedProto string
externalHost string
expected []string
}{
{
name: "externalHost is the only candidate",
hostHeader: "backend:8333",
externalHost: "api.example.com:9000",
expected: []string{"api.example.com:9000"},
},
{
name: "X-Forwarded-Host with port is trusted as-is",
hostHeader: "backend:8333",
forwardedHost: "example.com:9000",
forwardedPort: "443",
expected: []string{"example.com:9000"},
},
{
name: "plain Host with port is the only candidate",
hostHeader: "example.com:8080",
expected: []string{"example.com:8080"},
},
{
name: "portless X-Forwarded-Host, hostnames match: r.Host port first, then X-Forwarded-Port, then bare",
hostHeader: "example.com:8333",
forwardedHost: "example.com",
forwardedPort: "9000",
forwardedProto: "http",
expected: []string{"example.com:8333", "example.com:9000", "example.com"},
},
{
name: "portless X-Forwarded-Host, hostnames match, no X-Forwarded-Port: bare host as fallback",
hostHeader: "example.com:8333",
forwardedHost: "example.com",
expected: []string{"example.com:8333", "example.com"},
},
{
name: "portless X-Forwarded-Host, hostnames differ: X-Forwarded-Port, then bare",
hostHeader: "backend:8333",
forwardedHost: "example.com",
forwardedPort: "9000",
expected: []string{"example.com:9000", "example.com"},
},
{
name: "default X-Forwarded-Port collapses into the bare candidate",
hostHeader: "example.com:8333",
forwardedHost: "example.com",
forwardedPort: "443",
forwardedProto: "https",
expected: []string{"example.com:8333", "example.com"},
},
{
name: "portless Host with X-Forwarded-Port: forwarded port, then bare",
hostHeader: "example.com",
forwardedPort: "9000",
expected: []string{"example.com:9000", "example.com"},
},
{
name: "bracketed portless IPv6 X-Forwarded-Host matches the request host",
hostHeader: "[::1]:8333",
forwardedHost: "[::1]",
expected: []string{"[::1]:8333", "::1"},
},
{
name: "unbracketed portless IPv6 X-Forwarded-Host with X-Forwarded-Port",
hostHeader: "backend:8333",
forwardedHost: "::1",
forwardedPort: "8080",
expected: []string{"[::1]:8080", "::1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "http://"+tt.hostHeader+"/bucket/object", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Host = tt.hostHeader
if tt.forwardedHost != "" {
req.Header.Set("X-Forwarded-Host", tt.forwardedHost)
}
if tt.forwardedPort != "" {
req.Header.Set("X-Forwarded-Port", tt.forwardedPort)
}
if tt.forwardedProto != "" {
req.Header.Set("X-Forwarded-Proto", tt.forwardedProto)
}
result := extractHostHeaderCandidates(req, tt.externalHost)
if !slices.Equal(result, tt.expected) {
t.Errorf("extractHostHeaderCandidates() = %v, want %v", result, tt.expected)
}
})
}
}
func TestExtractSignedHeadersCase(t *testing.T) {
tests := []struct {
name string
+232
View File
@@ -0,0 +1,232 @@
package s3api
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
"github.com/seaweedfs/seaweedfs/weed/iam/oidc"
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestGroupsRolesPolicyEnforcement verifies that OIDC groups and roles claims reach
// the request-time policy evaluation of an STS session, so a single role's permission
// policy can scope bucket access with ForAnyValue:StringEquals on jwt:groups / jwt:roles.
// The full path is exercised: AssumeRoleWithWebIdentity embeds the claims in the session
// JWT, AuthenticateJWT restores them (as []interface{} after the JSON round-trip), and
// AuthorizeAction evaluates the conditions.
func TestGroupsRolesPolicyEnforcement(t *testing.T) {
ctx := context.Background()
iamManager := setupGroupsRolesIAMManager(t)
s3iam := NewS3IAMIntegration(iamManager, "localhost:8888")
// One role for everyone; each bucket statement is gated on a groups or roles claim
abacPolicy := &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{
{
Sid: "TeamABucketByGroup",
Effect: "Allow",
Action: []string{"s3:GetObject", "s3:PutObject"},
Resource: []string{
"arn:aws:s3:::team-a-bucket/*",
},
Condition: map[string]map[string]interface{}{
"ForAnyValue:StringEquals": {
"jwt:groups": "team-a",
},
},
},
{
Sid: "TeamBBucketByRole",
Effect: "Allow",
Action: []string{"s3:GetObject", "s3:PutObject"},
Resource: []string{
"arn:aws:s3:::team-b-bucket/*",
},
Condition: map[string]map[string]interface{}{
"ForAnyValue:StringEquals": {
"jwt:roles": "team-b-rw",
},
},
},
},
}
require.NoError(t, iamManager.CreatePolicy(ctx, "", "TeamABACPolicy", abacPolicy))
require.NoError(t, iamManager.CreateRole(ctx, "", "TeamABACRole", &integration.RoleDefinition{
RoleName: "TeamABACRole",
TrustPolicy: &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "test-oidc",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
AttachedPolicies: []string{"TeamABACPolicy"},
}))
tests := []struct {
name string
token string
allowTeamA bool
allowTeamB bool
}{
{
name: "group member gets team-a bucket only",
token: groupsRolesJWT(t, "team-a-user", []string{"team-a"}, nil),
allowTeamA: true,
allowTeamB: false,
},
{
name: "role holder gets team-b bucket only",
token: groupsRolesJWT(t, "team-b-user", nil, []string{"team-b-rw"}),
allowTeamA: false,
allowTeamB: true,
},
{
name: "member of both gets both buckets in one session",
token: groupsRolesJWT(t, "both-teams-user", []string{"team-a", "team-b"}, []string{"team-a-rw", "team-b-rw"}),
allowTeamA: true,
allowTeamB: true,
},
{
name: "user without matching claims is denied everywhere",
token: groupsRolesJWT(t, "no-team-user", []string{"other-team"}, []string{"other-role"}),
allowTeamA: false,
allowTeamB: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
response, err := iamManager.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
RoleArn: "arn:aws:iam::role/TeamABACRole",
WebIdentityToken: tt.token,
RoleSessionName: "abac-test-session",
})
require.NoError(t, err)
identity, errCode := authenticateSessionToken(t, s3iam, response.Credentials.SessionToken)
require.Equal(t, s3err.ErrNone, errCode)
assert.Equal(t, tt.allowTeamA, authorizeGet(ctx, s3iam, identity, "team-a-bucket"), "team-a-bucket access")
assert.Equal(t, tt.allowTeamB, authorizeGet(ctx, s3iam, identity, "team-b-bucket"), "team-b-bucket access")
})
}
}
// TestGroupsRolesSessionRequestContext pins the session round-trip itself: the groups
// and roles claims must come back from the session JWT as multi-valued context keys.
func TestGroupsRolesSessionRequestContext(t *testing.T) {
ctx := context.Background()
iamManager := setupGroupsRolesIAMManager(t)
require.NoError(t, iamManager.CreateRole(ctx, "", "ContextRole", &integration.RoleDefinition{
RoleName: "ContextRole",
TrustPolicy: &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "test-oidc",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
}))
response, err := iamManager.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
RoleArn: "arn:aws:iam::role/ContextRole",
WebIdentityToken: groupsRolesJWT(t, "both-teams-user", []string{"team-a", "team-b"}, []string{"team-a-rw", "team-b-rw"}),
RoleSessionName: "context-test-session",
})
require.NoError(t, err)
sessionInfo, err := iamManager.GetSTSService().ValidateSessionToken(ctx, response.Credentials.SessionToken)
require.NoError(t, err)
require.NotNil(t, sessionInfo.RequestContext)
// JWT serialization turns []string into []interface{}; assert that shape so a
// future change to the condition evaluator's type handling fails loudly here.
assert.Equal(t, []interface{}{"team-a", "team-b"}, sessionInfo.RequestContext["groups"])
assert.Equal(t, []interface{}{"team-a-rw", "team-b-rw"}, sessionInfo.RequestContext["roles"])
}
func setupGroupsRolesIAMManager(t *testing.T) *integration.IAMManager {
manager := integration.NewIAMManager()
config := &integration.IAMConfig{
STS: &sts.STSConfig{
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
MaxSessionLength: sts.FlexibleDuration{Duration: time.Hour * 12},
Issuer: "test-sts",
SigningKey: []byte("test-signing-key-32-characters-long"),
},
Policy: &policy.PolicyEngineConfig{
DefaultEffect: "Deny",
StoreType: "memory",
},
Roles: &integration.RoleStoreConfig{
StoreType: "memory",
},
}
require.NoError(t, manager.Initialize(config, func() string {
return "localhost:8888"
}))
provider := oidc.NewMockOIDCProvider("test-oidc")
require.NoError(t, provider.Initialize(&oidc.OIDCConfig{
Issuer: "https://test-issuer.com",
ClientID: "test-client-id",
}))
require.NoError(t, manager.RegisterIdentityProvider(provider))
return manager
}
// groupsRolesJWT builds a web identity token carrying groups and roles claims.
func groupsRolesJWT(t *testing.T, subject string, groups, roles []string) string {
claims := jwt.MapClaims{
"iss": "https://test-issuer.com",
"sub": subject,
"aud": "test-client-id",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
}
if groups != nil {
claims["groups"] = groups
}
if roles != nil {
claims["roles"] = roles
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("test-signing-key"))
require.NoError(t, err)
return token
}
func authenticateSessionToken(t *testing.T, s3iam *S3IAMIntegration, sessionToken string) (*IAMIdentity, s3err.ErrorCode) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Set("Authorization", "Bearer "+sessionToken)
return s3iam.AuthenticateJWT(context.Background(), req)
}
func authorizeGet(ctx context.Context, s3iam *S3IAMIntegration, identity *IAMIdentity, bucket string) bool {
req := httptest.NewRequest("GET", "/"+bucket+"/file.txt", http.NoBody)
req.Header.Set("Authorization", "Bearer "+identity.SessionToken)
return s3iam.AuthorizeAction(ctx, identity, s3_constants.ACTION_READ, bucket, "file.txt", req) == s3err.ErrNone
}
+190 -136
View File
@@ -109,7 +109,15 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
// Adjust marker if it ends with delimiter to skip all entries with that prefix
marker = adjustMarkerForDelimiter(marker, delimiter)
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
response, err := s3a.listFilerEntries(r.Context(), listObjectsRequest{
bucket: bucket,
prefix: originalPrefix,
marker: marker,
delimiter: delimiter,
maxKeys: maxKeys,
encodingTypeUrl: encodingTypeUrl,
fetchOwner: fetchOwner,
})
if err != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
@@ -173,7 +181,15 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
// Adjust marker if it ends with delimiter to skip all entries with that prefix
marker = adjustMarkerForDelimiter(marker, delimiter)
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
response, err := s3a.listFilerEntries(r.Context(), listObjectsRequest{
bucket: bucket,
prefix: originalPrefix,
marker: marker,
delimiter: delimiter,
maxKeys: uint16(maxKeys),
encodingTypeUrl: encodingTypeUrl,
fetchOwner: true,
})
if err != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
@@ -232,7 +248,20 @@ func sanitizeV1MarkerEcho(response *ListBucketResult, marker string, encodingTyp
}
}
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
type listObjectsRequest struct {
bucket string
prefix string
marker string
delimiter string
maxKeys uint16
encodingTypeUrl bool
fetchOwner bool
}
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsRequest) (response ListBucketResult, err error) {
bucket, originalPrefix, originalMarker := req.bucket, req.prefix, req.marker
maxKeys, delimiter := req.maxKeys, req.delimiter
encodingTypeUrl, fetchOwner := req.encodingTypeUrl, req.fetchOwner
// convert full path prefix into directory name and prefix for entry name
requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
bucketPrefix := s3a.bucketPrefix(bucket)
@@ -298,7 +327,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, bucket string, ori
for {
empty := true
nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, bucket, func(dir string, entry *filer_pb.Entry) {
nextMarker, doErr = s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: reqDir, prefix: prefix, marker: marker, delimiter: delimiter, bucket: bucket}, cursor, func(dir string, entry *filer_pb.Entry) {
empty = false
dirName, entryName, _ := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
if entry.IsDirectory {
@@ -557,7 +586,18 @@ func buildTruncatedNextMarker(requestDir, prefix, nextMarker string, lastEntryWa
return nextMarker
}
func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, bucket string, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
type listDirectoryRequest struct {
dir string
prefix string
marker string
delimiter string
bucket string
inclusiveStartFrom bool
}
func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.SeaweedFilerClient, req listDirectoryRequest, cursor *ListingCursor, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
dir, prefix, bucket := req.dir, req.prefix, req.bucket
marker, delimiter, inclusiveStartFrom := req.marker, req.delimiter, req.inclusiveStartFrom
// invariants
// prefix and marker should be under dir, marker may contain "/"
// maxKeys should be updated for each recursion
@@ -571,7 +611,7 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
if strings.Contains(marker, "/") {
subDir, subMarker := toParentAndDescendants(marker)
// println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, bucket, eachEntryFn)
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + subDir, marker: subMarker, delimiter: delimiter, bucket: bucket}, cursor, eachEntryFn)
if subErr != nil {
err = subErr
return
@@ -585,156 +625,170 @@ func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, d
}
// now marker is also a direct child of dir
request := &filer_pb.ListEntriesRequest{
Directory: dir,
Prefix: prefix,
Limit: uint32(cursor.maxKeys) + 2, // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
StartFromFileName: marker,
InclusiveStartFrom: inclusiveStartFrom,
}
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(ctx)
defer cancel()
stream, listErr := client.ListEntries(ctx, request)
if listErr != nil {
if errors.Is(listErr, filer_pb.ErrNotFound) {
return
}
err = fmt.Errorf("list entries %+v: %w", request, listErr)
return
}
// Entries that emit nothing (empty directories, the .uploads folder, the marker
// echo) consume the request window without consuming maxKeys, so one window may
// end before maxKeys is satisfied. Keep requesting from the last received entry
// until the quota is filled or a short window shows the directory is exhausted.
for {
resp, recvErr := stream.Recv()
if recvErr != nil {
if recvErr == io.EOF {
break
} else {
err = fmt.Errorf("iterating entries %+v: %v", request, recvErr)
request := &filer_pb.ListEntriesRequest{
Directory: dir,
Prefix: prefix,
Limit: uint32(cursor.maxKeys) + 2, // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
StartFromFileName: marker,
InclusiveStartFrom: inclusiveStartFrom,
}
stream, listErr := client.ListEntries(ctx, request)
if listErr != nil {
if errors.Is(listErr, filer_pb.ErrNotFound) {
return
}
}
entry := resp.Entry
if entry == nil {
continue
}
// listFilerEntries always calls doListFilerEntries with inclusiveStartFrom=false
// (S3 marker semantics are exclusive), but keep the guard explicit to preserve
// behavior if inclusive callers are introduced in the future.
if !inclusiveStartFrom && marker != "" && entry.Name == marker {
continue
err = fmt.Errorf("list entries %+v: %w", request, listErr)
return
}
if cursor.maxKeys <= 0 {
cursor.isTruncated = true
break
}
// Set nextMarker only when we have quota to process this entry
nextMarker = entry.Name
// Track whether this entry is the exact directory targeted by a trailing-slash prefix
// (e.g., prefix "foo" from original prefix "foo/"). After recursing into this directory,
// we must stop processing siblings to avoid matching unrelated entries like "foo1000".
matchedPrefixDir := cursor.prefixEndsOnDelimiter && entry.Name == prefix && entry.IsDirectory
if cursor.prefixEndsOnDelimiter {
if entry.Name == prefix && entry.IsDirectory {
if delimiter != "/" {
cursor.prefixEndsOnDelimiter = false
}
} else {
continue
}
}
if entry.IsDirectory {
// glog.V(4).Infof("List Dir Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
continue
}
// Process .versions directories immediately to create logical versioned object entries
// These directories are never traversed (we continue here), so each is only encountered once
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
// Extract object name from .versions directory name
baseObjectName := strings.TrimSuffix(entry.Name, s3_constants.VersionsFolder)
// Construct full object path relative to bucket
bucketFullPath := s3a.bucketDir(bucket)
bucketRelativePath := strings.TrimPrefix(dir, bucketFullPath)
bucketRelativePath = strings.TrimPrefix(bucketRelativePath, "/")
var fullObjectPath string
if bucketRelativePath == "" {
fullObjectPath = baseObjectName
var entriesReceived uint32
var lastEntryName string
for {
resp, recvErr := stream.Recv()
if recvErr != nil {
if recvErr == io.EOF {
break
} else {
fullObjectPath = bucketRelativePath + "/" + baseObjectName
}
// Use metadata from the already-fetched .versions directory entry
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry); err == nil {
eachEntryFn(dir, latestVersionEntry)
} else if !errors.Is(err, ErrDeleteMarker) {
// Log unexpected errors (delete markers are expected)
glog.V(2).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
err = fmt.Errorf("iterating entries %+v: %v", request, recvErr)
return
}
}
entry := resp.Entry
if entry == nil {
continue
}
entriesReceived++
lastEntryName = entry.Name
// listFilerEntries always calls doListFilerEntries with inclusiveStartFrom=false
// (S3 marker semantics are exclusive), but keep the guard explicit to preserve
// behavior if inclusive callers are introduced in the future.
if !inclusiveStartFrom && marker != "" && entry.Name == marker {
continue
}
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
// whether it exists, so a real but empty directory must be reported for
// that probe.
explicitDirProbe := cursor.prefixEndsOnDelimiter
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
if cursor.maxKeys <= 0 {
cursor.isTruncated = true
break
}
// Set nextMarker only when we have quota to process this entry
nextMarker = entry.Name
// Track whether this entry is the exact directory targeted by a trailing-slash prefix
// (e.g., prefix "foo" from original prefix "foo/"). After recursing into this directory,
// we must stop processing siblings to avoid matching unrelated entries like "foo1000".
matchedPrefixDir := cursor.prefixEndsOnDelimiter && entry.Name == prefix && entry.IsDirectory
if cursor.prefixEndsOnDelimiter {
if entry.Name == prefix && entry.IsDirectory {
if delimiter != "/" {
cursor.prefixEndsOnDelimiter = false
}
} else {
continue
}
isKeyObject := entry.IsDirectoryKeyObject()
if isKeyObject {
// Directory key objects (created via PutObject with trailing "/")
// must appear as regular keys in recursive listing mode.
}
if entry.IsDirectory {
// glog.V(4).Infof("List Dir Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
continue
}
// Process .versions directories immediately to create logical versioned object entries
// These directories are never traversed (we continue here), so each is only encountered once
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
// Extract object name from .versions directory name
baseObjectName := strings.TrimSuffix(entry.Name, s3_constants.VersionsFolder)
// Construct full object path relative to bucket
bucketFullPath := s3a.bucketDir(bucket)
bucketRelativePath := strings.TrimPrefix(dir, bucketFullPath)
bucketRelativePath = strings.TrimPrefix(bucketRelativePath, "/")
var fullObjectPath string
if bucketRelativePath == "" {
fullObjectPath = baseObjectName
} else {
fullObjectPath = bucketRelativePath + "/" + baseObjectName
}
// Use metadata from the already-fetched .versions directory entry
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry); err == nil {
eachEntryFn(dir, latestVersionEntry)
} else if !errors.Is(err, ErrDeleteMarker) {
// Log unexpected errors (delete markers are expected)
glog.V(2).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
}
continue
}
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
// whether it exists, so a real but empty directory must be reported for
// that probe.
explicitDirProbe := cursor.prefixEndsOnDelimiter
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
}
isKeyObject := entry.IsDirectoryKeyObject()
if isKeyObject {
// Directory key objects (created via PutObject with trailing "/")
// must appear as regular keys in recursive listing mode.
eachEntryFn(dir, entry)
}
// Recurse into subdirectory to list any children, noting whether the
// subtree produced any entries.
childEmitted := false
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + entry.Name, delimiter: delimiter, bucket: bucket}, cursor, func(d string, e *filer_pb.Entry) {
childEmitted = true
eachEntryFn(d, e)
})
if subErr != nil {
err = fmt.Errorf("doListFilerEntries2: %w", subErr)
return
}
// A real but empty directory (created out of band via mount, mkdir or
// the filer API, so it carries no MIME) is otherwise invisible to S3
// clients that detect directories by listing it under its own "<dir>/"
// prefix. Surface it as a directory marker for that explicit probe,
// identical to a directory created via PutObject with a trailing "/", so
// tools like hadoop-aws can find it. Plain listings are left untouched, so
// empty directories left behind by deleted objects are not shown as keys.
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && entry.Attributes != nil {
entry.Attributes.Mime = s3_constants.FolderMimeType
eachEntryFn(dir, entry)
}
// println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
nextMarker = entry.Name + "/" + subNextMarker
if cursor.isTruncated {
return
}
if matchedPrefixDir {
return
}
// println("doListFilerEntries2 nextMarker", nextMarker)
} else {
eachEntryFn(dir, entry)
}
// Recurse into subdirectory to list any children, noting whether the
// subtree produced any entries.
childEmitted := false
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, bucket, func(d string, e *filer_pb.Entry) {
childEmitted = true
eachEntryFn(d, e)
})
if subErr != nil {
err = fmt.Errorf("doListFilerEntries2: %w", subErr)
return
}
// A real but empty directory (created out of band via mount, mkdir or
// the filer API, so it carries no MIME) is otherwise invisible to S3
// clients that detect directories by listing it under its own "<dir>/"
// prefix. Surface it as a directory marker for that explicit probe,
// identical to a directory created via PutObject with a trailing "/", so
// tools like hadoop-aws can find it. Plain listings are left untouched, so
// empty directories left behind by deleted objects are not shown as keys.
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && entry.Attributes != nil {
entry.Attributes.Mime = s3_constants.FolderMimeType
eachEntryFn(dir, entry)
}
// println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
nextMarker = entry.Name + "/" + subNextMarker
if cursor.isTruncated {
return
}
if matchedPrefixDir {
return
}
// println("doListFilerEntries2 nextMarker", nextMarker)
} else {
eachEntryFn(dir, entry)
// glog.V(4).Infof("List File Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
}
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
}
} else {
eachEntryFn(dir, entry)
// glog.V(4).Infof("List File Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
}
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
}
}
// Versioned directories are processed above (lines 524-546)
return
if cursor.isTruncated || entriesReceived < request.Limit {
return
}
marker = lastEntryName
inclusiveStartFrom = false
}
}
func getListObjectsV2Args(values url.Values) (prefix, startAfter, delimiter string, token OptionalString, encodingTypeUrl bool, fetchOwner bool, maxkeys uint16, allowUnordered bool, errCode s3err.ErrorCode) {
@@ -1,6 +1,7 @@
package s3api
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -38,14 +39,14 @@ func TestDirectoryListedAsCommonPrefix(t *testing.T) {
var seenFiles []string
_, err := s3a.doListFilerEntries(
context.Background(),
client,
"/buckets/xoa-bucket/xo-vm-backups/data",
"", // prefix
listDirectoryRequest{
dir: "/buckets/xoa-bucket/xo-vm-backups/data",
delimiter: "/", // should yield directory for CommonPrefix processing
bucket: "xoa-bucket",
},
cursor,
"", // marker
"/", // delimiter="/" - should yield directory for CommonPrefix processing
false,
"xoa-bucket",
func(dir string, entry *filer_pb.Entry) {
if entry.IsDirectory {
seenDirs = append(seenDirs, entry.Name)
@@ -88,7 +89,7 @@ func TestEmptyDirectorySurfacedAsMarker(t *testing.T) {
// Mirrors the getFileStatus probe: prefix "logs/" with delimiter "/".
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var seen []*filer_pb.Entry
_, err := s3a.doListFilerEntries(client, "/buckets/test", "logs", cursor, "", "/", false, "test",
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "logs", delimiter: "/", bucket: "test"}, cursor,
func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry)
})
@@ -129,7 +130,7 @@ func TestNonEmptyDirectoryGetsNoPhantomMarker(t *testing.T) {
// Recursive listing under the "data/" prefix.
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var seen []string
_, err := s3a.doListFilerEntries(client, "/buckets/test", "data", cursor, "", "", false, "test",
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "data", bucket: "test"}, cursor,
func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
@@ -173,7 +174,7 @@ func TestEmptyDirectoryHiddenInFlatListing(t *testing.T) {
// Plain flat listing: no prefix, no delimiter.
cursor := &ListingCursor{maxKeys: 1000}
var seen []string
_, err := s3a.doListFilerEntries(client, "/buckets/test", "", cursor, "", "", false, "test",
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", bucket: "test"}, cursor,
func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
+128 -10
View File
@@ -44,8 +44,7 @@ type testFilerClient struct {
func (c *testFilerClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
entries := c.entriesByDir[in.Directory]
// Simplified mock: implements basic prefix filtering but ignores Limit, StartFromFileName, and InclusiveStartFrom
// to keep test logic focused. Prefix "/" is treated as no filter for bucket root compatibility.
// Simplified mock: prefix "/" is treated as no filter for bucket root compatibility.
if in.Prefix != "" && in.Prefix != "/" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
@@ -56,7 +55,16 @@ func (c *testFilerClient) ListEntries(ctx context.Context, in *filer_pb.ListEntr
entries = filtered
}
// Respect Limit
if in.StartFromFileName != "" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
if e.Name > in.StartFromFileName || (in.InclusiveStartFrom && e.Name == in.StartFromFileName) {
filtered = append(filtered, e)
}
}
entries = filtered
}
if in.Limit > 0 && int(in.Limit) < len(entries) {
entries = entries[:in.Limit]
}
@@ -300,7 +308,7 @@ func TestDoListFilerEntries_BucketRootPrefixSlashDelimiterSlash_ListsDirectories
cursor := &ListingCursor{maxKeys: 1000}
seen := make([]string, 0)
_, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "/", cursor, "", "/", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", prefix: "/", delimiter: "/", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
if entry.IsDirectory {
seen = append(seen, entry.Name)
}
@@ -322,7 +330,7 @@ func TestDoListFilerEntries_ExclusiveStartSkipsMarkerEcho(t *testing.T) {
cursor := &ListingCursor{maxKeys: 1000}
var seen []string
nextMarker, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "", cursor, "test.txt", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
nextMarker, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", marker: "test.txt", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
@@ -346,7 +354,7 @@ func TestDoListFilerEntries_ExclusiveStartSkipsMarkerEchoWithSubsequentEntries(t
cursor := &ListingCursor{maxKeys: 1000}
var seen []string
nextMarker, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "", cursor, "test.txt", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
nextMarker, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", marker: "test.txt", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
@@ -355,6 +363,116 @@ func TestDoListFilerEntries_ExclusiveStartSkipsMarkerEchoWithSubsequentEntries(t
assert.Equal(t, "zebra.txt", nextMarker)
}
func TestDoListFilerEntries_EmptyDirectoriesDoNotHideLaterEntries(t *testing.T) {
// With maxKeys=1 the listing window is 3 entries. The first window holds only
// empty directories, so the real object further down must still be found.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "00-empty-1", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-2", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-3", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-4", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-5", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "zz-real", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/zz-real": {
{Name: "file.log", Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1}
var seen []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/zz-real/file.log"}, seen)
assert.False(t, cursor.isTruncated)
}
func TestDoListFilerEntries_EmptyDirectoriesInSubdirectoryDoNotHideSiblings(t *testing.T) {
// The recursion into "logs" gets its own listing window; empty subdirectories
// filling that window must not skip the object behind them.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "logs", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/logs": {
{Name: "00-empty-1", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-2", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-3", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-4", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-5", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "zz.log", Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1}
var seen []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/logs/zz.log"}, seen)
assert.False(t, cursor.isTruncated)
}
func TestDoListFilerEntries_TruncationAcrossEmptyDirectories(t *testing.T) {
// Two real objects separated by empty directories: the first fills the quota
// and the listing must report truncation with a resumable marker.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "00-empty-1", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-2", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-3", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "mm-real", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "pp-empty", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "zz-real", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/mm-real": {
{Name: "file.log", Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/zz-real": {
{Name: "file.log", Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1}
var seen []string
nextMarker, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/mm-real/file.log"}, seen)
assert.True(t, cursor.isTruncated)
cursor = &ListingCursor{maxKeys: 1}
seen = nil
_, err = s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", marker: nextMarker, bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/zz-real/file.log"}, seen)
assert.False(t, cursor.isTruncated)
}
func TestAllowUnorderedWithDelimiterValidation(t *testing.T) {
t.Run("should return error when allow-unordered=true and delimiter are both present", func(t *testing.T) {
// Create a request with both allow-unordered=true and delimiter
@@ -765,7 +883,7 @@ func TestListObjectsV2_Regression(t *testing.T) {
// Call doListFilerEntries directly to unit test listing logic in isolation,
// simulating parameters passed from listFilerEntries for prefix "reports/".
_, err := s3a.doListFilerEntries(client, "/buckets/reports", "reports", cursor, "", "", false, "reports", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/reports", prefix: "reports", bucket: "reports"}, cursor, func(dir string, entry *filer_pb.Entry) {
if !entry.IsDirectory {
results = append(results, entry.Name)
}
@@ -803,7 +921,7 @@ func TestListObjectsV2_Regression_Sorting(t *testing.T) {
// Without the fix, Limit=1 would cause the lister to stop after "reports-archive",
// missing the intended "reports" directory.
_, err := s3a.doListFilerEntries(client, "/buckets/reports", "reports", cursor, "", "", false, "reports", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/reports", prefix: "reports", bucket: "reports"}, cursor, func(dir string, entry *filer_pb.Entry) {
if !entry.IsDirectory {
results = append(results, entry.Name)
}
@@ -846,7 +964,7 @@ func TestListObjectsV2_PrefixEndingWithSlash_DoesNotMatchSiblings(t *testing.T)
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var results []string
_, err := s3a.doListFilerEntries(client, "/buckets/bucket/path/to/list", "1", cursor, "", "", false, "bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/bucket/path/to/list", prefix: "1", bucket: "bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
if !entry.IsDirectory {
results = append(results, entry.Name)
}
@@ -878,7 +996,7 @@ func TestListObjectsV2_PrefixEndingWithSlash_WithDelimiter(t *testing.T) {
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var results []string
_, err := s3a.doListFilerEntries(client, "/buckets/bucket/path/to/list", "1", cursor, "", "/", false, "bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/bucket/path/to/list", prefix: "1", delimiter: "/", bucket: "bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
results = append(results, entry.Name)
})
@@ -136,7 +136,7 @@ func TestListObjectsWithVersionedObjects(t *testing.T) {
commonPrefixes := []PrefixEntry{}
bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, tt.bucket)
_, err := s3a.doListFilerEntries(filerClient, bucketPrefix[:len(bucketPrefix)-1], tt.prefix, cursor, "", tt.delimiter, false, tt.bucket, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: bucketPrefix[:len(bucketPrefix)-1], prefix: tt.prefix, delimiter: tt.delimiter, bucket: tt.bucket}, cursor, func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -237,7 +237,7 @@ func TestVersionedObjectsNoDuplication(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(1000)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -295,7 +295,7 @@ func TestVersionedObjectsWithDeleteMarker(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(1000)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -344,7 +344,7 @@ func TestVersionedObjectsMaxKeys(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(3)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -406,7 +406,7 @@ func TestVersionsDirectoryNotTraversed(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(1000)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(customClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(context.Background(), customClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -111,6 +111,9 @@ func wormDeleteCondition(worm, bypass bool) *filer_pb.WriteCondition {
// rather than a dangling pointer) and deletes the version file. lock_key is the
// object (serializing the pointer recompute); for object-lock buckets the
// condition gates the delete on the version's WORM guards evaluated on the owner.
// Deleting the last version also removes the emptied .versions/ directory —
// leaving it behind would keep re-triggering the read path's self-heal rescans
// on every GET of the key (Veeam probes its deleted lock objects forever).
func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, bucket, object, versionId string, worm, bypass bool) s3err.ErrorCode {
if !isValidVersionID(versionId) {
return s3err.ErrInvalidRequest
@@ -125,7 +128,7 @@ func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, buck
Condition: cond,
Mutations: []*filer_pb.ObjectMutation{
s3a.latestPointerRecompute(bucket, object, isNewFormatVersionId(versionId), versionFileName, false),
{Type: filer_pb.ObjectMutation_DELETE, Directory: versionsPath, Name: versionFileName, IsDeleteData: true},
{Type: filer_pb.ObjectMutation_DELETE, Directory: versionsPath, Name: versionFileName, IsDeleteData: true, RemoveEmptyParent: true},
},
}
resp, err := s3a.objectTxnOnFiler(owner, req)
+16 -7
View File
@@ -1957,13 +1957,22 @@ func (s3a *S3ApiServer) healStaleLatestVersionPointer(bucket, normalizedObject s
}
if latestEntry == nil {
// Best-effort clear the stale latest-version pointer so subsequent
// reads short-circuit to ErrNotFound directly instead of replaying
// getLatestObjectVersion's read-retry loop and re-entering self-heal
// on every request. Orphan entries (files in .versions/ that lack
// the version-id extended attribute) remain in place; from the S3
// API perspective the object is correctly absent.
s3a.clearStaleLatestVersionPointer(bucket, normalizedObject, bucketDir, versionsObjectPath, versionsEntry, "healStaleLatestVersionPointer")
// No version remains: remove the residue directory outright so future
// reads take the clean ErrNotFound path instead of re-entering this
// self-heal (and its rescan + surfaced warning) on every request. The
// non-recursive rm makes this safe against a concurrent PUT — a new
// child fails the rm, and a directory removed just before that PUT's
// version file lands is recreated by the create's parent handling.
if rmErr := s3a.rm(bucketDir, versionsObjectPath, true, false); rmErr == nil {
versioningHealInfof("healed", "bucket=%s key=%s mode=empty_dir_removed", bucket, normalizedObject)
} else {
// Orphan entries (files in .versions/ that lack the version-id
// extended attribute) block the teardown and remain in place for an
// operator; fall back to clearing the stale pointer so reads at
// least short-circuit. From the S3 API perspective the object is
// correctly absent either way.
s3a.clearStaleLatestVersionPointer(bucket, normalizedObject, bucketDir, versionsObjectPath, versionsEntry, "healStaleLatestVersionPointer")
}
// Wrap filer_pb.ErrNotFound so callers can distinguish genuine
// object-absence (nothing left to promote) from scan failures
// (I/O errors during list) via errors.Is.
+15 -3
View File
@@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
@@ -391,10 +392,21 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
case filer_pb.ObjectMutation_DELETE:
fullpath := util.NewFullPath(m.Directory, m.Name)
err := fs.filer.DeleteEntryMetaAndData(ctx, fullpath, m.IsRecursive, false, m.IsDeleteData, fromOtherCluster, signatures, 0)
if err == filer_pb.ErrNotFound {
return nil
if err != nil && err != filer_pb.ErrNotFound {
return err
}
return err
if m.RemoveEmptyParent {
// A parent that exists only to hold this child (e.g. a .versions/
// directory losing its last version) is torn down in the same locked
// transaction. Best-effort: a non-empty or already-removed parent is
// the expected no-op, and a failed teardown must not fail the
// already-applied delete.
parentErr := fs.filer.DeleteEntryMetaAndData(ctx, util.FullPath(m.Directory), false, false, false, fromOtherCluster, signatures, 0)
if parentErr != nil && parentErr != filer_pb.ErrNotFound && !strings.Contains(parentErr.Error(), filer.MsgFailDelNonEmptyFolder) {
glog.V(1).InfofCtx(ctx, "remove empty parent %s: %v", m.Directory, parentErr)
}
}
return nil
case filer_pb.ObjectMutation_PATCH_EXTENDED:
fullpath := util.NewFullPath(m.Directory, m.Name)
@@ -619,6 +619,86 @@ func TestObjectTransactionVersionDeleteWithWorm(t *testing.T) {
}
}
// Deleting the LAST version tears down the emptied .versions/ directory in the
// same transaction (remove_empty_parent on the DELETE), so a fully-drained key
// leaves no residue to re-trigger the read path's self-heal on every GET. A
// remaining child keeps the directory; a replay after the child is already
// gone still tidies it.
func TestObjectTransactionDeleteRemovesEmptyParent(t *testing.T) {
now := time.Unix(1700000000, 0)
seed := func(withSibling bool) map[string]*filer.Entry {
entries := map[string]*filer.Entry{
"/buckets/b/obj/.versions": {
Attr: filer.Attr{Inode: 2, Mtime: now, Crtime: now, Mode: 0755 | (1 << 31)},
Extended: map[string][]byte{"latestName": []byte("v_a"), "latestVid": []byte("v1")},
},
"/buckets/b/obj/.versions/v_a": {
Attr: filer.Attr{Inode: 10, Mtime: now, Crtime: now, Mode: 0644},
Extended: map[string][]byte{"vid": []byte("v1")},
},
}
if withSibling {
entries["/buckets/b/obj/.versions/orphan"] = &filer.Entry{
Attr: filer.Attr{Inode: 11, Mtime: now, Crtime: now, Mode: 0644},
}
}
return entries
}
// Mirrors routedDeleteSpecificVersion: repoint excluding the dying version,
// then delete it and tidy the parent.
mkReq := func() *filer_pb.ObjectTransactionRequest {
return &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/b/obj",
Mutations: []*filer_pb.ObjectMutation{
{Type: filer_pb.ObjectMutation_RECOMPUTE_LATEST, Directory: "/buckets/b/obj", Name: ".versions",
Recompute: &filer_pb.Recompute{ScanDir: "/buckets/b/obj/.versions", Descending: true, ExcludeName: "v_a",
NameToKey: "latestName", CopyExtended: map[string]string{"latestVid": "vid"}}},
{Type: filer_pb.ObjectMutation_DELETE, Directory: "/buckets/b/obj/.versions", Name: "v_a", RemoveEmptyParent: true},
},
}
}
// Last version: the emptied directory goes with it.
fs, store := newTxnTestServer(seed(false))
resp, err := fs.ObjectTransaction(context.Background(), mkReq())
if err != nil || resp.Error != "" {
t.Fatalf("txn failed: err=%v resp=%q", err, resp.Error)
}
if _, ok := store.entries["/buckets/b/obj/.versions/v_a"]; ok {
t.Errorf("version should be deleted")
}
if _, ok := store.entries["/buckets/b/obj/.versions"]; ok {
t.Errorf(".versions directory emptied by the delete should be removed")
}
// A remaining child keeps the directory (non-recursive teardown declines).
fs, store = newTxnTestServer(seed(true))
resp, err = fs.ObjectTransaction(context.Background(), mkReq())
if err != nil || resp.Error != "" {
t.Fatalf("txn failed: err=%v resp=%q", err, resp.Error)
}
if _, ok := store.entries["/buckets/b/obj/.versions/orphan"]; !ok {
t.Errorf("sibling must survive the teardown attempt")
}
if _, ok := store.entries["/buckets/b/obj/.versions"]; !ok {
t.Errorf(".versions directory with a remaining child must not be removed")
}
// Replay: the child is already gone, the empty parent is still tidied.
fs, store = newTxnTestServer(map[string]*filer.Entry{
"/buckets/b/obj/.versions": {
Attr: filer.Attr{Inode: 2, Mtime: now, Crtime: now, Mode: 0755 | (1 << 31)},
},
})
resp, err = fs.ObjectTransaction(context.Background(), mkReq())
if err != nil || resp.Error != "" {
t.Fatalf("replay txn failed: err=%v resp=%q", err, resp.Error)
}
if _, ok := store.entries["/buckets/b/obj/.versions"]; ok {
t.Errorf("replayed delete should still remove the empty directory")
}
}
// PATCH_EXTENDED with touch_mtime bumps the entry's Mtime (a metadata-replace
// copy) while merging Extended.
func TestObjectTransactionPatchTouchMtime(t *testing.T) {
+7 -6
View File
@@ -85,10 +85,10 @@ func (vs *VolumeServer) VolumeTierMoveDatFromRemote(req *volume_server_pb.Volume
}
// Trim the remote file reference and persist the .vif (util.WriteFile fsyncs it)
// BEFORE deleting the remote object. After this point hasRemoteFile is false, so a
// crash before DeleteFile merely leaks the remote object while the volume reloads
// its local .dat. The volume must NEVER be left with a .vif referencing the remote
// object while that object is deleted.
// BEFORE deleting the remote object. After this the .vif no longer references the
// remote object, so a crash before DeleteFile merely leaks the remote object while
// the volume reloads its local .dat as non-remote. The volume must NEVER be left
// with a .vif referencing the remote object while that object is deleted.
v.GetVolumeInfo().Files = v.GetVolumeInfo().Files[1:]
if err := v.SaveVolumeInfo(); err != nil {
return fmt.Errorf("volume %d failed to save remote file info: %v", v.Id, err)
@@ -127,8 +127,9 @@ func swapToLocalDatBackend(v *storage.Volume, datFileName string) error {
return err
}
// Swap under the volume's data lock so concurrent reads never see a closed
// or half-swapped backend.
v.SwapDataBackend(backend.NewDiskFile(dataFile))
// or half-swapped backend, clearing hasRemoteFile in the same step since the
// volume now serves from the local .dat.
v.SwapDataBackend(backend.NewDiskFile(dataFile), false)
return nil
}
+11 -3
View File
@@ -121,8 +121,8 @@ func (f *tierTestBackendFile) ReadAt(p []byte, off int64) (int, error) {
func (f *tierTestBackendFile) WriteAt(p []byte, off int64) (int, error) { panic("not implemented") }
func (f *tierTestBackendFile) Truncate(off int64) error { panic("not implemented") }
func (f *tierTestBackendFile) Close() error { return nil }
func (f *tierTestBackendFile) Name() string { return f.key }
func (f *tierTestBackendFile) Sync() error { return nil }
func (f *tierTestBackendFile) Name() string { return f.key }
func (f *tierTestBackendFile) Sync() error { return nil }
func (f *tierTestBackendFile) GetStat() (int64, time.Time, error) {
files := f.tierInfo.GetFiles()
if len(files) == 0 {
@@ -136,7 +136,9 @@ type fakeTierStream struct {
grpc.ServerStream
}
func (s *fakeTierStream) Send(*volume_server_pb.VolumeTierMoveDatFromRemoteResponse) error { return nil }
func (s *fakeTierStream) Send(*volume_server_pb.VolumeTierMoveDatFromRemoteResponse) error {
return nil
}
func newTierTestStore(t *testing.T, dir string) *storage.Store {
t.Helper()
@@ -276,6 +278,12 @@ func TestTierMoveDatFromRemote_KeepRemote_LeavesReplicaLocal(t *testing.T) {
if _, ok := v.DataBackend.(*backend.DiskFile); !ok {
t.Fatalf("after keep-remote download the data backend must be local DiskFile, got %T", v.DataBackend)
}
// The live volume must also report non-remote immediately, without waiting for
// a remount: a delete arriving before the remount would otherwise skip the .dat
// tombstone, and the phantom-.dat guard would stay disabled.
if v.HasRemoteFile() {
t.Fatal("after download the live volume must no longer be remote-backed")
}
// Remount and confirm the volume is no longer remote-backed and reads come
// from the local .dat (matching the bytes uploaded before tiering).
+4 -3
View File
@@ -64,14 +64,15 @@ func (c *commandS3BucketList) Do(args []string, commandEnv *CommandEnv, writer i
return nil
}
collection := getCollectionName(commandEnv, entry.Name)
var collectionSize, fileCount float64
var collectionSize, logicalSize, fileCount float64
if collectionInfo, found := collectionInfos[collection]; found {
collectionSize = collectionInfo.Size
logicalSize = collectionInfo.LogicalSize()
fileCount = collectionInfo.FileCount - collectionInfo.DeleteCount
}
fmt.Fprintf(writer, " %s\tsize:%.0f\tchunk:%.0f", entry.Name, collectionSize, fileCount)
fmt.Fprintf(writer, " %s\tsize:%.0f\tlogical:%.0f\tchunk:%.0f", entry.Name, collectionSize, logicalSize, fileCount)
if entry.Quota > 0 {
fmt.Fprintf(writer, "\tquota:%d\tusage:%.2f%%", entry.Quota, float64(collectionSize)*100/float64(entry.Quota))
fmt.Fprintf(writer, "\tquota:%d\tusage:%.2f%%", entry.Quota, logicalSize*100/float64(entry.Quota))
}
// Show bucket owner (use %q to escape special characters)
if entry.Extended != nil {
+47 -6
View File
@@ -2,6 +2,7 @@ package shell
import (
"context"
"errors"
"flag"
"fmt"
"io"
@@ -38,6 +39,8 @@ func (c *commandS3VersionsAudit) Help() string {
Veeam/etc. as "Storage not found" on the next GET
- orphan (directory has files lacking the version-id extended attr,
which the post-delete cleanup path will refuse to rm)
- empty (no pointer and no children — residue of a fully-drained key;
every GET of the key replays the read-side self-heal rescan)
Example:
# Audit a whole bucket
@@ -52,9 +55,10 @@ func (c *commandS3VersionsAudit) Help() string {
s3.versions.audit -prefix /buckets/mybucket -heal
This command is read-only by default. With -heal, it clears the stale
latest-version pointer on stranded directories; the blob is already
gone, so reads then return NoSuchKey via the clean-miss path instead
of replaying the 10-retry self-heal loop on every request.
latest-version pointer on stranded directories and removes empty ones;
the blob is already gone, so reads then return NoSuchKey via the
clean-miss path instead of replaying the 10-retry self-heal loop on
every request.
`
}
@@ -81,6 +85,7 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
clean uint64
stranded uint64
orphanOnly uint64
empty uint64
healed uint64
healFailed uint64
)
@@ -117,6 +122,7 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
versionsPath := string(parentPath) + "/" + entry.Name
pointerSeen := false
hasOrphan := false
hasChild := false
const auditPageSize = 1024
var startName string
for {
@@ -128,6 +134,7 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
}
pageEntries++
lastEntryName = child.Name
hasChild = true
hasVersionId := false
if child.Extended != nil {
if _, ok := child.Extended[s3_constants.ExtVersionIdKey]; ok {
@@ -154,12 +161,26 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
switch {
case pointerFile == "":
// No pointer set. Orphan-only and clean are now mutually
// No pointer set. Empty, orphan-only and clean are mutually
// exclusive so the final report's category counts sum to
// versionsDirs.
if hasOrphan {
switch {
case !hasChild:
atomic.AddUint64(&empty, 1)
if *verbose {
fmt.Fprintf(writer, "empty: %s\n", versionsPath)
}
if *doHeal {
if err := removeEmptyVersionsDir(ctx, client, parentPath, entry); err != nil {
atomic.AddUint64(&healFailed, 1)
fmt.Fprintf(writer, "heal failed: %s: %v\n", versionsPath, err)
} else {
atomic.AddUint64(&healed, 1)
}
}
case hasOrphan:
atomic.AddUint64(&orphanOnly, 1)
} else {
default:
atomic.AddUint64(&clean, 1)
}
case pointerSeen:
@@ -190,6 +211,7 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
fmt.Fprintf(writer, " clean : %d\n", clean)
fmt.Fprintf(writer, " stranded : %d\n", stranded)
fmt.Fprintf(writer, " orphan-only : %d\n", orphanOnly)
fmt.Fprintf(writer, " empty : %d\n", empty)
if *doHeal {
fmt.Fprintf(writer, " healed : %d\n", healed)
fmt.Fprintf(writer, " heal failed : %d\n", healFailed)
@@ -222,6 +244,25 @@ func healStrandedPointer(ctx context.Context, client filer_pb.SeaweedFilerClient
return err
}
// removeEmptyVersionsDir deletes a .versions/ directory that holds no
// children: residue of a fully-drained key. Non-recursive on purpose so a
// concurrent write landing a new version fails the delete instead of being
// lost with it.
func removeEmptyVersionsDir(ctx context.Context, client filer_pb.SeaweedFilerClient, parentPath util.FullPath, entry *filer_pb.Entry) error {
resp, err := client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{
Directory: string(parentPath),
Name: entry.Name,
IsDeleteData: true,
})
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
// filerClientWrapper adapts a raw SeaweedFilerClient to the
// filer_pb.FilerClient interface that List / TraverseBfs expect.
type filerClientWrapper struct {
+41 -24
View File
@@ -71,11 +71,12 @@ func (c *commandVolumeBalance) Help() string {
sizes are handled correctly. Set it to 0 (or >=100) to disable. Servers running an older build that does
not report disk bytes are not gated, and balancing falls back to slot-only behavior for them.
The -byDiskUsage flag ranks servers by the actual data they hold (sum of volume sizes) instead of the
default slot-density metric. The default metric normalizes by maxVolumeCount, so a server whose
maxVolumeCount is configured too high for its disk looks nearly empty even when its disk is physically
full, and balancing can drain less-full servers onto it. Use -byDiskUsage to balance actual data
distribution instead. It assumes comparable disk sizes across servers of the same disk type.
The -byDiskUsage flag ranks servers by their reported physical disk used percentage instead of the
default slot-density metric. If any server does not report physical disk bytes (older build), ranking
falls back to the sum of volume sizes for all servers, since the two scales are not comparable. The
default metric normalizes by maxVolumeCount, so a server whose maxVolumeCount is configured too high
for its disk looks nearly empty even when its disk is physically full, and balancing can drain
less-full servers onto it. Use -byDiskUsage to balance actual disk usage instead.
Algorithm:
@@ -129,7 +130,7 @@ func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer
// TODO: remove this alias
applyBalancingAlias := balanceCommand.Bool("force", false, "apply the balancing plan (alias for -apply)")
volumesPerExec := balanceCommand.Int("volumesPerExec", 0, "how many volumes to move in one run (default is 0 for unlimited)")
byDiskUsage := balanceCommand.Bool("byDiskUsage", false, "rank servers by actual data held (sum of volume sizes) instead of slot density; use when maxVolumeCount is set too high for the disk. Assumes comparable disk sizes per disk type.")
byDiskUsage := balanceCommand.Bool("byDiskUsage", false, "rank servers by reported physical disk used percent instead of slot density; falls back to sum of volume sizes for all servers when any server does not report disk bytes. Use when maxVolumeCount is set too high for the disk.")
maxDiskUsagePercent := balanceCommand.Int("maxDiskUsagePercent", balancer.DefaultMaxDiskUsagePercent, "skip a move target whose physical disk used%% is at/above this; judged per server against its own disk, so heterogeneous disk sizes are fine. 0 or >=100 disables. Auto-skipped for servers that do not report disk bytes.")
balanceCommand.Func("volumeBy", "only apply the balancing for ALL volumes and ACTIVE or FULL", func(flagValue string) error {
@@ -339,29 +340,45 @@ func capacityByMinVolumeDensity(diskType types.DiskType, volumeSizeLimitMb uint6
}
}
// capacityByActualDataUsage ranks servers purely by how much actual data they
// hold (sum of volume sizes), ignoring MaxVolumeCount. The slot-density metric
// divides by MaxVolumeCount, so a server whose MaxVolumeCount was configured too
// high for its disk looks nearly empty even when its disk is physically full and
// gets picked as a move target. This function keeps the fullest-by-data server
// ranked as full so balancing drains it instead of piling onto it. It assumes
// comparable disk sizes across servers of the same disk type. Capacity is a
// uniform constant so the density ratio is proportional to actual data; the
// constant cancels out of every ratio comparison in balanceSelectedVolume.
func capacityByActualDataUsage(diskType types.DiskType, volumeSizeLimitMb uint64) DensityFunc {
// capacityByDiskUsage ranks servers by reported physical disk used percentage.
// This makes a physically full disk rank as a move source, even if the regular
// SeaweedFS volumes in topology do not make it look like the largest data holder.
// The percent scale is only comparable when every server reports disk bytes, so
// if any node lacks DiskTotalBytes (older build), all nodes fall back to the
// previous ranking by summed volume sizes with a uniform capacity: mixing the two
// scales would rank non-reporting servers as orders of magnitude fuller, and
// normalizing the fallback by MaxVolumeCount instead would reintroduce the
// over-configured-maxVolumeCount distortion this flag exists to avoid.
func capacityByDiskUsage(diskType types.DiskType, volumeSizeLimitMb uint64, nodes []*Node) DensityFunc {
if volumeSizeLimitMb == 0 {
volumeSizeLimitMb = util.VolumeSizeLimitGB * util.KiByte
}
volumeSizeLimitBytes := volumeSizeLimitMb * util.MiByte
allReportDiskBytes := true
for _, n := range nodes {
if diskInfo, found := n.info.DiskInfos[string(diskType)]; found && diskInfo != nil && diskInfo.DiskTotalBytes == 0 {
allReportDiskBytes = false
break
}
}
return func(info *master_pb.DataNodeInfo) (float64, uint64) {
diskInfo, found := info.DiskInfos[string(diskType)]
if !found || diskInfo == nil {
return 0, 0
}
if allReportDiskBytes && diskInfo.DiskTotalBytes > 0 {
usedBytes := uint64(0)
if diskInfo.DiskFreeBytes < diskInfo.DiskTotalBytes {
usedBytes = diskInfo.DiskTotalBytes - diskInfo.DiskFreeBytes
}
return float64(diskInfo.DiskTotalBytes) / float64(volumeSizeLimitBytes),
balancer.UsedVolumeEquivalents(usedBytes, volumeSizeLimitBytes)
}
var volumeSizes uint64
for _, volumeInfo := range diskInfo.VolumeInfos {
volumeSizes += volumeInfo.Size
}
if volumeSizeLimitMb == 0 {
volumeSizeLimitMb = util.VolumeSizeLimitGB * util.KiByte
}
return 1, balancer.UsedVolumeEquivalents(volumeSizes, volumeSizeLimitMb*util.MiByte)
return 1, balancer.UsedVolumeEquivalents(volumeSizes, volumeSizeLimitBytes)
}
}
@@ -486,7 +503,7 @@ func (c *commandVolumeBalance) balanceSelectedVolume(diskType types.DiskType, vo
}
capacityFunc := capacityByMinVolumeDensity(diskType, volumeSizeLimitMb)
if c.byDiskUsage {
capacityFunc = capacityByActualDataUsage(diskType, volumeSizeLimitMb)
capacityFunc = capacityByDiskUsage(diskType, volumeSizeLimitMb, nodes)
}
for _, dn := range nodes {
capacity, volumeCount := capacityFunc(dn.info)
@@ -544,9 +561,9 @@ func (c *commandVolumeBalance) balanceSelectedVolume(diskType types.DiskType, vo
}
sortCandidatesFn(candidateVolumes)
for _, emptyNode := range nodesWithCapacity[:fullNodeIndex] {
// In byte-usage mode capacity is a uniform constant, so a target's
// free volume slots aren't reflected in its ranking; skip targets that
// are already at MaxVolumeCount so balancing never exceeds the slot limit.
// In byte-usage mode the ranking ignores volume slots, so skip targets
// that are already at MaxVolumeCount so balancing never exceeds the
// slot limit.
if c.byDiskUsage && !emptyNode.hasFreeVolumeSlot(diskType) {
continue
}
+62
View File
@@ -444,6 +444,68 @@ func TestBalanceByDiskUsage(t *testing.T) {
}
}
// When volume servers report physical disk bytes, -byDiskUsage should use the
// filesystem fullness as the source ranking. This covers the production-shaped
// case where a 99%-used disk does not have the largest sum of regular
// VolumeInfos, so ranking by volume bytes alone drains the wrong server.
func TestBalanceByDiskUsageUsesPhysicalDiskUsageWhenReported(t *testing.T) {
const gb = 1024 * 1024 * 1024
volumeSizeLimitMb := uint64(1024)
physicalFull := makeByteNode("physical-full", 2000, 1000*gb, 10*gb, mkByteVolumes(1, 5, 1000)) // 99% used
dataHeavy := makeByteNode("data-heavy", 2000, 1000*gb, 530*gb, mkByteVolumes(101, 20, 1000)) // 47% used, more volume bytes
target := makeByteNode("target", 2000, 1000*gb, 900*gb, mkByteVolumes(201, 1, 1000)) // 10% used
beforePhysicalFull := volCount(physicalFull)
beforeDataHeavy := volCount(dataHeavy)
beforeTarget := volCount(target)
c := &commandVolumeBalance{
volumeSizeLimitMb: volumeSizeLimitMb,
byDiskUsage: true,
diskUsageHighWaterPercent: 90,
}
runBalance(t, c, []*Node{physicalFull, dataHeavy, target})
if got := volCount(physicalFull); got >= beforePhysicalFull {
t.Fatalf("-byDiskUsage should drain the physically fullest server, got %d volumes (was %d)", got, beforePhysicalFull)
}
if got := volCount(dataHeavy); got != beforeDataHeavy {
t.Fatalf("-byDiskUsage should not drain the lower physical-usage data-heavy server first, got %d volumes (was %d)", got, beforeDataHeavy)
}
if got := volCount(target); got <= beforeTarget {
t.Fatalf("expected the low-usage target to receive volumes, got %d volumes (was %d)", got, beforeTarget)
}
}
// A fleet where only some servers report physical disk bytes must not mix the
// percent scale with the volume-bytes scale: a non-reporting server's ratio is
// whole volume-equivalents while reporting servers stay below 1.0, so the
// balancer would drain a nearly empty old-build server onto physically fuller
// ones. With mixed reporting, ranking falls back to data size for everyone.
func TestBalanceByDiskUsageMixedReportingFallsBackToDataSize(t *testing.T) {
const gb = 1024 * 1024 * 1024
oldEmpty := makeByteNode("old-empty", 2000, 0, 0, mkByteVolumes(1, 2, 1000)) // no disk bytes reported
newFull := makeByteNode("new-full", 2000, 1000*gb, 500*gb, mkByteVolumes(101, 20, 1000))
newTarget := makeByteNode("new-target", 2000, 1000*gb, 990*gb, mkByteVolumes(201, 1, 1000))
beforeOldEmpty := volCount(oldEmpty)
beforeNewFull := volCount(newFull)
c := &commandVolumeBalance{
volumeSizeLimitMb: 1024,
byDiskUsage: true,
diskUsageHighWaterPercent: 90,
}
runBalance(t, c, []*Node{oldEmpty, newFull, newTarget})
if got := volCount(oldEmpty); got < beforeOldEmpty {
t.Fatalf("the nearly empty non-reporting server should not be drained, got %d volumes (was %d)", got, beforeOldEmpty)
}
if got := volCount(newFull); got >= beforeNewFull {
t.Fatalf("the data-heavy server should drain under the fallback ranking, got %d volumes (was %d)", got, beforeNewFull)
}
}
// makeByteNode builds a single-disk Node carrying physical disk bytes, for the
// disk-fullness gate tests.
func makeByteNode(id string, maxVolumeCount int64, totalBytes, freeBytes uint64, volumes []*master_pb.VolumeInformationMessage) *Node {
+164 -176
View File
@@ -6,6 +6,7 @@ import (
"io"
"strconv"
"strings"
"sync"
"time"
"slices"
@@ -49,8 +50,10 @@ func (c *commandVolumeFixReplication) Help() string {
Note:
* each time this will only add back one replica for each volume id that is under replicated.
If there are multiple replicas are missing, e.g. replica count is > 2, you may need to run this multiple times.
* do not run this too quickly within seconds, since the new volume replica may take a few seconds
* do not run this too quickly within seconds, since the new volume replica may take a few seconds
to register itself to the master.
* under-replicated volumes are copied up to -maxParallelization at a time, with at most
-maxParallelizationPerServer concurrent copies onto any single destination server.
`
}
@@ -70,6 +73,7 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
doDelete := volFixReplicationCommand.Bool("doDelete", true, "Also delete over-replicated volumes besides fixing under-replication")
doCheck := volFixReplicationCommand.Bool("doCheck", true, "Also check synchronization before deleting")
maxParallelization := volFixReplicationCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
maxParallelizationPerServer := volFixReplicationCommand.Int("maxParallelizationPerServer", 1, "run up to X volume copies onto the same destination server in parallel")
retryCount := volFixReplicationCommand.Int("retry", 5, "how many times to retry")
volumesPerStep := volFixReplicationCommand.Int("volumesPerStep", 0, "how many volumes to fix in one cycle")
@@ -154,7 +158,7 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
ewg.Reset()
ewg.Add(func() error {
// find the most underpopulated data nodes
fixedVolumeReplicas, err = c.fixUnderReplicatedVolumes(commandEnv, writer, *applyChanges, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount, *volumesPerStep)
fixedVolumeReplicas, err = c.fixUnderReplicatedVolumes(commandEnv, writer, *applyChanges, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount, *volumesPerStep, *maxParallelization, *maxParallelizationPerServer)
return err
})
if *doDelete {
@@ -336,7 +340,7 @@ func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, wr
return nil
}
func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, retryCount int, volumesPerStep int) (fixedVolumes map[string]int, err error) {
func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, retryCount int, volumesPerStep int, maxParallelization int, maxParallelizationPerServer int) (fixedVolumes map[string]int, err error) {
fixedVolumes = map[string]int{}
if len(volumeIds) == 0 {
@@ -346,61 +350,137 @@ func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *Comm
if len(volumeIds) > volumesPerStep && volumesPerStep > 0 {
volumeIds = volumeIds[0:volumesPerStep]
}
// own a private copy of the locations list: the scheduler re-sorts it on
// every reservation, and the caller's slice is shared with the concurrent
// delete phases
allLocations = slices.Clone(allLocations)
scheduler := newVolumeCopyScheduler(maxParallelizationPerServer)
var fixedVolumesMu sync.Mutex
ewg := NewErrorWaitGroup(maxParallelization)
for _, vid := range volumeIds {
for i := 0; i < retryCount+1; i++ {
var copied bool
if copied, err = c.fixOneUnderReplicatedVolume(commandEnv, writer, applyChanges, volumeReplicas, vid, allLocations); err == nil {
if applyChanges && copied {
fixedVolumes[strconv.FormatUint(uint64(vid), 10)] = len(volumeReplicas[vid])
ewg.Add(func() error {
for i := 0; i < retryCount+1; i++ {
if copied, err := c.fixOneUnderReplicatedVolume(commandEnv, writer, applyChanges, volumeReplicas, vid, allLocations, scheduler); err == nil {
if applyChanges && copied {
fixedVolumesMu.Lock()
fixedVolumes[strconv.FormatUint(uint64(vid), 10)] = len(volumeReplicas[vid])
fixedVolumesMu.Unlock()
}
break
} else {
fmt.Fprintf(writer, "fixing under replicated volume %d: %v\n", vid, err)
}
break
} else {
fmt.Fprintf(writer, "fixing under replicated volume %d: %v\n", vid, err)
}
}
return nil
})
}
return fixedVolumes, nil
return fixedVolumes, ewg.Wait()
}
func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location) (bool, error) {
// volumeCopyScheduler serializes destination selection for concurrent volume
// copies: selection and free-slot accounting are atomic so parallel fixes see
// each other's reservations, and the per-server cap keeps many simultaneous
// copies from swamping one destination's disks.
type volumeCopyScheduler struct {
mu sync.Mutex
cond *sync.Cond
inflight map[string]int // destination dataNode.Id -> copies in flight
maxPerServer int
}
func newVolumeCopyScheduler(maxPerServer int) *volumeCopyScheduler {
if maxPerServer <= 0 {
maxPerServer = 1
}
s := &volumeCopyScheduler{
inflight: make(map[string]int),
maxPerServer: maxPerServer,
}
s.cond = sync.NewCond(&s.mu)
return s
}
// reserveTarget picks the emptiest data node satisfying the replica placement
// and reserves a volume slot on it. When every eligible destination is at the
// per-server copy cap it waits for a copy to finish instead of failing.
// Returns nil only when no data node can accept the replica at all. With
// countInflight=false (simulation) the slot is reserved but no copy is
// counted in flight.
func (s *volumeCopyScheduler) reserveTarget(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, allLocations []location, diskType string, countInflight bool) *location {
s.mu.Lock()
defer s.mu.Unlock()
fn := capacityByFreeVolumeCount(types.ToDiskType(diskType))
for {
keepDataNodesSorted(allLocations, types.ToDiskType(diskType))
eligibleButBusy := false
for _, dst := range allLocations {
// check whether data nodes satisfy the constraints
if fn(dst.dataNode) <= 0 || !satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
continue
}
if countInflight && s.inflight[dst.dataNode.Id] >= s.maxPerServer {
eligibleButBusy = true
continue
}
addVolumeCount(dst.dataNode.DiskInfos[diskType], 1)
if countInflight {
s.inflight[dst.dataNode.Id]++
}
return &dst
}
if !eligibleButBusy {
return nil
}
s.cond.Wait()
}
}
// releaseTarget ends a copy counted by reserveTarget. A failed copy also
// returns the reserved volume slot, so retries do not drain the topology's
// free-slot accounting.
func (s *volumeCopyScheduler) releaseTarget(dst *location, diskType string, copied bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.inflight[dst.dataNode.Id]--
if s.inflight[dst.dataNode.Id] <= 0 {
delete(s.inflight, dst.dataNode.Id)
}
if !copied {
addVolumeCount(dst.dataNode.DiskInfos[diskType], -1)
}
s.cond.Broadcast()
}
func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location, scheduler *volumeCopyScheduler) (bool, error) {
replicas := volumeReplicas[vid]
replica := pickOneReplicaToCopyFrom(replicas)
replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
foundNewLocation := false
keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
for _, dst := range allLocations {
// check whether data nodes satisfy the constraints
if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
// ask the volume server to replicate the volume
foundNewLocation = true
fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
if !applyChanges {
// adjust volume count
addVolumeCount(dst.dataNode.DiskInfos[replica.info.DiskType], 1)
return true, nil
}
err := replicateVolumeToServer(commandEnv.option.GrpcDialOption, writer, needle.VolumeId(replica.info.Id),
pb.NewServerAddressFromDataNode(replica.location.dataNode),
pb.NewServerAddressFromDataNode(dst.dataNode),
replica.info.DiskType)
if err != nil {
return false, err
}
// adjust volume count
addVolumeCount(dst.dataNode.DiskInfos[replica.info.DiskType], 1)
return true, nil
}
}
if !foundNewLocation {
dst := scheduler.reserveTarget(replicaPlacement, replicas, allLocations, replica.info.DiskType, applyChanges)
if dst == nil {
fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
return false, nil
}
return false, nil
// ask the volume server to replicate the volume
fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
if !applyChanges {
return true, nil
}
err := replicateVolumeToServer(commandEnv.option.GrpcDialOption, writer, needle.VolumeId(replica.info.Id),
pb.NewServerAddressFromDataNode(replica.location.dataNode),
pb.NewServerAddressFromDataNode(dst.dataNode),
replica.info.DiskType)
scheduler.releaseTarget(dst, replica.info.DiskType, err == nil)
if err != nil {
return false, err
}
return true, nil
}
func addVolumeCount(info *master_pb.DiskInfo, count int) {
@@ -419,24 +499,11 @@ func keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
}
func satisfyReplicaCurrentLocation(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica) bool {
existingDataCenters, existingRacks, _ := countReplicas(replicas)
if replicaPlacement.DiffDataCenterCount+1 > len(existingDataCenters) {
return false
locs := make([]balancer.Location, len(replicas))
for i, r := range replicas {
locs[i] = toBalancerLocation(r.location)
}
if replicaPlacement.DiffRackCount+1 > len(existingRacks) {
return false
}
if replicaPlacement.SameRackCount > 0 {
foundSatisfyRack := false
for _, rackCount := range existingRacks {
if rackCount >= replicaPlacement.SameRackCount+1 {
foundSatisfyRack = true
}
}
return foundSatisfyRack
}
return true
return balancer.SatisfyReplicaCurrentLocation(replicaPlacement, locs)
}
/*
@@ -518,129 +585,50 @@ func (l location) DataCenter() string {
return l.dc
}
func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
mostRecent := replicas[0]
for _, replica := range replicas {
if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
mostRecent = replica
}
}
return mostRecent
}
func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
diffDc = make(map[string]int)
diffRack = make(map[string]int)
diffNode = make(map[string]int)
for _, replica := range replicas {
diffDc[replica.location.DataCenter()] += 1
diffRack[replica.location.Rack()] += 1
diffNode[replica.location.String()] += 1
}
return
}
// pickOneReplicaToDelete selects the replica to trim when over-replicated.
// It only ever removes the smallest of multiple healthy writable replicas: a
// ReadOnly/integrity-flagged replica is never chosen for deletion, and the
// trim is refused (returns nil) when removing a writable replica would leave
// only ReadOnly survivors. VolumeStatus file_count>0 alone cannot prove the
// survivors' .dat is readable, so we do not over-claim survivor health.
// pickSmallestReplica returns the smallest replica (ties broken by oldest then
// lowest compact revision), or nil for an empty set.
func pickSmallestReplica(replicas []*VolumeReplica) *VolumeReplica {
if len(replicas) == 0 {
return nil
}
sorted := slices.Clone(replicas)
slices.SortFunc(sorted, func(a, b *VolumeReplica) int {
if a.info.Size != b.info.Size {
return int(a.info.Size - b.info.Size)
}
if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
return int(a.info.ModifiedAtSecond - b.info.ModifiedAtSecond)
}
if a.info.CompactRevision != b.info.CompactRevision {
return int(a.info.CompactRevision - b.info.CompactRevision)
}
return 0
})
return sorted[0]
}
func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
// Over-replication trim: only ever remove a writable replica, and only
// when another writable one survives, so a healthy copy is never deleted
// down to a read-only (e.g. full or integrity-flagged) survivor.
var writable []*VolumeReplica
for _, r := range replicas {
if !r.info.ReadOnly {
writable = append(writable, r)
}
}
if len(writable) < 2 {
return nil
}
// Prefer a writable replica whose removal still satisfies placement, so the
// trim does not strip the only replica in a required failure domain. Fall
// back to the smallest writable if none keeps placement (a later misplaced
// cycle then re-balances).
var placementSafe []*VolumeReplica
// toBalancerReplicas adapts shell replicas to the shared selection shape in
// weed/topology/balancer; selection results come back as indices into the
// same slice.
func toBalancerReplicas(replicas []*VolumeReplica) []balancer.Replica {
out := make([]balancer.Replica, len(replicas))
for i, r := range replicas {
if r.info.ReadOnly {
continue
}
if !isMisplaced(otherThan(replicas, i), replicaPlacement) {
placementSafe = append(placementSafe, r)
out[i] = balancer.Replica{Location: toBalancerLocation(r.location)}
if r.info != nil {
out[i].Size = r.info.Size
out[i].ModifiedAtSecond = r.info.ModifiedAtSecond
out[i].CompactRevision = r.info.CompactRevision
out[i].ReadOnly = r.info.ReadOnly
}
}
if len(placementSafe) > 0 {
return pickSmallestReplica(placementSafe)
return out
}
func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
if i := balancer.PickOneReplicaToCopyFrom(toBalancerReplicas(replicas)); i >= 0 {
return replicas[i]
}
return pickSmallestReplica(writable)
return nil
}
// pickOneReplicaToDelete selects the replica to trim when over-replicated;
// see balancer.PickOneReplicaToDelete for the survivor-safety rules.
// VolumeStatus file_count>0 alone cannot prove the survivors' .dat is
// readable, so we do not over-claim survivor health.
func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
if i := balancer.PickOneReplicaToDelete(toBalancerReplicas(replicas), replicaPlacement); i >= 0 {
return replicas[i]
}
return nil
}
// check and fix misplaced volumes
func isMisplaced(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) bool {
for i := 0; i < len(replicas); i++ {
others := otherThan(replicas, i)
if !satisfyReplicaPlacement(replicaPlacement, others, *replicas[i].location) {
return true
}
}
return false
return balancer.IsMisplaced(toBalancerReplicas(replicas), replicaPlacement)
}
func otherThan(replicas []*VolumeReplica, index int) (others []*VolumeReplica) {
for i := 0; i < len(replicas); i++ {
if index != i {
others = append(others, replicas[i])
}
func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
if i := balancer.PickOneMisplacedVolume(toBalancerReplicas(replicas), replicaPlacement); i >= 0 {
return replicas[i]
}
return
}
func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) (toDelete *VolumeReplica) {
// Relocation, not over-replication: pick the smallest replica to delete
// and recreate at a correct placement. Unlike the trim this must still act
// on read-only replicas (e.g. a full but misplaced volume), so it does not
// use pickOneReplicaToDelete's writable-survivor guard.
var deletionCandidates []*VolumeReplica
for i := 0; i < len(replicas); i++ {
others := otherThan(replicas, i)
if !isMisplaced(others, replicaPlacement) {
deletionCandidates = append(deletionCandidates, replicas[i])
}
}
if toDelete = pickSmallestReplica(deletionCandidates); toDelete != nil {
return toDelete
}
return pickSmallestReplica(replicas)
return nil
}
@@ -0,0 +1,144 @@
package shell
import (
"io"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
)
func testFixLocation(dc, rack, id string, maxVolumes int64) location {
return location{
dc: dc,
rack: rack,
dataNode: &master_pb.DataNodeInfo{
Id: id,
DiskInfos: map[string]*master_pb.DiskInfo{
"": {MaxVolumeCount: maxVolumes, FreeVolumeCount: maxVolumes},
},
},
}
}
func TestReserveTargetSpreadsAcrossServers(t *testing.T) {
src := testFixLocation("dc1", "r1", "dn0", 0)
allLocations := []location{
src,
testFixLocation("dc1", "r1", "dn1", 10),
testFixLocation("dc1", "r1", "dn2", 5),
testFixLocation("dc1", "r1", "dn3", 3),
}
// keepDataNodesSorted reorders allLocations in place, so keep stable
// per-node copies; the shared dataNode pointers carry the accounting
byId := make(map[string]*location)
for _, loc := range allLocations {
loc := loc
byId[loc.dataNode.Id] = &loc
}
replicas := []*VolumeReplica{
{location: &src, info: &master_pb.VolumeInformationMessage{Id: 1}},
}
rp, _ := super_block.NewReplicaPlacementFromString("001")
// with all copies in flight, consecutive reservations must not converge on
// the emptiest server
s := newVolumeCopyScheduler(1)
var reserved []*location
got := make(map[string]bool)
for i := 0; i < 3; i++ {
dst := s.reserveTarget(rp, replicas, allLocations, "", true)
if dst == nil {
t.Fatalf("reservation %d found no destination", i)
}
reserved = append(reserved, dst)
got[dst.dataNode.Id] = true
}
for _, id := range []string{"dn1", "dn2", "dn3"} {
if !got[id] {
t.Errorf("expected a reservation on %s, got %v", id, got)
}
}
// every eligible destination is at the copy cap: the next reservation
// waits for a free slot instead of failing
done := make(chan *location)
go func() {
done <- s.reserveTarget(rp, replicas, allLocations, "", true)
}()
select {
case dst := <-done:
t.Fatalf("reserveTarget should wait while all destinations are at the copy cap, got %s", dst.dataNode.Id)
case <-time.After(100 * time.Millisecond):
}
s.releaseTarget(byId["dn1"], "", true)
var waited *location
select {
case waited = <-done:
case <-time.After(5 * time.Second):
t.Fatal("reserveTarget did not wake up after a copy slot freed")
}
if waited == nil || waited.dataNode.Id != "dn1" {
t.Fatalf("expected the freed dn1 to take the waiting copy, got %+v", waited)
}
// a successful copy keeps its volume slot, a failed one returns it
s.releaseTarget(waited, "", true)
if count := byId["dn1"].dataNode.DiskInfos[""].VolumeCount; count != 2 {
t.Errorf("dn1 should keep 2 reserved slots, got %d", count)
}
for _, dst := range reserved {
if dst.dataNode.Id != "dn1" {
s.releaseTarget(dst, "", false)
if count := dst.dataNode.DiskInfos[""].VolumeCount; count != 0 {
t.Errorf("%s should have its failed reservation returned, got volume count %d", dst.dataNode.Id, count)
}
}
}
if len(s.inflight) != 0 {
t.Errorf("all copies released, but %d still in flight", len(s.inflight))
}
}
func TestFixUnderReplicatedVolumesInParallel(t *testing.T) {
src := testFixLocation("dc1", "r1", "dn0", 0)
allLocations := []location{
src,
testFixLocation("dc1", "r1", "dn1", 4),
testFixLocation("dc1", "r1", "dn2", 4),
testFixLocation("dc1", "r1", "dn3", 4),
}
rp, _ := super_block.NewReplicaPlacementFromString("001")
volumeReplicas := make(map[uint32][]*VolumeReplica)
var volumeIds []uint32
for vid := uint32(1); vid <= 12; vid++ {
volumeReplicas[vid] = []*VolumeReplica{
{location: &src, info: &master_pb.VolumeInformationMessage{Id: vid, ReplicaPlacement: uint32(rp.Byte())}},
}
volumeIds = append(volumeIds, vid)
}
c := &commandVolumeFixReplication{collectionPattern: new(string)}
fixedVolumes, err := c.fixUnderReplicatedVolumes(nil, io.Discard, false, volumeIds, volumeReplicas, allLocations, 0, 0, 8, 1)
if err != nil {
t.Fatalf("fixUnderReplicatedVolumes: %v", err)
}
if len(fixedVolumes) != 0 {
t.Errorf("simulation should not record fixed volumes, got %d", len(fixedVolumes))
}
// 12 volumes must exactly fill the 3x4 free slots without over-reserving
// any single destination
for _, loc := range allLocations {
if loc.dataNode.Id == "dn0" {
continue
}
diskInfo := loc.dataNode.DiskInfos[""]
if diskInfo.VolumeCount != 4 || diskInfo.FreeVolumeCount != 0 {
t.Errorf("%s expected exactly 4 reserved slots, got volume count %d, free %d",
loc.dataNode.Id, diskInfo.VolumeCount, diskInfo.FreeVolumeCount)
}
}
}
+5 -1
View File
@@ -233,7 +233,11 @@ func markVolumeWritable(grpcDialOption grpc.DialOption, volumeId needle.VolumeId
}
func markVolumeReplicaWritable(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, location wdclient.Location, writable, persist bool) error {
fmt.Printf("markVolumeReadonly %d on %s ...\n", volumeId, location.Url)
if writable {
fmt.Printf("markVolumeWritable %d on %s ...\n", volumeId, location.Url)
} else {
fmt.Printf("markVolumeReadonly %d on %s persist=%v ...\n", volumeId, location.Url, persist)
}
return markVolumeWritable(grpcDialOption, volumeId, location.ServerAddress(), writable, persist)
}
+26
View File
@@ -54,3 +54,29 @@ func TestParseFileIdFromString(t *testing.T) {
t.Errorf("%s : needleId is too long", fidStr1)
}
}
func TestNeedleIdFileId(t *testing.T) {
tests := []struct {
key types.NeedleId
volumeId uint32
want string
}{
{types.NeedleId(1), 3, "3,0100000000"},
{types.NeedleId(0x123), 3, "3,012300000000"},
{types.NeedleId(0x1234), 7, "7,123400000000"},
}
for _, tt := range tests {
fid := tt.key.FileId(tt.volumeId)
if fid != tt.want {
t.Errorf("NeedleId(%d).FileId(%d) = %s, want %s", tt.key, tt.volumeId, fid, tt.want)
}
fileId, err := ParseFileIdFromString(fid)
if err != nil {
t.Errorf("%s : should be OK: %v", fid, err)
continue
}
if fileId.VolumeId != VolumeId(tt.volumeId) || fileId.Key != tt.key || fileId.Cookie != 0 {
t.Errorf("src : %s, dest : %v", fid, fileId)
}
}
}
+80 -11
View File
@@ -147,9 +147,9 @@ func (f *localDirBackendFile) Truncate(off int64) error {
return os.Truncate(filepath.Join(f.backend.root, f.key), off)
}
func (f *localDirBackendFile) Close() error { return nil }
func (f *localDirBackendFile) Name() string { return f.key }
func (f *localDirBackendFile) Sync() error { return nil }
func (f *localDirBackendFile) Close() error { return nil }
func (f *localDirBackendFile) Name() string { return f.key }
func (f *localDirBackendFile) Sync() error { return nil }
func (f *localDirBackendFile) GetStat() (int64, time.Time, error) {
files := f.tierInfo.GetFiles()
if len(files) == 0 {
@@ -174,11 +174,13 @@ func registerTestBackend(t *testing.T, b *localDirBackend) {
})
}
// tierUpVolume creates a real on-disk volume, writes a few needles, then
// uploads the .dat to the fake backend and rewrites the volume in remote
// mode (mirrors the production flow in volume_grpc_tier_upload.go but
// in-process).
func tierUpVolume(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (collection string, key string) {
// tierUpVolumeLive creates a real on-disk volume, writes a few needles, then
// uploads the .dat to the fake backend and rewrites the volume in remote mode
// (mirrors the production flow in volume_grpc_tier_upload.go but in-process).
// It returns the still-open volume, exactly as a volume server holds it after a
// live `volume.tier.upload` — no reload. Callers that want the on-disk state a
// server sees after restart use tierUpVolume, which closes it.
func tierUpVolumeLive(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (v *Volume, key string) {
t.Helper()
v, err := NewVolume(dir, dir, "", vid, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
require.NoError(t, err)
@@ -208,10 +210,16 @@ func tierUpVolume(t *testing.T, dir string, vid needle.VolumeId, b *localDirBack
require.NoError(t, v.LoadRemoteFile())
require.NoError(t, os.Remove(v.FileName(".dat")))
// Close the volume cleanly. Tests below reload it from disk to mirror
// what a volume server does on restart with a tiered volume.
v.Close()
return v, uploadKey
}
// tierUpVolume runs tierUpVolumeLive then closes the volume. Tests using it
// reload from disk to mirror what a volume server does on restart with a
// tiered volume.
func tierUpVolume(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (collection string, key string) {
t.Helper()
v, uploadKey := tierUpVolumeLive(t, dir, vid, b)
v.Close()
return v.Collection, uploadKey
}
@@ -259,6 +267,67 @@ func TestRemoteTier_DiskScanLoadsRemoteOnlyVolume(t *testing.T) {
v.Close()
}
// TestRemoteTier_LiveTierUpload_StillReportsToMaster covers a live
// `volume.tier.upload`: the .dat is removed and the volume serves from remote,
// but the same in-memory Volume keeps heartbeating with no reload. The
// phantom-.dat guard must not suppress it just because .dat is gone —
// LoadRemoteFile has flipped it into remote mode, so ToVolumeInformationMessage
// must still report it to the master. If HasRemoteFile stayed false the volume
// would vanish from the topology ("volume not found").
func TestRemoteTier_LiveTierUpload_StillReportsToMaster(t *testing.T) {
b := newLocalDirBackend(t)
registerTestBackend(t, b)
dir := t.TempDir()
const vid = needle.VolumeId(67)
v, _ := tierUpVolumeLive(t, dir, vid, b)
defer v.Close()
// A store-owned volume always carries its DiskLocation; NewVolume leaves it
// nil, so give it one for the IsReadOnly disk-space check inside the heartbeat.
v.location = &DiskLocation{Directory: dir, DiskType: types.HddType}
require.True(t, v.HasRemoteFile(), "a tier-uploaded volume is in remote mode even before any reload")
require.False(t, util.FileExists(v.FileName(".dat")), "tier-up should have removed the local .dat")
_, msg := v.ToVolumeInformationMessage()
require.NotNil(t, msg, "tier-uploaded volume must still report to master")
require.NotEmpty(t, msg.RemoteStorageName, "reported volume must carry its remote backend name")
}
// TestRemoteTier_ReloadUnderDataLock_NoDeadlock guards the reload-under-lock
// path: CommitCompact holds dataFileAccessLock and calls v.load(), which for a
// remote-tiered volume swaps the data backend. That swap must go through the
// lock-free loadRemoteFileLocked; if load() instead used the public
// LoadRemoteFile (which takes dataFileAccessLock), it would re-enter the held
// lock and deadlock.
func TestRemoteTier_ReloadUnderDataLock_NoDeadlock(t *testing.T) {
b := newLocalDirBackend(t)
registerTestBackend(t, b)
dir := t.TempDir()
const vid = needle.VolumeId(68)
v, _ := tierUpVolumeLive(t, dir, vid, b)
v.location = &DiskLocation{Directory: dir, DiskType: types.HddType}
require.True(t, v.HasRemoteFile())
done := make(chan error, 1)
go func() {
// Mirror CommitCompact: hold the data lock across the reload.
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
done <- v.load(true, false, v.needleMapKind, 0, v.Version())
}()
select {
case err := <-done:
require.NoError(t, err)
require.True(t, v.HasRemoteFile(), "volume must stay remote-tiered after reload")
v.Close()
case <-time.After(10 * time.Second):
t.Fatal("reload under dataFileAccessLock deadlocked: load() re-entered the held lock via LoadRemoteFile")
}
}
// TestRemoteTier_Move_KeepsRemoteObject simulates the move-on-source-after-copy
// step of a balance: Destroy(onlyEmpty=false, keepRemoteData=true). The remote
// object must survive — the destination's freshly-copied .vif points at it.
+2 -2
View File
@@ -102,7 +102,7 @@ func TestLocalVolumesLen(t *testing.T) {
// Mark some as remote
if i < tc.remoteVolumes {
vol.hasRemoteFile = true
vol.hasRemoteFile.Store(true)
vol.volumeInfo.Files = []*volume_server_pb.RemoteFile{
{BackendType: "s3", BackendId: "test", Key: "test-key"},
}
@@ -250,7 +250,7 @@ func createTestVolume(vid needle.VolumeId, isRemote bool) *Volume {
}
if isRemote {
vol.hasRemoteFile = true
vol.hasRemoteFile.Store(true)
vol.volumeInfo.Files = []*volume_server_pb.RemoteFile{
{BackendType: "s3", BackendId: "test", Key: "remote-key-" + strconv.Itoa(int(vid))},
}
+6 -1
View File
@@ -36,7 +36,12 @@ func (k NeedleId) String() string {
}
func (k NeedleId) FileId(volumeId uint32) string {
return fmt.Sprintf("%d,%s00000000", volumeId, k.String())
// pad to even length so strict hex fid parsers accept it
needleIdHex := k.String()
if len(needleIdHex)%2 == 1 {
needleIdHex = "0" + needleIdHex
}
return fmt.Sprintf("%d,%s00000000", volumeId, needleIdHex)
}
func ParseNeedleId(idString string) (NeedleId, error) {
+19 -6
View File
@@ -32,7 +32,7 @@ type Volume struct {
noWriteOrDelete bool // if readonly, either noWriteOrDelete or noWriteCanDelete
noWriteCanDelete bool // if readonly, either noWriteOrDelete or noWriteCanDelete
noWriteLock sync.RWMutex
hasRemoteFile bool // if the volume has a remote file
hasRemoteFile atomic.Bool // if the volume is tiered: data lives in a remote backend
MemoryMapMaxSizeMb uint32
super_block.SuperBlock
@@ -312,17 +312,30 @@ func (v *Volume) Close() {
v.doClose()
}
// SwapDataBackend atomically replaces the data backend (e.g. swapping a
// remote-tier backend for a freshly downloaded local .dat), closing the old
// one. Held under dataFileAccessLock so a concurrent read/write never observes
// a half-swapped or closed backend.
func (v *Volume) SwapDataBackend(newBackend backend.BackendStorageFile) {
// SwapDataBackend atomically replaces the data backend and updates the
// remote-tier flag under dataFileAccessLock, closing the old backend. Both tier
// directions go through here so hasRemoteFile always matches the live backend:
// tier-down passes hasRemoteFile=false (now serving a local .dat), tier-up
// passes true. Keeping the swap and the flag under one lock means the heartbeat
// never observes a half-swapped backend or a flag that disagrees with it — a
// stale-false flag would make doDeleteRequest skip the new .dat's tombstones and
// disable the phantom-.dat guard.
func (v *Volume) SwapDataBackend(newBackend backend.BackendStorageFile, hasRemoteFile bool) {
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
v.swapDataBackendLocked(newBackend, hasRemoteFile)
}
// swapDataBackendLocked is the body of SwapDataBackend for callers that already
// hold dataFileAccessLock (e.g. load() reached while CommitCompact holds the
// lock). Reusing it from those under-lock paths avoids re-entering the
// non-reentrant lock, which would deadlock.
func (v *Volume) swapDataBackendLocked(newBackend backend.BackendStorageFile, hasRemoteFile bool) {
if v.DataBackend != nil {
v.DataBackend.Close()
}
v.DataBackend = newBackend
v.hasRemoteFile.Store(hasRemoteFile)
}
func (v *Volume) doClose() {
+4 -1
View File
@@ -161,7 +161,10 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
v.noWriteCanDelete = true
v.noWriteOrDelete = false
glog.V(0).Infof("loading volume %d from remote %v", v.Id, v.volumeInfo)
if err := v.LoadRemoteFile(); err != nil {
// loadRemoteFileLocked, not LoadRemoteFile: load() is reached from
// CommitCompact with dataFileAccessLock already held, and the locking
// variant would deadlock re-entering it.
if err := v.loadRemoteFileLocked(); err != nil {
return fmt.Errorf("load remote file %v: %w", v.volumeInfo, err)
}
// Set lastModifiedTsSeconds from remote file to prevent premature expiry on startup
+27 -9
View File
@@ -19,13 +19,15 @@ func (v *Volume) GetVolumeInfo() *volume_server_pb.VolumeInfo {
func (v *Volume) maybeLoadVolumeInfo() (found bool) {
var err error
v.volumeInfo, v.hasRemoteFile, found, err = volume_info.MaybeLoadVolumeInfo(v.FileName(".vif"))
var hasRemoteFile bool
v.volumeInfo, hasRemoteFile, found, err = volume_info.MaybeLoadVolumeInfo(v.FileName(".vif"))
v.hasRemoteFile.Store(hasRemoteFile)
if v.volumeInfo.Version == 0 {
v.volumeInfo.Version = uint32(needle.GetCurrentVersion())
}
if v.hasRemoteFile {
if hasRemoteFile {
glog.V(0).Infof("volume %d is tiered to %s as %s and read only", v.Id,
v.volumeInfo.Files[0].BackendName(), v.volumeInfo.Files[0].Key)
} else {
@@ -55,21 +57,37 @@ func (v *Volume) maybeLoadVolumeInfo() (found bool) {
}
func (v *Volume) HasRemoteFile() bool {
return v.hasRemoteFile
return v.hasRemoteFile.Load()
}
// LoadRemoteFile swaps the data backend to the remote tier object under
// dataFileAccessLock. Call this from a context that does NOT already hold the
// lock — the live tier-upload handler, where the heartbeat may be reading the
// backend concurrently. load() must instead use loadRemoteFileLocked, since it
// can be reached with the lock already held (CommitCompact).
func (v *Volume) LoadRemoteFile() error {
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
return v.loadRemoteFileLocked()
}
// loadRemoteFileLocked swaps the data backend to the remote tier object. The
// caller must hold dataFileAccessLock or be single-threaded (load() during
// construction or a compaction-commit reload). It marks the volume tiered in the
// same locked step so a later heartbeat does not treat a removed local .dat as a
// phantom volume and stop reporting it to the master.
func (v *Volume) loadRemoteFileLocked() error {
// Callers only reach here for a tiered volume (HasRemoteFile / a just-appended
// remote file), but guard the index so a stray call is a clean error, not a panic.
if len(v.volumeInfo.GetFiles()) == 0 {
return fmt.Errorf("volume %d has no remote file to load", v.Id)
}
tierFile := v.volumeInfo.GetFiles()[0]
backendStorage, found := backend.BackendStorages[tierFile.BackendName()]
if !found {
return fmt.Errorf("backend storage %s not found", tierFile.BackendName())
}
if v.DataBackend != nil {
v.DataBackend.Close()
}
v.DataBackend = backendStorage.NewStorageFile(tierFile.Key, v.volumeInfo)
v.swapDataBackendLocked(backendStorage.NewStorageFile(tierFile.Key, v.volumeInfo), true)
return nil
}
+1 -1
View File
@@ -274,7 +274,7 @@ func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
var offset uint64
var err error
size := nv.Size
if !v.hasRemoteFile {
if !v.HasRemoteFile() {
n.Data = nil
n.UpdateAppendAtNs(v.lastAppendAtNs)
offset, _, _, err = n.Append(v.DataBackend, v.Version())
+161
View File
@@ -0,0 +1,161 @@
package balancer
import (
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
)
// Replica pairs a replica's placement location with the volume attributes
// replica-selection decisions need. Like Location for placement checks, it is
// the shared shape the shell (from master_pb) and workers adapt to. Selection
// functions return an index into the given slice (-1 when nothing qualifies),
// so callers can map the choice back to their own richer replica type.
type Replica struct {
Location Location
Size uint64
ModifiedAtSecond int64
CompactRevision uint32
ReadOnly bool
}
// SatisfyReplicaCurrentLocation reports whether the existing replicas already
// span the failure domains the policy requires (enough data centers, enough
// racks, and the same-rack count somewhere). A volume whose replica count is
// right but whose spread falls short still needs another replica.
func SatisfyReplicaCurrentLocation(rp *super_block.ReplicaPlacement, replicas []Location) bool {
dcCounts, rackCounts, _ := countReplicas(replicas)
if rp.DiffDataCenterCount+1 > len(dcCounts) {
return false
}
if rp.DiffRackCount+1 > len(rackCounts) {
return false
}
if rp.SameRackCount > 0 {
for _, rackCount := range rackCounts {
if rackCount >= rp.SameRackCount+1 {
return true
}
}
return false
}
return true
}
// PickOneReplicaToCopyFrom returns the most recently modified replica, the
// best source for adding a new replica.
func PickOneReplicaToCopyFrom(replicas []Replica) int {
mostRecent := -1
for i, r := range replicas {
if mostRecent < 0 || r.ModifiedAtSecond > replicas[mostRecent].ModifiedAtSecond {
mostRecent = i
}
}
return mostRecent
}
// IsMisplaced reports whether any replica sits at a location inconsistent
// with the replication policy given the other replicas' locations.
func IsMisplaced(replicas []Replica, rp *super_block.ReplicaPlacement) bool {
for i := range replicas {
others := otherThan(replicas, i)
locs := make([]Location, len(others))
for j, r := range others {
locs[j] = r.Location
}
if !SatisfyReplicaPlacement(rp, locs, replicas[i].Location) {
return true
}
}
return false
}
// PickSmallestReplica returns the smallest replica (ties broken by oldest
// then lowest compact revision).
func PickSmallestReplica(replicas []Replica) int {
smallest := -1
for i := range replicas {
if smallest < 0 || lessReplica(replicas[i], replicas[smallest]) {
smallest = i
}
}
return smallest
}
// PickOneReplicaToDelete selects the replica to trim when over-replicated.
// It only ever removes the smallest of multiple healthy writable replicas: a
// ReadOnly/integrity-flagged replica is never chosen for deletion, and the
// trim is refused (returns -1) when removing a writable replica would leave
// only ReadOnly survivors. Among the writable replicas it prefers one whose
// removal still satisfies placement, so the trim does not strip the only
// replica in a required failure domain; it falls back to the smallest
// writable if none keeps placement (a later misplaced cycle then
// re-balances).
func PickOneReplicaToDelete(replicas []Replica, rp *super_block.ReplicaPlacement) int {
var writable []int
for i, r := range replicas {
if !r.ReadOnly {
writable = append(writable, i)
}
}
if len(writable) < 2 {
return -1
}
var placementSafe []int
for _, i := range writable {
if !IsMisplaced(otherThan(replicas, i), rp) {
placementSafe = append(placementSafe, i)
}
}
if len(placementSafe) > 0 {
return pickSmallestAmong(replicas, placementSafe)
}
return pickSmallestAmong(replicas, writable)
}
// PickOneMisplacedVolume selects the replica to delete and recreate at a
// correct placement. This is relocation, not over-replication: unlike
// PickOneReplicaToDelete it must still act on read-only replicas (e.g. a full
// but misplaced volume), so it does not use the writable-survivor guard. It
// prefers a replica whose removal leaves the others well placed, and falls
// back to the smallest replica.
func PickOneMisplacedVolume(replicas []Replica, rp *super_block.ReplicaPlacement) int {
var deletionCandidates []int
for i := range replicas {
if !IsMisplaced(otherThan(replicas, i), rp) {
deletionCandidates = append(deletionCandidates, i)
}
}
if smallest := pickSmallestAmong(replicas, deletionCandidates); smallest >= 0 {
return smallest
}
return PickSmallestReplica(replicas)
}
func pickSmallestAmong(replicas []Replica, candidates []int) int {
smallest := -1
for _, i := range candidates {
if smallest < 0 || lessReplica(replicas[i], replicas[smallest]) {
smallest = i
}
}
return smallest
}
func lessReplica(a, b Replica) bool {
if a.Size != b.Size {
return a.Size < b.Size
}
if a.ModifiedAtSecond != b.ModifiedAtSecond {
return a.ModifiedAtSecond < b.ModifiedAtSecond
}
return a.CompactRevision < b.CompactRevision
}
func otherThan(replicas []Replica, index int) (others []Replica) {
for i := range replicas {
if index != i {
others = append(others, replicas[i])
}
}
return
}
+198 -47
View File
@@ -2,6 +2,7 @@ package log_buffer
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"sync"
@@ -93,6 +94,12 @@ type LogBuffer struct {
hasOffsets bool
// Disk chunk cache for historical data reads
diskChunkCache *DiskChunkCache
// curSnap is a GC-owned copy of the current window's append-only prefix
// buf[:len(curSnap)], shared by all readers so each byte is copied once per
// window instead of once per reader. Extended lazily under curSnapMu; reset
// at seal. Existing holders keep their prefix slices, which never mutate.
curSnapMu sync.Mutex
curSnap []byte
sync.RWMutex
}
@@ -606,6 +613,13 @@ func (logBuffer *LogBuffer) copyToFlushInternal(withCallback bool) *dataToFlush
// CRITICAL: logBuffer.offset is the "next offset to assign", so last offset in buffer is offset-1
lastOffsetInBuffer := logBuffer.offset - 1
logBuffer.buf = logBuffer.prevBuffers.SealBuffer(logBuffer.startTime, logBuffer.stopTime, logBuffer.buf, logBuffer.pos, logBuffer.bufferStartOffset, lastOffsetInBuffer)
// Hand a fully extended prefix snapshot to the sealed slot so sealed
// readers reuse it instead of re-copying the window; reset for the next
// window either way (holders keep their immutable prefix slices).
if len(logBuffer.curSnap) == logBuffer.pos {
logBuffer.prevBuffers.buffers[len(logBuffer.prevBuffers.buffers)-1].snapshot = logBuffer.curSnap[:logBuffer.pos:logBuffer.pos]
}
logBuffer.curSnap = nil
// Use zero time (time.Time{}) not epoch time (time.Unix(0,0))
// Epoch time (1970) breaks time-based reads after flush
logBuffer.startTime = time.Time{}
@@ -701,7 +715,11 @@ func (d *dataToFlush) releaseMemory() {
bufferPool.Put(d.data)
}
func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bufferCopy *bytes.Buffer, batchIndex int64, err error) {
// ReadFromBuffer returns the in-memory log data at lastReadPosition. isPooled
// reports whether the returned buffer is a private pooled copy the caller must
// return via ReleaseMemory; when false the buffer wraps a snapshot shared with
// other readers and must not be released (or written to).
func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bufferCopy *bytes.Buffer, batchIndex int64, isPooled bool, err error) {
logBuffer.RLock()
defer logBuffer.RUnlock()
@@ -728,19 +746,19 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Case 3: try disk read (historical data might exist)
if requestedOffset < logBuffer.offset {
// Data was in the buffer range but buffer is now empty = flushed to disk
return nil, -2, ResumeFromDiskError
return nil, -2, false, ResumeFromDiskError
}
// requestedOffset == logBuffer.offset: Current position
// CRITICAL: For subscribers starting from offset 0, try disk read first
// (historical data might exist from previous runs)
if requestedOffset == 0 && logBuffer.bufferStartOffset == 0 && logBuffer.offset == 0 {
// Initial state: try disk read before waiting for new data
return nil, -2, ResumeFromDiskError
return nil, -2, false, ResumeFromDiskError
}
// Otherwise, wait for new data to arrive
return nil, logBuffer.offset, nil
return nil, logBuffer.offset, false, nil
}
return copiedBytes(logBuffer.buf[:logBuffer.pos]), logBuffer.offset, nil
return logBuffer.currentSnapshotView(0, logBuffer.pos), logBuffer.offset, false, nil
}
// Check previous buffers for the requested offset
@@ -750,9 +768,9 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// (prevBuffers are created when buffer is flushed)
if buf.size == 0 {
// Empty prevBuffer covering this offset means data was flushed
return nil, -2, ResumeFromDiskError
return nil, -2, false, ResumeFromDiskError
}
return copiedBytes(buf.buf[:buf.size]), buf.offset, nil
return sharedBufferView(buf, 0), buf.offset, false, nil
}
}
@@ -760,16 +778,16 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if requestedOffset < logBuffer.bufferStartOffset {
// Data not in current buffers - must be on disk (flushed or never existed)
// Return ResumeFromDiskError to trigger disk read
return nil, -2, ResumeFromDiskError
return nil, -2, false, ResumeFromDiskError
}
if requestedOffset > logBuffer.offset {
// Future data, not available yet
return nil, logBuffer.offset, nil
return nil, logBuffer.offset, false, nil
}
// Offset not found - return nil
return nil, logBuffer.offset, nil
return nil, logBuffer.offset, false, nil
}
// TIMESTAMP-BASED READ (original logic)
@@ -798,7 +816,7 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Buffer is empty - return ResumeFromDiskError so caller can read from disk
// This fixes issue #4977 where SubscribeMetadata stalls because
// MetaAggregator.MetaLogBuffer is empty in single-filer setups
return nil, -2, ResumeFromDiskError
return nil, -2, false, ResumeFromDiskError
} else if lastReadPosition.Time.Before(tsMemory) { // case 2.3
// For time-based reads, only check timestamp for disk reads
// Don't use offset comparisons as they're not meaningful for time-based subscriptions
@@ -812,7 +830,7 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Treat first read with sentinel/zero offset as inclusive of earliest in-memory data
} else {
// Data not in memory buffers - read from disk
return nil, -2, ResumeFromDiskError
return nil, -2, false, ResumeFromDiskError
}
}
@@ -821,17 +839,17 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if lastReadPosition.Time.Equal(logBuffer.stopTime) && !logBuffer.stopTime.IsZero() {
// For first-read sentinel/zero offset, allow inclusive read at the boundary
if lastReadPosition.Offset > 0 {
return nil, logBuffer.offset, nil
return nil, logBuffer.offset, false, nil
}
}
if lastReadPosition.Time.After(logBuffer.stopTime) && !logBuffer.stopTime.IsZero() {
return nil, logBuffer.offset, nil
return nil, logBuffer.offset, false, nil
}
// Also check prevBuffers when current buffer is empty (startTime is zero)
if lastReadPosition.Time.Before(logBuffer.startTime) || logBuffer.startTime.IsZero() {
for _, buf := range logBuffer.prevBuffers.buffers {
if buf.startTime.After(lastReadPosition.Time) {
return copiedBytes(buf.buf[:buf.size]), buf.offset, nil
return sharedBufferView(buf, 0), buf.offset, false, nil
}
if !buf.startTime.After(lastReadPosition.Time) && buf.stopTime.After(lastReadPosition.Time) {
searchTime := lastReadPosition.Time
@@ -842,19 +860,19 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if err != nil {
// Buffer corruption detected - return error wrapped with ErrBufferCorrupted
glog.Errorf("ReadFromBuffer: buffer corruption in prevBuffer: %v", err)
return nil, -1, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
return nil, -1, false, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
}
if pos < buf.size {
return copiedBytes(buf.buf[pos:buf.size]), buf.offset, nil
return sharedBufferView(buf, pos), buf.offset, false, nil
}
}
}
// If current buffer is not empty, return it
if logBuffer.pos > 0 {
return copiedBytes(logBuffer.buf[:logBuffer.pos]), logBuffer.offset, nil
return logBuffer.currentSnapshotView(0, logBuffer.pos), logBuffer.offset, false, nil
}
// Buffer is empty and no data in prevBuffers - wait for new data
return nil, logBuffer.offset, nil
return nil, logBuffer.offset, false, nil
}
lastTs := lastReadPosition.Time.UnixNano()
@@ -886,7 +904,7 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if err != nil {
// Buffer corruption detected in binary search
glog.Errorf("ReadFromBuffer: buffer corruption at idx[%d] pos %d: %v", mid, pos, err)
return nil, -1, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
return nil, -1, false, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
}
if t <= searchTs {
l = mid + 1
@@ -897,11 +915,11 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if err != nil {
// Buffer corruption detected in binary search (previous entry)
glog.Errorf("ReadFromBuffer: buffer corruption at idx[%d] pos %d: %v", mid-1, logBuffer.idx[mid-1], err)
return nil, -1, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
return nil, -1, false, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
}
}
if prevT <= searchTs {
return copiedBytes(logBuffer.buf[pos:logBuffer.pos]), logBuffer.offset, nil
return logBuffer.currentSnapshotView(pos, logBuffer.pos), logBuffer.offset, false, nil
}
h = mid
}
@@ -909,9 +927,13 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Binary search didn't find the timestamp - data may have been flushed to disk already
// Returning -2 signals to caller that data is not available in memory
return nil, -2, nil
return nil, -2, false, nil
}
// ReleaseMemory returns a pooled buffer for reuse. Only call it for buffers
// ReadFromBuffer reported as pooled: recycling a shared sealed-window view
// would let the next copiedBytes overwrite bytes other readers still hold.
func (logBuffer *LogBuffer) ReleaseMemory(b *bytes.Buffer) {
bufferPool.Put(b)
}
@@ -936,18 +958,6 @@ var bufferPool = sync.Pool{
},
}
// logEntryPool reduces allocations in readTs which is called frequently during binary search
var logEntryPool = sync.Pool{
New: func() interface{} {
return &filer_pb.LogEntry{}
},
}
// resetLogEntry clears a LogEntry for pool reuse
func resetLogEntry(e *filer_pb.LogEntry) {
proto.Reset(e)
}
func copiedBytes(buf []byte) (copied *bytes.Buffer) {
copied = bufferPool.Get().(*bytes.Buffer)
copied.Reset()
@@ -955,6 +965,37 @@ func copiedBytes(buf []byte) (copied *bytes.Buffer) {
return
}
// sharedBufferView wraps the sealed window's shared snapshot from pos onward.
// The returned buffer aliases memory shared with other readers: it must be
// treated as read-only and never passed to ReleaseMemory (the full-slice cap
// makes an accidental append reallocate instead of scribbling on the snapshot).
func sharedBufferView(mb *MemBuffer, pos int) *bytes.Buffer {
snap := mb.sharedSnapshot()
return bytes.NewBuffer(snap[pos:len(snap):len(snap)])
}
// currentSnapshotView returns buf[from:to] of the current window as a view of
// the shared prefix snapshot, extending the snapshot to cover [0:to) first.
// buf[:pos] is append-only until the window seals, so extension only ever
// appends stable bytes; earlier holders' slices are unaffected. Callers must
// hold the read lock (keeps buf and pos stable during extension).
func (logBuffer *LogBuffer) currentSnapshotView(from, to int) *bytes.Buffer {
logBuffer.curSnapMu.Lock()
if cap(logBuffer.curSnap) < to {
// First use in this window (or the rare window whose array outgrew the
// previous one): size to the window array so extensions never reallocate.
grown := make([]byte, len(logBuffer.curSnap), len(logBuffer.buf))
copy(grown, logBuffer.curSnap)
logBuffer.curSnap = grown
}
if len(logBuffer.curSnap) < to {
logBuffer.curSnap = append(logBuffer.curSnap, logBuffer.buf[len(logBuffer.curSnap):to]...)
}
snap := logBuffer.curSnap[:to]
logBuffer.curSnapMu.Unlock()
return bytes.NewBuffer(snap[from:to:to])
}
func readTs(buf []byte, pos int) (size int, ts int64, err error) {
// Bounds check for size field (overflow-safe)
if pos < 0 || pos > len(buf)-4 {
@@ -970,19 +1011,129 @@ func readTs(buf []byte, pos int) (size int, ts int64, err error) {
entryData := buf[pos+4 : pos+4+size]
// Use pooled LogEntry to avoid allocation on every call
logEntry := logEntryPool.Get().(*filer_pb.LogEntry)
defer func() {
resetLogEntry(logEntry)
logEntryPool.Put(logEntry)
}()
err = proto.Unmarshal(entryData, logEntry)
// Read only LogEntry.ts_ns rather than unmarshaling the whole entry. This
// runs on every binary-search probe in ReadFromBuffer; a full proto.Unmarshal
// there allocates fresh slices for the data/key byte fields on each call, which
// dominated allocation churn under metadata-subscription fan-out.
ts, err = readTsNs(entryData)
if err != nil {
// Return error instead of failing fast
// This allows caller to handle corruption gracefully
return 0, 0, fmt.Errorf("corrupted log buffer: failed to unmarshal LogEntry at pos %d, size %d: %w", pos, size, err)
return 0, 0, fmt.Errorf("corrupted log buffer at pos %d, size %d: %w", pos, size, err)
}
return size, logEntry.TsNs, nil
return size, ts, nil
}
// readTsNs scans a marshaled LogEntry and returns its ts_ns (field 1, varint)
// without decoding the data/key byte fields. Fields serialize in number order,
// so ts_ns is normally the first tag and this returns after one varint; the full
// scan keeps it correct for any field order. A missing field 1 means the proto3
// default, ts_ns == 0.
func readTsNs(entryData []byte) (tsNs int64, err error) {
for i := 0; i < len(entryData); {
tag, n := binary.Uvarint(entryData[i:])
if n <= 0 {
return 0, fmt.Errorf("bad field tag at %d", i)
}
i += n
fieldNum := tag >> 3
switch tag & 0x7 { // wire type
case 0: // varint
v, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return 0, fmt.Errorf("bad varint for field %d", fieldNum)
}
i += m
if fieldNum == 1 { // ts_ns
return int64(v), nil
}
case 1: // 64-bit
i += 8
case 2: // length-delimited: read length, skip payload without copying
l, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return 0, fmt.Errorf("bad length for field %d", fieldNum)
}
i += m
if l > uint64(len(entryData)-i) {
return 0, fmt.Errorf("field %d length %d overruns buffer", fieldNum, l)
}
i += int(l)
case 5: // 32-bit
i += 4
default:
return 0, fmt.Errorf("unknown wire type for field %d", fieldNum)
}
if i > len(entryData) {
return 0, fmt.Errorf("field %d overruns buffer", fieldNum)
}
}
return 0, nil
}
// unmarshalLogEntryAliased decodes a marshaled LogEntry into out, pointing the
// data and key fields at sub-slices of entryData instead of copying them. A full
// proto.Unmarshal allocates fresh slices for those byte fields on every entry
// (protobuf consumeBytesNoZero), which dominated allocation churn when many
// metadata subscribers each re-read the in-memory log window.
//
// The aliased data/key are only valid while entryData is, i.e. for the duration
// of the eachLogEntryFn callback. Callers must copy anything they retain past the
// callback; all current subscribers do (they re-decode data into their own event
// or hand it to a synchronous grpc Send).
func unmarshalLogEntryAliased(entryData []byte, out *filer_pb.LogEntry) error {
out.TsNs = 0
out.PartitionKeyHash = 0
out.Data = nil
out.Key = nil
out.Offset = 0
for i := 0; i < len(entryData); {
tag, n := binary.Uvarint(entryData[i:])
if n <= 0 {
return fmt.Errorf("bad field tag at %d", i)
}
i += n
fieldNum := tag >> 3
switch tag & 0x7 { // wire type
case 0: // varint: ts_ns / partition_key_hash / offset
v, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return fmt.Errorf("bad varint for field %d", fieldNum)
}
i += m
switch fieldNum {
case 1:
out.TsNs = int64(v)
case 2:
out.PartitionKeyHash = int32(v)
case 5:
out.Offset = int64(v)
}
case 2: // length-delimited: data / key, aliased not copied
l, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return fmt.Errorf("bad length for field %d", fieldNum)
}
i += m
if l > uint64(len(entryData)-i) {
return fmt.Errorf("field %d length %d overruns buffer", fieldNum, l)
}
switch fieldNum {
case 3:
out.Data = entryData[i : i+int(l)]
case 4:
out.Key = entryData[i : i+int(l)]
}
i += int(l)
case 1: // 64-bit
i += 8
case 5: // 32-bit
i += 4
default:
return fmt.Errorf("unknown wire type for field %d", fieldNum)
}
if i > len(entryData) {
return fmt.Errorf("field %d overruns buffer", fieldNum)
}
}
return nil
}
@@ -118,7 +118,7 @@ func TestReadFromBufferCorruption(t *testing.T) {
// Try to read - should detect corruption
startPos := MessagePosition{Time: lb.startTime}
buf, offset, err := lb.ReadFromBuffer(startPos)
buf, offset, _, err := lb.ReadFromBuffer(startPos)
// Should return corruption error
if err == nil {
@@ -148,7 +148,7 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
for testOffset := int64(0); testOffset < currentOffset; testOffset += 10 {
// Try to read from buffer
requestPosition := NewMessagePositionFromOffset(testOffset)
buf, _, err := logBuffer.ReadFromBuffer(requestPosition)
buf, _, _, err := logBuffer.ReadFromBuffer(requestPosition)
isReadable := (buf != nil && len(buf.Bytes()) > 0) || err == ResumeFromDiskError
status := "OK"
@@ -50,7 +50,7 @@ func TestBufferQueryability(t *testing.T) {
// Test immediate queryability - read from buffer starting from beginning
startPosition := NewMessagePosition(0, 0) // Start from beginning
bufferCopy, batchIndex, err := logBuffer.ReadFromBuffer(startPosition)
bufferCopy, batchIndex, _, err := logBuffer.ReadFromBuffer(startPosition)
if err != nil {
t.Fatalf("ReadFromBuffer failed: %v", err)
@@ -131,7 +131,7 @@ func TestMultipleEntriesQueryability(t *testing.T) {
// Read all entries
startPosition := NewMessagePosition(0, 0)
bufferCopy, batchIndex, err := logBuffer.ReadFromBuffer(startPosition)
bufferCopy, batchIndex, _, err := logBuffer.ReadFromBuffer(startPosition)
if err != nil {
t.Fatalf("ReadFromBuffer failed: %v", err)
@@ -207,7 +207,7 @@ func TestSchemaRegistryScenario(t *testing.T) {
// Simulate the SQL query scenario - read from offset 0
startPosition := NewMessagePosition(0, 0)
bufferCopy, _, err := logBuffer.ReadFromBuffer(startPosition)
bufferCopy, _, _, err := logBuffer.ReadFromBuffer(startPosition)
if err != nil {
t.Fatalf("Schema registry scenario failed: %v", err)
@@ -268,7 +268,7 @@ func TestTimeBasedFirstReadBeforeEarliest(t *testing.T) {
// Start read 1ns before earliest memory, with offset sentinel (-2)
startPos := NewMessagePosition(baseTs.Add(-time.Nanosecond).UnixNano(), -2)
buf, _, err := logBuffer.ReadFromBuffer(startPos)
buf, _, _, err := logBuffer.ReadFromBuffer(startPos)
if err != nil {
t.Fatalf("ReadFromBuffer returned err: %v", err)
}
@@ -293,7 +293,7 @@ func TestEarliestTimeExactRead(t *testing.T) {
}
startPos := NewMessagePosition(ts.UnixNano(), -2)
buf, _, err := logBuffer.ReadFromBuffer(startPos)
buf, _, _, err := logBuffer.ReadFromBuffer(startPos)
if err != nil {
t.Fatalf("ReadFromBuffer err: %v", err)
}
+6 -6
View File
@@ -101,7 +101,7 @@ func TestReadFromBufferTimestampBased_AfterFlushReturnsNewerData(t *testing.T) {
}
}
buf, _, err := lb.ReadFromBuffer(NewMessagePosition(sealed.stopTime.UnixNano(), sealed.offset))
buf, _, _, err := lb.ReadFromBuffer(NewMessagePosition(sealed.stopTime.UnixNano(), sealed.offset))
if err != nil {
t.Fatalf("ReadFromBuffer returned error: %v", err)
}
@@ -200,7 +200,7 @@ func TestReadFromBuffer_OldOffsetReturnsResumeFromDiskError(t *testing.T) {
requestPosition := NewMessagePositionFromOffset(tt.requestedOffset)
// Try to read from the buffer
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
// Verify the error matches expectations
if tt.expectError != nil {
@@ -257,7 +257,7 @@ func TestReadFromBuffer_OldOffsetWithNoPrevBuffers(t *testing.T) {
// Before the fix, this would return (nil, offset, nil) causing an infinite wait
// After the fix, this should return ResumeFromDiskError
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
t.Logf("DEBUG: ReadFromBuffer returned: buf=%v, batchIdx=%d, err=%v", buf != nil, batchIdx, err)
t.Logf("DEBUG: Buffer state: bufferStartOffset=%d, offset=%d, pos=%d",
@@ -295,7 +295,7 @@ func TestReadFromBuffer_EmptyBufferAtCurrentOffset(t *testing.T) {
// BUG: Without fix, this returns empty buffer instead of checking disk
// FIX: Should return ResumeFromDiskError because buffer is empty (pos=0) despite valid range
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
t.Logf("DEBUG: ReadFromBuffer returned: buf=%v, batchIdx=%d, err=%v", buf != nil, batchIdx, err)
t.Logf("DEBUG: Buffer state: bufferStartOffset=%d, offset=%d, pos=%d",
@@ -362,7 +362,7 @@ func TestReadFromBuffer_OffsetRanges(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
requestPosition := NewMessagePositionFromOffset(tc.requestedOffset)
_, _, err := lb.ReadFromBuffer(requestPosition)
_, _, _, err := lb.ReadFromBuffer(requestPosition)
if tc.expectedError != nil {
if err != tc.expectedError {
@@ -424,7 +424,7 @@ func TestReadFromBuffer_InitializedFromDisk(t *testing.T) {
// Schema Registry tries to read offset 0 (should be on disk)
requestPosition := NewMessagePositionFromOffset(0)
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
t.Logf("After writing new message:")
t.Logf(" bufferStartOffset=%d, offset=%d, pos=%d", lb.bufferStartOffset, lb.offset, lb.pos)
+18 -14
View File
@@ -6,8 +6,6 @@ import (
"fmt"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -103,6 +101,7 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
// loop through all messages
var bytesBuf *bytes.Buffer
var bytesBufPooled bool
var batchIndex int64
lastReadPosition = startPosition
var entryCounter int64
@@ -115,7 +114,7 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
// responsive 250ms cadence resumes for active readers.
caughtUpToDiskHead := false
defer func() {
if bytesBuf != nil {
if bytesBuf != nil && bytesBufPooled {
logBuffer.ReleaseMemory(bytesBuf)
}
// println("LoopProcessLogData", readerName, "sent messages total", entryCounter)
@@ -123,10 +122,11 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
for {
if bytesBuf != nil {
if bytesBuf != nil && bytesBufPooled {
logBuffer.ReleaseMemory(bytesBuf)
bytesBuf = nil // keep the deferred release from double-freeing if ReadFromBuffer panics
}
bytesBuf, batchIndex, err = logBuffer.ReadFromBuffer(lastReadPosition)
bytesBuf, batchIndex, bytesBufPooled, err = logBuffer.ReadFromBuffer(lastReadPosition)
if err == ResumeFromDiskError {
// Try to read from disk if readFromDiskFn is available
if logBuffer.ReadFromDiskFn != nil {
@@ -150,11 +150,11 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
// HasData() and ReadFromBuffer lock separately, so a racing write can make
// HasData() see data the empty-buffer read missed. Re-read; only bail if the
// position is genuinely behind the in-memory window (flushed to disk).
reBuf, _, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
reBuf, _, rePooled, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
if reErr == ResumeFromDiskError {
return lastReadPosition, isDone, ResumeFromDiskError
}
if reBuf != nil {
if reBuf != nil && rePooled {
logBuffer.ReleaseMemory(reBuf)
}
continue
@@ -261,7 +261,8 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
// data/key alias entryData; valid only within eachLogDataFn below.
if err = unmarshalLogEntryAliased(entryData, logEntry); err != nil {
glog.Errorf("unexpected unmarshal mq_pb.Message: %v", err)
pos += 4 + int(size)
continue
@@ -316,13 +317,14 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
// loop through all messages
var bytesBuf *bytes.Buffer
var bytesBufPooled bool
var offset int64
lastReadPosition = startPosition
var entryCounter int64
// See LoopProcessLogData for the caughtUpToDiskHead invariant.
caughtUpToDiskHead := false
defer func() {
if bytesBuf != nil {
if bytesBuf != nil && bytesBufPooled {
logBuffer.ReleaseMemory(bytesBuf)
}
// println("LoopProcessLogDataWithOffset", readerName, "sent messages total", entryCounter)
@@ -336,10 +338,11 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
return
}
if bytesBuf != nil {
if bytesBuf != nil && bytesBufPooled {
logBuffer.ReleaseMemory(bytesBuf)
bytesBuf = nil // keep the deferred release from double-freeing if ReadFromBuffer panics
}
bytesBuf, offset, err = logBuffer.ReadFromBuffer(lastReadPosition)
bytesBuf, offset, bytesBufPooled, err = logBuffer.ReadFromBuffer(lastReadPosition)
glog.V(4).Infof("ReadFromBuffer for %s returned bytesBuf=%v, offset=%d, err=%v", readerName, bytesBuf != nil, offset, err)
// Check for buffer corruption error before other error handling
@@ -375,11 +378,11 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
// HasData() and ReadFromBuffer lock separately, so a racing write can make
// HasData() see data the empty-buffer read missed. Re-read; only bail if the
// position is genuinely behind the in-memory window (flushed to disk).
reBuf, _, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
reBuf, _, rePooled, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
if reErr == ResumeFromDiskError {
return lastReadPosition, isDone, ResumeFromDiskError
}
if reBuf != nil {
if reBuf != nil && rePooled {
logBuffer.ReleaseMemory(reBuf)
}
continue
@@ -523,7 +526,8 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
// data/key alias entryData; valid only within eachLogDataFn below.
if err = unmarshalLogEntryAliased(entryData, logEntry); err != nil {
glog.Errorf("unexpected unmarshal mq_pb.Message: %v", err)
pos += 4 + int(size)
continue
+230
View File
@@ -0,0 +1,230 @@
package log_buffer
import (
"bytes"
"math"
"math/rand"
"testing"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// readTsNs must return exactly what a full proto.Unmarshal would put in TsNs,
// for every field combination, without decoding data/key.
func TestReadTsNsMatchesUnmarshal(t *testing.T) {
cases := []*filer_pb.LogEntry{
{}, // all defaults: ts_ns absent on the wire => 0
{TsNs: 1}, // minimal
{TsNs: 1783396413597780505}, // realistic nanosecond timestamp
{TsNs: math.MaxInt64}, // 9-byte varint
{TsNs: -1}, // negative int64 => 10-byte varint
{TsNs: math.MinInt64}, // extreme negative
{TsNs: 42, PartitionKeyHash: 7}, // ts followed by another varint field
{TsNs: 12345, Data: []byte("some-metadata-event-payload"), Key: []byte("/buckets/pvc-x/1.log")},
{TsNs: 99, Data: make([]byte, 64*1024), Key: []byte("k"), Offset: 555}, // large data, all fields
{Data: []byte("no-ts"), Key: []byte("k"), Offset: 9}, // ts_ns == 0 with other fields present
}
for i, e := range cases {
data, err := proto.Marshal(e)
if err != nil {
t.Fatalf("case %d marshal: %v", i, err)
}
got, err := readTsNs(data)
if err != nil {
t.Fatalf("case %d readTsNs: %v", i, err)
}
if got != e.TsNs {
t.Errorf("case %d: readTsNs=%d want %d", i, got, e.TsNs)
}
}
}
// Fuzz against proto.Unmarshal with randomized entries.
func TestReadTsNsFuzz(t *testing.T) {
r := rand.New(rand.NewSource(1))
for i := 0; i < 5000; i++ {
e := &filer_pb.LogEntry{
TsNs: r.Int63() - r.Int63(),
PartitionKeyHash: r.Int31(),
Offset: r.Int63(),
}
if r.Intn(2) == 0 {
e.Data = make([]byte, r.Intn(300))
r.Read(e.Data)
}
if r.Intn(2) == 0 {
e.Key = make([]byte, r.Intn(64))
r.Read(e.Key)
}
data, err := proto.Marshal(e)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var want filer_pb.LogEntry
if err := proto.Unmarshal(data, &want); err != nil {
t.Fatalf("unmarshal: %v", err)
}
got, err := readTsNs(data)
if err != nil {
t.Fatalf("readTsNs iter %d: %v", i, err)
}
if got != want.TsNs {
t.Fatalf("iter %d: readTsNs=%d want %d", i, got, want.TsNs)
}
}
}
// readTsNs must not panic and must report an error on truncated/garbage input.
func TestReadTsNsCorrupted(t *testing.T) {
inputs := [][]byte{
{0x08}, // ts_ns tag with no value
{0x1a, 0xff, 0xff, 0xff}, // data field, length overruns buffer
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}, // overlong tag
}
for i, in := range inputs {
if _, err := readTsNs(in); err == nil {
t.Errorf("input %d: expected error, got nil", i)
}
}
}
// unmarshalLogEntryAliased must produce the same fields as proto.Unmarshal.
func TestUnmarshalLogEntryAliasedMatchesUnmarshal(t *testing.T) {
r := rand.New(rand.NewSource(2))
for i := 0; i < 5000; i++ {
e := &filer_pb.LogEntry{
TsNs: r.Int63() - r.Int63(),
PartitionKeyHash: r.Int31() - r.Int31(),
Offset: r.Int63() - r.Int63(),
}
if r.Intn(2) == 0 {
e.Data = make([]byte, r.Intn(4096))
r.Read(e.Data)
}
if r.Intn(2) == 0 {
e.Key = make([]byte, r.Intn(128))
r.Read(e.Key)
}
data, err := proto.Marshal(e)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var want, got filer_pb.LogEntry
if err := proto.Unmarshal(data, &want); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if err := unmarshalLogEntryAliased(data, &got); err != nil {
t.Fatalf("aliased iter %d: %v", i, err)
}
if got.TsNs != want.TsNs || got.PartitionKeyHash != want.PartitionKeyHash ||
got.Offset != want.Offset || !bytes.Equal(got.Data, want.Data) || !bytes.Equal(got.Key, want.Key) {
t.Fatalf("iter %d mismatch:\n got=%+v\nwant=%+v", i, &got, &want)
}
}
}
// The decoded data/key must point into the source buffer, not a copy.
func TestUnmarshalLogEntryAliasedAliases(t *testing.T) {
data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: 5, Data: []byte("payload"), Key: []byte("path")})
if err != nil {
t.Fatal(err)
}
var out filer_pb.LogEntry
if err := unmarshalLogEntryAliased(data, &out); err != nil {
t.Fatal(err)
}
if string(out.Data) != "payload" || string(out.Key) != "path" {
t.Fatalf("decoded data=%q key=%q", out.Data, out.Key)
}
for i := range data { // mutate source; an alias must observe it, a copy must not
data[i] ^= 0xFF
}
if string(out.Data) == "payload" || string(out.Key) == "path" {
t.Fatal("data/key were copied, expected an alias into the source buffer")
}
}
// sampleEntryData returns a marshaled LogEntry whose Data is a realistic
// marshaled metadata event, as delivered on the subscribe path.
func sampleEntryData(tb testing.TB) []byte {
event := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/pvc-bf458866-0413-4cca-99c6-3b7386a80855",
EventNotification: &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "object-000123",
Attributes: &filer_pb.FuseAttributes{FileSize: 4096, Mtime: 1783396413},
Chunks: []*filer_pb.FileChunk{
{FileId: "3,01637037d6", Size: 4096, Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 23283, Cookie: 2015}},
},
},
},
}
payload, err := proto.Marshal(event)
if err != nil {
tb.Fatal(err)
}
data, err := proto.Marshal(&filer_pb.LogEntry{
TsNs: 1783396413597780505, PartitionKeyHash: 12345, Offset: 2013258,
Key: []byte("/buckets/pvc-bf458866/object-000123"), Data: payload,
})
if err != nil {
tb.Fatal(err)
}
return data
}
// Per-entry decode cost on the delivery path: the old full unmarshal copies the
// data/key byte fields; the aliased decode does not. The delta is what the fix
// saves for every entry a subscriber reads (and, for non-matching entries a
// subscriber filters out, the whole saving with nothing decoded downstream).
func BenchmarkLogEntryDecodeCopy(b *testing.B) {
data := sampleEntryData(b)
var out filer_pb.LogEntry
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := proto.Unmarshal(data, &out); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkLogEntryDecodeAlias(b *testing.B) {
data := sampleEntryData(b)
var out filer_pb.LogEntry
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := unmarshalLogEntryAliased(data, &out); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkReadTs(b *testing.B) {
e := &filer_pb.LogEntry{
TsNs: 1783396413597780505,
PartitionKeyHash: 12345,
Data: make([]byte, 4*1024), // typical metadata event payload
Key: []byte("/buckets/pvc-bf458866/1.log"),
Offset: 2013258,
}
data, err := proto.Marshal(e)
if err != nil {
b.Fatal(err)
}
buf := make([]byte, 4+len(data))
util.Uint32toBytes(buf, uint32(len(data)))
copy(buf[4:], data)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, _, err := readTs(buf, 0); err != nil {
b.Fatal(err)
}
}
}
+22
View File
@@ -2,6 +2,7 @@ package log_buffer
import (
"fmt"
"sync"
"time"
)
@@ -12,6 +13,25 @@ type MemBuffer struct {
stopTime time.Time
startOffset int64 // First offset in this buffer
offset int64 // Last offset in this buffer (endOffset)
// snapshot is a GC-owned copy of buf[:size] shared by all readers of this
// sealed window, so N subscribers reading the same window cost one copy
// instead of N pooled copies. Created lazily by the first reader; travels
// with the window when SealBuffer shifts slots. Immutable once created.
snapMu sync.Mutex
snapshot []byte
}
// sharedSnapshot returns the shared read-only copy of this sealed window,
// creating it on first use. Callers must hold the LogBuffer read lock, which
// keeps buf stable (SealBuffer mutates slots only under the write lock).
func (mb *MemBuffer) sharedSnapshot() []byte {
mb.snapMu.Lock()
defer mb.snapMu.Unlock()
if mb.snapshot == nil {
mb.snapshot = append([]byte(nil), mb.buf[:mb.size]...)
}
return mb.snapshot
}
type SealedBuffers struct {
@@ -41,6 +61,7 @@ func (sbs *SealedBuffers) SealBuffer(startTime, stopTime time.Time, buf []byte,
sbs.buffers[i].stopTime = sbs.buffers[i+1].stopTime
sbs.buffers[i].startOffset = sbs.buffers[i+1].startOffset
sbs.buffers[i].offset = sbs.buffers[i+1].offset
sbs.buffers[i].snapshot = sbs.buffers[i+1].snapshot // snapshot follows its window
}
sbs.buffers[size-1].buf = buf
sbs.buffers[size-1].size = pos
@@ -48,6 +69,7 @@ func (sbs *SealedBuffers) SealBuffer(startTime, stopTime time.Time, buf []byte,
sbs.buffers[size-1].stopTime = stopTime
sbs.buffers[size-1].startOffset = startOffset
sbs.buffers[size-1].offset = endOffset
sbs.buffers[size-1].snapshot = nil
return oldBuf
}
@@ -0,0 +1,275 @@
package log_buffer
import (
"fmt"
"runtime/debug"
"sync"
"testing"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func addEntries(tb testing.TB, lb *LogBuffer, n int, payloadSize int, tag string) {
payload := make([]byte, payloadSize)
for i := 0; i < n; i++ {
key := []byte(fmt.Sprintf("/%s/%d", tag, i))
if err := lb.AddDataToBuffer(key, payload, time.Now().UnixNano()); err != nil {
tb.Fatal(err)
}
}
}
// Sealed-window reads must hand every reader the same shared snapshot rather
// than a fresh copy each.
func TestSealedReadsShareOneSnapshot(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 10, 1024, "a")
lb.ForceFlush() // seal the window
addEntries(t, lb, 1, 1024, "b")
pos := NewMessagePosition(1, -2) // far in the past => sealed window hit
buf1, _, pooled1, err1 := lb.ReadFromBuffer(pos)
buf2, _, pooled2, err2 := lb.ReadFromBuffer(pos)
if err1 != nil || err2 != nil {
t.Fatalf("read errors: %v %v", err1, err2)
}
if buf1 == nil || buf2 == nil {
t.Fatal("expected sealed data in memory")
}
if pooled1 || pooled2 {
t.Fatalf("sealed reads should not be pooled copies: %v %v", pooled1, pooled2)
}
b1, b2 := buf1.Bytes(), buf2.Bytes()
if len(b1) == 0 || len(b1) != len(b2) {
t.Fatalf("unexpected lengths %d %d", len(b1), len(b2))
}
if &b1[0] != &b2[0] {
t.Fatal("sealed reads made independent copies; expected one shared snapshot")
}
}
// A shared snapshot must stay intact after its window rotates out and the
// backing array is recycled and overwritten by new writes.
func TestSharedSnapshotSurvivesRecycle(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 5, 2048, "keep")
lb.ForceFlush()
pos := NewMessagePosition(1, -2)
buf, _, pooled, err := lb.ReadFromBuffer(pos)
if err != nil || buf == nil || pooled {
t.Fatalf("expected shared sealed read, got buf=%v pooled=%v err=%v", buf != nil, pooled, err)
}
before := append([]byte(nil), buf.Bytes()...)
// Rotate the sealed window all the way out so its array is recycled and
// overwritten with different content.
for i := 0; i < PreviousBufferCount+1; i++ {
addEntries(t, lb, 5, 2048, "overwrite")
lb.ForceFlush()
}
addEntries(t, lb, 5, 2048, "overwrite")
if string(before) != string(buf.Bytes()) {
t.Fatal("shared snapshot content changed after its window was recycled")
}
}
// Race test: concurrent lagging readers against a writer that keeps sealing
// and recycling windows. Every delivered entry must unmarshal cleanly with the
// expected payload — corruption here means a reader saw recycled bytes.
func TestSharedSnapshotConcurrentIntegrity(t *testing.T) {
// The writer below is deliberately unthrottled, so transient marshal garbage
// scales with host speed; on linux/386 a fast runner can hit the 4GB
// address-space ceiling. Cap the heap so the GC paces the writer instead.
prevLimit := debug.SetMemoryLimit(1 << 30)
defer debug.SetMemoryLimit(prevLimit)
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
const payloadByte = 0x5A
payload := make([]byte, 8*1024)
for i := range payload {
payload[i] = payloadByte
}
var stop sync.WaitGroup
done := make(chan struct{})
stop.Add(1)
go func() { // writer: fill and seal aggressively so arrays recycle under the readers
defer stop.Done()
for i := 0; ; i++ {
select {
case <-done:
return
default:
}
if err := lb.AddDataToBuffer([]byte(fmt.Sprintf("/k/%d", i)), payload, time.Now().UnixNano()); err != nil {
t.Error(err)
return
}
if i%200 == 0 {
lb.ForceFlush()
}
}
}()
var readers sync.WaitGroup
errCh := make(chan error, 16)
for r := 0; r < 8; r++ {
readers.Add(1)
go func(r int) {
defer readers.Done()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
start := NewMessagePosition(time.Now().Add(-500*time.Millisecond).UnixNano(), -2)
lb.LoopProcessLogData(fmt.Sprintf("r%d", r), start, 0,
func() bool { return time.Now().Before(deadline) },
func(le *filer_pb.LogEntry) (bool, error) {
if len(le.Data) != len(payload) {
err := fmt.Errorf("payload length %d, want %d", len(le.Data), len(payload))
select {
case errCh <- err:
default:
}
return true, err
}
for _, b := range le.Data {
if b != payloadByte {
err := fmt.Errorf("corrupted payload byte %x", b)
select {
case errCh <- err:
default:
}
return true, err
}
}
return false, nil
})
}
}(r)
}
readers.Wait()
close(done)
stop.Wait()
select {
case err := <-errCh:
t.Fatal(err)
default:
}
}
// Current-window reads must share the prefix snapshot: two behind-readers get
// views of the same backing array, and the view content must stay intact while
// the writer keeps appending and eventually seals and recycles the window.
func TestCurrentWindowPrefixSharing(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 8, 1024, "cur")
pos := NewMessagePosition(1, -2) // behind => full current-window read
buf1, _, pooled1, err1 := lb.ReadFromBuffer(pos)
buf2, _, pooled2, err2 := lb.ReadFromBuffer(pos)
if err1 != nil || err2 != nil || buf1 == nil || buf2 == nil {
t.Fatalf("reads: %v %v %v %v", buf1 != nil, err1, buf2 != nil, err2)
}
if pooled1 || pooled2 {
t.Fatalf("current-window behind-reads should be shared, got pooled %v %v", pooled1, pooled2)
}
b1, b2 := buf1.Bytes(), buf2.Bytes()
if len(b1) == 0 || len(b1) != len(b2) || &b1[0] != &b2[0] {
t.Fatalf("expected one shared prefix snapshot, lens %d %d", len(b1), len(b2))
}
before := append([]byte(nil), b1...)
// Keep appending: the prefix must be extended, not reallocated or mutated.
addEntries(t, lb, 8, 1024, "more")
buf3, _, _, err3 := lb.ReadFromBuffer(pos)
if err3 != nil || buf3 == nil {
t.Fatalf("read3: %v %v", buf3 != nil, err3)
}
if len(buf3.Bytes()) <= len(before) {
t.Fatalf("extended read %d should exceed first read %d", len(buf3.Bytes()), len(before))
}
if string(buf3.Bytes()[:len(before)]) != string(before) {
t.Fatal("prefix changed when the snapshot was extended")
}
// Seal + rotate the window fully out; earlier views must stay intact.
for i := 0; i < PreviousBufferCount+1; i++ {
lb.ForceFlush()
addEntries(t, lb, 4, 1024, "rotate")
}
if string(b1) != string(before) {
t.Fatal("shared current-window view changed after seal and recycle")
}
}
// A sealed window whose prefix snapshot was fully extended must reuse it
// rather than re-copying on the first sealed read.
func TestSealHandsOffCompleteSnapshot(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 6, 512, "h")
pos := NewMessagePosition(1, -2)
buf1, _, _, err := lb.ReadFromBuffer(pos) // extends prefix snapshot to full window
if err != nil || buf1 == nil {
t.Fatalf("read1: %v %v", buf1 != nil, err)
}
lb.ForceFlush()
addEntries(t, lb, 1, 512, "next")
buf2, _, pooled, err := lb.ReadFromBuffer(pos) // sealed read of the same window
if err != nil || buf2 == nil || pooled {
t.Fatalf("read2: buf=%v pooled=%v err=%v", buf2 != nil, pooled, err)
}
b1, b2 := buf1.Bytes(), buf2.Bytes()
if len(b1) == 0 || len(b1) > len(b2) || &b1[0] != &b2[0] {
t.Fatalf("sealed read should reuse the handed-off snapshot (lens %d %d)", len(b1), len(b2))
}
}
// Sanity: sealed-read content must byte-match what a proto round-trip expects.
func TestSharedSnapshotContentMatches(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 3, 512, "x")
lb.ForceFlush()
buf, _, _, err := lb.ReadFromBuffer(NewMessagePosition(1, -2))
if err != nil || buf == nil {
t.Fatalf("read: buf=%v err=%v", buf != nil, err)
}
data := buf.Bytes()
count := 0
for pos := 0; pos+4 < len(data); {
size, _, err := readTs(data, pos)
if err != nil {
t.Fatalf("entry %d: %v", count, err)
}
var le filer_pb.LogEntry
if err := proto.Unmarshal(data[pos+4:pos+4+size], &le); err != nil {
t.Fatalf("entry %d unmarshal: %v", count, err)
}
if want := fmt.Sprintf("/x/%d", count); string(le.Key) != want {
t.Fatalf("entry %d key %q, want %q", count, le.Key, want)
}
pos += 4 + size
count++
}
if count != 3 {
t.Fatalf("read %d entries, want 3", count)
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
var (
MAJOR_VERSION = int32(4)
MINOR_VERSION = int32(38)
MINOR_VERSION = int32(39)
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
VERSION = util.SizeLimit + " " + VERSION_NUMBER
COMMIT = ""
+48 -5
View File
@@ -723,19 +723,23 @@ func (h *VolumeBalanceHandler) executeSingleMove(
return err
}
if err := task.Execute(execCtx, params); err != nil {
execErr := h.checkMoveStillValid(execCtx, request.GetClusterContext().GetMasterGrpcAddresses(), params.VolumeId, params.Sources[0].Node, params.Targets[0].Node)
if execErr == nil {
execErr = task.Execute(execCtx, params)
}
if execErr != nil {
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
State: plugin_pb.JobState_JOB_STATE_FAILED,
ProgressPercent: 100,
Stage: "failed",
Message: err.Error(),
Message: execErr.Error(),
Activities: []*plugin_pb.ActivityEvent{
pluginworker.BuildExecutorActivity("failed", err.Error()),
pluginworker.BuildExecutorActivity("failed", execErr.Error()),
},
})
return err
return execErr
}
sourceNode := params.Sources[0].Node
@@ -766,6 +770,41 @@ func (h *VolumeBalanceHandler) executeSingleMove(
})
}
// checkMoveStillValid re-checks a planned move against the master's live
// view right before executing it. The admin lock is released between
// detection and execution, so the plan can go stale: the volume may have
// left the source, or the target may have gained a replica that the copy
// would overwrite and the source delete would then reduce to a single copy.
// Without master addresses (older admin) the check is skipped and the move
// relies on the task's own execution-time guards.
func (h *VolumeBalanceHandler) checkMoveStillValid(ctx context.Context, masterAddresses []string, volumeID uint32, sourceNode, targetNode string) error {
if len(masterAddresses) == 0 {
glog.Warningf("volume balance: no master addresses in cluster context, skipping pre-move check for volume %d", volumeID)
return nil
}
locations, err := pluginworker.LookupVolumeLocations(ctx, masterAddresses, h.grpcDialOption, volumeID)
if err != nil {
return fmt.Errorf("pre-move check for volume %d: %w", volumeID, err)
}
return checkMovePreconditions(locations, volumeID, sourceNode, targetNode)
}
func checkMovePreconditions(locations []string, volumeID uint32, sourceNode, targetNode string) error {
sourceFound := false
for _, location := range locations {
switch strings.TrimSpace(location) {
case targetNode:
return fmt.Errorf("stale move: volume %d already has a replica on target %s", volumeID, targetNode)
case sourceNode:
sourceFound = true
}
}
if !sourceFound {
return fmt.Errorf("stale move: volume %d is no longer on source %s", volumeID, sourceNode)
}
return nil
}
// executeBatchMoves runs multiple volume moves concurrently within a single job.
func (h *VolumeBalanceHandler) executeBatchMoves(
ctx context.Context,
@@ -881,6 +920,7 @@ func (h *VolumeBalanceHandler) executeBatchMoves(
sem := make(chan struct{}, maxConcurrent)
results := make(chan moveResult, totalMoves)
masterAddresses := request.GetClusterContext().GetMasterGrpcAddresses()
for i, move := range moves {
sem <- struct{}{} // acquire slot
@@ -899,7 +939,10 @@ func (h *VolumeBalanceHandler) executeBatchMoves(
})
moveParams := buildMoveTaskParams(m, bp)
err := task.Execute(batchCtx, moveParams)
err := h.checkMoveStillValid(batchCtx, masterAddresses, m.VolumeId, m.SourceNode, m.TargetNode)
if err == nil {
err = task.Execute(batchCtx, moveParams)
}
results <- moveResult{
index: idx,
volumeID: m.VolumeId,
@@ -503,6 +503,9 @@ func TestExecuteDispatchesBatchPath(t *testing.T) {
err = handler.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: job,
}, sender)
if err != nil {
t.Fatalf("handler.Execute: %v", err)
}
// Expect an error since no real volume servers exist
// But verify the batch path was taken by checking the assigned message
@@ -792,3 +795,30 @@ func (r *recordingDetectionSender) SendActivity(event *plugin_pb.ActivityEvent)
}
return nil
}
func TestCheckMovePreconditions(t *testing.T) {
tests := []struct {
name string
locations []string
wantErr string
}{
{"valid move", []string{"10.0.0.1:8080", "10.0.0.3:8080"}, ""},
{"volume left the source", []string{"10.0.0.3:8080"}, "no longer on source"},
{"volume gone entirely", nil, "no longer on source"},
{"target already has a replica", []string{"10.0.0.1:8080", "10.0.0.2:8080"}, "already has a replica on target"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := checkMovePreconditions(tt.locations, 5, "10.0.0.1:8080", "10.0.0.2:8080")
if tt.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("expected error containing %q, got %v", tt.wantErr, err)
}
})
}
}