Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 b89d7e36bf install.sh: offer the vector engine on linux only
Releases build weed-vector for linux amd64/arm64 only, so --component vector
on darwin or windows downloaded a missing asset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK
2026-11-14 11:26:49 -08:00
b067266e6b shell: fix s3.circuitBreaker help examples and error messages (#12657)
* shell: fix s3.circuitBreaker help examples and error messages

The help examples used -type count, but -type accepts Count and MB (as
its flag description says), so both examples failed with "type not
valid, only 'count' and 'bytes' are allowed", an error that names
neither accepted value. Two other errors pointed at flags that do not
exist: -max and -counts, where the flag is -values.

Use -type Count in the examples, name Count and MB in the type error,
and -values in the value errors. TestCircuitBreakerHelpExamplesRun runs
every help example and fails on master for the two -type count lines.

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>

* shell: name the bad action and the -actions flag in s3.circuitBreaker

The unknown-action error pointed at a nonexistent -action flag and echoed
the whole -actions list instead of the action that was rejected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:17:52 -08:00
b3a58506aa filer: report a SQL listing that fails partway through (#12654)
* filer: report a SQL listing that fails partway through

ListDirectoryPrefixedEntries never checked rows.Err() after its rows.Next()
loop. When the result set failed partway, for example on a lost
connection, rows.Next() returned false and the listing returned the
entries read so far with a nil error, so callers saw a shorter directory
instead of an error. Check rows.Err() once the loop has run to the end,
as the scan in abstract_sql_store_scan.go already does. A listing the
callback stopped on purpose is left alone: rows.Err() would return a
canceled request context's error there.

This covers every store built on AbstractSqlStore (mysql, mysql2,
postgres, postgres2, sqlite).

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>

* filer: wait for the canceled SQL listing to release its rows in the test

A fixed sleep let the callback return before database/sql closed the
rows, so a listing that always consulted rows.Err could still pass.
Wait, bounded, until the connection is back in the pool instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:14:54 -08:00
anantandanant b42993d24a shell: make TestCircuitBreakerShell compare against the expected configs (#12656)
The test unmarshalled the command's output into both actual and expect,
so it compared the output with itself and the expected JSON in each case
was never checked; it also skipped the first case. Compare every case's
output with its expected config as S3CircuitBreakerConfig messages (the
output includes default fields such as "enabled": false that the
expected JSON leaves out), and restore LoadConfig when the test ends.

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: anant <170962632+antcybersec@users.noreply.github.com>
2026-11-14 11:14:14 -08:00
Chris LuandClaude Opus 5.5 fd4603d657 s3 lifecycle: count filer entries a walk reads but skips as progress (#12658)
* dailyrun: count entries read from the filer, skipped ones included

A versioned bucket's pre-pass and a resumed walk read entries without
emitting them, so a walk can read for hours with no visited entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: count listed entries as progress work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:12:33 -08:00
Chris LuandClaude Opus 5.5 53377bcb5d mount: keep a handle dirty when a write lands during its flush (#12652)
A flush uploads the dirty pages without the handle lock, then commits the
entry under it. A write in between grows the entry's size, but its pages
are not in the committed chunks. Clearing dirtyMetadata then made the next
flush skip the commit, leaving a file with the new size and no chunk for
the write, which reads back as zeros.

Count page writes on the handle and clear dirtyMetadata only when none
landed since the flush started uploading.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:11:01 -08:00
1167ca8cf5 vacuum: report a request dropped because another vacuum is running (#12648)
* vacuum: report a request dropped because another vacuum is running

The master runs one vacuum at a time. A request that arrives while
another one is running, the automatic vacuum or an earlier request, is
dropped: Topology.Vacuum logs "Vacuum is already running" and returns.
The VacuumVolume RPC and /vol/vacuum then answered as if the vacuum had
run, so volume.vacuum printed nothing and exited 0 with no volume
compacted. Where the automatic vacuum is busy for hours, an explicit
volume.vacuum -volumeId could do nothing every time, and nothing said so.

Topology.Vacuum now returns ErrVacuumRunning for a dropped request. The
RPC returns it and /vol/vacuum answers 409 with it. volume.vacuum names
the request that failed, because a list of volumes or collections is
sent as several requests and a vacuum that starts in between fails only
the later ones. Requests are still dropped, not queued, and the
automatic vacuum ignores the error as before.

The integration tests that need their /vol/vacuum request to run ask
again while the master answers 409.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* docs: note the 409 answer from /vol/vacuum while another vacuum runs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-14 11:07:44 -08:00
Chris LuandClaude Opus 5.5 512f898600 s3 lifecycle: report work-based job progress during a pass (#12644)
* s3 lifecycle: report work-based job progress during a pass

The daily pass sent progress only while starting, so a healthy scan that
ran for many hours could reach the admin's 24-hour no-progress guard.
Worker heartbeats prove the worker is alive, not that this job moves.

While dailyrun.Run is in progress the handler now sends a progress update
every 5 minutes, and only when the pass's counters (entries visited,
replay events, RPC outcomes including errors) moved since the last
delivered update. An idle tick sends nothing, so a stalled pass still
expires. A failed send is retried on the next tick. The reporter is
stopped and joined before the completion is sent, so no progress can
follow the terminal result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: test that progress, not heartbeats, keeps an old job active

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: label progress phase and bucket as the last started

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:55:08 -08:00
Chris LuandClaude Opus 5.5 858f8cbad8 s3 lifecycle: check internal S3 authentication before starting a pass (#12645)
* s3 lifecycle: add a LifecycleReady RPC that only authorizes the caller

LifecycleReady runs the same checkAdminAuth as LifecycleDelete and reads
no bucket or object metadata, so a lifecycle worker can confirm that an S3
front accepts its internal credentials before it starts a pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: check S3 fronts with LifecycleReady before the pass

Execute used to dial the first registered S3 front and start loading
policies and walking buckets, so a missing or mismatched
jwt.filer_signing.key surfaced only as repeated per-bucket delete
failures. It now checks each front in order with LifecycleReady, using
the credentials LifecycleDelete sends, under a 10s bound that also
follows parent cancellation. The first front that passes serves the
pass; fronts that fail are reported in the job's progress and the log.
When none passes, the job fails before any listing with an error that
names the front and says whether this worker has the key set, without
key or token material. Fronts that predate LifecycleReady are checked
with an empty LifecycleDelete, which they authorize and then reject
before any lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:53:07 -08:00
Chris LuandClaude Opus 5.5 c819e3fbea s3 lifecycle: per-pass run results and last full-pass status (#12643)
* s3 lifecycle: collect per-pass bucket results and work counters

WalkBuckets kept only the first bucket error and logged the rest. A
RunStats shared by the walker, the walker dispatcher and the replay
drain now records every bucket's walk result (walked, failed, skipped
on cancellation), entry and object visits, replay events, and
LifecycleDelete outcomes under the dispatch_total outcome labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: persist the last fully successful pass

Shard cursors and walk timestamps advance on partial passes as well, so
neither says when lifecycle last covered every policy. Keep that in its
own record next to the cursors, plus a worker gauge for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: report each pass's result in the job record

The job ended with a fixed success summary, or with only the first error,
and malformed lifecycle policies were V(1) logs. The completion now
carries the pass status (complete, partial, failed, canceled), bucket
totals and failures, invalid policies, entry, object and event counts,
LifecycleDelete outcomes, the last phase and bucket, the elapsed time
and the last full pass, on failed passes as well.

Only a complete pass advances the full-pass record; a malformed policy
makes the pass partial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep a failed job's result in its record

Completions with Success=false dropped Result.Summary and
Result.OutputValues, so a handler could not report what a failed run
had done, which buckets failed, or how far it got. Keep them; the error
message still drives the job's message and run record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: chart the time since the last full lifecycle pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a replay halted on an unresolved delete is a partial pass

BLOCKED, RETRY_LATER and exhausted transport retries stop a shard's
replay without an error, leaving its due events for a later pass. Count
those shards and report the pass as partial, so it no longer advances
the full-pass record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a pass with throttled walks is not a full pass

WalkerInterval can skip the walk for walk-only rules (ExpirationDate,
ExpiredDeleteMarker, NewerNoncurrent) with no error. Count those shards
and keep the full-pass record for passes that evaluated every rule; the
job reports full_pass and walks_deferred.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: keep the saved full-pass time when the save fails

Publishing a timestamp that never reached the filer let the gauge move
back on the next job's reload. Keep the previous value and report the
save error in the job result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: drop a failed attempt's summary when the retry reports none

Retries reuse the job record, and failed completions now keep their
result summary, so a retry that completes without a Result showed the
failed attempt's summary, and a successful one used it as its message.
Clear the summary when a completion carries no Result, as the output
values already are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:50:37 -08:00
Chris LuandClaude Opus 5.5 6ad4b07598 mount: scope and order the final-release writeback fence (#12651)
* mount: fence a dropped handle only when it holds unpublished content

dirtyMetadata is also set by chmod, xattr and fallocate, so a failed
metadata-only close refused every later write of the inode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fence the inode before its last handle leaves the handle map

A reopen between the map removal and the fence could publish at the
stale kernel EOF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fence a failed metadata flush only when the handle holds content

A refused synchronous flush or an abandoned writeback metadata flush of a
handle with only chmod, xattr or fallocate changes fenced the inode, so
later writes were refused until FORGET.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: count a size change on an open handle as unpublished content

A truncate or extend through an open handle changes the entry's size and
chunks, but it set only dirtyMetadata. A failed close then skipped the
final-release fence, so a reopen before FORGET could publish against the
untruncated entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: mark copied content dirty before each page of a streaming copy

A copy that failed or was cancelled after earlier pages were accepted left
dirtyContent false, so the final-release fence skipped that content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: mark copied content dirty only after a page is accepted

A copy whose first page is rejected leaves the destination unchanged and
the kernel EOF where it was, so fencing the inode on release only blocked
later writes until FORGET.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: skip the server-side copy while the destination holds unpublished content

A whole-file server copy clears dirtyContent when it commits, so a page a
cancelled streaming copy left behind would lose its release fence. Fall
back to the streaming copy instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: skip the server-side copy while the source holds unpublished content

The filer copies the stored source, so pages still pending on the source
handle would be missing from the destination. The streaming copy reads
them through the dirty pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check the publication fence before a server-side whole-file copy

The filer copy publishes the destination without going through the
flush-time guard, so a fenced writeback inode could still take new
content before FORGET. Fall back to the streaming copy, whose flush is
guarded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:47:33 -08:00
Ping Qiu 65ecb6aa12 fix(mount): prevent negative activity-score shifts (#12631)
fix(mount): bound activity decay shifts across time regressions
2026-11-14 10:46:57 -08:00
Chris LuandClaude Opus 5.5 0a38738076 filer: keep the listing snapshot below later and unfinished event stamps (#12642)
filer: take the listing snapshot as a claim below later and unfinished stamps

A ListEntries snapshot tells the client that every event at or below it is
already in the listing, so the mount drops those events from a directory
build and fences them with the directory floor. The snapshot was a raw
time.Now(), which an event stamp can tie on a coarse clock: on Windows a
mkdir right after a listing of its parent was stamped with the snapshot's
own timestamp, the mount took it as listed, and the new directory stayed
missing from a parent marked cached. A create stamped before the snapshot
but not yet in the store was dropped the same way.

Take the snapshot through the same in-flight claim the idle heartbeat uses:
it stays below every unfinished stamp, and every later stamp lands above it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 01:17:51 -08:00
10f8b2d5b1 mount: guard peer-truncate gaps, stale append EOF, and terminal writeback refusal (#12630)
* mount: guard append gaps over concurrent content merges

* mount: fence a writeback inode when its async publication is abandoned

A drain that gives up on a non-precondition error left the token clear, so a
reopened writeback handle could publish past the stored EOF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fence a writeback inode when its async data flush fails

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fence the inode when its last handle drops uncommitted content

A synchronous release whose final flush fails destroys the handle's dirty
pages, while under writeback the kernel EOF already counts them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 01:13:37 -08:00
65 changed files with 3864 additions and 263 deletions

No files matched your search

+4
View File
@@ -271,6 +271,10 @@ curl "http://localhost:9333/vol/vacuum?garbageThreshold=0.4"
Vacuuming makes a volume read-only, copies live needles to a new volume, and
swaps it in.
The master runs one vacuum at a time. A request that arrives while the
automatic vacuum or another request is running does nothing and gets
`409 Conflict` with `{"error":"another vacuum is running, try again later"}`.
### Delete a collection
```bash
+9 -19
View File
@@ -157,19 +157,16 @@ worker_asset_name() {
echo "weed-worker_${os}_${arch}.tar.gz"
}
# The vector engine behind the S3 Vectors API, built like the worker.
# The vector engine behind the S3 Vectors API, published for linux only like
# the worker.
vector_asset_name() {
local os="$1" arch="$2"
if [ "$os" = "windows" ]; then
echo "weed-vector_${os}_${arch}.zip"
else
echo "weed-vector_${os}_${arch}.tar.gz"
fi
echo "weed-vector_${os}_${arch}.tar.gz"
}
vector_platform_supported() {
case "$1/$2" in
linux/amd64|linux/arm64|darwin/amd64|darwin/arm64|windows/amd64) return 0 ;;
linux/amd64|linux/arm64) return 0 ;;
*) return 1 ;;
esac
}
@@ -283,26 +280,19 @@ install_component() {
;;
vector)
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}"
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}. Supported: linux/amd64, linux/arm64"
asset_name="$(vector_asset_name "$os" "$arch")"
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
download "$download_url" "${tmpdir}/${asset_name}"
info "Extracting ${asset_name}..."
local vector_name="weed-vector"
if [ "$os" = "windows" ]; then
command -v unzip >/dev/null || error "unzip is required for Windows vector archives"
unzip -q "${tmpdir}/${asset_name}" -d "$tmpdir"
vector_name="weed-vector.exe"
else
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
fi
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
local vector_bin
vector_bin="$(find "$tmpdir" -name "$vector_name" -type f | head -1)"
[ -n "$vector_bin" ] || error "Could not find $vector_name binary in archive"
vector_bin="$(find "$tmpdir" -name weed-vector -type f | head -1)"
[ -n "$vector_bin" ] || error "Could not find weed-vector binary in archive"
chmod +x "$vector_bin"
install_binary "$vector_bin" "$vector_name"
install_binary "$vector_bin" weed-vector
VECTOR_INSTALLED=true
ok "Installed weed-vector to ${INSTALL_DIR}/weed-vector"
;;
+96
View File
@@ -10263,6 +10263,102 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Time Since Last Full Lifecycle Pass",
"description": "Time since a pass covered every shard and lifecycle policy without an error; never excluded",
"type": "timeseries",
"id": 261,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 51
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "time() - max(SeaweedFS_s3_lifecycle_daily_run_last_full_pass_timestamp_seconds{cluster=~\"$cluster\"} > 0)",
"range": true,
"refId": "A",
"legendFormat": "last full pass"
}
],
"pluginVersion": "10.3.1"
}
]
},
@@ -44,12 +44,22 @@ func vacuumVolumes(t *testing.T) {
require.NotEmpty(t, defaultConfig.MasterEndpoint, "vacuum needs a master endpoint; set MASTER_ENDPOINT")
endpoint := strings.TrimRight(defaultConfig.MasterEndpoint, "/") + "/vol/vacuum?garbageThreshold=0.001"
httpClient := &http.Client{Timeout: 30 * time.Second}
resp, err := httpClient.Get(endpoint)
require.NoError(t, err, "vacuum request to %s", endpoint)
defer resp.Body.Close()
_, err = io.Copy(io.Discard, resp.Body)
require.NoError(t, err, "reading the vacuum response")
require.Equal(t, http.StatusOK, resp.StatusCode, "vacuum request to %s", endpoint)
// The master runs one vacuum at a time and answers 409 to a request it
// dropped because its automatic vacuum was running. Ask until ours runs.
deadline := time.Now().Add(time.Minute)
for {
resp, err := httpClient.Get(endpoint)
require.NoError(t, err, "vacuum request to %s", endpoint)
_, err = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
require.NoError(t, err, "reading the vacuum response")
if resp.StatusCode == http.StatusConflict && time.Now().Before(deadline) {
time.Sleep(500 * time.Millisecond)
continue
}
require.Equal(t, http.StatusOK, resp.StatusCode, "vacuum request to %s", endpoint)
return
}
}
func requireVersionBody(t *testing.T, client *s3.Client, bucketName, objectKey, versionId string, want []byte, msg string) {
+15 -5
View File
@@ -983,11 +983,21 @@ func TestTusAbortedPatchKeepsStoredChunks(t *testing.T) {
require.Equal(t, http.StatusNoContent, patchResp.StatusCode)
// A vacuum reclaims whatever the filer deleted, so the file survives this
// only if the chunks the session kept are still stored.
vacuumResp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%s/vol/vacuum?garbageThreshold=0.001", testMasterPort))
require.NoError(t, err)
vacuumResp.Body.Close()
require.Equal(t, http.StatusOK, vacuumResp.StatusCode)
// only if the chunks the session kept are still stored. The master answers
// 409 to a request it dropped because its automatic vacuum was running, so
// ask until ours runs.
vacuumDeadline := time.Now().Add(time.Minute)
for {
vacuumResp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%s/vol/vacuum?garbageThreshold=0.001", testMasterPort))
require.NoError(t, err)
vacuumResp.Body.Close()
if vacuumResp.StatusCode == http.StatusConflict && time.Now().Before(vacuumDeadline) {
time.Sleep(500 * time.Millisecond)
continue
}
require.Equal(t, http.StatusOK, vacuumResp.StatusCode)
break
}
getResp, err := client.Get(cluster.FilerURL() + targetPath)
require.NoError(t, err)
+6 -4
View File
@@ -1120,13 +1120,15 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr
if completed.RequestId != "" {
tracked.RequestID = completed.RequestId
}
if completed.Result != nil {
tracked.ResultSummary = completed.Result.Summary
} else {
tracked.ResultSummary = ""
}
if completed.Success {
tracked.State = strings.ToLower(plugin_pb.JobState_JOB_STATE_SUCCEEDED.String())
tracked.Progress = 100
tracked.Stage = "completed"
if completed.Result != nil {
tracked.ResultSummary = completed.Result.Summary
}
tracked.Message = tracked.ResultSummary
if tracked.Message == "" {
tracked.Message = "completed"
@@ -1159,7 +1161,7 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr
detail.Message = clone.Message
detail.ErrorMessage = clone.ErrorMessage
detail.ResultSummary = clone.ResultSummary
if completed.Success && completed.Result != nil {
if completed.Result != nil {
detail.ResultOutputValues = configValueMapToPlain(completed.Result.OutputValues)
} else {
detail.ResultOutputValues = nil
+147
View File
@@ -594,6 +594,95 @@ func TestBuildJobDetailIncludesActivitiesAndRunRecord(t *testing.T) {
}
}
func TestBuildJobDetailKeepsFailedJobResult(t *testing.T) {
t.Parallel()
pluginSvc, err := New(Options{DataDir: t.TempDir()})
if err != nil {
t.Fatalf("New: %v", err)
}
defer pluginSvc.Shutdown()
pluginSvc.trackExecutionStart("req-failed", "worker-f", &plugin_pb.JobSpec{
JobId: "job-failed",
JobType: "s3_lifecycle",
}, 1)
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
RequestId: "req-failed",
JobId: "job-failed",
JobType: "s3_lifecycle",
Success: false,
ErrorMessage: "walk bad-a: filer down",
Result: &plugin_pb.JobResult{
Summary: "pass failed",
OutputValues: map[string]*plugin_pb.ConfigValue{
"buckets_failed": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
},
},
CompletedAt: timestamppb.Now(),
})
pluginSvc.Shutdown()
detail, found, err := pluginSvc.BuildJobDetail("job-failed", 100, 5)
if err != nil {
t.Fatalf("BuildJobDetail error: %v", err)
}
if !found || detail == nil || detail.Job == nil {
t.Fatalf("expected job detail")
}
if detail.Job.State != "job_state_failed" || detail.Job.ErrorMessage != "walk bad-a: filer down" {
t.Fatalf("expected the failure to be kept, got state=%q error=%q", detail.Job.State, detail.Job.ErrorMessage)
}
if detail.Job.ResultSummary != "pass failed" {
t.Fatalf("expected the failed job's result summary, got %q", detail.Job.ResultSummary)
}
if detail.Job.ResultOutputValues["buckets_failed"] == nil {
t.Fatalf("expected the failed job's result output values, got %+v", detail.Job.ResultOutputValues)
}
}
func TestRetryWithoutResultDropsFailedAttemptSummary(t *testing.T) {
t.Parallel()
pluginSvc, err := New(Options{DataDir: t.TempDir()})
if err != nil {
t.Fatalf("New: %v", err)
}
defer pluginSvc.Shutdown()
job := &plugin_pb.JobSpec{JobId: "job-retry", JobType: "s3_lifecycle"}
pluginSvc.trackExecutionStart("req-retry", "worker-r", job, 1)
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
RequestId: "req-retry",
JobId: "job-retry",
JobType: "s3_lifecycle",
Success: false,
ErrorMessage: "walk bad-a: filer down",
Result: &plugin_pb.JobResult{Summary: "pass failed"},
CompletedAt: timestamppb.Now(),
})
pluginSvc.trackExecutionStart("req-retry", "worker-r", job, 2)
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
RequestId: "req-retry",
JobId: "job-retry",
JobType: "s3_lifecycle",
Success: true,
CompletedAt: timestamppb.Now(),
})
pluginSvc.Shutdown()
detail, found, err := pluginSvc.BuildJobDetail("job-retry", 100, 5)
if err != nil {
t.Fatalf("BuildJobDetail error: %v", err)
}
if !found || detail == nil || detail.Job == nil {
t.Fatalf("expected job detail")
}
if detail.Job.ResultSummary != "" || detail.Job.Message != "completed" {
t.Fatalf("expected the failed attempt's summary to be dropped, got summary=%q message=%q", detail.Job.ResultSummary, detail.Job.Message)
}
}
func TestBuildJobDetailLoadsFromDiskWhenMemoryCleared(t *testing.T) {
t.Parallel()
@@ -704,6 +793,64 @@ func TestExpireStaleJobsCancelsTheJobOnItsWorker(t *testing.T) {
expectCancelFor(t, session, "req-stale")
}
// A job older than the stale limit stays active while its worker reports
// progress for it; the worker's heartbeat alone does not keep it alive.
func TestExpireStaleJobsKeepsAJobThatReportsProgress(t *testing.T) {
t.Parallel()
pluginSvc, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
defer pluginSvc.Shutdown()
const workerID = "worker-1"
session := &streamSession{workerID: workerID, outgoing: make(chan *plugin_pb.AdminToWorkerMessage, 8), done: make(chan struct{})}
pluginSvc.putSession(session)
pluginSvc.handleWorkerMessage(session, &plugin_pb.WorkerToAdminMessage{
Body: &plugin_pb.WorkerToAdminMessage_Hello{Hello: &plugin_pb.WorkerHello{WorkerId: workerID}},
})
pluginSvc.trackExecutionStart("req-working", workerID, &plugin_pb.JobSpec{JobId: "job-working", JobType: "s3_lifecycle"}, 1)
pluginSvc.trackExecutionStart("req-stalled", workerID, &plugin_pb.JobSpec{JobId: "job-stalled", JobType: "s3_lifecycle"}, 1)
startedAt := time.Now().UTC().Add(-defaultStaleActiveJobTimeout - time.Hour)
pluginSvc.jobsMu.Lock()
for _, job := range pluginSvc.jobs {
job.CreatedAt = timeToPtr(startedAt)
job.UpdatedAt = timeToPtr(startedAt)
}
pluginSvc.jobsMu.Unlock()
pluginSvc.handleWorkerMessage(session, &plugin_pb.WorkerToAdminMessage{
Body: &plugin_pb.WorkerToAdminMessage_Heartbeat{Heartbeat: &plugin_pb.WorkerHeartbeat{
WorkerId: workerID,
ExecutionSlotsTotal: 4,
ExecutionSlotsUsed: 2,
RunningWork: []*plugin_pb.RunningWork{
{WorkId: "job-working", Kind: plugin_pb.WorkKind_WORK_KIND_EXECUTION, JobType: "s3_lifecycle"},
{WorkId: "job-stalled", Kind: plugin_pb.WorkKind_WORK_KIND_EXECUTION, JobType: "s3_lifecycle"},
},
}},
})
pluginSvc.handleWorkerMessage(session, &plugin_pb.WorkerToAdminMessage{
Body: &plugin_pb.WorkerToAdminMessage_JobProgressUpdate{JobProgressUpdate: &plugin_pb.JobProgressUpdate{
JobId: "job-working", JobType: "s3_lifecycle", RequestId: "req-working",
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "walk", Message: "entries=10",
}},
})
if n := pluginSvc.expireStaleJobs(time.Now().UTC()); n != 1 {
t.Fatalf("expired %d jobs, want only the stalled one", n)
}
if got, _ := pluginSvc.GetTrackedJob("job-working"); got == nil || got.State != "job_state_running" {
t.Fatalf("expected the job reporting progress to stay running, got %+v", got)
}
if got, _ := pluginSvc.GetTrackedJob("job-stalled"); got == nil || got.State != StateFailed {
t.Fatalf("expected the heartbeat-only job to be failed, got %+v", got)
}
expectCancelFor(t, session, "req-stalled")
}
func expectNoCancel(t *testing.T, session *streamSession) {
t.Helper()
select {
@@ -428,6 +428,7 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
}
defer rows.Close()
stoppedEarly := false
for rows.Next() {
var name string
var data []byte
@@ -452,10 +453,20 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
}
if !resEachEntryFunc {
stoppedEarly = true
break
}
}
// rows.Next also returns false when the result set fails partway, for
// example on a lost connection; that must not read as the end of the
// directory. A listing the callback stopped on purpose has no such error
// to report (rows.Err would return a canceled context's error instead).
if err == nil && !stoppedEarly {
if rowsErr := rows.Err(); rowsErr != nil {
err = fmt.Errorf("list %s: %w", dirPath, rowsErr)
}
}
return lastFileName, err
}
@@ -2,10 +2,13 @@ package abstract_sql
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -140,3 +143,74 @@ func TestBucketHooksSkipInvalidBucketNames(t *testing.T) {
t.Error(err)
}
}
type listGen struct{ SqlGenerator }
func (listGen) GetSqlListExclusive(string) string { return "SELECT name, meta" }
func (listGen) GetSqlListInclusive(string) string { return "SELECT name, meta" }
// A listing that loses its connection partway through must report the error,
// not return the rows read so far as if the directory ended there.
func TestListDirectoryEntriesReportsRowIterationError(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer db.Close()
meta, err := (&filer.Entry{}).EncodeAttributesAndChunks()
if err != nil {
t.Fatal(err)
}
connLost := errors.New("connection reset by peer")
mock.ExpectQuery("SELECT name, meta").WillReturnRows(
sqlmock.NewRows([]string{"name", "meta"}).
AddRow("a.txt", meta).
AddRow("b.txt", meta).
RowError(1, connLost))
store := &AbstractSqlStore{SqlGenerator: listGen{}, DB: db}
var listed []string
_, err = store.ListDirectoryEntries(context.Background(), "/dir", "", true, 100, func(entry *filer.Entry) (bool, error) {
listed = append(listed, entry.Name())
return true, nil
})
if !errors.Is(err, connLost) {
t.Fatalf("ListDirectoryEntries error = %v, want %v (listed %v)", err, connLost, listed)
}
}
// A listing the callback stops on purpose is not a failure, even if the
// request context is canceled before the rows are closed.
func TestListDirectoryEntriesStoppedByCallbackWithCanceledContext(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer db.Close()
meta, err := (&filer.Entry{}).EncodeAttributesAndChunks()
if err != nil {
t.Fatal(err)
}
mock.ExpectQuery("SELECT name, meta").WillReturnRows(
sqlmock.NewRows([]string{"name", "meta"}).AddRow("a.txt", meta).AddRow("b.txt", meta))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store := &AbstractSqlStore{SqlGenerator: listGen{}, DB: db}
_, err = store.ListDirectoryEntries(ctx, "/dir", "", true, 100, func(entry *filer.Entry) (bool, error) {
cancel()
// database/sql closes the rows on a background goroutine; once the
// connection is back in the pool, rows.Err reports the cancellation.
for deadline := time.Now().Add(5 * time.Second); db.Stats().InUse > 0; time.Sleep(time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("the canceled listing still holds its connection")
}
}
return false, nil
})
if err != nil {
t.Fatalf("ListDirectoryEntries error = %v, want nil", err)
}
}
+4 -3
View File
@@ -204,9 +204,10 @@ func (f *Filer) LocalFlushedThroughTsNs(nowNs int64) int64 {
}
// LocalDeliveredThroughTsNs caps a delivery-freshness claim (an idle
// heartbeat's timestamp) by the oldest in-flight stamp: a stamped-but-
// unappended event has not been streamed to anyone, and a peer aggregator
// turns the claim into its delivery low-watermark.
// heartbeat's timestamp, a listing snapshot) by the oldest in-flight stamp: a
// stamped-but-unappended event has not been streamed to anyone, nor is its
// write certain to be visible yet, and a peer aggregator turns the claim into
// its delivery low-watermark.
func (f *Filer) LocalDeliveredThroughTsNs(nowNs int64) int64 {
return f.metaLogInflight.claimThrough(nowNs)
}
+1
View File
@@ -0,0 +1 @@
Concurrent writers to one file from different mounts require `-dlm`; without it, a conflicting write fails with EIO and the file may refuse further appends until reopened after the cache drops.
+84
View File
@@ -0,0 +1,84 @@
package mount
import (
"fmt"
"sort"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// A publication owner carries provider refusal evidence through every retry.
// Helpers and the periodic flusher never retire content that is still owned.
type contentPublication struct {
refused bool
failure *atomic.Bool
// writes is the handle's pageWrites before its pages were flushed. A
// later write is not in the published chunks, so it keeps the handle dirty.
writes uint64
}
func (p *contentPublication) retire(err error) {
if err != nil && p.refused {
p.abandon()
}
}
// An abandoned writeback drain leaves the kernel EOF past the stored one,
// whatever the filer answered.
func (p *contentPublication) abandon() {
if p.failure != nil {
p.failure.Store(true)
}
}
func (wfs *WFS) checkContentPublication(fh *FileHandle, base *filer_pb.Entry) error {
if wfs.option.WritebackCache && (fh.writebackContentError == nil || fh.writebackContentError.Load()) {
return fmt.Errorf("writeback inode awaits Forget after content refusal: %w", filer_pb.ErrPreconditionFailed)
}
// This guard shares the CAS version with CreateEntry. A rewritten or
// manifest bounding range cannot conceal the original kernel WRITE frontier.
var eof uint64
if base != nil {
eof = filer.FileSize(base)
}
if !wfs.option.WritebackCache && fh.pendingAppend && fh.pendingAppendOffset > eof {
return fmt.Errorf("append offset %d exceeds committed EOF %d: %w", fh.pendingAppendOffset, eof, filer_pb.ErrPreconditionFailed)
}
return nil
}
// Only used when a peer shrank the file: a merge must not acknowledge a gap
// between that stored EOF and local pending content. Ordinary sparse pwrite
// without a concurrent truncate is unaffected. Compare copies, never reorder
// a handle's chunks. A manifest's bounding range is not proof of coverage.
func contentGapAfter(entry *filer_pb.Entry, start uint64) bool {
end := filer.FileSize(entry)
if start >= end {
return false
}
chunks := append([]*filer_pb.FileChunk(nil), entry.Chunks...)
sort.SliceStable(chunks, func(i, j int) bool { return chunks[i].Offset < chunks[j].Offset })
covered := start
if uint64(len(entry.Content)) > covered {
covered = uint64(len(entry.Content))
}
for _, c := range chunks {
if covered >= end {
return false
}
if c.Offset < 0 || c.Size > ^uint64(0)-uint64(c.Offset) {
return true
}
left, right := uint64(c.Offset), uint64(c.Offset)+c.Size
if right <= covered {
continue
}
if left > covered || c.IsChunkManifest {
return true
}
covered = right
}
return covered < end
}
+212
View File
@@ -0,0 +1,212 @@
//go:build !freebsd
package mount
import (
"bytes"
"context"
"syscall"
"testing"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/protobuf/proto"
)
// These caller controls measure published bytes; none imports #12608 internals.
func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
for _, scenario := range []string{"peer-append", "peer-replaced-file", "peer-truncate"} {
t.Run(scenario, func(t *testing.T) {
base := attributeAppendEntry(1)
stored := attributeAppendEntry(2)
pending := attributeAppendEntry(2)
pending.Chunks[1].Fid.FileKey = 3
pending.Chunks[1].Offset = 512
pending.Attributes.FileSize = 768
blobs := map[string][]byte{}
for i, c := range stored.Chunks {
blobs[c.GetFileIdString()] = bytes.Repeat([]byte{[]byte{'O', 'P'}[i]}, 256)
}
blobs[pending.Chunks[1].GetFileIdString()] = bytes.Repeat([]byte{'C'}, 256)
switch scenario {
case "peer-replaced-file":
stored = attributeAppendEntry(1)
stored.Attributes.Inode = 99
stored.Chunks[0].Fid.FileKey = 900
blobs[stored.Chunks[0].GetFileIdString()] = bytes.Repeat([]byte{'R'}, 256)
case "peer-truncate":
base = attributeAppendEntry(2)
stored = attributeAppendEntry(1)
pending = attributeAppendEntry(3)
blobs[pending.Chunks[2].GetFileIdString()] = bytes.Repeat([]byte{'C'}, 256)
blobs[base.Chunks[1].GetFileIdString()] = bytes.Repeat([]byte{'A'}, 256)
}
stored.Attributes.FileMode, stored.CommitTsNs = 0600, 20000
original := proto.Clone(stored).(*filer_pb.Entry)
peer := &g6ConditionalPeer{entry: proto.Clone(stored).(*filer_pb.Entry), blobs: blobs}
w := newInvalidateTestWFS(t)
startFakeFiler(t, w, peer)
w.mapPbIdFromFilerToLocal(base)
w.mapPbIdFromFilerToLocal(pending)
fh := newFileHandle(w, 1, 42, pending)
t.Cleanup(fh.dirtyPages.Destroy)
fh.RememberPath("/dir/file")
fh.baseEntry.Store(base)
fh.dirtyMetadata = true
code := fuse.OK
if periodic {
if err := w.flushFileMetadata(fh); err != nil {
code = fuse.EIO
t.Logf("periodic error: %v", err)
}
} else {
code = w.doFlush(context.Background(), fh, 1000, 20, false, 0)
}
peer.mu.Lock()
defer peer.mu.Unlock()
actual := g6StoredBytes(t, peer)
t.Logf("scenario=%s status=%v size=%d rejected=%d gap[256,512)-zero=%v", scenario, code, len(actual), peer.rejected, len(actual) >= 512 && bytes.Equal(actual[256:512], make([]byte, 256)))
if scenario == "peer-replaced-file" {
if code != fuse.EIO || !g6EntryEqual(peer.entry, original) || !bytes.Equal(actual, bytes.Repeat([]byte{'R'}, 256)) {
t.Fatal("replacement must be refused without publishing stale content")
}
return
}
if scenario == "peer-truncate" && code == fuse.EIO {
if !g6EntryEqual(peer.entry, original) || !bytes.Equal(actual, bytes.Repeat([]byte{'O'}, 256)) {
t.Fatal("refusal changed peer truncate")
}
return
}
want := bytes.Repeat([]byte{'O'}, 256)
if scenario == "peer-append" {
want = append(want, bytes.Repeat([]byte{'P'}, 256)...)
}
want = append(want, bytes.Repeat([]byte{'C'}, 256)...)
if code != fuse.OK || peer.entry.Attributes.FileMode != 0600 || peer.entry.Attributes.FileSize != uint64(len(want)) || !bytes.Equal(actual, want) {
t.Fatalf("unsafe merge: status=%v size=%d want-size=%d exact-bytes=%v; peer/local bytes must survive without a gap", code, len(actual), len(want), bytes.Equal(actual, want))
}
})
}
}
func TestMasterCommittedEOFAppendHasNoGap(t *testing.T) {
for _, appendOpen := range []bool{true, false} {
name := "append"
if !appendOpen {
name = "intentional-sparse-pwrite"
}
t.Run(name, func(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, h := g6AppendHandle(t, peer, base, 2100)
if !appendOpen {
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY}, out); code != fuse.OK {
t.Fatal(code)
}
h = out.Fh
}
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: h, Offset: 512, Size: 256}, bytes.Repeat([]byte{'B'}, 256)); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: h})
peer.mu.Lock()
defer peer.mu.Unlock()
actual := g6StoredBytes(t, peer)
if appendOpen {
if code != fuse.EIO || peer.entry.Attributes.FileSize != 256 || !bytes.Equal(actual, bytes.Repeat([]byte{'O'}, 256)) {
t.Fatalf("stale append frontier published a gap: status=%v size=%d interval[256,512)-zero=%v", code, len(actual), len(actual) >= 512 && bytes.Equal(actual[256:512], make([]byte, 256)))
}
} else {
want := append(bytes.Repeat([]byte{'O'}, 256), make([]byte, 256)...)
want = append(want, bytes.Repeat([]byte{'B'}, 256)...)
if code != fuse.OK || !bytes.Equal(actual, want) || peer.entry.Attributes.FileSize != 768 {
t.Fatal("intentional sparse pwrite must remain allowed", code, len(actual))
}
}
})
}
}
func TestMasterConflictThenAppendCannotPublishGap(t *testing.T) {
for _, mode := range []struct {
name string
writeback, coalesced bool
}{{"normal", false, false}, {"writeback", true, false}, {"writeback-coalesced", true, true}} {
t.Run(mode.name, func(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, h := g6AppendHandle(t, peer, base, 2200, mode.writeback)
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: h, Offset: 256, Size: 256}, bytes.Repeat([]byte{'A'}, 256)); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
// Model the native compactor's output, including independently uploaded
// bytes and the rewrite marker: a single chunk containing original O+A.
// No product implementation is supplied or changed by this fixture.
fh := w.GetHandle(FileHandleId(h))
if err := fh.dirtyPages.FlushData(); err != nil {
t.Fatal(err)
}
compacted := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 8000, Cookie: 1}, Size: 512, ModifiedTsNs: 100}
peer.mu.Lock()
peer.blobs[compacted.GetFileIdString()] = append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
peer.mu.Unlock()
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Chunks = []*filer_pb.FileChunk{proto.Clone(compacted).(*filer_pb.FileChunk)}
e.Attributes.FileSize = 512
})
fh.noteRewrite()
replacement := attributeAppendEntry(1)
replacement.Chunks[0].Fid.FileKey = 900
replacement.Attributes.FileMode, replacement.CommitTsNs = 0600, 20000
peer.mu.Lock()
peer.entry = proto.Clone(replacement).(*filer_pb.Entry)
peer.clock = 20000
peer.blobs[replacement.Chunks[0].GetFileIdString()] = bytes.Repeat([]byte{'P'}, 256)
peer.mu.Unlock()
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: h}); code != fuse.EIO {
t.Fatal("setup: native real rewrite conflict must be refused", code)
}
w.Release(nil, &fuse.ReleaseIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: h, ReleaseFlags: fuse.FUSE_RELEASE_FLOCK_UNLOCK})
if _, kept := w.fhMap.FindFileHandle(42); kept {
t.Fatal("failed synchronous close retained handle")
}
peer.mu.Lock()
unchanged := g6EntryEqual(peer.entry, replacement)
peer.mu.Unlock()
if !unchanged {
t.Fatal("refused close published over peer")
}
if err := w.metaCache.InsertEntry(context.Background(), filer.FromPbEntry("/dir", proto.Clone(replacement).(*filer_pb.Entry)), 20000); err != nil {
t.Fatal(err)
}
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY | syscall.O_APPEND}, out); code != fuse.OK {
t.Fatal(code)
}
g6AppendUploader(t, w.GetHandle(FileHandleId(out.Fh)), 2300, peer)
offset := uint64(512)
payload := bytes.Repeat([]byte{'B'}, 256)
if mode.coalesced {
offset = 0
payload = append(bytes.Repeat([]byte{'P'}, 256), make([]byte, 256)...)
payload = append(payload, bytes.Repeat([]byte{'B'}, 256)...)
}
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: uint32(len(payload))}, payload); n != uint32(len(payload)) || code != fuse.OK {
t.Fatal(n, code)
}
code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh})
peer.mu.Lock()
defer peer.mu.Unlock()
actual := g6StoredBytes(t, peer)
if code != fuse.EIO || peer.entry.Attributes.FileSize != 256 || !bytes.Equal(actual, bytes.Repeat([]byte{'P'}, 256)) {
t.Fatalf("terminal conflict followed by false success/gap: status=%v size=%d interval[256,512)-zero=%v", code, len(actual), len(actual) >= 512 && bytes.Equal(actual[256:512], make([]byte, 256)))
}
})
}
}
func TestContentGapPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, false) }
func TestContentGapPeriodicPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, true) }
+600
View File
@@ -0,0 +1,600 @@
//go:build !freebsd
package mount
import (
"bytes"
"context"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"io"
"os"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
)
func g6AppendHandle(t *testing.T, peer *g6ConditionalPeer, base *filer_pb.Entry, key uint64, writeback ...bool) (*WFS, uint64) {
t.Helper()
w := newInvalidateTestWFS(t)
w.option.CacheDirForWrite = t.TempDir()
w.option.DefaultPermissions = true
w.option.WritebackCache = len(writeback) > 0 && writeback[0]
w.posixLocks = NewPosixLockTable()
w.option.ConcurrentWriters = 1
w.concurrentWriters = util.NewLimitedConcurrentExecutor(1)
startFakeFiler(t, w, peer)
w.inodeToPath.Lookup("/dir", 1, true, false, 0, false)
w.inodeToPath.Lookup("/dir/file", 1, false, false, 42, true)
w.inodeToPath.MarkChildrenCached("/dir")
if err := w.metaCache.InsertEntry(context.Background(), filer.FromPbEntry("/dir", proto.Clone(base).(*filer_pb.Entry)), 1); err != nil {
t.Fatal(err)
}
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY | syscall.O_APPEND}, out); code != fuse.OK {
t.Fatal(code)
}
fh := w.GetHandle(FileHandleId(out.Fh))
peer.mu.Lock()
if peer.blobs == nil {
peer.blobs = make(map[string][]byte)
}
peer.blobs[base.Chunks[0].GetFileIdString()] = bytes.Repeat([]byte{'O'}, 256)
peer.mu.Unlock()
g6AppendUploader(t, fh, key, peer)
return w, out.Fh
}
func g6AppendUploader(t *testing.T, fh *FileHandle, key uint64, peer *g6ConditionalPeer) {
t.Helper()
t.Cleanup(fh.dirtyPages.Destroy)
fh.dirtyPages.randomWriter.(*ChunkedDirtyPages).saveDataAsChunk = func(util.FullPath) filer.SaveDataAsChunkFunctionType {
return func(r io.Reader, _ string, offset, ts int64, _ uint64) (*filer_pb.FileChunk, error) {
body, err := io.ReadAll(r)
if err != nil {
return nil, err
}
key++
chunk := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: key, Cookie: 1}, Offset: offset, Size: uint64(len(body)), ModifiedTsNs: ts}
peer.mu.Lock()
peer.blobs[chunk.GetFileIdString()] = append([]byte(nil), body...)
peer.mu.Unlock()
return chunk, nil
}
}
}
func TestAppendAfterRefusedFlushHasNoHole(t *testing.T) {
base := attributeAppendEntry(1)
base.CommitTsNs = 100
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 100)
write := func(w *WFS, handle, offset uint64, value byte) {
t.Helper()
data := bytes.Repeat([]byte{value}, 256)
n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: offset, Size: 256}, data)
if n != 256 || code != fuse.OK {
t.Fatalf("write: %d %v", n, code)
}
}
write(w, handle, 256, 'A')
// A peer chmod changes only attributes after this handle observed its base.
peer.mu.Lock()
peer.entry.Attributes.FileMode = 0600
peer.entry.CommitTsNs++
peer.mu.Unlock()
first := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle})
t.Logf("first fsync=%v", first)
w.Release(nil, &fuse.ReleaseIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, ReleaseFlags: fuse.FUSE_RELEASE_FLOCK_UNLOCK})
peer.mu.Lock()
latest := proto.Clone(peer.entry).(*filer_pb.Entry)
peer.mu.Unlock()
if err := w.metaCache.InsertEntry(context.Background(), filer.FromPbEntry("/dir", latest), 3000); err != nil {
t.Fatal(err)
}
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY | syscall.O_APPEND}, out); code != fuse.OK {
t.Fatal(code)
}
next, nextHandle := w, out.Fh
g6AppendUploader(t, w.GetHandle(FileHandleId(nextHandle)), 200, peer)
// FUSE WRITE offsets are supplied by the kernel; its cached EOF advanced
// on the first successful WRITE even when that handle's fsync failed.
write(next, nextHandle, 512, 'B')
if code := next.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: nextHandle}); code != fuse.OK {
t.Fatal(code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
want = append(want, bytes.Repeat([]byte{'B'}, 256)...)
if peer.entry.Attributes.FileSize != 768 || peer.entry.Attributes.FileMode != 0600 || !bytes.Equal(g6StoredBytes(t, peer), want) {
t.Fatal("original/A/B bytes, size or peer mode changed")
}
for _, offset := range []int64{0, 256, 512} {
covered := false
for _, c := range peer.entry.Chunks {
if c.Offset <= offset && c.Offset+int64(c.Size) >= offset+256 {
covered = true
}
}
if !covered {
t.Fatalf("fsync acknowledged a hole [%d,%d): first=%v chunks=%v", offset, offset+256, first, peer.entry.Chunks)
}
}
}
type g6ConditionalPeer struct {
filer_pb.UnimplementedSeaweedFilerServer
mu sync.Mutex
entry *filer_pb.Entry
rejected int
refuse bool
blobs map[string][]byte
clock int64
beforeCreate func(context.Context)
}
func g6EntryEqual(current, expected *filer_pb.Entry) bool {
actual := filer.FromPbEntry("", proto.Clone(current).(*filer_pb.Entry)).ToProtoEntry()
want := proto.Clone(expected).(*filer_pb.Entry)
filer_pb.BeforeEntrySerialization(actual.Chunks)
filer_pb.BeforeEntrySerialization(want.Chunks)
return proto.Equal(actual, filer.FromPbEntry("", want).ToProtoEntry())
}
func g6StoredBytes(t *testing.T, s *g6ConditionalPeer) []byte {
t.Helper()
result := make([]byte, s.entry.Attributes.FileSize)
for _, c := range s.entry.Chunks {
body, ok := s.blobs[c.GetFileIdString()]
if !ok || uint64(len(body)) != c.Size || c.Offset < 0 || uint64(c.Offset)+c.Size > uint64(len(result)) {
t.Fatalf("invalid stored reference %v", c)
}
copy(result[c.Offset:], body)
}
return result
}
func (s *g6ConditionalPeer) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(s.entry).(*filer_pb.Entry)}, nil
}
func (s *g6ConditionalPeer) UpdateEntry(_ context.Context, r *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
for _, c := range r.GetCondition().GetClauses() {
if c.Kind != filer_pb.WriteCondition_IF_ENTRY_EQUAL || !g6EntryEqual(s.entry, c.ExpectedEntry) {
return nil, status.Error(codes.FailedPrecondition, "entry changed")
}
}
s.entry = proto.Clone(r.Entry).(*filer_pb.Entry)
s.clock = max(max(s.clock, s.entry.CommitTsNs), 10000) + 1
s.entry.CommitTsNs = s.clock
return &filer_pb.UpdateEntryResponse{LogTsNs: s.clock, MetadataEvent: &filer_pb.SubscribeMetadataResponse{Directory: r.Directory, TsNs: s.clock, EventNotification: &filer_pb.EventNotification{NewEntry: proto.Clone(s.entry).(*filer_pb.Entry)}}}, nil
}
func (s *g6ConditionalPeer) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if s.beforeCreate != nil {
s.beforeCreate(ctx)
}
s.mu.Lock()
defer s.mu.Unlock()
if s.refuse {
s.rejected++
return &filer_pb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
}
for _, c := range r.GetCondition().GetClauses() {
match := c.Kind == filer_pb.WriteCondition_IF_NOT_EXISTS && s.entry == nil || c.Kind == filer_pb.WriteCondition_IF_ENTRY_EQUAL && s.entry != nil && c.ExpectedEntry != nil && g6EntryEqual(s.entry, c.ExpectedEntry)
if !match {
s.rejected++
return &filer_pb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
}
}
s.entry = proto.Clone(r.Entry).(*filer_pb.Entry)
s.clock = max(max(s.clock, s.entry.CommitTsNs), 10000) + 1
s.entry.CommitTsNs = s.clock
return &filer_pb.CreateEntryResponse{LogTsNs: s.entry.CommitTsNs, MetadataEvent: &filer_pb.SubscribeMetadataResponse{Directory: r.Directory, TsNs: s.entry.CommitTsNs, EventNotification: &filer_pb.EventNotification{NewEntry: proto.Clone(s.entry).(*filer_pb.Entry)}}}, nil
}
func TestG6AppendFsyncAfterPeerAttribute(t *testing.T) {
for _, op := range []string{"none", "chmod", "chown", "utimes", "setxattr"} {
t.Run(op, func(t *testing.T) {
writer := newInvalidateTestWFS(t)
attr := newInvalidateTestWFS(t)
attr.atimeMap = make(map[uint64]time.Time)
base := attributeAppendEntry(1)
base.CommitTsNs = 100
s := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
s.blobs = map[string][]byte{base.Chunks[0].GetFileIdString(): bytes.Repeat([]byte{'O'}, 256), attributeAppendEntry(2).Chunks[1].GetFileIdString(): bytes.Repeat([]byte{'A'}, 256)}
startFakeFiler(t, writer, s)
startFakeFiler(t, attr, s)
path := util.FullPath("/dir/file")
local := proto.Clone(base).(*filer_pb.Entry)
writer.mapPbIdFromFilerToLocal(local)
fh := newFileHandle(writer, 1, 42, local)
fh.RememberPath(path)
t.Cleanup(fh.dirtyPages.Destroy)
writer.fhMap.inode2fh[42], writer.fhMap.fh2inode[1] = fh, 42
pending := attributeAppendEntry(2).Chunks[1]
fh.UpdateEntry(func(e *filer_pb.Entry) { e.Chunks = append(e.Chunks, pending); e.Attributes.FileSize = 512 })
fh.dirtyMetadata = true
attr.inodeToPath.Lookup("/dir", 1, true, false, 0, false)
attr.inodeToPath.Lookup(path, 1, false, false, 42, true)
attr.inodeToPath.MarkChildrenCached("/dir")
if err := attr.metaCache.InsertEntry(context.Background(), filer.FromPbEntry("/dir", base), 1); err != nil {
t.Fatal(err)
}
code := fuse.OK
if op == "setxattr" {
code = attr.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: 42}}, "user.test", []byte("peer acknowledged"))
} else if op != "none" {
in := &fuse.SetAttrIn{}
in.NodeId = 42
switch op {
case "chmod":
in.Valid, in.Mode = fuse.FATTR_MODE, 0600
case "chown":
in.Valid, in.Owner.Uid, in.Owner.Gid = fuse.FATTR_UID|fuse.FATTR_GID, 1001, 21
case "utimes":
in.Valid, in.Mtime, in.Mtimensec = fuse.FATTR_MTIME, 123, 456
}
code = attr.SetAttr(nil, in, &fuse.AttrOut{})
}
if code != fuse.OK {
t.Fatalf("peer attribute: %v", code)
}
s.mu.Lock()
wantChunk, gotChunk := proto.Clone(base.Chunks[0]).(*filer_pb.FileChunk), proto.Clone(s.entry.Chunks[0]).(*filer_pb.FileChunk)
filer_pb.BeforeEntrySerialization([]*filer_pb.FileChunk{wantChunk, gotChunk})
contentUnchanged := proto.Equal(wantChunk, gotChunk) && len(s.entry.Chunks) == 1
ackedPeer := proto.Clone(s.entry).(*filer_pb.Entry)
s.mu.Unlock()
if !contentUnchanged {
t.Fatal("peer attribute changed content before append publication")
}
if code = writer.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: 1}); code != fuse.OK {
t.Fatalf("append after acknowledged peer %s returned %v; pending=%d base=%d rejected=%d", op, code, len(fh.entry.Chunks), len(fh.baseEntry.Load().Chunks), s.rejected)
}
s.mu.Lock()
defer s.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
if s.entry.Attributes.FileSize != 512 || !bytes.Equal(g6StoredBytes(t, s), want) {
t.Fatal("append lost original/pending bytes or size")
}
a, b := s.entry.Attributes, ackedPeer.Attributes
if op == "chmod" && a.FileMode != b.FileMode || op == "chown" && (a.Uid != b.Uid || a.Gid != b.Gid) || op == "utimes" && (a.Mtime != b.Mtime || a.MtimeNs != b.MtimeNs) || op == "setxattr" && !bytes.Equal(s.entry.Extended[XATTR_PREFIX+"user.test"], ackedPeer.Extended[XATTR_PREFIX+"user.test"]) {
t.Fatal("append rolled back acknowledged peer attributes")
}
})
}
}
func TestAppendCompatibleCommittedPrefix(t *testing.T) {
w := newInvalidateTestWFS(t)
base, current, pending := attributeAppendEntry(1), attributeAppendEntry(2), attributeAppendEntry(3)
current.Attributes.FileMode = 0600
peer := &g6ConditionalPeer{entry: current, blobs: make(map[string][]byte)}
for i, c := range pending.Chunks {
peer.blobs[c.GetFileIdString()] = bytes.Repeat([]byte{[]byte{'O', 'A', 'B'}[i]}, 256)
}
startFakeFiler(t, w, peer)
w.mapPbIdFromFilerToLocal(base)
w.mapPbIdFromFilerToLocal(pending)
fh := newFileHandle(w, 1, 42, pending)
t.Cleanup(fh.dirtyPages.Destroy)
fh.RememberPath("/dir/file")
fh.baseEntry.Store(base)
fh.dirtyMetadata = true
if code := w.doFlush(context.Background(), fh, 1000, 20, false, 0); code != fuse.OK {
t.Fatal(code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
want = append(want, bytes.Repeat([]byte{'B'}, 256)...)
if peer.rejected != 1 || peer.entry.Attributes.FileMode != 0600 || peer.entry.Attributes.FileSize != 768 || !bytes.Equal(g6StoredBytes(t, peer), want) {
t.Fatal("prefix rebase lost bytes, size or peer attributes")
}
}
func TestAsyncRefusalAfterForgetDoesNotPoisonRelookup(t *testing.T) {
testAsyncRefusalAfterForget(t, false)
}
func TestAsyncPublicationBlockedBeforeCaptureDoesNotPoisonRelookup(t *testing.T) {
testAsyncRefusalAfterForget(t, true)
}
func testAsyncRefusalAfterForget(t *testing.T, publicationBlocked bool) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry), refuse: true}
entered, resume := make(chan struct{}), make(chan struct{})
var once, resumeOnce sync.Once
release := func() { resumeOnce.Do(func() { close(resume) }) }
peer.beforeCreate = func(ctx context.Context) {
once.Do(func() {
close(entered)
select {
case <-resume:
case <-ctx.Done():
}
})
}
w, handle := g6AppendHandle(t, peer, base, 1000, true)
w.pendingAsyncFlush = make(map[uint64]chan struct{})
w.startAsyncFlushWorkers(1)
t.Cleanup(w.WaitForAsyncFlush)
t.Cleanup(release)
unlockPublication := func() {}
if publicationBlocked {
unlock := w.lockMetadataPublication("/dir/file")
var unlockOnce sync.Once
unlockPublication = func() { unlockOnce.Do(unlock) }
t.Cleanup(unlockPublication)
}
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: 256, Size: 256}, bytes.Repeat([]byte{'A'}, 256)); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
w.Release(nil, &fuse.ReleaseIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle})
w.pendingAsyncFlushMu.Lock()
done := w.pendingAsyncFlush[42]
w.pendingAsyncFlushMu.Unlock()
if done == nil {
t.Fatal("Release did not queue an async publication")
}
waitEntered := func() {
t.Helper()
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("async publication did not reach the filer")
}
}
if publicationBlocked {
if blocked, _ := waitFlushPublication(t, make(chan fuse.Status)); !blocked {
t.Fatal("worker was not blocked before publication capture")
}
} else {
waitEntered()
}
w.Forget(42, 1)
w.inodeToPath.Lookup("/dir/file", 1, false, false, 42, true)
if publicationBlocked {
unlockPublication()
waitEntered()
}
release()
select {
case <-done:
case <-time.After(15 * time.Second):
t.Fatal("async refusal did not finish")
}
peer.mu.Lock()
if peer.rejected != 4*(maxContentFlushMerges+1) {
t.Errorf("refusals = %d, want sixteen (four outer attempts, four merge attempts each)", peer.rejected)
}
peer.refuse = false
peer.mu.Unlock()
if _, found := w.fhMap.FindFileHandle(42); found {
t.Fatal("async close retained a handle")
}
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY | syscall.O_APPEND}, out); code != fuse.OK {
t.Fatal(code)
}
g6AppendUploader(t, w.GetHandle(FileHandleId(out.Fh)), 1100, peer)
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: 256, Size: 256}, bytes.Repeat([]byte{'B'}, 256)); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh}); code != fuse.OK {
t.Fatalf("new inode lifetime inherited stale EIO: %v", code)
}
w.Release(nil, &fuse.ReleaseIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, ReleaseFlags: fuse.FUSE_RELEASE_FLOCK_UNLOCK})
peer.mu.Lock()
defer peer.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'B'}, 256)...)
if peer.entry.Attributes.FileSize != 512 || !bytes.Equal(g6StoredBytes(t, peer), want) {
t.Fatal("relookup publication changed original/new bytes or size")
}
}
func TestAppendAfterPendingPositionalExtensionPublishes(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, appendHandle := g6AppendHandle(t, peer, base, 1000)
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY}, out); code != fuse.OK {
t.Fatal(code)
}
write := func(h, offset uint64, value byte) {
t.Helper()
n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: h, Offset: offset, Size: 256}, bytes.Repeat([]byte{value}, 256))
if n != 256 || code != fuse.OK {
t.Fatal("write", n, code)
}
}
write(out.Fh, 256, 'A')
write(appendHandle, 512, 'B') // the kernel appends at its EOF, which includes A
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: appendHandle}); code != fuse.OK {
t.Fatal("append over a pending extension", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
want = append(want, bytes.Repeat([]byte{'B'}, 256)...)
if !bytes.Equal(g6StoredBytes(t, peer), want) {
t.Fatal("pending extension or append bytes changed")
}
}
func TestPositionalSparseWriteStillPublishes(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, _ := g6AppendHandle(t, peer, base, 900)
out := &fuse.OpenOut{}
if code := w.Open(nil, &fuse.OpenIn{InHeader: fuse.InHeader{NodeId: 42}, Flags: syscall.O_WRONLY}, out); code != fuse.OK {
t.Fatal(code)
}
n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: 512, Size: 256}, bytes.Repeat([]byte{'S'}, 256))
if n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
if code = w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh}); code != fuse.OK {
t.Fatal("positional sparse write", code)
}
assertSparseWrite(t, peer)
}
func TestSparseWriteAfterAppendFlagClearedPublishes(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 950)
n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: 512, Size: 256, Flags: syscall.O_WRONLY}, bytes.Repeat([]byte{'S'}, 256))
if n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
if code = w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle}); code != fuse.OK {
t.Fatal("sparse write after clearing O_APPEND", code)
}
assertSparseWrite(t, peer)
}
func assertSparseWrite(t *testing.T, peer *g6ConditionalPeer) {
t.Helper()
peer.mu.Lock()
defer peer.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), make([]byte, 256)...)
want = append(want, bytes.Repeat([]byte{'S'}, 256)...)
if !bytes.Equal(g6StoredBytes(t, peer), want) {
t.Fatal("sparse positional data changed")
}
}
func TestTruncatingOpenDiscardsRefusedAppend(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 1700)
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: 512, Size: 256}, bytes.Repeat([]byte{'A'}, 256)); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle}); code == fuse.OK {
t.Fatal("append past the committed EOF published")
}
dir, _ := w.inodeToPath.GetInode("/dir")
out := &fuse.CreateOut{}
if code := w.Create(nil, &fuse.CreateIn{InHeader: fuse.InHeader{NodeId: dir}, Flags: syscall.O_WRONLY | syscall.O_CREAT | syscall.O_TRUNC, Mode: 0644}, "file", out); code != fuse.OK {
t.Fatal("O_TRUNC create", code)
}
g6AppendUploader(t, w.GetHandle(FileHandleId(out.Fh)), 1800, peer)
payload := bytes.Repeat([]byte{'Z'}, 256)
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Size: 256}, payload); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh}); code != fuse.OK {
t.Fatal("rewrite after an O_TRUNC open", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
if !bytes.Equal(g6StoredBytes(t, peer), payload) {
t.Fatal("truncate and rewrite did not publish the new bytes")
}
}
type g6TtlRuleFiler struct{ *g6ConditionalPeer }
func (s *g6TtlRuleFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if r.Entry.IsDirectory {
return &filer_pb.CreateEntryResponse{}, nil
}
r = proto.Clone(r).(*filer_pb.CreateEntryRequest)
if r.Entry.Attributes.TtlSec == 0 {
r.Entry.Attributes.TtlSec = 3600
}
return s.g6ConditionalPeer.CreateEntry(ctx, r)
}
func (s *g6TtlRuleFiler) UpdateEntry(ctx context.Context, r *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
if r.Entry.IsDirectory {
return &filer_pb.UpdateEntryResponse{}, nil
}
return s.g6ConditionalPeer.UpdateEntry(ctx, r)
}
func TestEagerCreateWriteKeepsFilerDefaults(t *testing.T) {
peer := &g6ConditionalPeer{blobs: make(map[string][]byte)}
w := newInvalidateTestWFS(t)
w.option.EagerFilerCreate = true
w.option.ConcurrentWriters = 1
w.concurrentWriters = util.NewLimitedConcurrentExecutor(1)
startFakeFiler(t, w, &g6TtlRuleFiler{peer})
dir := w.inodeToPath.Lookup("/dir", 1, true, false, 0, false)
w.inodeToPath.MarkChildrenCached("/")
w.inodeToPath.MarkChildrenCached("/dir")
dirEntry := &filer_pb.Entry{Name: "dir", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: uint32(os.ModeDir | 0777), Inode: dir}}
if err := w.metaCache.InsertEntry(context.Background(), filer.FromPbEntry("/", dirEntry), 1); err != nil {
t.Fatal(err)
}
out := &fuse.CreateOut{}
if code := w.Create(nil, &fuse.CreateIn{InHeader: fuse.InHeader{NodeId: dir, Caller: fuse.Caller{Owner: fuse.Owner{Uid: 1000, Gid: 20}}}, Flags: syscall.O_WRONLY, Mode: 0644}, "file", out); code != fuse.OK {
t.Fatal("create", code)
}
g6AppendUploader(t, w.GetHandle(FileHandleId(out.Fh)), 2100, peer)
payload := bytes.Repeat([]byte{'E'}, 256)
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: out.NodeId}, Fh: out.Fh, Size: 256}, payload); n != 256 || code != fuse.OK {
t.Fatal(n, code)
}
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: out.NodeId}, Fh: out.Fh}); code != fuse.OK {
t.Fatal("write after an eager create", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
if peer.entry.Attributes.TtlSec != 3600 || !bytes.Equal(g6StoredBytes(t, peer), payload) {
t.Fatal("eager create lost the stored defaults or the written bytes")
}
}
type g6LostAnswerFiler struct {
*g6ConditionalPeer
lost atomic.Bool
}
func (s *g6LostAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
resp, err := s.g6ConditionalPeer.CreateEntry(ctx, r)
if err == nil && resp.Error == "" && s.lost.CompareAndSwap(false, true) {
return nil, status.Error(codes.Unavailable, "answer lost after commit")
}
return resp, err
}
func TestLostAnswerToOwnShrinkingFlushIsNotAConflict(t *testing.T) {
base := attributeAppendEntry(2)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 2200)
fake := &g6LostAnswerFiler{g6ConditionalPeer: peer}
startFakeFiler(t, w, fake)
if code := w.SetAttr(nil, &fuse.SetAttrIn{SetAttrInCommon: fuse.SetAttrInCommon{InHeader: fuse.InHeader{NodeId: 42}, Valid: fuse.FATTR_SIZE | fuse.FATTR_FH, Fh: handle}}, &fuse.AttrOut{}); code != fuse.OK {
t.Fatal("ftruncate", code)
}
payload := bytes.Repeat([]byte{'N'}, 128)
if n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Size: 128}, payload); n != 128 || code != fuse.OK {
t.Fatal(n, code)
}
if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle}); code != fuse.OK {
t.Fatal("own committed overwrite reported as a conflict", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
if !fake.lost.Load() || !bytes.Equal(g6StoredBytes(t, peer), payload) {
t.Fatal("lost answer was not exercised or the overwrite did not land")
}
}
+20 -11
View File
@@ -23,7 +23,7 @@ var IsDebugFileReadWrite = false
type FileHandle struct {
fh FileHandleId
counter int64
fhs map[FileHandleId]struct{} // live fh values, one per open; guarded by fhMap's lock
fhs map[FileHandleId]bool // live fh values, one per open; guarded by fhMap's lock
entry *LockedEntry
// Nested handle lock order: wfs.fhLockTable[fh.fh] -> entryLock ->
// LockedEntry.RWMutex. Paths may use a subset, but must never acquire an
@@ -34,15 +34,19 @@ type FileHandle struct {
wfs *WFS
// cache file has been written to
dirtyMetadata bool
dirtyPages *PageWriter
reader *filer.ChunkReadAt
contentType string
asyncFlushPending bool // set in writebackCache mode to defer flush to Release
asyncFlushUid uint32 // saved uid for deferred metadata flush
asyncFlushGid uint32 // saved gid for deferred metadata flush
savedDir string // last known parent path if inode-to-path state is forgotten
savedName string // last known file name if inode-to-path state is forgotten
pendingAppend bool
pendingAppendOffset uint64
writebackContentError *atomic.Bool
dirtyMetadata bool
dirtyContent bool
dirtyPages *PageWriter
reader *filer.ChunkReadAt
contentType string
asyncFlushPending bool // set in writebackCache mode to defer flush to Release
asyncFlushUid uint32 // saved uid for deferred metadata flush
asyncFlushGid uint32 // saved gid for deferred metadata flush
savedDir string // last known parent path if inode-to-path state is forgotten
savedName string // last known file name if inode-to-path state is forgotten
isDeleted bool
// deleteEpoch counts the times isDeleted was raised, all of them under the
@@ -54,6 +58,9 @@ type FileHandle struct {
// could not be read; the next flush reads it before publishing.
linkRefresh []byte
// pageWrites counts the pages added to dirtyPages, under the handle lock.
pageWrites atomic.Uint64
// entryVersionTsNs is the filer log position the handle's entry reflects.
// State at or below it must not replace the entry — that rolls it back.
entryVersionTsNs atomic.Int64
@@ -96,7 +103,7 @@ func newFileHandle(wfs *WFS, handleId FileHandleId, inode uint64, entry *filer_p
fh := &FileHandle{
fh: handleId,
counter: 1,
fhs: map[FileHandleId]struct{}{handleId: {}},
fhs: map[FileHandleId]bool{handleId: false},
inode: inode,
wfs: wfs,
}
@@ -337,6 +344,8 @@ func (fh *FileHandle) ResetDirtyPages() {
fh.dirtyPages.Destroy()
fh.dirtyPages = newPageWriter(fh, fh.wfs.option.ChunkSizeLimit)
fh.dirtyMetadata = false
fh.dirtyContent = false
fh.pendingAppend = false
fh.contentType = ""
}
+30 -2
View File
@@ -2,6 +2,7 @@ package mount
import (
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -65,12 +66,26 @@ func (i *FileHandleToInode) MarkInodeRenamed(inode uint64) {
// open — reads on it return ENOENT, which the kernel reports to read() as EIO.
// Callers must treat a draining report as "wait for the pending flush, then
// retry the whole acquire", not as success.
func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *filer_pb.Entry, versionTsNs int64, signature int32) (*FileHandle, FileHandleId, bool, bool) {
func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *filer_pb.Entry, versionTsNs int64, signature int32, appendMode ...bool) (*FileHandle, FileHandleId, bool, bool) {
// Bind before publishing the handle or queuing any async close. Capture
// under the inode-table lock, but release it before taking the fhMap lock.
var writebackError *atomic.Bool
if wfs.option.WritebackCache {
wfs.inodeToPath.RLock()
state, found := wfs.writebackContentErrors.Load(inode)
if !found {
state, _ = wfs.writebackContentErrors.LoadOrStore(inode, new(atomic.Bool))
}
writebackError = state.(*atomic.Bool)
wfs.inodeToPath.RUnlock()
}
i.Lock()
defer i.Unlock()
fh, found := i.inode2fh[inode]
if !found {
fh = newFileHandle(wfs, FileHandleId(util.RandomUint64()), inode, entry)
fh.writebackContentError = writebackError
fh.fhs[fh.fh] = len(appendMode) > 0 && appendMode[0]
fh.entryVersionTsNs.Store(versionTsNs)
fh.entryVersionSignature.Store(signature)
i.inode2fh[inode] = fh
@@ -82,11 +97,20 @@ func (i *FileHandleToInode) AcquireFileHandle(wfs *WFS, inode uint64, entry *fil
}
fh.counter++
openFh := FileHandleId(util.RandomUint64())
fh.fhs[openFh] = struct{}{}
fh.fhs[openFh] = len(appendMode) > 0 && appendMode[0]
i.fh2inode[openFh] = inode
return fh, openFh, true, false
}
func (i *FileHandleToInode) isAppendHandle(openFh FileHandleId) bool {
i.RLock()
defer i.RUnlock()
if fh := i.inode2fh[i.fh2inode[openFh]]; fh != nil {
return fh.fhs[openFh]
}
return false
}
func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
i.Lock()
defer i.Unlock()
@@ -118,6 +142,10 @@ func (i *FileHandleToInode) ReleaseByHandle(fh FileHandleId) *FileHandle {
// via FindFileHandle during the background drain.
return fhHandle
}
// Fence before a reopen can see the inode without this handle.
if fhHandle.dirtyContent && !fhHandle.isDeleted {
(&contentPublication{failure: fhHandle.writebackContentError}).abandon()
}
delete(i.inode2fh, inode)
for openFh := range fhHandle.fhs {
delete(i.fh2inode, openFh)
+72
View File
@@ -0,0 +1,72 @@
//go:build !freebsd
package mount
import (
"bytes"
"io"
"testing"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/protobuf/proto"
)
// A FLUSH from another fd of the open file uploads its pages, then a WRITE
// lands before it commits. The commit carries the new size but not the
// write's chunk, so the next flush must still publish that chunk.
func TestFlushRacingWriteKeepsHandleDirty(t *testing.T) {
base := attributeAppendEntry(1)
base.CommitTsNs = 100
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 100)
fh := w.GetHandle(FileHandleId(handle))
write := func(offset uint64, value byte) {
t.Helper()
n, code := w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle, Offset: offset, Size: 256}, bytes.Repeat([]byte{value}, 256))
if n != 256 || code != fuse.OK {
t.Fatalf("write at %d: %d %v", offset, n, code)
}
}
flush := func() fuse.Status {
return w.Flush(nil, &fuse.FlushIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: handle})
}
uploading, resume := make(chan struct{}), make(chan struct{})
upload := fh.dirtyPages.randomWriter.(*ChunkedDirtyPages).saveDataAsChunk
first := true
fh.dirtyPages.randomWriter.(*ChunkedDirtyPages).saveDataAsChunk = func(p util.FullPath) filer.SaveDataAsChunkFunctionType {
save := upload(p)
return func(r io.Reader, name string, offset, ts int64, ttl uint64) (*filer_pb.FileChunk, error) {
if first {
first = false
close(uploading)
<-resume
}
return save(r, name, offset, ts, ttl)
}
}
write(256, 'A')
racing := make(chan fuse.Status, 1)
go func() { racing <- flush() }()
<-uploading
write(512, 'B')
close(resume)
if code := <-racing; code != fuse.OK {
t.Fatalf("racing flush: %v", code)
}
if code := flush(); code != fuse.OK {
t.Fatalf("owner flush: %v", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
want := append(bytes.Repeat([]byte{'O'}, 256), bytes.Repeat([]byte{'A'}, 256)...)
want = append(want, bytes.Repeat([]byte{'B'}, 256)...)
if got := g6StoredBytes(t, peer); !bytes.Equal(got, want) {
t.Fatalf("stored size %d chunks %v: the racing write's bytes were not published", peer.entry.Attributes.FileSize, peer.entry.Chunks)
}
}
+4 -3
View File
@@ -17,7 +17,8 @@ func NewActivityScore() *ActivityScore {
func (as *ActivityScore) MarkRead() {
now := time.Now().UnixNano()
last := atomic.SwapInt64(&as.lastActiveTsNs, now)
deltaTime := (now - last) >> 30 // about number of seconds
// Concurrent timestamp swaps or a clock adjustment can make last newer than now.
deltaTime := max(0, min(63, (now-last)>>30)) // about number of seconds
for {
old := atomic.LoadInt64(&as.decayedActivenessScore)
score := old>>deltaTime + 256
@@ -33,7 +34,7 @@ func (as *ActivityScore) MarkRead() {
func (as *ActivityScore) MarkWrite() {
now := time.Now().UnixNano()
last := atomic.SwapInt64(&as.lastActiveTsNs, now)
deltaTime := (now - last) >> 30 // about number of seconds
deltaTime := max(0, min(63, (now-last)>>30)) // about number of seconds
for {
old := atomic.LoadInt64(&as.decayedActivenessScore)
score := old>>deltaTime + 1024
@@ -47,6 +48,6 @@ func (as *ActivityScore) MarkWrite() {
}
func (as *ActivityScore) ActivityScore() int64 {
deltaTime := (time.Now().UnixNano() - atomic.LoadInt64(&as.lastActiveTsNs)) >> 30
deltaTime := max(0, min(63, (time.Now().UnixNano()-atomic.LoadInt64(&as.lastActiveTsNs))>>30))
return atomic.LoadInt64(&as.decayedActivenessScore) >> deltaTime
}
@@ -0,0 +1,39 @@
package page_writer
import (
"sync/atomic"
"testing"
"time"
)
func TestActivityScoreHandlesFutureTimestamp(t *testing.T) {
for _, test := range []struct {
name string
call func(*ActivityScore) int64
want int64
}{
{"MarkRead", func(score *ActivityScore) int64 {
score.MarkRead()
return score.ActivityScore()
}, 4352},
{"MarkWrite", func(score *ActivityScore) int64 {
score.MarkWrite()
return score.ActivityScore()
}, 5120},
{"ActivityScore", (*ActivityScore).ActivityScore, 4096},
} {
t.Run(test.name, func(t *testing.T) {
score := NewActivityScore()
atomic.StoreInt64(&score.lastActiveTsNs, time.Now().Add(time.Hour).UnixNano())
atomic.StoreInt64(&score.decayedActivenessScore, 4096)
defer func() {
if caught := recover(); caught != nil {
t.Fatalf("future last-active timestamp must not panic: %v", caught)
}
}()
if got := test.call(score); got != test.want {
t.Fatalf("score=%d, want %d without backwards-time decay", got, test.want)
}
})
}
}
+2
View File
@@ -133,6 +133,8 @@ type Option struct {
}
type WFS struct {
// Metadata-only refusal token, detached at final Forget; no live resources retained.
writebackContentErrors sync.Map
// https://dl.acm.org/doi/fullHtml/10.1145/3310148
// follow https://github.com/hanwen/go-fuse/blob/master/fuse/api.go
fuse.RawFileSystem
+6 -1
View File
@@ -61,6 +61,7 @@ func (wfs *WFS) completeAsyncFlush(fh *FileHandle) {
// is a permanent one and the chunk data has been freed.
if err := fh.dirtyPages.FlushData(); err != nil {
glog.Errorf("completeAsyncFlush inode %d: data flush failed: %v", fh.inode, err)
(&contentPublication{failure: fh.writebackContentError}).abandon()
// Data is lost at this point. Proceed to cleanup to avoid resource leaks and unmount hangs.
} else if fh.dirtyMetadata {
// Phase 2: Flush metadata unless the file was explicitly unlinked.
@@ -139,10 +140,11 @@ func isFilerUnreachable(err error) bool {
// nothing else holds these references: like the writeback chunk uploads, it
// keeps retrying for as long as the filer is unreachable.
func (wfs *WFS) flushMetadataWithRetry(fh *FileHandle, dir, name string, fileFullPath util.FullPath) error {
publication := &contentPublication{failure: fh.writebackContentError, writes: fh.pageWrites.Load()}
attempts := 0
err := retryMetadataFlushUntil(context.Background(), func() error {
attempts++
return wfs.flushMetadataToFiler(context.Background(), fh, dir, name, fh.asyncFlushUid, fh.asyncFlushGid, nil)
return wfs.flushMetadataToFiler(context.Background(), fh, dir, name, fh.asyncFlushUid, fh.asyncFlushGid, nil, publication)
}, isFilerUnreachable, func(nextAttempt, totalAttempts int, backoff time.Duration, err error) {
if totalAttempts == 0 {
glog.Warningf("completeAsyncFlush %s: filer unreachable, retrying metadata flush (attempt %d) after %v: %v",
@@ -153,6 +155,9 @@ func (wfs *WFS) flushMetadataWithRetry(fh *FileHandle, dir, name string, fileFul
fileFullPath, nextAttempt, totalAttempts, backoff, err)
})
if err != nil {
if fh.dirtyContent {
publication.abandon()
}
glog.Errorf("completeAsyncFlush %s: metadata flush failed after %d attempts: %v - "+
"chunks are uploaded but NOT referenced in filer metadata; "+
"they will appear as orphans in volume.fsck",
+141
View File
@@ -80,6 +80,147 @@ func TestFlushMetadataWithRetryStopsOnFilerRefusal(t *testing.T) {
}
}
// Under writeback the kernel already moved EOF past the stored entry, so a
// drain that gives up must fence the inode whatever the filer answered.
func TestAbandonedWritebackFlushFencesInode(t *testing.T) {
originalSleep := metadataFlushSleep
t.Cleanup(func() {
metadataFlushSleep = originalSleep
})
metadataFlushSleep = func(ctx context.Context, d time.Duration) {}
for _, content := range []bool{true, false} {
const name = "abandoned-writeback.log"
wfs, _ := newCreateTestWFS(t)
fake := &rejectingCreateFiler{rejections: 1 << 20, refuse: func(req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
return nil, status.Error(codes.PermissionDenied, "denied")
}}
startFakeFiler(t, wfs, fake)
out := &fuse.CreateOut{}
if code := wfs.Create(make(chan struct{}), &fuse.CreateIn{
InHeader: fuse.InHeader{NodeId: 1},
Flags: syscall.O_WRONLY | syscall.O_CREAT,
Mode: 0o644,
}, name, out); code != fuse.OK {
t.Fatalf("Create status = %v, want OK", code)
}
fh := wfs.GetHandle(FileHandleId(out.Fh))
if fh == nil {
t.Fatal("Create did not register an open file handle")
}
wfs.option.WritebackCache = true
fh.writebackContentError = new(atomic.Bool)
fh.dirtyMetadata = true
fh.dirtyContent = content
if err := wfs.flushMetadataWithRetry(fh, "/", name, util.FullPath("/").Child(name)); err == nil {
t.Fatal("flush against a refusing filer succeeded")
}
if got := fh.writebackContentError.Load(); got != content {
t.Fatalf("content=%v: fenced after abandoned writeback flush = %v, want %v", content, got, content)
}
if !content {
continue
}
if err := wfs.checkContentPublication(fh, nil); !errors.Is(err, filer_pb.ErrPreconditionFailed) {
t.Fatalf("checkContentPublication after abandonment = %v, want a precondition refusal", err)
}
}
}
func TestFailedFlockReleaseFencesInode(t *testing.T) {
originalSleep := metadataFlushSleep
t.Cleanup(func() {
metadataFlushSleep = originalSleep
})
metadataFlushSleep = func(ctx context.Context, d time.Duration) {}
for _, c := range []struct {
name string
content bool
truncate bool
wantFenced bool
}{
{"content", true, false, true},
{"metadata only", false, false, false},
{"truncate", false, true, true},
} {
t.Run(c.name, func(t *testing.T) {
const name = "flock-release.log"
wfs, _ := newCreateTestWFS(t)
wfs.posixLocks = NewPosixLockTable()
fake := &rejectingCreateFiler{rejections: 1 << 20, refuse: func(req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
return nil, status.Error(codes.PermissionDenied, "denied")
}}
startFakeFiler(t, wfs, fake)
out := &fuse.CreateOut{}
if code := wfs.Create(make(chan struct{}), &fuse.CreateIn{
InHeader: fuse.InHeader{NodeId: 1},
Flags: syscall.O_WRONLY | syscall.O_CREAT,
Mode: 0o644,
}, name, out); code != fuse.OK {
t.Fatalf("Create status = %v, want OK", code)
}
fh := wfs.GetHandle(FileHandleId(out.Fh))
if fh == nil {
t.Fatal("Create did not register an open file handle")
}
wfs.option.WritebackCache = true
fenced := new(atomic.Bool)
fh.writebackContentError = fenced
fh.dirtyMetadata = true
fh.dirtyContent = c.content
if c.truncate {
if code := wfs.SetAttr(make(chan struct{}), &fuse.SetAttrIn{SetAttrInCommon: fuse.SetAttrInCommon{
InHeader: fuse.InHeader{NodeId: out.NodeId},
Valid: fuse.FATTR_SIZE | fuse.FATTR_FH,
Fh: out.Fh,
Size: 64,
}}, &fuse.AttrOut{}); code != fuse.OK {
t.Fatalf("SetAttr size = %v, want OK", code)
}
}
wfs.Release(make(chan struct{}), &fuse.ReleaseIn{
InHeader: fuse.InHeader{NodeId: out.NodeId},
Fh: out.Fh,
ReleaseFlags: fuse.FUSE_RELEASE_FLOCK_UNLOCK,
})
if fake.calls.Load() == 0 {
t.Fatal("synchronous release did not attempt the flush")
}
if got := fenced.Load(); got != c.wantFenced {
t.Fatalf("fenced after failed release = %v, want %v", got, c.wantFenced)
}
})
}
}
func TestReleaseFencesBeforeReopenSeesInode(t *testing.T) {
wfs, _ := newCreateTestWFS(t)
wfs.option.WritebackCache = true
const inode = 42
entry := &filer_pb.Entry{Name: "f", Attributes: &filer_pb.FuseAttributes{}}
fh, id, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 1, 0)
fh.dirtyMetadata = true
fh.dirtyContent = true
released := wfs.fhMap.ReleaseByHandle(id)
if released != fh {
t.Fatal("last release did not hand back the handle")
}
reopened, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 1, 0)
if reopened == fh {
t.Fatal("reopen reused the released handle")
}
if err := wfs.checkContentPublication(reopened, nil); !errors.Is(err, filer_pb.ErrPreconditionFailed) {
t.Fatalf("publication on a reopen after an abandoned release = %v, want a precondition refusal", err)
}
released.ReleaseHandle()
}
func TestIsFilerUnreachable(t *testing.T) {
path := "/unavailable/transport.log"
cases := []struct {
+3
View File
@@ -191,6 +191,9 @@ func (wfs *WFS) SetAttr(cancel <-chan struct{}, input *fuse.SetAttrIn, out *fuse
if fh != nil {
fh.dirtyMetadata = true
if includeSize {
fh.dirtyContent = true
}
return fuse.OK
}
if path == "" {
+9 -2
View File
@@ -188,9 +188,11 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
glog.Errorf("AddPage error: %v", err)
return 0, writeErrorToFuseStatus(err)
}
fhOut.pageWrites.Add(1)
// Accumulate for the next loop iteration
totalCopied += numBytesRead
fhOut.dirtyContent = true
}
if totalCopied == 0 {
@@ -209,6 +211,10 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
}
func (wfs *WFS) tryServerSideWholeFileCopy(cancel <-chan struct{}, in *fuse.CopyFileRangeIn, fhIn, fhOut *FileHandle) (written uint32, handled bool, code fuse.Status) {
if err := wfs.checkContentPublication(fhOut, nil); err != nil {
glog.V(4).Infof("server-side copy: skipped (%v)", err)
return 0, false, fuse.OK
}
copyRequest, ok := wholeFileServerCopyCandidate(fhIn, fhOut, in)
if !ok {
return 0, false, fuse.OK
@@ -256,6 +262,7 @@ func (wfs *WFS) applyServerSideWholeFileCopyResult(fhIn, fhOut *FileHandle, dstP
fhOut.contentType = entry.Attributes.Mime
}
fhOut.dirtyMetadata = false
fhOut.dirtyContent = false
wfs.updateServerSideWholeFileCopyMetaCache(dstPath, entry)
// Note: we intentionally skip fuseServer.InodeNotify/EntryNotify here.
// This runs inside the CopyFileRange request handler; those notifies
@@ -316,8 +323,8 @@ func wholeFileServerCopyCandidate(fhIn, fhOut *FileHandle, in *fuse.CopyFileRang
glog.V(4).Infof("server-side copy: skipped (same file handle)")
return wholeFileServerCopyRequest{}, false
}
if fhIn.dirtyMetadata || fhOut.dirtyMetadata {
glog.V(4).Infof("server-side copy: skipped (dirty metadata: in=%v out=%v)", fhIn.dirtyMetadata, fhOut.dirtyMetadata)
if fhIn.dirtyMetadata || fhIn.dirtyContent || fhOut.dirtyMetadata || fhOut.dirtyContent {
glog.V(4).Infof("server-side copy: skipped (dirty handle: in=%v/%v out=%v/%v)", fhIn.dirtyMetadata, fhIn.dirtyContent, fhOut.dirtyMetadata, fhOut.dirtyContent)
return wholeFileServerCopyRequest{}, false
}
if in.OffIn != 0 || in.OffOut != 0 {
+86
View File
@@ -72,6 +72,14 @@ func TestWholeFileServerCopyCandidate(t *testing.T) {
}
srcHandle.dirtyMetadata = false
for _, h := range []*FileHandle{srcHandle, dstHandle} {
h.dirtyContent = true
if _, ok := wholeFileServerCopyCandidate(srcHandle, dstHandle, in); ok {
t.Fatal("handle with unpublished content should disable whole-file server copy")
}
h.dirtyContent = false
}
in.Len = 4
if _, ok := wholeFileServerCopyCandidate(srcHandle, dstHandle, in); ok {
t.Fatal("short copy request should disable whole-file server copy")
@@ -355,3 +363,81 @@ func newCopyRangeTestWFSWithMetaCache(t *testing.T) *WFS {
return wfs
}
func TestStreamingCopyMarksOnlyAcceptedContentDirty(t *testing.T) {
for _, c := range []struct {
name string
addFails bool
wantOK bool
wantDirty bool
}{
{"accepted", false, true, true},
{"rejected first page", true, false, false},
} {
t.Run(c.name, func(t *testing.T) {
wfs := newCopyRangeTestWFS()
srcInode := wfs.inodeToPath.Lookup(util.FullPath("/src.txt"), 1, false, false, 0, true)
dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dst.txt"), 1, false, false, 0, true)
srcHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
Name: "src.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: srcInode},
Content: []byte("hello"),
}, 0, 0)
dstHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
Name: "dst.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: dstInode},
}, 0, 0)
if c.addFails {
dstHandle.dirtyPages.randomWriter.(*ChunkedDirtyPages).setLastError(errors.New("swap file unavailable"))
}
_, status := wfs.CopyFileRange(make(chan struct{}), &fuse.CopyFileRangeIn{
FhIn: uint64(srcHandle.fh),
FhOut: uint64(dstHandle.fh),
OffIn: 1,
OffOut: 0,
Len: 4,
})
if (status == fuse.OK) != c.wantOK {
t.Fatalf("CopyFileRange status = %v, want OK = %v", status, c.wantOK)
}
if dstHandle.dirtyContent != c.wantDirty {
t.Fatalf("dirtyContent = %v, want %v", dstHandle.dirtyContent, c.wantDirty)
}
})
}
}
func TestServerSideCopySkipsFencedDestination(t *testing.T) {
wfs := newCopyRangeTestWFS()
wfs.option.WritebackCache = true
srcInode := wfs.inodeToPath.Lookup(util.FullPath("/src.txt"), 1, false, false, 0, true)
dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dst.txt"), 1, false, false, 0, true)
srcHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{
Name: "src.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: srcInode},
Content: []byte("hello"),
}, 0, 0)
dstHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{
Name: "dst.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: dstInode},
}, 0, 0)
srcHandle.RememberPath("/src.txt")
dstHandle.RememberPath("/dst.txt")
dstHandle.writebackContentError.Store(true)
originalCopy := performServerSideWholeFileCopy
t.Cleanup(func() { performServerSideWholeFileCopy = originalCopy })
performServerSideWholeFileCopy = func(<-chan struct{}, *WFS, wholeFileServerCopyRequest) (*filer_pb.Entry, entryVersion, serverSideWholeFileCopyOutcome, error) {
t.Fatal("fenced destination must not publish through the filer copy")
return nil, entryVersion{}, serverSideWholeFileCopyCommitted, nil
}
if _, handled, _ := wfs.tryServerSideWholeFileCopy(make(chan struct{}), &fuse.CopyFileRangeIn{
FhIn: uint64(srcHandle.fh),
FhOut: uint64(dstHandle.fh),
Len: 8,
}, srcHandle, dstHandle); handled {
t.Fatal("fenced destination should fall back to the streaming copy")
}
}
+1 -1
View File
@@ -102,7 +102,7 @@ func (wfs *WFS) Create(cancel <-chan struct{}, in *fuse.CreateIn, name string, o
var openFh FileHandleId
var existed, draining bool
for {
fileHandle, openFh, existed, draining = wfs.fhMap.AcquireFileHandle(wfs, inode, newEntry, 0, 0)
fileHandle, openFh, existed, draining = wfs.fhMap.AcquireFileHandle(wfs, inode, newEntry, 0, 0, in.Flags&syscall.O_APPEND != 0)
if !draining {
break
}
+25 -5
View File
@@ -191,6 +191,7 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
// Synchronous flush path (normal mode, fsync, or no dirty data)
fh.asyncFlushPending = false
publication := &contentPublication{failure: fh.writebackContentError, writes: fh.pageWrites.Load()}
// Check quota including uncommitted writes for real-time enforcement
isOverQuota := wfs.IsOverQuotaWithUncommitted()
@@ -223,13 +224,16 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
}
if err := retryMetadataFlushIf(ctx, func() error {
return wfs.flushMetadataToFiler(ctx, fh, dir, name, uid, gid, commit)
return wfs.flushMetadataToFiler(ctx, fh, dir, name, uid, gid, commit, publication)
}, func(err error) bool {
return !commit.spent() && isRetryableFilerError(err)
}, func(nextAttempt, totalAttempts int, backoff time.Duration, err error) {
glog.Warningf("%v fh %d flush: retrying metadata flush (attempt %d/%d) after %v: %v",
fileFullPath, fh.fh, nextAttempt, totalAttempts, backoff, err)
}); err != nil {
if fh.dirtyContent {
publication.retire(err)
}
glog.Errorf("%v fh %d flush: %v", fileFullPath, fh.fh, err)
return grpcErrorToFuseStatus(err)
}
@@ -250,7 +254,11 @@ func (wfs *WFS) doFlush(ctx context.Context, fh *FileHandle, uid, gid uint32, al
//
// commit bounds the filer calls made here, over all attempts of one flush; nil
// leaves them to the per-call filer timeouts.
func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, name string, uid, gid uint32, commit *commitBudget) error {
func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, name string, uid, gid uint32, commit *commitBudget, publications ...*contentPublication) error {
publication := &contentPublication{writes: fh.pageWrites.Load()}
if len(publications) > 0 {
publication = publications[0]
}
fileFullPath, dir, name := wfs.flushTarget(fh, dir, name)
var unlock func()
var fhActiveLock *util.ActiveLock
@@ -355,7 +363,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
// The chunk merge and the manifest above read and upload chunks, which can
// take longer than the whole commit budget. It is charged only from here.
commitCtx, end := commit.begin(ctx)
resp, merged, err := wfs.createContentEntry(commitCtx, fh, request, baseSnapshot, false)
resp, merged, err := wfs.createContentEntry(commitCtx, fh, request, baseSnapshot, false, publication)
end()
if err != nil {
glog.Errorf("fh flush create %s: %v", fileFullPath, err)
@@ -383,8 +391,10 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(dir))
}
if err == nil {
if err == nil && fh.pageWrites.Load() == publication.writes {
fh.pendingAppend = false
fh.dirtyMetadata = false
fh.dirtyContent = false
}
return err
@@ -413,7 +423,7 @@ func (wfs *WFS) flushTarget(fh *FileHandle, dir, name string) (util.FullPath, st
// replayed onto it and published against it, so a peer's acknowledged chunks
// survive. merged is that entry in local ids; nil when the request went as is.
// With writes still buffered, the merge must keep room for them.
func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request *filer_pb.CreateEntryRequest, local *filer_pb.Entry, buffered bool) (resp *filer_pb.CreateEntryResponse, merged *filer_pb.Entry, err error) {
func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request *filer_pb.CreateEntryRequest, local *filer_pb.Entry, buffered bool, publication *contentPublication) (resp *filer_pb.CreateEntryResponse, merged *filer_pb.Entry, err error) {
base := fh.baseEntry.Load()
guard := &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}
if base != nil {
@@ -423,10 +433,16 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
}
sent := request.Entry
for attempt := 0; ; attempt++ {
if guardErr := wfs.checkContentPublication(fh, guard.ExpectedEntry); guardErr != nil {
return nil, nil, guardErr
}
request.Condition = &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{guard}}
err = wfs.withFilerClient(ctx, false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
var callErr error
resp, callErr = filer_pb.CreateEntryWithResponse(ctx, client, request)
if errors.Is(callErr, filer_pb.ErrPreconditionFailed) {
publication.refused = true
}
return callErr
})
if err == nil && request.Entry != sent {
@@ -583,6 +599,10 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
size = int64(localSize)
}
merged.Attributes.FileSize = uint64(size)
// A peer truncate must not turn local pending data into a successful hole.
if filer.FileSize(stored) < filer.FileSize(base) && contentGapAfter(merged, filer.FileSize(stored)) {
return nil, false
}
return merged, true
}
+17
View File
@@ -10,6 +10,14 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// isAppendWrite honors current F_SETFL flags; adapters without flags use the open.
func (wfs *WFS) isAppendWrite(in *fuse.WriteIn) bool {
if in.Flags != 0 {
return in.Flags&syscall.O_APPEND != 0
}
return wfs.fhMap.isAppendHandle(FileHandleId(in.Fh))
}
/**
* Write data
*
@@ -60,6 +68,13 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
return 0, fuse.OK
}
// Only an append past all locally owned bytes needs the stored EOF guard.
if in.Offset > entry.Attributes.FileSize && wfs.isAppendWrite(in) {
if !fh.pendingAppend || in.Offset < fh.pendingAppendOffset {
fh.pendingAppendOffset = in.Offset
}
fh.pendingAppend = true
}
entry.Content = nil
offset := int64(in.Offset)
oldFileSize := int64(entry.Attributes.FileSize)
@@ -87,6 +102,7 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
glog.Errorf("AddPage error: %v", err)
return 0, writeErrorToFuseStatus(err)
}
fh.pageWrites.Add(1)
written = uint32(len(data))
@@ -96,6 +112,7 @@ func (wfs *WFS) Write(cancel <-chan struct{}, in *fuse.WriteIn, data []byte) (wr
}
fh.dirtyMetadata = true
fh.dirtyContent = true
// Invalidate the mtime cache so the next Open will not set FOPEN_KEEP_CACHE.
wfs.invalidateOpenMtimeCache(in.NodeId)
+1 -1
View File
@@ -70,7 +70,7 @@ func (wfs *WFS) AcquireHandle(ctx context.Context, inode uint64, flags, uid, gid
}
// need to AcquireFileHandle again to ensure correct handle counter
var existed, draining bool
fileHandle, openFh, existed, draining = wfs.fhMap.AcquireFileHandle(wfs, inode, entry, entryVersionTsNs.tsNs, entryVersionTsNs.signature)
fileHandle, openFh, existed, draining = wfs.fhMap.AcquireFileHandle(wfs, inode, entry, entryVersionTsNs.tsNs, entryVersionTsNs.signature, flags&syscall.O_APPEND != 0)
if draining {
// A RELEASE slipped between waitForPendingAsyncFlush and this
// attach: the handle's last open closed and its deferred flush
+4 -1
View File
@@ -68,7 +68,10 @@ func (wfs *WFS) Forget(nodeid, nlookup uint64) {
wfs.inodeToPath.Forget(nodeid, nlookup,
// Runs at the release, under the table's lock, so a lookup that
// rebuilds the same inode number afterwards keeps the times it sets.
wfs.forgetInMemoryTimes,
func(inode uint64) {
wfs.forgetInMemoryTimes(inode)
wfs.writebackContentErrors.Delete(inode)
},
func(dir util.FullPath) {
// Runs after Forget releases its lock; a concurrent lookup+rebuild can
// re-cache the directory in that window, so purge through the apply loop
+1 -1
View File
@@ -188,7 +188,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
baseSnapshot := proto.Clone(requestEntry).(*filer_pb.Entry)
wfs.mapPbIdFromLocalToFiler(request.Entry)
resp, merged, err := wfs.createContentEntry(context.Background(), fh, request, baseSnapshot, true)
resp, merged, err := wfs.createContentEntry(context.Background(), fh, request, baseSnapshot, true, &contentPublication{})
if err != nil {
return err
}
+7
View File
@@ -41,6 +41,9 @@ enum ActionKind {
// to the appropriate internal helper.
service SeaweedS3LifecycleInternal {
rpc LifecycleDelete(LifecycleDeleteRequest) returns (LifecycleDeleteResponse);
// LifecycleReady runs LifecycleDelete's authorization and nothing else,
// so a worker can check a front before it starts a pass.
rpc LifecycleReady(LifecycleReadyRequest) returns (LifecycleReadyResponse);
}
// LifecycleDeleteOutcome captures every per-event verdict the worker needs.
@@ -93,6 +96,10 @@ message LifecycleDeleteResponse {
string reason = 2;
}
message LifecycleReadyRequest {}
message LifecycleReadyResponse {}
// MessagePosition mirrors weed/util/log_buffer.MessagePosition for durable
// storage. ts_ns + offset uniquely identifies a position within a per-filer
// log buffer; per-shard cursors (see ReaderState) use this shape to skip past
+186 -107
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v6.33.4
// protoc v3.21.12
// source: s3_lifecycle.proto
package s3_lifecycle_pb
@@ -270,7 +270,7 @@ func (x LifecycleState_RuleMode) Number() protoreflect.EnumNumber {
// Deprecated: Use LifecycleState_RuleMode.Descriptor instead.
func (LifecycleState_RuleMode) EnumDescriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5, 0}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7, 0}
}
// DEGRADED_REASON_UNSPECIFIED replaces the old NONE sentinel: an unset
@@ -334,7 +334,7 @@ func (x LifecycleState_DegradedReason) Number() protoreflect.EnumNumber {
// Deprecated: Use LifecycleState_DegradedReason.Descriptor instead.
func (LifecycleState_DegradedReason) EnumDescriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5, 1}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7, 1}
}
type LifecycleDeleteRequest struct {
@@ -524,6 +524,78 @@ func (x *LifecycleDeleteResponse) GetReason() string {
return ""
}
type LifecycleReadyRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *LifecycleReadyRequest) Reset() {
*x = LifecycleReadyRequest{}
mi := &file_s3_lifecycle_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *LifecycleReadyRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LifecycleReadyRequest) ProtoMessage() {}
func (x *LifecycleReadyRequest) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LifecycleReadyRequest.ProtoReflect.Descriptor instead.
func (*LifecycleReadyRequest) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{2}
}
type LifecycleReadyResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *LifecycleReadyResponse) Reset() {
*x = LifecycleReadyResponse{}
mi := &file_s3_lifecycle_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *LifecycleReadyResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*LifecycleReadyResponse) ProtoMessage() {}
func (x *LifecycleReadyResponse) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use LifecycleReadyResponse.ProtoReflect.Descriptor instead.
func (*LifecycleReadyResponse) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{3}
}
// MessagePosition mirrors weed/util/log_buffer.MessagePosition for durable
// storage. ts_ns + offset uniquely identifies a position within a per-filer
// log buffer; per-shard cursors (see ReaderState) use this shape to skip past
@@ -538,7 +610,7 @@ type MessagePosition struct {
func (x *MessagePosition) Reset() {
*x = MessagePosition{}
mi := &file_s3_lifecycle_proto_msgTypes[2]
mi := &file_s3_lifecycle_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -550,7 +622,7 @@ func (x *MessagePosition) String() string {
func (*MessagePosition) ProtoMessage() {}
func (x *MessagePosition) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[2]
mi := &file_s3_lifecycle_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -563,7 +635,7 @@ func (x *MessagePosition) ProtoReflect() protoreflect.Message {
// Deprecated: Use MessagePosition.ProtoReflect.Descriptor instead.
func (*MessagePosition) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{2}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{4}
}
func (x *MessagePosition) GetTsNs() int64 {
@@ -593,7 +665,7 @@ type FilerShardCursor struct {
func (x *FilerShardCursor) Reset() {
*x = FilerShardCursor{}
mi := &file_s3_lifecycle_proto_msgTypes[3]
mi := &file_s3_lifecycle_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -605,7 +677,7 @@ func (x *FilerShardCursor) String() string {
func (*FilerShardCursor) ProtoMessage() {}
func (x *FilerShardCursor) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[3]
mi := &file_s3_lifecycle_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -618,7 +690,7 @@ func (x *FilerShardCursor) ProtoReflect() protoreflect.Message {
// Deprecated: Use FilerShardCursor.ProtoReflect.Descriptor instead.
func (*FilerShardCursor) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{3}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5}
}
func (x *FilerShardCursor) GetFilerId() string {
@@ -650,7 +722,7 @@ type EntryIdentity struct {
func (x *EntryIdentity) Reset() {
*x = EntryIdentity{}
mi := &file_s3_lifecycle_proto_msgTypes[4]
mi := &file_s3_lifecycle_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -662,7 +734,7 @@ func (x *EntryIdentity) String() string {
func (*EntryIdentity) ProtoMessage() {}
func (x *EntryIdentity) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[4]
mi := &file_s3_lifecycle_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -675,7 +747,7 @@ func (x *EntryIdentity) ProtoReflect() protoreflect.Message {
// Deprecated: Use EntryIdentity.ProtoReflect.Descriptor instead.
func (*EntryIdentity) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{4}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{6}
}
func (x *EntryIdentity) GetMtimeNs() int64 {
@@ -730,15 +802,15 @@ type LifecycleState struct {
LastSafetyScanTsNs int64 `protobuf:"varint,10,opt,name=last_safety_scan_ts_ns,json=lastSafetyScanTsNs,proto3" json:"last_safety_scan_ts_ns,omitempty"`
NextSafetyScanTsNs int64 `protobuf:"varint,11,opt,name=next_safety_scan_ts_ns,json=nextSafetyScanTsNs,proto3" json:"next_safety_scan_ts_ns,omitempty"`
// Counters for observability; no behavior depends on these.
// - evaluated_total: live entries the worker considered for this action
// (filter-matched + due-checked); includes objects that ended up not
// yet eligible.
// - expired_total: successful DONE outcomes (object/version/marker/MPU
// removed) under this action.
// - metadata_only_total: subset of expired_total where the worker
// short-circuited via volume-TTL routing (chunks left to volume GC).
// - error_total: outcomes that did NOT advance the cursor under this
// action (RETRY_LATER, BLOCKED, FATAL_EVENT_ERROR).
// - evaluated_total: live entries the worker considered for this action
// (filter-matched + due-checked); includes objects that ended up not
// yet eligible.
// - expired_total: successful DONE outcomes (object/version/marker/MPU
// removed) under this action.
// - metadata_only_total: subset of expired_total where the worker
// short-circuited via volume-TTL routing (chunks left to volume GC).
// - error_total: outcomes that did NOT advance the cursor under this
// action (RETRY_LATER, BLOCKED, FATAL_EVENT_ERROR).
EvaluatedTotal int64 `protobuf:"varint,12,opt,name=evaluated_total,json=evaluatedTotal,proto3" json:"evaluated_total,omitempty"`
ExpiredTotal int64 `protobuf:"varint,13,opt,name=expired_total,json=expiredTotal,proto3" json:"expired_total,omitempty"`
MetadataOnlyTotal int64 `protobuf:"varint,14,opt,name=metadata_only_total,json=metadataOnlyTotal,proto3" json:"metadata_only_total,omitempty"`
@@ -749,7 +821,7 @@ type LifecycleState struct {
func (x *LifecycleState) Reset() {
*x = LifecycleState{}
mi := &file_s3_lifecycle_proto_msgTypes[5]
mi := &file_s3_lifecycle_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -761,7 +833,7 @@ func (x *LifecycleState) String() string {
func (*LifecycleState) ProtoMessage() {}
func (x *LifecycleState) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[5]
mi := &file_s3_lifecycle_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -774,7 +846,7 @@ func (x *LifecycleState) ProtoReflect() protoreflect.Message {
// Deprecated: Use LifecycleState.ProtoReflect.Descriptor instead.
func (*LifecycleState) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{5}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7}
}
func (x *LifecycleState) GetRuleHash() []byte {
@@ -897,7 +969,7 @@ type PendingItem struct {
func (x *PendingItem) Reset() {
*x = PendingItem{}
mi := &file_s3_lifecycle_proto_msgTypes[6]
mi := &file_s3_lifecycle_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -909,7 +981,7 @@ func (x *PendingItem) String() string {
func (*PendingItem) ProtoMessage() {}
func (x *PendingItem) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[6]
mi := &file_s3_lifecycle_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -922,7 +994,7 @@ func (x *PendingItem) ProtoReflect() protoreflect.Message {
// Deprecated: Use PendingItem.ProtoReflect.Descriptor instead.
func (*PendingItem) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{6}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{8}
}
func (x *PendingItem) GetObjectPath() string {
@@ -967,7 +1039,7 @@ type BootstrapState struct {
func (x *BootstrapState) Reset() {
*x = BootstrapState{}
mi := &file_s3_lifecycle_proto_msgTypes[7]
mi := &file_s3_lifecycle_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -979,7 +1051,7 @@ func (x *BootstrapState) String() string {
func (*BootstrapState) ProtoMessage() {}
func (x *BootstrapState) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[7]
mi := &file_s3_lifecycle_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -992,7 +1064,7 @@ func (x *BootstrapState) ProtoReflect() protoreflect.Message {
// Deprecated: Use BootstrapState.ProtoReflect.Descriptor instead.
func (*BootstrapState) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{7}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{9}
}
func (x *BootstrapState) GetLastScannedPath() string {
@@ -1038,7 +1110,7 @@ type ReaderState struct {
func (x *ReaderState) Reset() {
*x = ReaderState{}
mi := &file_s3_lifecycle_proto_msgTypes[8]
mi := &file_s3_lifecycle_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1050,7 +1122,7 @@ func (x *ReaderState) String() string {
func (*ReaderState) ProtoMessage() {}
func (x *ReaderState) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[8]
mi := &file_s3_lifecycle_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1063,7 +1135,7 @@ func (x *ReaderState) ProtoReflect() protoreflect.Message {
// Deprecated: Use ReaderState.ProtoReflect.Descriptor instead.
func (*ReaderState) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{8}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{10}
}
func (x *ReaderState) GetPrimaryFilerEndpoint() string {
@@ -1110,7 +1182,7 @@ type FilerShardCursorList struct {
func (x *FilerShardCursorList) Reset() {
*x = FilerShardCursorList{}
mi := &file_s3_lifecycle_proto_msgTypes[9]
mi := &file_s3_lifecycle_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1122,7 +1194,7 @@ func (x *FilerShardCursorList) String() string {
func (*FilerShardCursorList) ProtoMessage() {}
func (x *FilerShardCursorList) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[9]
mi := &file_s3_lifecycle_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1135,7 +1207,7 @@ func (x *FilerShardCursorList) ProtoReflect() protoreflect.Message {
// Deprecated: Use FilerShardCursorList.ProtoReflect.Descriptor instead.
func (*FilerShardCursorList) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{9}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{11}
}
func (x *FilerShardCursorList) GetCursors() []*FilerShardCursor {
@@ -1159,7 +1231,7 @@ type TailDrainedKey struct {
func (x *TailDrainedKey) Reset() {
*x = TailDrainedKey{}
mi := &file_s3_lifecycle_proto_msgTypes[10]
mi := &file_s3_lifecycle_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1171,7 +1243,7 @@ func (x *TailDrainedKey) String() string {
func (*TailDrainedKey) ProtoMessage() {}
func (x *TailDrainedKey) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[10]
mi := &file_s3_lifecycle_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1184,7 +1256,7 @@ func (x *TailDrainedKey) ProtoReflect() protoreflect.Message {
// Deprecated: Use TailDrainedKey.ProtoReflect.Descriptor instead.
func (*TailDrainedKey) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{10}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{12}
}
func (x *TailDrainedKey) GetStreamKind() StreamKind {
@@ -1241,7 +1313,7 @@ type BlockerRecord struct {
func (x *BlockerRecord) Reset() {
*x = BlockerRecord{}
mi := &file_s3_lifecycle_proto_msgTypes[11]
mi := &file_s3_lifecycle_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1253,7 +1325,7 @@ func (x *BlockerRecord) String() string {
func (*BlockerRecord) ProtoMessage() {}
func (x *BlockerRecord) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[11]
mi := &file_s3_lifecycle_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1266,7 +1338,7 @@ func (x *BlockerRecord) ProtoReflect() protoreflect.Message {
// Deprecated: Use BlockerRecord.ProtoReflect.Descriptor instead.
func (*BlockerRecord) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{11}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{13}
}
func (x *BlockerRecord) GetStreamKind() StreamKind {
@@ -1384,7 +1456,7 @@ type StreamKey struct {
func (x *StreamKey) Reset() {
*x = StreamKey{}
mi := &file_s3_lifecycle_proto_msgTypes[12]
mi := &file_s3_lifecycle_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1396,7 +1468,7 @@ func (x *StreamKey) String() string {
func (*StreamKey) ProtoMessage() {}
func (x *StreamKey) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[12]
mi := &file_s3_lifecycle_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1409,7 +1481,7 @@ func (x *StreamKey) ProtoReflect() protoreflect.Message {
// Deprecated: Use StreamKey.ProtoReflect.Descriptor instead.
func (*StreamKey) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{12}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{14}
}
func (x *StreamKey) GetKey() isStreamKey_Key {
@@ -1494,7 +1566,7 @@ type OriginalKey struct {
func (x *OriginalKey) Reset() {
*x = OriginalKey{}
mi := &file_s3_lifecycle_proto_msgTypes[13]
mi := &file_s3_lifecycle_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1506,7 +1578,7 @@ func (x *OriginalKey) String() string {
func (*OriginalKey) ProtoMessage() {}
func (x *OriginalKey) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[13]
mi := &file_s3_lifecycle_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1519,7 +1591,7 @@ func (x *OriginalKey) ProtoReflect() protoreflect.Message {
// Deprecated: Use OriginalKey.ProtoReflect.Descriptor instead.
func (*OriginalKey) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{13}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{15}
}
func (x *OriginalKey) GetShard() string {
@@ -1553,7 +1625,7 @@ type PredicateKey struct {
func (x *PredicateKey) Reset() {
*x = PredicateKey{}
mi := &file_s3_lifecycle_proto_msgTypes[14]
mi := &file_s3_lifecycle_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1565,7 +1637,7 @@ func (x *PredicateKey) String() string {
func (*PredicateKey) ProtoMessage() {}
func (x *PredicateKey) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[14]
mi := &file_s3_lifecycle_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1578,7 +1650,7 @@ func (x *PredicateKey) ProtoReflect() protoreflect.Message {
// Deprecated: Use PredicateKey.ProtoReflect.Descriptor instead.
func (*PredicateKey) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{14}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{16}
}
func (x *PredicateKey) GetShard() string {
@@ -1608,7 +1680,7 @@ type BootstrapKey struct {
func (x *BootstrapKey) Reset() {
*x = BootstrapKey{}
mi := &file_s3_lifecycle_proto_msgTypes[15]
mi := &file_s3_lifecycle_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1620,7 +1692,7 @@ func (x *BootstrapKey) String() string {
func (*BootstrapKey) ProtoMessage() {}
func (x *BootstrapKey) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[15]
mi := &file_s3_lifecycle_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1633,7 +1705,7 @@ func (x *BootstrapKey) ProtoReflect() protoreflect.Message {
// Deprecated: Use BootstrapKey.ProtoReflect.Descriptor instead.
func (*BootstrapKey) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{15}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{17}
}
func (x *BootstrapKey) GetBucket() string {
@@ -1684,7 +1756,7 @@ type PendingKey struct {
func (x *PendingKey) Reset() {
*x = PendingKey{}
mi := &file_s3_lifecycle_proto_msgTypes[16]
mi := &file_s3_lifecycle_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1696,7 +1768,7 @@ func (x *PendingKey) String() string {
func (*PendingKey) ProtoMessage() {}
func (x *PendingKey) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[16]
mi := &file_s3_lifecycle_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1709,7 +1781,7 @@ func (x *PendingKey) ProtoReflect() protoreflect.Message {
// Deprecated: Use PendingKey.ProtoReflect.Descriptor instead.
func (*PendingKey) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{16}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{18}
}
func (x *PendingKey) GetBucket() string {
@@ -1762,7 +1834,7 @@ type RetryBudgetEntry struct {
func (x *RetryBudgetEntry) Reset() {
*x = RetryBudgetEntry{}
mi := &file_s3_lifecycle_proto_msgTypes[17]
mi := &file_s3_lifecycle_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1774,7 +1846,7 @@ func (x *RetryBudgetEntry) String() string {
func (*RetryBudgetEntry) ProtoMessage() {}
func (x *RetryBudgetEntry) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[17]
mi := &file_s3_lifecycle_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1787,7 +1859,7 @@ func (x *RetryBudgetEntry) ProtoReflect() protoreflect.Message {
// Deprecated: Use RetryBudgetEntry.ProtoReflect.Descriptor instead.
func (*RetryBudgetEntry) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{17}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{19}
}
func (x *RetryBudgetEntry) GetKey() *StreamKey {
@@ -1836,7 +1908,7 @@ type RetryTarget struct {
func (x *RetryTarget) Reset() {
*x = RetryTarget{}
mi := &file_s3_lifecycle_proto_msgTypes[18]
mi := &file_s3_lifecycle_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1848,7 +1920,7 @@ func (x *RetryTarget) String() string {
func (*RetryTarget) ProtoMessage() {}
func (x *RetryTarget) ProtoReflect() protoreflect.Message {
mi := &file_s3_lifecycle_proto_msgTypes[18]
mi := &file_s3_lifecycle_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1861,7 +1933,7 @@ func (x *RetryTarget) ProtoReflect() protoreflect.Message {
// Deprecated: Use RetryTarget.ProtoReflect.Descriptor instead.
func (*RetryTarget) Descriptor() ([]byte, []int) {
return file_s3_lifecycle_proto_rawDescGZIP(), []int{18}
return file_s3_lifecycle_proto_rawDescGZIP(), []int{20}
}
func (x *RetryTarget) GetKey() *StreamKey {
@@ -1929,7 +2001,9 @@ const file_s3_lifecycle_proto_rawDesc = "" +
"\x12engine_snapshot_id\x18\x15 \x01(\x04R\x10engineSnapshotId\"t\n" +
"\x17LifecycleDeleteResponse\x12A\n" +
"\aoutcome\x18\x01 \x01(\x0e2'.s3_lifecycle_pb.LifecycleDeleteOutcomeR\aoutcome\x12\x16\n" +
"\x06reason\x18\x02 \x01(\tR\x06reason\">\n" +
"\x06reason\x18\x02 \x01(\tR\x06reason\"\x17\n" +
"\x15LifecycleReadyRequest\"\x18\n" +
"\x16LifecycleReadyResponse\">\n" +
"\x0fMessagePosition\x12\x13\n" +
"\x05ts_ns\x18\x01 \x01(\x03R\x04tsNs\x12\x16\n" +
"\x06offset\x18\x02 \x01(\x03R\x06offset\"k\n" +
@@ -2093,9 +2167,10 @@ const file_s3_lifecycle_proto_rawDesc = "" +
"\bORIGINAL\x10\x01\x12\r\n" +
"\tPREDICATE\x10\x02\x12\r\n" +
"\tBOOTSTRAP\x10\x03\x12\v\n" +
"\aPENDING\x10\x042\x82\x01\n" +
"\aPENDING\x10\x042\xe5\x01\n" +
"\x1aSeaweedS3LifecycleInternal\x12d\n" +
"\x0fLifecycleDelete\x12'.s3_lifecycle_pb.LifecycleDeleteRequest\x1a(.s3_lifecycle_pb.LifecycleDeleteResponseB\\\n" +
"\x0fLifecycleDelete\x12'.s3_lifecycle_pb.LifecycleDeleteRequest\x1a(.s3_lifecycle_pb.LifecycleDeleteResponse\x12a\n" +
"\x0eLifecycleReady\x12&.s3_lifecycle_pb.LifecycleReadyRequest\x1a'.s3_lifecycle_pb.LifecycleReadyResponseB\\\n" +
"\x10seaweedfs.clientB\x10S3LifecycleProtoZ6github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pbb\x06proto3"
var (
@@ -2111,7 +2186,7 @@ func file_s3_lifecycle_proto_rawDescGZIP() []byte {
}
var file_s3_lifecycle_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
var file_s3_lifecycle_proto_msgTypes = make([]protoimpl.MessageInfo, 20)
var file_s3_lifecycle_proto_msgTypes = make([]protoimpl.MessageInfo, 22)
var file_s3_lifecycle_proto_goTypes = []any{
(ActionKind)(0), // 0: s3_lifecycle_pb.ActionKind
(LifecycleDeleteOutcome)(0), // 1: s3_lifecycle_pb.LifecycleDeleteOutcome
@@ -2120,58 +2195,62 @@ var file_s3_lifecycle_proto_goTypes = []any{
(LifecycleState_DegradedReason)(0), // 4: s3_lifecycle_pb.LifecycleState.DegradedReason
(*LifecycleDeleteRequest)(nil), // 5: s3_lifecycle_pb.LifecycleDeleteRequest
(*LifecycleDeleteResponse)(nil), // 6: s3_lifecycle_pb.LifecycleDeleteResponse
(*MessagePosition)(nil), // 7: s3_lifecycle_pb.MessagePosition
(*FilerShardCursor)(nil), // 8: s3_lifecycle_pb.FilerShardCursor
(*EntryIdentity)(nil), // 9: s3_lifecycle_pb.EntryIdentity
(*LifecycleState)(nil), // 10: s3_lifecycle_pb.LifecycleState
(*PendingItem)(nil), // 11: s3_lifecycle_pb.PendingItem
(*BootstrapState)(nil), // 12: s3_lifecycle_pb.BootstrapState
(*ReaderState)(nil), // 13: s3_lifecycle_pb.ReaderState
(*FilerShardCursorList)(nil), // 14: s3_lifecycle_pb.FilerShardCursorList
(*TailDrainedKey)(nil), // 15: s3_lifecycle_pb.TailDrainedKey
(*BlockerRecord)(nil), // 16: s3_lifecycle_pb.BlockerRecord
(*StreamKey)(nil), // 17: s3_lifecycle_pb.StreamKey
(*OriginalKey)(nil), // 18: s3_lifecycle_pb.OriginalKey
(*PredicateKey)(nil), // 19: s3_lifecycle_pb.PredicateKey
(*BootstrapKey)(nil), // 20: s3_lifecycle_pb.BootstrapKey
(*PendingKey)(nil), // 21: s3_lifecycle_pb.PendingKey
(*RetryBudgetEntry)(nil), // 22: s3_lifecycle_pb.RetryBudgetEntry
(*RetryTarget)(nil), // 23: s3_lifecycle_pb.RetryTarget
nil, // 24: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
(*LifecycleReadyRequest)(nil), // 7: s3_lifecycle_pb.LifecycleReadyRequest
(*LifecycleReadyResponse)(nil), // 8: s3_lifecycle_pb.LifecycleReadyResponse
(*MessagePosition)(nil), // 9: s3_lifecycle_pb.MessagePosition
(*FilerShardCursor)(nil), // 10: s3_lifecycle_pb.FilerShardCursor
(*EntryIdentity)(nil), // 11: s3_lifecycle_pb.EntryIdentity
(*LifecycleState)(nil), // 12: s3_lifecycle_pb.LifecycleState
(*PendingItem)(nil), // 13: s3_lifecycle_pb.PendingItem
(*BootstrapState)(nil), // 14: s3_lifecycle_pb.BootstrapState
(*ReaderState)(nil), // 15: s3_lifecycle_pb.ReaderState
(*FilerShardCursorList)(nil), // 16: s3_lifecycle_pb.FilerShardCursorList
(*TailDrainedKey)(nil), // 17: s3_lifecycle_pb.TailDrainedKey
(*BlockerRecord)(nil), // 18: s3_lifecycle_pb.BlockerRecord
(*StreamKey)(nil), // 19: s3_lifecycle_pb.StreamKey
(*OriginalKey)(nil), // 20: s3_lifecycle_pb.OriginalKey
(*PredicateKey)(nil), // 21: s3_lifecycle_pb.PredicateKey
(*BootstrapKey)(nil), // 22: s3_lifecycle_pb.BootstrapKey
(*PendingKey)(nil), // 23: s3_lifecycle_pb.PendingKey
(*RetryBudgetEntry)(nil), // 24: s3_lifecycle_pb.RetryBudgetEntry
(*RetryTarget)(nil), // 25: s3_lifecycle_pb.RetryTarget
nil, // 26: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
}
var file_s3_lifecycle_proto_depIdxs = []int32{
0, // 0: s3_lifecycle_pb.LifecycleDeleteRequest.action_kind:type_name -> s3_lifecycle_pb.ActionKind
9, // 1: s3_lifecycle_pb.LifecycleDeleteRequest.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
11, // 1: s3_lifecycle_pb.LifecycleDeleteRequest.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
1, // 2: s3_lifecycle_pb.LifecycleDeleteResponse.outcome:type_name -> s3_lifecycle_pb.LifecycleDeleteOutcome
7, // 3: s3_lifecycle_pb.FilerShardCursor.position:type_name -> s3_lifecycle_pb.MessagePosition
9, // 3: s3_lifecycle_pb.FilerShardCursor.position:type_name -> s3_lifecycle_pb.MessagePosition
0, // 4: s3_lifecycle_pb.LifecycleState.action_kind:type_name -> s3_lifecycle_pb.ActionKind
3, // 5: s3_lifecycle_pb.LifecycleState.mode:type_name -> s3_lifecycle_pb.LifecycleState.RuleMode
4, // 6: s3_lifecycle_pb.LifecycleState.degraded_reason:type_name -> s3_lifecycle_pb.LifecycleState.DegradedReason
9, // 7: s3_lifecycle_pb.PendingItem.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
24, // 8: s3_lifecycle_pb.ReaderState.last_processed_original:type_name -> s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
8, // 9: s3_lifecycle_pb.ReaderState.last_processed_predicate:type_name -> s3_lifecycle_pb.FilerShardCursor
15, // 10: s3_lifecycle_pb.ReaderState.tail_drained_streams:type_name -> s3_lifecycle_pb.TailDrainedKey
8, // 11: s3_lifecycle_pb.FilerShardCursorList.cursors:type_name -> s3_lifecycle_pb.FilerShardCursor
11, // 7: s3_lifecycle_pb.PendingItem.expected_identity:type_name -> s3_lifecycle_pb.EntryIdentity
26, // 8: s3_lifecycle_pb.ReaderState.last_processed_original:type_name -> s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry
10, // 9: s3_lifecycle_pb.ReaderState.last_processed_predicate:type_name -> s3_lifecycle_pb.FilerShardCursor
17, // 10: s3_lifecycle_pb.ReaderState.tail_drained_streams:type_name -> s3_lifecycle_pb.TailDrainedKey
10, // 11: s3_lifecycle_pb.FilerShardCursorList.cursors:type_name -> s3_lifecycle_pb.FilerShardCursor
2, // 12: s3_lifecycle_pb.TailDrainedKey.stream_kind:type_name -> s3_lifecycle_pb.StreamKind
2, // 13: s3_lifecycle_pb.BlockerRecord.stream_kind:type_name -> s3_lifecycle_pb.StreamKind
7, // 14: s3_lifecycle_pb.BlockerRecord.position:type_name -> s3_lifecycle_pb.MessagePosition
9, // 14: s3_lifecycle_pb.BlockerRecord.position:type_name -> s3_lifecycle_pb.MessagePosition
0, // 15: s3_lifecycle_pb.BlockerRecord.action_kind:type_name -> s3_lifecycle_pb.ActionKind
18, // 16: s3_lifecycle_pb.StreamKey.original:type_name -> s3_lifecycle_pb.OriginalKey
19, // 17: s3_lifecycle_pb.StreamKey.predicate:type_name -> s3_lifecycle_pb.PredicateKey
20, // 18: s3_lifecycle_pb.StreamKey.bootstrap:type_name -> s3_lifecycle_pb.BootstrapKey
21, // 19: s3_lifecycle_pb.StreamKey.pending:type_name -> s3_lifecycle_pb.PendingKey
7, // 20: s3_lifecycle_pb.OriginalKey.position:type_name -> s3_lifecycle_pb.MessagePosition
7, // 21: s3_lifecycle_pb.PredicateKey.position:type_name -> s3_lifecycle_pb.MessagePosition
20, // 16: s3_lifecycle_pb.StreamKey.original:type_name -> s3_lifecycle_pb.OriginalKey
21, // 17: s3_lifecycle_pb.StreamKey.predicate:type_name -> s3_lifecycle_pb.PredicateKey
22, // 18: s3_lifecycle_pb.StreamKey.bootstrap:type_name -> s3_lifecycle_pb.BootstrapKey
23, // 19: s3_lifecycle_pb.StreamKey.pending:type_name -> s3_lifecycle_pb.PendingKey
9, // 20: s3_lifecycle_pb.OriginalKey.position:type_name -> s3_lifecycle_pb.MessagePosition
9, // 21: s3_lifecycle_pb.PredicateKey.position:type_name -> s3_lifecycle_pb.MessagePosition
0, // 22: s3_lifecycle_pb.BootstrapKey.action_kind:type_name -> s3_lifecycle_pb.ActionKind
0, // 23: s3_lifecycle_pb.PendingKey.action_kind:type_name -> s3_lifecycle_pb.ActionKind
17, // 24: s3_lifecycle_pb.RetryBudgetEntry.key:type_name -> s3_lifecycle_pb.StreamKey
17, // 25: s3_lifecycle_pb.RetryTarget.key:type_name -> s3_lifecycle_pb.StreamKey
19, // 24: s3_lifecycle_pb.RetryBudgetEntry.key:type_name -> s3_lifecycle_pb.StreamKey
19, // 25: s3_lifecycle_pb.RetryTarget.key:type_name -> s3_lifecycle_pb.StreamKey
0, // 26: s3_lifecycle_pb.RetryTarget.action_kind:type_name -> s3_lifecycle_pb.ActionKind
14, // 27: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry.value:type_name -> s3_lifecycle_pb.FilerShardCursorList
16, // 27: s3_lifecycle_pb.ReaderState.LastProcessedOriginalEntry.value:type_name -> s3_lifecycle_pb.FilerShardCursorList
5, // 28: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleDelete:input_type -> s3_lifecycle_pb.LifecycleDeleteRequest
6, // 29: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleDelete:output_type -> s3_lifecycle_pb.LifecycleDeleteResponse
29, // [29:30] is the sub-list for method output_type
28, // [28:29] is the sub-list for method input_type
7, // 29: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleReady:input_type -> s3_lifecycle_pb.LifecycleReadyRequest
6, // 30: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleDelete:output_type -> s3_lifecycle_pb.LifecycleDeleteResponse
8, // 31: s3_lifecycle_pb.SeaweedS3LifecycleInternal.LifecycleReady:output_type -> s3_lifecycle_pb.LifecycleReadyResponse
30, // [30:32] is the sub-list for method output_type
28, // [28:30] is the sub-list for method input_type
28, // [28:28] is the sub-list for extension type_name
28, // [28:28] is the sub-list for extension extendee
0, // [0:28] is the sub-list for field type_name
@@ -2182,7 +2261,7 @@ func file_s3_lifecycle_proto_init() {
if File_s3_lifecycle_proto != nil {
return
}
file_s3_lifecycle_proto_msgTypes[12].OneofWrappers = []any{
file_s3_lifecycle_proto_msgTypes[14].OneofWrappers = []any{
(*StreamKey_Original)(nil),
(*StreamKey_Predicate)(nil),
(*StreamKey_Bootstrap)(nil),
@@ -2194,7 +2273,7 @@ func file_s3_lifecycle_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_s3_lifecycle_proto_rawDesc), len(file_s3_lifecycle_proto_rawDesc)),
NumEnums: 5,
NumMessages: 20,
NumMessages: 22,
NumExtensions: 0,
NumServices: 1,
},
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v6.33.4
// - protoc-gen-go-grpc v1.6.2
// - protoc v3.21.12
// source: s3_lifecycle.proto
package s3_lifecycle_pb
@@ -20,6 +20,7 @@ const _ = grpc.SupportPackageIsVersion9
const (
SeaweedS3LifecycleInternal_LifecycleDelete_FullMethodName = "/s3_lifecycle_pb.SeaweedS3LifecycleInternal/LifecycleDelete"
SeaweedS3LifecycleInternal_LifecycleReady_FullMethodName = "/s3_lifecycle_pb.SeaweedS3LifecycleInternal/LifecycleReady"
)
// SeaweedS3LifecycleInternalClient is the client API for SeaweedS3LifecycleInternal service.
@@ -34,6 +35,9 @@ const (
// to the appropriate internal helper.
type SeaweedS3LifecycleInternalClient interface {
LifecycleDelete(ctx context.Context, in *LifecycleDeleteRequest, opts ...grpc.CallOption) (*LifecycleDeleteResponse, error)
// LifecycleReady runs LifecycleDelete's authorization and nothing else,
// so a worker can check a front before it starts a pass.
LifecycleReady(ctx context.Context, in *LifecycleReadyRequest, opts ...grpc.CallOption) (*LifecycleReadyResponse, error)
}
type seaweedS3LifecycleInternalClient struct {
@@ -54,6 +58,16 @@ func (c *seaweedS3LifecycleInternalClient) LifecycleDelete(ctx context.Context,
return out, nil
}
func (c *seaweedS3LifecycleInternalClient) LifecycleReady(ctx context.Context, in *LifecycleReadyRequest, opts ...grpc.CallOption) (*LifecycleReadyResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(LifecycleReadyResponse)
err := c.cc.Invoke(ctx, SeaweedS3LifecycleInternal_LifecycleReady_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// SeaweedS3LifecycleInternalServer is the server API for SeaweedS3LifecycleInternal service.
// All implementations must embed UnimplementedSeaweedS3LifecycleInternalServer
// for forward compatibility.
@@ -66,6 +80,9 @@ func (c *seaweedS3LifecycleInternalClient) LifecycleDelete(ctx context.Context,
// to the appropriate internal helper.
type SeaweedS3LifecycleInternalServer interface {
LifecycleDelete(context.Context, *LifecycleDeleteRequest) (*LifecycleDeleteResponse, error)
// LifecycleReady runs LifecycleDelete's authorization and nothing else,
// so a worker can check a front before it starts a pass.
LifecycleReady(context.Context, *LifecycleReadyRequest) (*LifecycleReadyResponse, error)
mustEmbedUnimplementedSeaweedS3LifecycleInternalServer()
}
@@ -77,7 +94,10 @@ type SeaweedS3LifecycleInternalServer interface {
type UnimplementedSeaweedS3LifecycleInternalServer struct{}
func (UnimplementedSeaweedS3LifecycleInternalServer) LifecycleDelete(context.Context, *LifecycleDeleteRequest) (*LifecycleDeleteResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method LifecycleDelete not implemented")
return nil, status.Error(codes.Unimplemented, "method LifecycleDelete not implemented")
}
func (UnimplementedSeaweedS3LifecycleInternalServer) LifecycleReady(context.Context, *LifecycleReadyRequest) (*LifecycleReadyResponse, error) {
return nil, status.Error(codes.Unimplemented, "method LifecycleReady not implemented")
}
func (UnimplementedSeaweedS3LifecycleInternalServer) mustEmbedUnimplementedSeaweedS3LifecycleInternalServer() {
}
@@ -91,7 +111,7 @@ type UnsafeSeaweedS3LifecycleInternalServer interface {
}
func RegisterSeaweedS3LifecycleInternalServer(s grpc.ServiceRegistrar, srv SeaweedS3LifecycleInternalServer) {
// If the following call pancis, it indicates UnimplementedSeaweedS3LifecycleInternalServer was
// If the following call panics, it indicates UnimplementedSeaweedS3LifecycleInternalServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
@@ -119,6 +139,24 @@ func _SeaweedS3LifecycleInternal_LifecycleDelete_Handler(srv interface{}, ctx co
return interceptor(ctx, in, info, handler)
}
func _SeaweedS3LifecycleInternal_LifecycleReady_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LifecycleReadyRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SeaweedS3LifecycleInternalServer).LifecycleReady(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SeaweedS3LifecycleInternal_LifecycleReady_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SeaweedS3LifecycleInternalServer).LifecycleReady(ctx, req.(*LifecycleReadyRequest))
}
return interceptor(ctx, in, info, handler)
}
// SeaweedS3LifecycleInternal_ServiceDesc is the grpc.ServiceDesc for SeaweedS3LifecycleInternal service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -130,6 +168,10 @@ var SeaweedS3LifecycleInternal_ServiceDesc = grpc.ServiceDesc{
MethodName: "LifecycleDelete",
Handler: _SeaweedS3LifecycleInternal_LifecycleDelete_Handler,
},
{
MethodName: "LifecycleReady",
Handler: _SeaweedS3LifecycleInternal_LifecycleReady_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "s3_lifecycle.proto",
+9
View File
@@ -59,6 +59,15 @@ func (s3a *S3ApiServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_p
return s3a.lifecycleDispatch(ctx, req, entry)
}
// LifecycleReady authorizes the caller as LifecycleDelete does and touches
// no bucket or object metadata.
func (s3a *S3ApiServer) LifecycleReady(ctx context.Context, _ *s3_lifecycle_pb.LifecycleReadyRequest) (*s3_lifecycle_pb.LifecycleReadyResponse, error) {
if err := s3a.checkAdminAuth(ctx); err != nil {
return nil, err
}
return &s3_lifecycle_pb.LifecycleReadyResponse{}, nil
}
func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest, entry *filer_pb.Entry) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
metadataOnly := entryUsesMetadataOnlyDelete(entry)
switch req.ActionKind {
@@ -384,6 +384,38 @@ func TestLifecycleDelete_NoSigningKey_LocalPeerOnly(t *testing.T) {
}
}
func TestLifecycleReady_AuthorizesLikeLifecycleDelete(t *testing.T) {
good := security.GenJwtForFilerAdmin(security.SigningKey(testS3IamCacheSigningKey), 60)
bad := security.GenJwtForFilerAdmin(security.SigningKey("a-different-key"), 60)
remoteCtx := peer.NewContext(context.Background(),
&peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("203.0.113.7"), Port: 11111}})
cases := []struct {
name string
signingKey string
ctx context.Context
want codes.Code
}{
{"key, no token", testS3IamCacheSigningKey, context.Background(), codes.Unauthenticated},
{"key, mis-signed token", testS3IamCacheSigningKey, s3IamCacheBearerCtx(string(bad)), codes.Unauthenticated},
{"key, valid token", testS3IamCacheSigningKey, s3IamCacheBearerCtx(string(good)), codes.OK},
{"no key, remote peer", "", remoteCtx, codes.Unauthenticated},
{"no key, loopback peer", "", s3LocalPeerCtx(), codes.OK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := newTestS3IamCacheServer(t, tc.signingKey)
_, err := s.LifecycleReady(tc.ctx, &s3_lifecycle_pb.LifecycleReadyRequest{})
if got := status.Code(err); got != tc.want {
t.Fatalf("LifecycleReady: got code %v, want %v (err=%v)", got, tc.want, err)
}
_, deleteErr := s.LifecycleDelete(tc.ctx, &s3_lifecycle_pb.LifecycleDeleteRequest{})
if got := status.Code(deleteErr); got != tc.want {
t.Fatalf("LifecycleDelete disagrees: got code %v, want %v (err=%v)", got, tc.want, deleteErr)
}
})
}
}
func TestLifecycleDelete_CurrentExpirationRequiresLatestVersion(t *testing.T) {
listed := &filer_pb.Entry{
Name: "v_old",
+56
View File
@@ -18,6 +18,7 @@ import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
@@ -161,3 +162,58 @@ func (p *FilerCursorPersister) Save(ctx context.Context, shardID int, c Cursor)
}
return nil
}
const fullPassFileName = "full-pass.json"
// FullPass is the last pass that covered every shard and every lifecycle
// policy without an error. Shard cursors advance on partial passes too,
// so they cannot answer that.
type FullPass struct {
StartedAt time.Time
CompletedAt time.Time
}
type fullPassFile struct {
Version int `json:"version"`
StartedAtNs int64 `json:"started_at_ns"`
CompletedAtNs int64 `json:"completed_at_ns"`
}
func (p *FilerCursorPersister) LoadFullPass(ctx context.Context) (FullPass, bool, error) {
if p.Store == nil {
return FullPass{}, false, errors.New("FilerCursorPersister: nil Store")
}
content, err := p.Store.Read(ctx, CursorDir, fullPassFileName)
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return FullPass{}, false, nil
}
return FullPass{}, false, fmt.Errorf("full pass read: %w", err)
}
var f fullPassFile
if err := json.Unmarshal(content, &f); err != nil {
return FullPass{}, false, fmt.Errorf("full pass decode: %w", err)
}
if f.Version != cursorFileVersion {
return FullPass{}, false, fmt.Errorf("full pass version: got %d, want %d", f.Version, cursorFileVersion)
}
return FullPass{StartedAt: time.Unix(0, f.StartedAtNs).UTC(), CompletedAt: time.Unix(0, f.CompletedAtNs).UTC()}, true, nil
}
func (p *FilerCursorPersister) SaveFullPass(ctx context.Context, fp FullPass) error {
if p.Store == nil {
return errors.New("FilerCursorPersister: nil Store")
}
content, err := json.Marshal(fullPassFile{
Version: cursorFileVersion,
StartedAtNs: fp.StartedAt.UnixNano(),
CompletedAtNs: fp.CompletedAt.UnixNano(),
})
if err != nil {
return fmt.Errorf("full pass encode: %w", err)
}
if err := p.Store.Save(ctx, CursorDir, fullPassFileName, content); err != nil {
return fmt.Errorf("full pass save: %w", err)
}
return nil
}
@@ -4,6 +4,7 @@ import (
"context"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
@@ -153,3 +154,32 @@ func TestFilerCursorPersister_NilStoreErrors(t *testing.T) {
require.Error(t, err)
require.Error(t, p.Save(context.Background(), 0, Cursor{}))
}
func TestFilerCursorPersister_FullPassRoundTrip(t *testing.T) {
store := newFakeStore()
p := &FilerCursorPersister{Store: store}
_, found, err := p.LoadFullPass(context.Background())
require.NoError(t, err)
assert.False(t, found)
want := FullPass{
StartedAt: time.Unix(1_700_000_000, 123).UTC(),
CompletedAt: time.Unix(1_700_003_600, 456).UTC(),
}
require.NoError(t, p.SaveFullPass(context.Background(), want))
got, found, err := p.LoadFullPass(context.Background())
require.NoError(t, err)
require.True(t, found)
assert.Equal(t, want, got)
_, found, err = p.Load(context.Background(), 0)
require.NoError(t, err)
assert.False(t, found, "the full-pass record must not read as a shard cursor")
}
func TestFilerCursorPersister_FullPassRejectsUnknownVersion(t *testing.T) {
store := newFakeStore()
require.NoError(t, store.Save(context.Background(), CursorDir, fullPassFileName, []byte(`{"version":99,"completed_at_ns":1}`)))
_, _, err := (&FilerCursorPersister{Store: store}).LoadFullPass(context.Background())
assert.Error(t, err)
}
+28 -3
View File
@@ -91,6 +91,10 @@ type Config struct {
// 0 -> defaultSubscriptionReceiveTimeout.
SubscriptionReceiveTimeout time.Duration
// nil -> no per-pass summary. Share it with the walker's
// WalkBuckets and WalkerDispatcher to cover both paths.
Stats *RunStats
}
// Above the filer's 15m maxGapStall, so a subscriber parked on a gap is
@@ -240,6 +244,7 @@ func Run(ctx context.Context, cfg Config) error {
first = readerErr
}
}
cfg.Stats.setShardErrors(errCount)
status := "ok"
if first != nil {
status = "error"
@@ -562,6 +567,8 @@ func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow tim
lastWalkedNs = runNow.UnixNano()
walkedThisPass = true
}
} else if cfg.Walker != nil {
countDeferredWalk(cfg.Stats, snap, shardID, retentionWindow)
}
_ = walkedThisPass // empty-replay branch returns; no downstream walker.
return saveCursorAndPublish(ctx, cfg.Persister, shardID, Cursor{
@@ -625,6 +632,8 @@ func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow tim
}
lastWalkedNs = runNow.UnixNano()
}
} else if cfg.Walker != nil && !walkedThisPass {
countDeferredWalk(cfg.Stats, snap, shardID, retentionWindow)
}
// Cold start: scan from now-maxTTL so already-due objects within
@@ -644,7 +653,10 @@ func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow tim
// Walk-bound rules are never due inside the retention window; keep them
// out of the drain so their matches don't pin the cursor.
replayView := snap.ReplayView(retentionWindow)
lastOK, _, drainErr := drainShardEvents(ctx, cfg, runNow, shardID, replayView, startTsNs, events)
lastOK, halted, drainErr := drainShardEvents(ctx, cfg, runNow, shardID, replayView, startTsNs, events)
if halted && drainErr == nil {
cfg.Stats.shardHalted()
}
// Fresh ctx: a wall-clock cap on the pass (the shell driver's
// -runtime) cancels the drain's, and saving with it would drop the
// cursor and re-replay from the same floor next pass.
@@ -684,6 +696,17 @@ func saveCursorAndPublish(ctx context.Context, p CursorPersister, shardID int, c
return nil
}
// countDeferredWalk counts a shard whose walk-only rules waited for
// WalkerInterval, so the pass left them unevaluated.
func countDeferredWalk(s *RunStats, snap *engine.Snapshot, shardID int, retentionWindow time.Duration) {
if s == nil {
return
}
if _, walkView := snap.RulesForShard(shardID, retentionWindow); walkView != nil && len(walkView.AllActions()) > 0 {
s.walkDeferred()
}
}
// walkerDue answers the persisted-state throttle: has enough time
// elapsed since the last walker fire on this shard? interval == 0
// means "fire every pass" (the prior, unconditional behavior).
@@ -719,6 +742,7 @@ func drainShardEvents(ctx context.Context, cfg Config, runNow time.Time, shardID
cursorAdvanceTo := startTsNs
stuck := false
halted := false
cfg.Stats.startReplay()
drain:
for {
@@ -739,6 +763,7 @@ drain:
continue
}
stats.S3LifecycleDailyRunEventsScanned.WithLabelValues(strconv.Itoa(shardID)).Inc()
cfg.Stats.scanEvent()
matches := router.Route(ctx, snap, ev, runNow, cfg.Lister)
eventSkipped, eventHalted, eventErr := processMatches(ctx, cfg, runNow, ev, matches)
if eventErr != nil {
@@ -786,10 +811,10 @@ func processMatches(ctx context.Context, cfg Config, runNow time.Time, ev *reade
// "RPC_ERROR" matches the streaming dispatcher's label
// (dispatcher/dispatcher.go) so transport failures
// aggregate under one outcome key across paths.
stats.S3LifecycleDispatchCounter.WithLabelValues(m.Bucket, m.Key.ActionKind.String(), "RPC_ERROR").Inc()
countDispatch(cfg.Stats, m.Bucket, m.Key.ActionKind.String(), "RPC_ERROR")
return skippedAny, true, nil
}
stats.S3LifecycleDispatchCounter.WithLabelValues(m.Bucket, m.Key.ActionKind.String(), outcome.String()).Inc()
countDispatch(cfg.Stats, m.Bucket, m.Key.ActionKind.String(), outcome.String())
switch outcome {
case s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
@@ -126,6 +126,7 @@ func TestRun_HaltedShardDoesNotStarveOthers(t *testing.T) {
Persister: persister,
Lister: stubSiblingLister{},
Now: func() time.Time { return runNow },
Stats: &RunStats{},
}
done := make(chan error, 1)
@@ -145,4 +146,11 @@ func TestRun_HaltedShardDoesNotStarveOthers(t *testing.T) {
require.NoError(t, err)
require.True(t, found)
assert.Greater(t, starvedCursor.TsNs, seeded.TsNs, "starved shard's cursor must advance")
sum := cfg.Stats.Summary()
assert.Equal(t, PhaseReplay, sum.Phase)
assert.Equal(t, int64(2), sum.EventsScanned, "the halted shard stops after its first event")
assert.Equal(t, map[string]int64{"BLOCKED": 1, "DONE": 1}, sum.Outcomes)
assert.Zero(t, sum.ShardErrors)
assert.Equal(t, 1, sum.ShardsHalted, "a BLOCKED delete halts its shard without an error")
}
@@ -0,0 +1,265 @@
package dailyrun
import (
"context"
"strings"
"sync"
"sync/atomic"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
)
// Bounds what a summary carries per pass; the counts stay exact.
const (
maxReportedBucketFailures = 10
maxReportedErrorLen = 256
)
const (
PhaseWalk = "walk"
PhaseReplay = "replay"
)
type bucketState uint8
const (
bucketSkipped bucketState = iota + 1
bucketWalked
bucketFailed
)
type BucketFailure struct {
Bucket string
Error string
}
// RunSummary is a copy of a RunStats at one point in time. A bucket walked
// more than once in a pass counts once, as failed if any walk failed.
type RunSummary struct {
Phase string
Bucket string
BucketsWalked int
BucketsFailed int
BucketsSkipped int
// The first maxReportedBucketFailures failed buckets.
BucketFailures []BucketFailure
// Every listed entry, versions and delete markers included.
EntriesVisited int64
// Distinct object keys among the listed entries.
ObjectsVisited int64
// Every entry read from the filer, including the ones a walk skips
// without visiting (versioned pre-pass, resume start, other shards).
EntriesListed int64
EventsScanned int64
// LifecycleDelete outcomes keyed by the dispatch_total outcome label.
// They count RPC results, not reclaimed space.
Outcomes map[string]int64
ShardErrors int
// Shards whose replay stopped on an unresolved delete; their due
// events wait for a later pass.
ShardsHalted int
// Shards whose walk-only rules waited for WalkerInterval.
WalksDeferred int
}
// RunStats collects one pass's work. Safe for concurrent use; a nil
// *RunStats ignores every call.
type RunStats struct {
entries atomic.Int64
objects atomic.Int64
listed atomic.Int64
events atomic.Int64
mu sync.Mutex
phase string
bucket string
buckets map[string]bucketState
failures []BucketFailure
outcomes map[string]int64
shardErrors int
shardsHalted int
deferred int
}
func (s *RunStats) startBucket(bucket string) {
if s == nil {
return
}
s.mu.Lock()
s.phase, s.bucket = PhaseWalk, bucket
s.mu.Unlock()
}
func (s *RunStats) finishBucket(bucket string, state bucketState, err error) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.buckets == nil {
s.buckets = map[string]bucketState{}
}
prev := s.buckets[bucket]
if state <= prev {
return
}
s.buckets[bucket] = state
if state == bucketFailed && len(s.failures) < maxReportedBucketFailures {
s.failures = append(s.failures, BucketFailure{Bucket: bucket, Error: truncateError(err)})
}
}
func (s *RunStats) startReplay() {
if s == nil {
return
}
s.mu.Lock()
s.phase, s.bucket = PhaseReplay, ""
s.mu.Unlock()
}
func (s *RunStats) visitEntry(newObject bool) {
if s == nil {
return
}
s.entries.Add(1)
if newObject {
s.objects.Add(1)
}
}
// CountListed returns client with its ListEntries results counted as
// EntriesListed.
func (s *RunStats) CountListed(client filer_pb.SeaweedFilerClient) filer_pb.SeaweedFilerClient {
if s == nil || client == nil {
return client
}
return &listCountingClient{SeaweedFilerClient: client, stats: s}
}
type listCountingClient struct {
filer_pb.SeaweedFilerClient
stats *RunStats
}
func (c *listCountingClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (filer_pb.SeaweedFiler_ListEntriesClient, error) {
stream, err := c.SeaweedFilerClient.ListEntries(ctx, in, opts...)
if err != nil {
return nil, err
}
return &listCountingStream{SeaweedFiler_ListEntriesClient: stream, stats: c.stats}, nil
}
type listCountingStream struct {
filer_pb.SeaweedFiler_ListEntriesClient
stats *RunStats
}
func (s *listCountingStream) Recv() (*filer_pb.ListEntriesResponse, error) {
resp, err := s.SeaweedFiler_ListEntriesClient.Recv()
if err == nil && resp.GetEntry() != nil {
s.stats.listed.Add(1)
}
return resp, err
}
func (s *RunStats) scanEvent() {
if s == nil {
return
}
s.events.Add(1)
}
func (s *RunStats) recordOutcome(outcome string) {
if s == nil {
return
}
s.mu.Lock()
if s.outcomes == nil {
s.outcomes = map[string]int64{}
}
s.outcomes[outcome]++
s.mu.Unlock()
}
func (s *RunStats) setShardErrors(n int) {
if s == nil {
return
}
s.mu.Lock()
s.shardErrors = n
s.mu.Unlock()
}
func (s *RunStats) shardHalted() {
if s == nil {
return
}
s.mu.Lock()
s.shardsHalted++
s.mu.Unlock()
}
func (s *RunStats) walkDeferred() {
if s == nil {
return
}
s.mu.Lock()
s.deferred++
s.mu.Unlock()
}
func (s *RunStats) Summary() RunSummary {
if s == nil {
return RunSummary{}
}
out := RunSummary{
EntriesVisited: s.entries.Load(),
ObjectsVisited: s.objects.Load(),
EntriesListed: s.listed.Load(),
EventsScanned: s.events.Load(),
}
s.mu.Lock()
defer s.mu.Unlock()
out.Phase, out.Bucket = s.phase, s.bucket
for _, state := range s.buckets {
switch state {
case bucketWalked:
out.BucketsWalked++
case bucketFailed:
out.BucketsFailed++
case bucketSkipped:
out.BucketsSkipped++
}
}
out.BucketFailures = append([]BucketFailure(nil), s.failures...)
if len(s.outcomes) > 0 {
out.Outcomes = make(map[string]int64, len(s.outcomes))
for k, v := range s.outcomes {
out.Outcomes[k] = v
}
}
out.ShardErrors = s.shardErrors
out.ShardsHalted = s.shardsHalted
out.WalksDeferred = s.deferred
return out
}
func countDispatch(s *RunStats, bucket, kind, outcome string) {
stats.S3LifecycleDispatchCounter.WithLabelValues(bucket, kind, outcome).Inc()
s.recordOutcome(outcome)
}
func truncateError(err error) string {
if err == nil {
return ""
}
msg := err.Error()
if len(msg) <= maxReportedErrorLen {
return msg
}
return strings.ToValidUTF8(msg[:maxReportedErrorLen], "") + "..."
}
@@ -0,0 +1,191 @@
package dailyrun
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/bootstrap"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func allShards() []int {
out := make([]int, s3lifecycle.ShardCount)
for i := range out {
out[i] = i
}
return out
}
func TestWalkBuckets_RecordsEveryBucketFailure(t *testing.T) {
list := func(_ context.Context, bucket, _ string, _ func(*bootstrap.Entry) error) error {
if strings.HasPrefix(bucket, "bad") {
return errors.New("list " + bucket + " failed")
}
return nil
}
runStats := &RunStats{}
err := WalkBuckets(context.Background(), snapshotForBucketRule(t, "good", 7), []int{0},
[]string{"bad-a", "good", "bad-b"}, list, &recordingDispatcher{}, runStats)
require.Error(t, err)
assert.Contains(t, err.Error(), "bad-a", "the returned error stays the first bucket's")
sum := runStats.Summary()
assert.Equal(t, 1, sum.BucketsWalked)
assert.Equal(t, 2, sum.BucketsFailed)
assert.Equal(t, 0, sum.BucketsSkipped)
require.Len(t, sum.BucketFailures, 2)
assert.Equal(t, "bad-a", sum.BucketFailures[0].Bucket)
assert.Contains(t, sum.BucketFailures[0].Error, "list bad-a failed")
assert.Equal(t, "bad-b", sum.BucketFailures[1].Bucket)
assert.Equal(t, PhaseWalk, sum.Phase)
assert.Equal(t, "bad-b", sum.Bucket)
}
func TestWalkBuckets_CancelMarksRemainingBucketsSkipped(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
list := func(ctx context.Context, bucket, _ string, _ func(*bootstrap.Entry) error) error {
if bucket == "second" {
cancel()
return ctx.Err()
}
return nil
}
runStats := &RunStats{}
err := WalkBuckets(ctx, snapshotForBucketRule(t, "first", 7), []int{0},
[]string{"first", "second", "third"}, list, &recordingDispatcher{}, runStats)
assert.ErrorIs(t, err, context.Canceled)
sum := runStats.Summary()
assert.Equal(t, 1, sum.BucketsWalked)
assert.Equal(t, 0, sum.BucketsFailed, "a cancelled walk is not a bucket failure")
assert.Equal(t, 2, sum.BucketsSkipped)
assert.Empty(t, sum.BucketFailures)
}
func TestRunStats_FailedWalkWinsAcrossWalksOfOneBucket(t *testing.T) {
runStats := &RunStats{}
runStats.finishBucket("b", bucketSkipped, nil)
runStats.finishBucket("b", bucketWalked, nil)
runStats.finishBucket("b", bucketFailed, errors.New("first"))
runStats.finishBucket("b", bucketFailed, errors.New("second"))
runStats.finishBucket("b", bucketWalked, nil)
sum := runStats.Summary()
assert.Equal(t, 1, sum.BucketsFailed)
assert.Equal(t, 0, sum.BucketsWalked)
require.Len(t, sum.BucketFailures, 1)
assert.Equal(t, "first", sum.BucketFailures[0].Error)
}
func TestRunStats_BoundsReportedFailures(t *testing.T) {
runStats := &RunStats{}
long := strings.Repeat("x", 2*maxReportedErrorLen)
for i := 0; i < maxReportedBucketFailures+5; i++ {
runStats.finishBucket("b-"+intToStr(i), bucketFailed, errors.New(long))
}
sum := runStats.Summary()
assert.Equal(t, maxReportedBucketFailures+5, sum.BucketsFailed, "the count stays exact")
require.Len(t, sum.BucketFailures, maxReportedBucketFailures)
assert.LessOrEqual(t, len(sum.BucketFailures[0].Error), maxReportedErrorLen+len("..."))
}
func TestWalkBuckets_CountsEntriesAndObjects(t *testing.T) {
old := time.Now().Add(-90 * 24 * time.Hour)
entries := []*bootstrap.Entry{
{Path: "a", VersionID: "v3", ModTime: old, IsLatest: true},
{Path: "a", VersionID: "v2", ModTime: old},
{Path: "a", VersionID: "v1", ModTime: old},
{Path: "b", ModTime: old, IsLatest: true},
{Path: "dir", IsDirectory: true},
{Path: ".uploads/u1", DestKey: "c", IsDirectory: true, IsMPUInit: true, ModTime: old},
}
runStats := &RunStats{}
require.NoError(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "bkt", 7), allShards(),
[]string{"bkt"}, bootstrap.EntryCallback(entries), &recordingDispatcher{}, runStats))
sum := runStats.Summary()
assert.Equal(t, int64(5), sum.EntriesVisited, "versions and upload records count, plain directories do not")
assert.Equal(t, int64(2), sum.ObjectsVisited, "versions of one key count as one object")
assert.Equal(t, 1, sum.BucketsWalked)
}
func TestWalkerDispatcher_CountsOutcomes(t *testing.T) {
runStats := &RunStats{}
a := sampleAction(t, s3lifecycle.ActionKindExpirationDays)
e := &bootstrap.Entry{Path: "obj"}
d := &WalkerDispatcher{Client: &walkerStubClient{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, Stats: runStats}
require.NoError(t, d.Delete(context.Background(), a, e))
require.NoError(t, d.Delete(context.Background(), a, e))
d.Client = &walkerStubClient{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK}
require.NoError(t, d.Delete(context.Background(), a, e))
d.Client = &walkerStubClient{err: errors.New("unavailable")}
require.Error(t, d.Delete(context.Background(), a, e))
d.Client = &walkerStubClient{nilResp: true}
require.Error(t, d.Delete(context.Background(), a, e))
assert.Equal(t, map[string]int64{"DONE": 2, "SKIPPED_OBJECT_LOCK": 1, "RPC_ERROR": 2}, runStats.Summary().Outcomes)
}
func TestProcessMatches_CountsOutcomes(t *testing.T) {
runNow := time.Now()
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: [8]byte{1}, ActionKind: s3lifecycle.ActionKindExpirationDays}
matches := []router.Match{
{Key: rule, Bucket: "b", ObjectKey: "a", DueTime: runNow.Add(-time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "b", DueTime: runNow.Add(-time.Hour)},
{Key: rule, Bucket: "b", ObjectKey: "c", DueTime: runNow.Add(-time.Hour)},
}
client := &recordingClient{responses: []s3_lifecycle_pb.LifecycleDeleteOutcome{
s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
}}
runStats := &RunStats{}
_, halted, err := processMatches(context.Background(), Config{Client: client, Stats: runStats}, runNow, &reader.Event{}, matches)
require.NoError(t, err)
assert.True(t, halted)
assert.Equal(t, map[string]int64{"DONE": 1, "NOOP_RESOLVED": 1, "RETRY_LATER": 1}, runStats.Summary().Outcomes)
}
func TestRunStats_NilIsANoOp(t *testing.T) {
var runStats *RunStats
runStats.startBucket("b")
runStats.finishBucket("b", bucketFailed, errors.New("x"))
runStats.startReplay()
runStats.visitEntry(true)
runStats.scanEvent()
runStats.recordOutcome("DONE")
runStats.setShardErrors(1)
assert.Equal(t, RunSummary{}, runStats.Summary())
}
// A walk can read a bucket without visiting anything: the versioned
// pre-pass reads plain files without emitting them, and a resumed walk
// skips every key up to its start.
func TestRunStats_CountListedCountsSkippedEntries(t *testing.T) {
mtime := time.Now().Add(-7 * 24 * time.Hour)
client := &fakeFiler{tree: map[string][]*filer_pb.Entry{
"/buckets/bkt": {file("a.txt", mtime, 1), file("b.txt", mtime, 1), file("c.txt", mtime, 1)},
}}
stats := &RunStats{}
emitted := 0
require.NoError(t, FilerListFunc(stats.CountListed(client), "/buckets", nil)(context.Background(), "bkt", "c.txt", func(*bootstrap.Entry) error {
emitted++
return nil
}))
assert.Zero(t, emitted)
assert.Equal(t, int64(6), stats.Summary().EntriesListed, "both passes over the versioned bucket")
var nilStats *RunStats
assert.Same(t, client, nilStats.CountListed(client))
}
@@ -14,12 +14,13 @@ import (
// WalkBuckets runs bootstrap.Walk for each bucket using a per-bucket
// ListFunc wrapped to drop entries whose ShardID isn't in shards.
// Returns the first bucket error; remaining buckets log and continue
// so one bucket's filer error doesn't kill the whole walk.
// so one bucket's filer error doesn't kill the whole walk. Every
// bucket's result goes to runStats when it is non-nil.
//
// Composable shape: callers (the worker handler) supply a real
// filer-backed ListFunc and a real Dispatcher (WalkerDispatcher).
// Tests pass bootstrap.EntryCallback and a stub Dispatcher.
func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, buckets []string, list bootstrap.ListFunc, dispatch bootstrap.Dispatcher) error {
func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, buckets []string, list bootstrap.ListFunc, dispatch bootstrap.Dispatcher, runStats *RunStats) error {
if view == nil {
return errors.New("WalkBuckets: nil view")
}
@@ -33,13 +34,26 @@ func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, bucke
for _, sh := range shards {
shardSet[sh] = true
}
filtered := perShardListFunc(list, shardSet)
filtered := perShardListFunc(list, shardSet, runStats)
var firstErr error
for _, b := range buckets {
for i, b := range buckets {
if err := ctx.Err(); err != nil {
for _, rest := range buckets[i:] {
runStats.finishBucket(rest, bucketSkipped, nil)
}
return err
}
if _, err := bootstrap.Walk(ctx, view, b, filtered, dispatch, bootstrap.WalkOptions{}); err != nil {
runStats.startBucket(b)
_, err := bootstrap.Walk(ctx, view, b, filtered, dispatch, bootstrap.WalkOptions{})
switch {
case err == nil:
runStats.finishBucket(b, bucketWalked, nil)
case ctx.Err() != nil:
runStats.finishBucket(b, bucketSkipped, nil)
default:
runStats.finishBucket(b, bucketFailed, err)
}
if err != nil {
if firstErr == nil {
firstErr = fmt.Errorf("walk %s: %w", b, err)
} else {
@@ -57,8 +71,10 @@ func WalkBuckets(ctx context.Context, view *engine.Snapshot, shards []int, bucke
// MPU init records carry the user's destination in DestKey, so the
// shard predicate must use DestKey there to match what the dispatcher
// will send.
func perShardListFunc(inner bootstrap.ListFunc, shardSet map[int]bool) bootstrap.ListFunc {
func perShardListFunc(inner bootstrap.ListFunc, shardSet map[int]bool, runStats *RunStats) bootstrap.ListFunc {
return func(ctx context.Context, bucket, start string, cb func(*bootstrap.Entry) error) error {
// Listings emit every version of a key back to back.
lastPath := ""
return inner(ctx, bucket, start, func(e *bootstrap.Entry) error {
if e == nil {
return nil
@@ -66,6 +82,10 @@ func perShardListFunc(inner bootstrap.ListFunc, shardSet map[int]bool) bootstrap
if !shardSet[entryShardID(bucket, e)] {
return nil
}
if !e.IsDirectory || e.IsMPUInit {
runStats.visitEntry(!e.IsMPUInit && e.Path != lastPath)
lastPath = e.Path
}
return cb(e)
})
}
@@ -105,7 +105,7 @@ func TestWalkBuckets_DispatchesOnlyShardMatchingEntries(t *testing.T) {
snap := snapshotForBucketRule(t, bucket, 7) // 30-day-old objects expire
d := &recordingDispatcher{}
err := WalkBuckets(context.Background(), snap, []int{targetShard}, []string{bucket},
bootstrap.EntryCallback(all), d)
bootstrap.EntryCallback(all), d, nil)
require.NoError(t, err)
gotPaths := make([]string, 0, len(d.calls))
@@ -124,9 +124,9 @@ func TestWalkBuckets_DispatchesOnlyShardMatchingEntries(t *testing.T) {
}
func TestWalkBuckets_NilGuards(t *testing.T) {
require.Error(t, WalkBuckets(context.Background(), nil, []int{0}, nil, bootstrap.EntryCallback(nil), &recordingDispatcher{}))
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, nil, &recordingDispatcher{}))
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, bootstrap.EntryCallback(nil), nil))
require.Error(t, WalkBuckets(context.Background(), nil, []int{0}, nil, bootstrap.EntryCallback(nil), &recordingDispatcher{}, nil))
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, nil, &recordingDispatcher{}, nil))
require.Error(t, WalkBuckets(context.Background(), snapshotForBucketRule(t, "b", 7), []int{0}, nil, bootstrap.EntryCallback(nil), nil, nil))
}
func TestWalkBuckets_OneBucketErrorDoesNotStopOthers(t *testing.T) {
@@ -141,7 +141,7 @@ func TestWalkBuckets_OneBucketErrorDoesNotStopOthers(t *testing.T) {
}
snap := snapshotForBucketRule(t, "good", 7)
err := WalkBuckets(context.Background(), snap, []int{0}, []string{"bad", "good"}, list, &recordingDispatcher{})
err := WalkBuckets(context.Background(), snap, []int{0}, []string{"bad", "good"}, list, &recordingDispatcher{}, nil)
require.Error(t, err)
assert.ErrorIs(t, err, listErr)
}
@@ -153,7 +153,7 @@ func TestWalkBuckets_HonorsContextCancellationBetweenBuckets(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := WalkBuckets(ctx, snapshotForBucketRule(t, "b", 7), []int{0}, []string{"b"},
bootstrap.EntryCallback(nil), &recordingDispatcher{})
bootstrap.EntryCallback(nil), &recordingDispatcher{}, nil)
assert.ErrorIs(t, err, context.Canceled)
}
@@ -24,6 +24,8 @@ type WalkerDispatcher struct {
// daily-run's processMatches uses so the walker and replay paths
// can't combine to burst past the cap. nil disables throttling.
Limiter *rate.Limiter
// nil skips per-pass outcome counts.
Stats *RunStats
}
// Compile-time check.
@@ -75,17 +77,17 @@ func (d *WalkerDispatcher) Delete(ctx context.Context, action *engine.CompiledAc
if err != nil {
// "RPC_ERROR" matches the streaming dispatcher and processMatches
// labels so transport-class failures aggregate under one key.
stats.S3LifecycleDispatchCounter.WithLabelValues(action.Bucket, kindLabel, "RPC_ERROR").Inc()
countDispatch(d.Stats, action.Bucket, kindLabel, "RPC_ERROR")
return fmt.Errorf("walker dispatch %s/%s %s: %w", action.Bucket, objectPath, action.Key.ActionKind, err)
}
if resp == nil {
// A misbehaving server stub returning (nil, nil) would panic on
// the switch below. Bucket under RPC_ERROR rather than a new
// label — operationally it's the same class of failure.
stats.S3LifecycleDispatchCounter.WithLabelValues(action.Bucket, kindLabel, "RPC_ERROR").Inc()
countDispatch(d.Stats, action.Bucket, kindLabel, "RPC_ERROR")
return fmt.Errorf("walker dispatch %s/%s %s: nil response", action.Bucket, objectPath, action.Key.ActionKind)
}
stats.S3LifecycleDispatchCounter.WithLabelValues(action.Bucket, kindLabel, resp.Outcome.String()).Inc()
countDispatch(d.Stats, action.Bucket, kindLabel, resp.Outcome.String())
switch resp.Outcome {
case s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
@@ -136,13 +136,16 @@ func TestRunShard_WalkerThrottle(t *testing.T) {
runNow2 := runNow.Add(tc.secondPassAfter)
closedEvents2 := make(chan *readerEventAlias)
close(closedEvents2)
cfg.Stats = &RunStats{}
require.NoError(t, runShard(context.Background(), cfg, snap, runNow2, 0, closedEvents2, nil))
afterPass2, _, _ := p.Load(context.Background(), 0)
assert.Equal(t, tc.wantTotalCalls, calls, "walker calls after 2 passes")
if tc.wantSecondAdvNs {
assert.Equal(t, runNow2.UnixNano(), afterPass2.LastWalkedNs, "throttle allowed the second walk")
assert.Zero(t, cfg.Stats.Summary().WalksDeferred)
} else {
assert.Equal(t, runNow.UnixNano(), afterPass2.LastWalkedNs, "throttle suppressed the second walk; anchor unchanged")
assert.Equal(t, 1, cfg.Stats.Summary().WalksDeferred, "a throttled walk leaves its rules unevaluated")
}
})
}
+1 -1
View File
@@ -78,7 +78,7 @@ func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream file
includeLastFile := req.InclusiveStartFrom
snapshotTsNs := req.SnapshotTsNs
if snapshotTsNs == 0 {
snapshotTsNs = time.Now().UnixNano()
snapshotTsNs = fs.filer.LocalDeliveredThroughTsNs(time.Now().UnixNano())
}
sentSnapshot := false
var listErr error
@@ -0,0 +1,74 @@
package weed_server
import (
"context"
"strconv"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
type captureListStream struct {
grpc.ServerStream
responses []*filer_pb.ListEntriesResponse
trailer metadata.MD
}
func (s *captureListStream) Context() context.Context { return context.Background() }
func (s *captureListStream) Send(resp *filer_pb.ListEntriesResponse) error {
s.responses = append(s.responses, resp)
return nil
}
func (s *captureListStream) SetTrailer(md metadata.MD) { s.trailer = md }
func (s *captureListStream) snapshotTsNs(t *testing.T) int64 {
t.Helper()
values := s.trailer.Get(filer_pb.ListSnapshotTsNsTrailerKey)
if len(values) != 1 {
t.Fatalf("snapshot trailer = %v", values)
}
tsNs, err := strconv.ParseInt(values[0], 10, 64)
if err != nil {
t.Fatalf("snapshot trailer %q: %v", values[0], err)
}
return tsNs
}
// A listing snapshot tells the client every event at or below it is in the
// listing, so the client drops those events. It must stay below a create that
// is stamped but may not be in the store yet, and below every stamp issued
// after it, or a create landing right after the listing never reaches the
// client's cache.
func TestListEntriesSnapshotBelowUnfinishedAndLaterStamps(t *testing.T) {
store := newRenameTestStore()
store.entries["/dir"] = newDirectoryEntry("/dir", 100)
f := newRenameTestFiler(t, store)
fs := &FilerServer{filer: f, option: &FilerOption{DirListingLimit: 1000}}
inFlightTsNs := f.StampMetaLogInflightForTest()
stream := &captureListStream{}
if err := fs.ListEntries(&filer_pb.ListEntriesRequest{Directory: "/dir"}, stream); err != nil {
t.Fatalf("ListEntries: %v", err)
}
f.DoneMetaLogInflightForTest(inFlightTsNs)
snapshotTsNs := stream.snapshotTsNs(t)
if snapshotTsNs >= inFlightTsNs {
t.Fatalf("snapshot %d covers the unfinished stamp %d", snapshotTsNs, inFlightTsNs)
}
stream = &captureListStream{}
if err := fs.ListEntries(&filer_pb.ListEntriesRequest{Directory: "/dir"}, stream); err != nil {
t.Fatalf("ListEntries: %v", err)
}
snapshotTsNs = stream.snapshotTsNs(t)
laterTsNs := f.StampMetaLogInflightForTest()
f.DoneMetaLogInflightForTest(laterTsNs)
if laterTsNs <= snapshotTsNs {
t.Fatalf("stamp %d issued after the listing is not above its snapshot %d", laterTsNs, snapshotTsNs)
}
}
+5 -1
View File
@@ -407,7 +407,11 @@ func (ms *MasterServer) VacuumVolume(ctx context.Context, req *master_pb.VacuumV
resp := &master_pb.VacuumVolumeResponse{}
ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, req.VolumeId, req.Collection, ms.preallocateSize, false, 0)
// A request that lost the vacuum guard to the automatic vacuum or to another
// request did nothing. Returning success would tell the caller it ran.
if err := ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, req.VolumeId, req.Collection, ms.preallocateSize, false, 0); err != nil {
return nil, err
}
return resp, nil
}
+4 -1
View File
@@ -61,7 +61,10 @@ func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Reque
}
}
// glog.Infoln("garbageThreshold =", gcThreshold)
ms.Topo.Vacuum(ms.grpcDialOption, gcThreshold, ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, 0, "", ms.preallocateSize, false, 0)
if err := ms.Topo.Vacuum(ms.grpcDialOption, gcThreshold, ms.option.MaxParallelVacuumPerServer, ms.option.MaxParallelVacuumPerRack, 0, "", ms.preallocateSize, false, 0); err != nil {
writeJsonError(w, r, http.StatusConflict, err)
return
}
ms.dirStatusHandler(w, r)
}
+8 -8
View File
@@ -34,13 +34,13 @@ func (c *commandS3CircuitBreaker) Help() string {
# examples
# add circuit breaker config for global
s3.circuitBreaker -global -type count -actions Read,Write -values 500,200 -apply
s3.circuitBreaker -global -type Count -actions Read,Write -values 500,200 -apply
# disable global config
s3.circuitBreaker -global -disable -apply
# add circuit breaker config for buckets x,y,z
s3.circuitBreaker -buckets x,y,z -type count -actions Read,Write -values 200,100 -apply
s3.circuitBreaker -buckets x,y,z -type Count -actions Read,Write -values 200,100 -apply
# disable circuit breaker config of x
s3.circuitBreaker -buckets x -disable -apply
@@ -207,7 +207,7 @@ func loadConfig(commandEnv *CommandEnv, dir string, file string, buf *bytes.Buff
func insertOrUpdateValues(cbOptions *s3_pb.S3CircuitBreakerOptions, cmdActions []string, cmdValues []int64, limitType *string) error {
if len(*limitType) == 0 {
return fmt.Errorf("type not valid, only 'count' and 'bytes' are allowed")
return fmt.Errorf("type not valid, only 'Count' and 'MB' are allowed")
}
if cbOptions.Actions == nil {
@@ -289,7 +289,7 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
}
}
if !found {
return nil, nil, nil, fmt.Errorf("value(%s) of flag[-action] not valid, allowed actions: %v", *actions, s3_constants.AllowedActions)
return nil, nil, nil, fmt.Errorf("value(%s) of flag[-actions] not valid, allowed actions: %v", action, s3_constants.AllowedActions)
}
}
}
@@ -307,7 +307,7 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
elements := strings.Split(*values, ",")
if len(cmdActions) != len(elements) {
if len(elements) != 1 || len(elements) == 0 {
return nil, nil, nil, fmt.Errorf("count of flag[-actions] and flag[-counts] not equal")
return nil, nil, nil, fmt.Errorf("count of flag[-actions] and flag[-values] not equal")
}
v, err := strconv.Atoi(elements[0])
if err != nil {
@@ -333,7 +333,7 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
}
v, err := parseMBToBytes(elements[0])
if err != nil {
return nil, nil, nil, fmt.Errorf("value of -max must be a legal number(s)")
return nil, nil, nil, fmt.Errorf("value of -values must be a legal number(s)")
}
for range cmdActions {
cmdValues = append(cmdValues, v)
@@ -342,13 +342,13 @@ func (c *commandS3CircuitBreaker) initActionsAndValues(buckets, actions, limitTy
for _, value := range elements {
v, err := parseMBToBytes(value)
if err != nil {
return nil, nil, nil, fmt.Errorf("value of -max must be a legal number(s)")
return nil, nil, nil, fmt.Errorf("value of -values must be a legal number(s)")
}
cmdValues = append(cmdValues, v)
}
}
default:
return nil, nil, nil, fmt.Errorf("type not valid, only 'count' and 'bytes' are allowed")
return nil, nil, nil, fmt.Errorf("type not valid, only 'Count' and 'MB' are allowed")
}
} else {
*limitType = ""
@@ -0,0 +1,53 @@
package shell
import (
"bytes"
"strings"
"testing"
)
// Every example in the s3.circuitBreaker help text has to run as written.
func TestCircuitBreakerHelpExamplesRun(t *testing.T) {
originalLoadConfig := LoadConfig
t.Cleanup(func() { LoadConfig = originalLoadConfig })
LoadConfig = func(*CommandEnv, string, string, *bytes.Buffer) error { return nil }
cmd := &commandS3CircuitBreaker{}
examples := 0
for _, line := range strings.Split(cmd.Help(), "\n") {
fields := strings.Fields(line)
if len(fields) == 0 || fields[0] != cmd.Name() {
continue
}
examples++
// Leave out -apply: it saves the result inside the filer.
var args []string
for _, f := range fields[1:] {
if f != "-apply" {
args = append(args, f)
}
}
var out bytes.Buffer
if err := cmd.Do(args, nil, &out); err != nil {
t.Errorf("%s: %v", strings.TrimSpace(line), err)
}
}
if examples == 0 {
t.Fatal("found no examples in the help text")
}
}
func TestCircuitBreakerInvalidActionError(t *testing.T) {
originalLoadConfig := LoadConfig
t.Cleanup(func() { LoadConfig = originalLoadConfig })
LoadConfig = func(*CommandEnv, string, string, *bytes.Buffer) error { return nil }
cmd := &commandS3CircuitBreaker{}
err := cmd.Do([]string{"-global", "-type", "Count", "-actions", "Read,Bogus", "-values", "1,2"}, nil, &bytes.Buffer{})
if err == nil {
t.Fatal("expected an error for an unknown action")
}
if msg := err.Error(); !strings.Contains(msg, "value(Bogus)") || !strings.Contains(msg, "flag[-actions]") {
t.Errorf("error should name the bad action and -actions: %v", err)
}
}
+20 -18
View File
@@ -2,10 +2,13 @@ package shell
import (
"bytes"
"encoding/json"
"reflect"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
type Case struct {
@@ -256,6 +259,8 @@ var (
func TestCircuitBreakerShell(t *testing.T) {
var writeBuf bytes.Buffer
cmd := &commandS3CircuitBreaker{}
originalLoadConfig := LoadConfig
t.Cleanup(func() { LoadConfig = originalLoadConfig })
LoadConfig = func(commandEnv *CommandEnv, dir string, file string, buf *bytes.Buffer) error {
_, err := buf.Write(writeBuf.Bytes())
if err != nil {
@@ -270,23 +275,20 @@ func TestCircuitBreakerShell(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if i != 0 {
result := writeBuf.String()
actual := make(map[string]interface{})
err := json.Unmarshal([]byte(result), &actual)
if err != nil {
t.Error(err)
}
expect := make(map[string]interface{})
err = json.Unmarshal([]byte(result), &expect)
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(actual, expect) {
t.Fatal("result of s3 circuit breaker shell command is unexpected!")
}
// Compare as configs: the command writes default fields such as
// "enabled": false that the expected JSON leaves out.
actual := &s3_pb.S3CircuitBreakerConfig{}
if err := filer.ParseS3ConfigurationFromBytes(writeBuf.Bytes(), actual); err != nil {
t.Fatalf("case %d %v: parse output: %v", i, tc.args, err)
}
// Strict parsing, so a misspelled field in the expected JSON fails.
expect := &s3_pb.S3CircuitBreakerConfig{}
if err := protojson.Unmarshal([]byte(tc.result), expect); err != nil {
t.Fatalf("case %d: parse expected result: %v", i, err)
}
if !proto.Equal(actual, expect) {
t.Fatalf("case %d %v:\ngot %v\nwant %v", i, tc.args, actual, expect)
}
}
}
+1 -1
View File
@@ -167,7 +167,7 @@ func (c *commandS3LifecycleRunShard) Do(args []string, env *CommandEnv, writer i
}
walker := dailyrun.WalkerFunc(func(walkCtx context.Context, view *engine.Snapshot, shards []int) error {
return dailyrun.WalkBuckets(walkCtx, view, shards, buckets,
dailyrun.FilerListFunc(filerClient, bucketsPath, view), walkerDispatch)
dailyrun.FilerListFunc(filerClient, bucketsPath, view), walkerDispatch, nil)
})
return dailyrun.Run(passCtx, dailyrun.Config{
Shards: shards,
+19 -1
View File
@@ -38,6 +38,10 @@ func (c *commandVacuum) Help() string {
Without -volumeId this runs the same sweep as the automatic vacuum, which skips
read-only volumes. Name a read-only volume with -volumeId to vacuum it anyway.
The master runs one vacuum at a time. While the automatic vacuum or another
request is running, this command fails instead of waiting for its turn. Run it
again later, or pause the automatic vacuum first with volume.vacuum.disable.
`
}
@@ -157,13 +161,27 @@ func (c *commandVacuum) Do(args []string, commandEnv *CommandEnv, writer io.Writ
return err
})
if err != nil {
return err
// A list of volumes or collections is several requests, and a vacuum
// that starts in between only fails the ones after it.
return fmt.Errorf("vacuum %s: %w", describeVacuumRequest(req), err)
}
}
return nil
}
func describeVacuumRequest(req *master_pb.VacuumVolumeRequest) string {
switch {
case req.VolumeId != 0 && req.Collection != "":
return fmt.Sprintf("volume %d in collection %s", req.VolumeId, req.Collection)
case req.VolumeId != 0:
return fmt.Sprintf("volume %d", req.VolumeId)
case req.Collection != "":
return "collection " + req.Collection
}
return "all volumes"
}
// vidReplica pairs a volume replica's read-only state with the server that
// reports it, so the unnamed-collection sweep can reproduce the master's
// low-disk-space exception client-side.
+13
View File
@@ -954,6 +954,18 @@ var (
Help: "Per-shard timestamp (UnixNano) of the most recent successful walker fire. 0 means the shard hasn't completed a walk yet.",
}, []string{"shard"})
// S3LifecycleDailyRunLastFullPassTimestampSeconds is when the last
// lifecycle pass that covered every shard and every lifecycle policy
// without an error finished. Partial, failed and cancelled passes leave
// it alone, unlike the per-shard cursor and walk gauges.
S3LifecycleDailyRunLastFullPassTimestampSeconds = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: subsystemS3Lifecycle,
Name: "daily_run_last_full_pass_timestamp_seconds",
Help: "Unix time the last fully successful lifecycle pass finished. 0 means none is known yet.",
})
AdminMaintenanceTasksByStatus = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
@@ -1141,6 +1153,7 @@ func init() {
Gather.MustRegister(S3LifecycleDailyRunShardDurationSeconds)
Gather.MustRegister(S3LifecycleDailyRunEventsScanned)
Gather.MustRegister(S3LifecycleDailyRunLastWalkedNs)
Gather.MustRegister(S3LifecycleDailyRunLastFullPassTimestampSeconds)
Gather.MustRegister(UploadErrorCounter)
+13 -2
View File
@@ -2,6 +2,7 @@ package topology
import (
"context"
"errors"
"io"
"sync"
"sync/atomic"
@@ -255,13 +256,22 @@ func (t *Topology) batchVacuumVolumeCleanup(grpcDialOption grpc.DialOption, vl *
}
}
func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float64, maxParallelVacuumPerServer int, maxParallelVacuumPerRack int, volumeId uint32, collection string, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) {
// ErrVacuumRunning is what Vacuum returns when another vacuum holds the
// topology-wide guard. The request was dropped, not queued: nothing waits for
// the running vacuum, so the caller has to ask again.
var ErrVacuumRunning = errors.New("another vacuum is running, try again later")
// Vacuum runs one vacuum at a time. A call that finds another one running,
// the automatic vacuum or an earlier request, does nothing and returns
// ErrVacuumRunning, so that a request for a volume cannot look done when it
// never started.
func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float64, maxParallelVacuumPerServer int, maxParallelVacuumPerRack int, volumeId uint32, collection string, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) error {
// if there is vacuum going on, return immediately
swapped := atomic.CompareAndSwapInt64(&t.vacuumLockCounter, 0, 1)
if !swapped {
glog.V(0).Infof("Vacuum is already running")
return
return ErrVacuumRunning
}
defer atomic.StoreInt64(&t.vacuumLockCounter, 0)
@@ -301,6 +311,7 @@ func (t *Topology) Vacuum(grpcDialOption grpc.DialOption, garbageThreshold float
break
}
}
return nil
}
func (t *Topology) vacuumOneVolumeLayout(grpcDialOption grpc.DialOption, volumeLayout *VolumeLayout, c *Collection, garbageThreshold float64, maxParallelVacuumPerServer int, maxParallelVacuumPerRack int, preallocate int64, automatic bool, deleteEmptyAfter time.Duration) {
+77
View File
@@ -518,6 +518,83 @@ func TestVacuumStalledVolumeServerReleasesGuard(t *testing.T) {
}
}
// A request that finds another vacuum running is dropped, not queued. It has
// to say so: returning as if it had run leaves the caller believing its volume
// was compacted.
func TestVacuumReportsAnotherVacuumRunning(t *testing.T) {
fake := &fakeVacuumServer{
checks: map[uint32]*volume_server_pb.VacuumVolumeCheckResponse{
1: {GarbageRatio: 0.9},
2: {GarbageRatio: 0.9},
},
entered: make(chan string, 1),
compactGate: make(chan struct{}),
compactTracker: &compactTracker{},
}
grpcPort, dialOption := startFakeVolumeServer(t, fake)
topo := NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
dn := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1").
GetOrCreateDataNode("127.0.0.1", 8080, grpcPort, "127.0.0.1", "dn", map[string]uint32{"": 10})
var volumes []storage.VolumeInfo
for vid := 1; vid <= 2; vid++ {
volumes = append(volumes, storage.VolumeInfo{
Id: needle.VolumeId(vid),
Size: 1 << 20,
Collection: "c",
ModifiedAtSecond: time.Now().Unix(),
Version: needle.GetCurrentVersion(),
ReplicaPlacement: &super_block.ReplicaPlacement{},
Ttl: needle.EMPTY_TTL,
})
}
dn.UpdateVolumes(volumes)
for _, v := range volumes {
topo.RegisterVolumeLayout(v, dn)
}
committed := func() []uint32 {
fake.mu.Lock()
defer fake.mu.Unlock()
return append([]uint32(nil), fake.committed...)
}
// the first request holds the guard for as long as its compaction is gated
first := make(chan error, 1)
go func() {
first <- topo.Vacuum(dialOption, 0.3, 1, 0, 1, "c", 0, false, 0)
}()
select {
case <-fake.entered:
case <-time.After(15 * time.Second):
t.Fatal("the first vacuum never reached the compact phase")
}
if err := topo.Vacuum(dialOption, 0.3, 1, 0, 2, "c", 0, false, 0); !errors.Is(err, ErrVacuumRunning) {
t.Fatalf("vacuum of volume 2 while volume 1 is compacting: err = %v, want ErrVacuumRunning", err)
}
if got := committed(); len(got) != 0 {
t.Fatalf("committed volumes = %v, want none while the first vacuum is gated", got)
}
close(fake.compactGate)
select {
case err := <-first:
if err != nil {
t.Fatalf("the first vacuum: %v", err)
}
case <-time.After(15 * time.Second):
t.Fatal("the first vacuum did not finish after the gate opened")
}
// with the guard free again, the same request runs
if err := topo.Vacuum(dialOption, 0.3, 1, 0, 2, "c", 0, false, 0); err != nil {
t.Fatalf("vacuum of volume 2 after the first one finished: %v", err)
}
if got := committed(); len(got) != 2 || got[0] != 1 || got[1] != 2 {
t.Fatalf("committed volumes = %v, want [1 2]", got)
}
}
// A replica tiered to remote storage is never compacted by a vacuum, not even
// on an explicit request with a zero threshold: its .dat is the remote object.
// volume.tier.compact is the way to reclaim its garbage.
+90 -30
View File
@@ -2,6 +2,7 @@ package s3_lifecycle
import (
"context"
"errors"
"fmt"
"math"
"strconv"
@@ -19,6 +20,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
"github.com/seaweedfs/seaweedfs/weed/stats"
"golang.org/x/time/rate"
"google.golang.org/grpc"
)
@@ -248,34 +250,43 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
return fmt.Errorf("buckets path: %w", err)
}
dialCtx, dialCancel = context.WithTimeout(runCtx, 30*time.Second)
s3Conn, err := pb.GrpcDial(dialCtx, s3Endpoints[0], false, h.grpcDialOption)
dialCancel()
if err != nil {
return fmt.Errorf("dial s3 %s: %w", s3Endpoints[0], err)
s3Conn, s3Endpoint, skipped := h.selectS3Front(runCtx, s3Endpoints)
if s3Conn == nil {
return noReadyS3Error(skipped)
}
defer s3Conn.Close()
if len(skipped) > 0 {
skippedErr := errors.Join(skipped...)
glog.Warningf("s3 lifecycle: using s3 %s, skipped: %v", s3Endpoint, skippedErr)
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId, JobType: jobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "starting",
Message: fmt.Sprintf("using s3 %s, skipped: %v", s3Endpoint, skippedErr),
})
}
rpc := s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(s3Conn)
if err := h.executeDailyReplay(runCtx, request, bucketsPath, filerClient, rpc, cfg, sender); err != nil {
report, err := h.executeDailyReplay(runCtx, request, bucketsPath, filerClient, rpc, cfg, sender)
if err != nil {
return err
}
return sendSuccessCompletion(request, sender)
return sendCompletion(request, sender, report)
}
const dailyReplaySuccessSummary = "s3 lifecycle daily replay completed"
// JobCompleted must set JobType to the handler's jobType constant;
// routed requests may leave request.Job.JobType empty, and the admin
// ignores completions with empty JobType.
func sendSuccessCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender) error {
// ignores completions with empty JobType. Failed passes carry their
// result too, so every bucket failure stays in the job record.
func sendCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender, report *runReport) error {
return sender.SendCompleted(&plugin_pb.JobCompleted{
JobId: request.Job.JobId,
JobType: jobType,
Success: true,
JobId: request.Job.JobId,
JobType: jobType,
Success: report.err == nil,
ErrorMessage: report.errorMessage(),
Result: &plugin_pb.JobResult{
Summary: dailyReplaySuccessSummary,
Summary: report.summaryLine(),
OutputValues: report.outputValues(),
},
})
}
@@ -283,14 +294,17 @@ func sendSuccessCompletion(request *plugin_pb.ExecuteJobRequest, sender pluginwo
// executeDailyReplay runs one bounded daily-replay pass via
// dailyrun.Run. The walker fires inside runShard on rule-content edits
// and against the steady-state walk view; all rule kinds are serviced.
func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.ExecuteJobRequest, bucketsPath string, filerClient filer_pb.SeaweedFilerClient, rpc s3_lifecycle_pb.SeaweedS3LifecycleInternalClient, cfg Config, sender pluginworker.ExecutionSender) error {
// The returned error covers setup only; the pass's own error is in the
// report.
func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.ExecuteJobRequest, bucketsPath string, filerClient filer_pb.SeaweedFilerClient, rpc s3_lifecycle_pb.SeaweedS3LifecycleInternalClient, cfg Config, sender pluginworker.ExecutionSender) (*runReport, error) {
startedAt := time.Now()
eng := engine.New()
inputs, parseErrors, err := scheduler.LoadCompileInputs(ctx, filerClient, bucketsPath)
if err != nil {
return fmt.Errorf("daily_replay: load lifecycle inputs: %w", err)
return nil, fmt.Errorf("daily_replay: load lifecycle inputs: %w", err)
}
for _, pe := range parseErrors {
glog.V(1).Infof("daily_replay: %s: %v", pe.Bucket, pe.Err)
glog.Warningf("daily_replay: invalid lifecycle policy on bucket %s: %v", pe.Bucket, pe.Err)
}
eng.Compile(inputs, engine.CompileOptions{PriorStates: scheduler.AllActivePriorStates(inputs)})
@@ -313,28 +327,34 @@ func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.Exe
buckets = append(buckets, in.Bucket)
}
}
persister := &dailyrun.FilerCursorPersister{Store: dispatcher.NewFilerStoreClient(filerClient)}
report := &runReport{bucketsTotal: len(buckets) + len(parseErrors), invalidPolicies: parseErrors}
loadLastFullPass(ctx, persister, report)
runStats := &dailyrun.RunStats{}
// Share the limiter with processMatches so walker + replay can't
// combine to burst past the cluster cap.
walkerDispatch := &dailyrun.WalkerDispatcher{Client: client, Limiter: limiter}
walkerDispatch := &dailyrun.WalkerDispatcher{Client: client, Limiter: limiter, Stats: runStats}
walker := dailyrun.WalkerFunc(func(walkCtx context.Context, view *engine.Snapshot, shards []int) error {
return dailyrun.WalkBuckets(walkCtx, view, shards, buckets,
dailyrun.FilerListFunc(filerClient, bucketsPath, view), walkerDispatch)
dailyrun.FilerListFunc(runStats.CountListed(filerClient), bucketsPath, view), walkerDispatch, runStats)
})
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId, JobType: jobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "starting",
Message: fmt.Sprintf("daily_replay shards=%d workers=%d rate=%s buckets=%d walker=on",
len(shards), cfg.Workers, limiterDesc, len(buckets)),
Message: fmt.Sprintf("daily_replay shards=%d workers=%d rate=%s buckets=%d invalid_policies=%d walker=on",
len(shards), cfg.Workers, limiterDesc, len(buckets), len(parseErrors)),
})
runErr := dailyrun.Run(ctx, dailyrun.Config{
stopProgress := startProgressReporter(request, sender, runStats.Summary, progressInterval)
report.err = dailyrun.Run(ctx, dailyrun.Config{
Shards: shards,
BucketsPath: bucketsPath,
Engine: eng,
FilerClient: filerClient,
Client: client,
Persister: &dailyrun.FilerCursorPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
Persister: persister,
Lister: dispatcher.NewFilerSiblingLister(filerClient, bucketsPath),
Workers: cfg.Workers,
Limiter: limiter,
@@ -342,12 +362,51 @@ func (h *Handler) executeDailyReplay(ctx context.Context, request *plugin_pb.Exe
Walker: walker,
WalkerInterval: cfg.WalkerInterval,
ClientName: "worker-s3-lifecycle-daily",
Stats: runStats,
})
if runErr != nil {
glog.Warningf("daily_replay: %v", runErr)
return runErr
stopProgress()
report.canceled = ctx.Err() != nil
report.elapsed = time.Since(startedAt)
report.summary = runStats.Summary()
if report.err != nil {
glog.Warningf("daily_replay: %v", report.err)
}
return nil
recordFullPass(ctx, persister, report, startedAt)
return report, nil
}
func loadLastFullPass(ctx context.Context, persister *dailyrun.FilerCursorPersister, report *runReport) {
fp, found, err := persister.LoadFullPass(ctx)
if err != nil {
glog.Warningf("daily_replay: %v", err)
return
}
if found {
report.lastFullPass = fp.CompletedAt
publishFullPass(fp)
}
}
// recordFullPass advances the full-pass record only when the pass
// covered every shard and every policy.
func recordFullPass(ctx context.Context, persister *dailyrun.FilerCursorPersister, report *runReport, startedAt time.Time) {
if !report.fullPass() {
return
}
fp := dailyrun.FullPass{StartedAt: startedAt.UTC(), CompletedAt: time.Now().UTC()}
saveCtx, saveCancel := context.WithTimeout(ctx, 10*time.Second)
defer saveCancel()
if err := persister.SaveFullPass(saveCtx, fp); err != nil {
glog.Warningf("daily_replay: %v", err)
report.fullPassSaveErr = err
return
}
report.lastFullPass = fp.CompletedAt
publishFullPass(fp)
}
func publishFullPass(fp dailyrun.FullPass) {
stats.S3LifecycleDailyRunLastFullPassTimestampSeconds.Set(float64(fp.CompletedAt.UnixNano()) / 1e9)
}
// buildLimiterFromClusterContext parses the per-worker share the admin
@@ -404,8 +463,9 @@ func parsePositiveInt(s string) (int, bool) {
}
// clusterS3Endpoints returns the master-discovered S3 gRPC addresses for the
// cluster. The handler dials the first reachable one; the master refreshes
// the list on KeepConnected so a stale entry self-heals on the next run.
// cluster. The handler uses the first one that passes checkLifecycleReady;
// the master refreshes the list on KeepConnected so a stale entry self-heals
// on the next run.
func clusterS3Endpoints(cc *plugin_pb.ClusterContext) []string {
if cc == nil {
return nil
+148 -6
View File
@@ -4,10 +4,16 @@ import (
"context"
"errors"
"math"
"strings"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
@@ -468,15 +474,15 @@ func TestExecute_EmptyJobTypeAccepted(t *testing.T) {
assert.Contains(t, err.Error(), "no s3 servers", "validation flowed past the type check")
}
// ---------- sendSuccessCompletion ----------
// ---------- sendCompletion ----------
func TestSendSuccessCompletion_EmitsCanonicalCompletion(t *testing.T) {
func TestSendCompletion_EmitsCanonicalCompletion(t *testing.T) {
sender := &recordingExecSender{}
request := &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{JobId: "job-123"}, // empty JobType (broadcast routing)
}
require.NoError(t, sendSuccessCompletion(request, sender))
require.NoError(t, sendCompletion(request, sender, &runReport{bucketsTotal: 2}))
require.Len(t, sender.completed, 1, "exactly one completion must be sent")
c := sender.completed[0]
@@ -484,20 +490,140 @@ func TestSendSuccessCompletion_EmitsCanonicalCompletion(t *testing.T) {
assert.NotEmpty(t, c.JobType, "an empty JobType is dropped by the admin")
assert.Equal(t, "job-123", c.JobId, "completion must echo the original JobId")
assert.True(t, c.Success, "a clean replay is a success completion")
assert.Empty(t, c.ErrorMessage)
require.NotNil(t, c.Result)
assert.NotEmpty(t, c.Result.Summary, "admin UI surfaces a non-empty Result.Summary")
assert.True(t, strings.HasPrefix(c.Result.Summary, "s3 lifecycle daily replay completed:"), c.Result.Summary)
assert.Equal(t, runStatusComplete, c.Result.OutputValues["status"].GetStringValue())
assert.Equal(t, int64(2), c.Result.OutputValues["buckets_total"].GetInt64Value())
}
func TestSendSuccessCompletion_PropagatesSendError(t *testing.T) {
func TestSendCompletion_PropagatesSendError(t *testing.T) {
sentinel := errors.New("stream closed")
sender := &recordingExecSender{completedErr: sentinel}
request := &plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{JobId: "job-456"}}
err := sendSuccessCompletion(request, sender)
err := sendCompletion(request, sender, &runReport{})
require.Error(t, err)
assert.ErrorIs(t, err, sentinel)
}
func TestSendCompletion_FailedPassKeepsEveryBucketFailure(t *testing.T) {
sender := &recordingExecSender{}
report := &runReport{
err: errors.New("shard=3: steady walk: walk bad-a: filer down"),
bucketsTotal: 3,
summary: dailyrun.RunSummary{
BucketsWalked: 1,
BucketsFailed: 2,
BucketFailures: []dailyrun.BucketFailure{
{Bucket: "bad-a", Error: "filer down"},
{Bucket: "bad-b", Error: "outcome=BLOCKED"},
},
Outcomes: map[string]int64{"DONE": 4, "RPC_ERROR": 1},
},
}
require.NoError(t, sendCompletion(&plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{JobId: "j"}}, sender, report))
require.Len(t, sender.completed, 1)
c := sender.completed[0]
assert.False(t, c.Success)
assert.Contains(t, c.ErrorMessage, "walk bad-a: filer down")
assert.Contains(t, c.ErrorMessage, "2 of 3 buckets failed")
require.NotNil(t, c.Result, "a failed pass still reports its result")
values := c.Result.OutputValues
assert.Equal(t, runStatusFailed, values["status"].GetStringValue())
assert.Equal(t, int64(2), values["buckets_failed"].GetInt64Value())
assert.Equal(t, []string{"bad-a: filer down", "bad-b: outcome=BLOCKED"}, values["bucket_failures"].GetStringList().GetValues())
assert.Equal(t, int64(4), values["rpc_done"].GetInt64Value())
assert.Equal(t, int64(1), values["rpc_error"].GetInt64Value())
assert.True(t, strings.HasPrefix(c.Result.Summary, "s3 lifecycle daily replay failed:"), c.Result.Summary)
}
func TestRunReport_InvalidPolicyIsPartial(t *testing.T) {
report := &runReport{
bucketsTotal: 2,
invalidPolicies: []scheduler.ParseError{{Bucket: "broken", Err: errors.New("bad xml")}},
}
assert.Equal(t, runStatusPartial, report.status())
assert.True(t, strings.HasPrefix(report.summaryLine(), "s3 lifecycle daily replay partial:"), report.summaryLine())
assert.Contains(t, report.summaryLine(), "invalid_policies=1")
values := report.outputValues()
assert.Equal(t, int64(1), values["invalid_policies"].GetInt64Value())
assert.Equal(t, []string{"broken: bad xml"}, values["invalid_policy_buckets"].GetStringList().GetValues())
}
func TestRunReport_CanceledWinsOverError(t *testing.T) {
report := &runReport{canceled: true, err: context.Canceled}
assert.Equal(t, runStatusCanceled, report.status())
report.err = nil
assert.Equal(t, runStatusCanceled, report.status(), "a drain cut short returns no error")
}
// ---------- full pass record ----------
type memFilerStore struct {
files map[string][]byte
saveErr error
}
func (s *memFilerStore) Read(_ context.Context, dir, name string) ([]byte, error) {
b, ok := s.files[dir+"/"+name]
if !ok {
return nil, filer_pb.ErrNotFound
}
return b, nil
}
func (s *memFilerStore) Save(_ context.Context, dir, name string, content []byte) error {
if s.saveErr != nil {
return s.saveErr
}
s.files[dir+"/"+name] = content
return nil
}
func TestRecordFullPass_OnlyACompletePassAdvances(t *testing.T) {
previous := dailyrun.FullPass{StartedAt: time.Unix(1_700_000_000, 0).UTC(), CompletedAt: time.Unix(1_700_000_600, 0).UTC()}
for name, report := range map[string]*runReport{
"failed": {err: errors.New("walk failed")},
"canceled": {canceled: true},
"partial": {invalidPolicies: []scheduler.ParseError{{Bucket: "b", Err: errors.New("bad")}}},
"halted": {summary: dailyrun.RunSummary{ShardsHalted: 1}},
"deferred": {summary: dailyrun.RunSummary{WalksDeferred: 16}},
} {
t.Run(name, func(t *testing.T) {
persister := &dailyrun.FilerCursorPersister{Store: &memFilerStore{files: map[string][]byte{}}}
require.NoError(t, persister.SaveFullPass(context.Background(), previous))
loadLastFullPass(context.Background(), persister, report)
recordFullPass(context.Background(), persister, report, time.Now())
got, found, err := persister.LoadFullPass(context.Background())
require.NoError(t, err)
require.True(t, found)
assert.Equal(t, previous, got)
assert.Equal(t, previous.CompletedAt, report.lastFullPass)
assert.Equal(t, "2023-11-14T22:23:20Z", report.outputValues()["last_full_pass_at"].GetStringValue())
})
}
t.Run("complete", func(t *testing.T) {
persister := &dailyrun.FilerCursorPersister{Store: &memFilerStore{files: map[string][]byte{}}}
require.NoError(t, persister.SaveFullPass(context.Background(), previous))
report := &runReport{}
startedAt := time.Now().Add(-time.Minute)
recordFullPass(context.Background(), persister, report, startedAt)
got, found, err := persister.LoadFullPass(context.Background())
require.NoError(t, err)
require.True(t, found)
assert.True(t, got.CompletedAt.After(previous.CompletedAt))
assert.Equal(t, startedAt.UTC(), got.StartedAt)
assert.Equal(t, got.CompletedAt, report.lastFullPass)
assert.InDelta(t, float64(got.CompletedAt.UnixNano())/1e9,
testutil.ToFloat64(stats.S3LifecycleDailyRunLastFullPassTimestampSeconds), 1e-3)
})
}
// ---------- lookupBucketsPath ----------
// stubFilerConfigClient implements filer_pb.SeaweedFilerClient for the
@@ -548,3 +674,19 @@ func TestLookupBucketsPath_EmptyDirBucketsFallsBackToDefault(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "/buckets", got)
}
func TestRecordFullPass_FailedSaveKeepsThePreviousTimestamp(t *testing.T) {
store := &memFilerStore{files: map[string][]byte{}}
persister := &dailyrun.FilerCursorPersister{Store: store}
previous := dailyrun.FullPass{StartedAt: time.Unix(1_700_000_000, 0).UTC(), CompletedAt: time.Unix(1_700_000_600, 0).UTC()}
require.NoError(t, persister.SaveFullPass(context.Background(), previous))
report := &runReport{}
loadLastFullPass(context.Background(), persister, report)
store.saveErr = errors.New("filer unavailable")
recordFullPass(context.Background(), persister, report, time.Now())
assert.Equal(t, previous.CompletedAt, report.lastFullPass, "an unsaved pass must not replace the saved timestamp")
assert.InDelta(t, float64(previous.CompletedAt.Unix()), testutil.ToFloat64(stats.S3LifecycleDailyRunLastFullPassTimestampSeconds), 1e-3)
assert.Contains(t, report.outputValues()["full_pass_save_error"].GetStringValue(), "filer unavailable")
}
@@ -0,0 +1,71 @@
package s3_lifecycle
import (
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
)
// A long pass must keep refreshing the admin's stale-job clock, but only
// with work it actually did: an idle tick sends nothing.
const progressInterval = 5 * time.Minute
func runWork(s dailyrun.RunSummary) int64 {
work := s.EntriesVisited + s.EntriesListed + s.EventsScanned
for _, n := range s.Outcomes {
work += n
}
return work
}
func progressMessage(s dailyrun.RunSummary) string {
return fmt.Sprintf("s3 lifecycle daily replay running: last_phase=%s last_bucket=%s entries=%d objects=%d listed=%d events=%d rpc_done=%d rpc_errors=%d",
s.Phase, s.Bucket, s.EntriesVisited, s.ObjectsVisited, s.EntriesListed, s.EventsScanned, s.Outcomes["DONE"], s.Outcomes["RPC_ERROR"])
}
// startProgressReporter returns stop, which returns only once no further
// progress can be sent, so the caller can send the completion after it.
func startProgressReporter(request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender, summarize func() dailyrun.RunSummary, interval time.Duration) (stop func()) {
done := make(chan struct{})
finished := make(chan struct{})
go func() {
defer close(finished)
ticker := time.NewTicker(interval)
defer ticker.Stop()
var reported int64
for {
select {
case <-done:
return
case <-ticker.C:
}
summary := summarize()
work := runWork(summary)
if work == reported {
continue
}
select {
case <-done:
return
default:
}
if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId, JobType: jobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "running",
Message: progressMessage(summary),
}); err != nil {
glog.V(1).Infof("s3 lifecycle job %s: send progress: %v", request.Job.JobId, err)
continue
}
reported = work
}
}()
return func() {
close(done)
<-finished
}
}
@@ -0,0 +1,133 @@
package s3_lifecycle
import (
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
"github.com/stretchr/testify/require"
)
type progressSender struct {
mu sync.Mutex
progress []*plugin_pb.JobProgressUpdate
failures int
attempts int
}
func (s *progressSender) SendProgress(p *plugin_pb.JobProgressUpdate) error {
s.mu.Lock()
defer s.mu.Unlock()
s.attempts++
if s.failures > 0 {
s.failures--
return errors.New("stream closed")
}
s.progress = append(s.progress, p)
return nil
}
func (s *progressSender) SendCompleted(*plugin_pb.JobCompleted) error { return nil }
func (s *progressSender) sent() []*plugin_pb.JobProgressUpdate {
s.mu.Lock()
defer s.mu.Unlock()
return append([]*plugin_pb.JobProgressUpdate(nil), s.progress...)
}
func (s *progressSender) tries() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.attempts
}
type fakeRun struct {
entries, listed, events, done, rpcErrors atomic.Int64
}
func (f *fakeRun) summary() dailyrun.RunSummary {
return dailyrun.RunSummary{
Phase: dailyrun.PhaseWalk,
Bucket: "b1",
EntriesVisited: f.entries.Load(),
EntriesListed: f.listed.Load(),
EventsScanned: f.events.Load(),
Outcomes: map[string]int64{"DONE": f.done.Load(), "RPC_ERROR": f.rpcErrors.Load()},
}
}
func progressRequest() *plugin_pb.ExecuteJobRequest {
return &plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{JobId: "job-1"}}
}
const testInterval = 5 * time.Millisecond
func TestProgressReporter_IdleTicksSendNothing(t *testing.T) {
sender := &progressSender{}
run := &fakeRun{}
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
time.Sleep(20 * testInterval)
stop()
require.Empty(t, sender.sent())
}
func TestProgressReporter_ReportsEachKindOfWork(t *testing.T) {
sender := &progressSender{}
run := &fakeRun{}
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
defer stop()
bumps := []*atomic.Int64{&run.entries, &run.listed, &run.events, &run.done, &run.rpcErrors}
for i, counter := range bumps {
counter.Add(1)
require.Eventually(t, func() bool { return len(sender.sent()) == i+1 }, time.Second, testInterval)
}
time.Sleep(10 * testInterval)
updates := sender.sent()
require.Len(t, updates, len(bumps), "unchanged work must not refresh the job")
last := updates[len(updates)-1]
require.Equal(t, "job-1", last.JobId)
require.Equal(t, jobType, last.JobType)
require.Equal(t, plugin_pb.JobState_JOB_STATE_RUNNING, last.State)
require.Equal(t, "running", last.Stage)
require.Contains(t, last.Message, "last_phase=walk last_bucket=b1")
require.Contains(t, last.Message, "entries=1")
require.Contains(t, last.Message, "listed=1")
require.Contains(t, last.Message, "events=1")
require.Contains(t, last.Message, "rpc_done=1")
require.Contains(t, last.Message, "rpc_errors=1")
}
func TestProgressReporter_RetriesAFailedSendWithoutNewWork(t *testing.T) {
sender := &progressSender{failures: 2}
run := &fakeRun{}
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
defer stop()
run.entries.Add(3)
require.Eventually(t, func() bool { return len(sender.sent()) == 1 }, time.Second, testInterval)
require.Equal(t, 3, sender.tries())
time.Sleep(10 * testInterval)
require.Equal(t, 3, sender.tries(), "a delivered report must not be resent")
require.Contains(t, sender.sent()[0].Message, "entries=3")
}
func TestProgressReporter_NoProgressAfterStop(t *testing.T) {
sender := &progressSender{}
run := &fakeRun{}
stop := startProgressReporter(progressRequest(), sender, run.summary, testInterval)
run.done.Add(1)
require.Eventually(t, func() bool { return len(sender.sent()) == 1 }, time.Second, testInterval)
stop()
tries := sender.tries()
run.done.Add(1)
run.entries.Add(1)
time.Sleep(10 * testInterval)
require.Equal(t, tries, sender.tries())
}
@@ -0,0 +1,74 @@
package s3_lifecycle
import (
"context"
"errors"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/credential"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var lifecycleReadyTimeout = 10 * time.Second
// checkLifecycleReady authenticates to one S3 front with the credentials
// LifecycleDelete uses, without touching bucket or object metadata.
func checkLifecycleReady(ctx context.Context, c s3_lifecycle_pb.SeaweedS3LifecycleInternalClient) error {
ctx, cancel := context.WithTimeout(ctx, lifecycleReadyTimeout)
defer cancel()
ctx, _ = credential.WithS3InternalAdminAuth(ctx)
_, err := c.LifecycleReady(ctx, &s3_lifecycle_pb.LifecycleReadyRequest{})
if status.Code(err) == codes.Unimplemented {
// Older fronts authorize an empty delete, then reject it before any lookup.
_, err = c.LifecycleDelete(ctx, &s3_lifecycle_pb.LifecycleDeleteRequest{})
}
return err
}
// selectS3Front returns a connection to the first front that passes
// checkLifecycleReady, plus why each earlier front was skipped. A nil
// connection means none passed.
func (h *Handler) selectS3Front(ctx context.Context, endpoints []string) (*grpc.ClientConn, string, []error) {
var skipped []error
for _, addr := range endpoints {
if err := ctx.Err(); err != nil {
return nil, "", append(skipped, err)
}
dialCtx, dialCancel := context.WithTimeout(ctx, 30*time.Second)
conn, err := pb.GrpcDial(dialCtx, addr, false, h.grpcDialOption)
dialCancel()
if err != nil {
skipped = append(skipped, fmt.Errorf("dial s3 %s: %w", addr, err))
continue
}
if err := checkLifecycleReady(ctx, s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(conn)); err != nil {
conn.Close()
skipped = append(skipped, readinessError(addr, err))
continue
}
return conn, addr, skipped
}
return nil, "", skipped
}
func readinessError(addr string, err error) error {
switch status.Code(err) {
case codes.Unauthenticated, codes.PermissionDenied:
workerKey := "is not set"
if util.GetViper().GetString("jwt.filer_signing.key") != "" {
workerKey = "is set"
}
return fmt.Errorf("s3 %s rejected lifecycle credentials: %w; this worker's jwt.filer_signing.key %s, and it must match the key in the s3 server's security.toml (an s3 server without the key accepts only local callers)", addr, err, workerKey)
}
return fmt.Errorf("s3 %s readiness check: %w", addr, err)
}
func noReadyS3Error(skipped []error) error {
return fmt.Errorf("no s3 server is ready for lifecycle deletes: %w", errors.Join(skipped...))
}
@@ -0,0 +1,280 @@
package s3_lifecycle
import (
"context"
"errors"
"net"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
const (
frontKey = "readiness-test-front-key"
otherKey = "readiness-test-other-key"
)
type testFront struct {
s3_lifecycle_pb.UnimplementedSeaweedS3LifecycleInternalServer
key string
legacy bool
block bool
readies atomic.Int32
deletes atomic.Int32
}
func (f *testFront) LifecycleReady(ctx context.Context, _ *s3_lifecycle_pb.LifecycleReadyRequest) (*s3_lifecycle_pb.LifecycleReadyResponse, error) {
f.readies.Add(1)
if f.legacy {
return nil, status.Error(codes.Unimplemented, "method LifecycleReady not implemented")
}
if f.block {
<-ctx.Done()
return nil, status.FromContextError(ctx.Err()).Err()
}
if err := security.CheckGrpcAdminToken(ctx, security.SigningKey(f.key)); err != nil {
return nil, err
}
return &s3_lifecycle_pb.LifecycleReadyResponse{}, nil
}
func (f *testFront) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
f.deletes.Add(1)
if err := security.CheckGrpcAdminToken(ctx, security.SigningKey(f.key)); err != nil {
return nil, err
}
if req.Bucket == "" || req.ObjectPath == "" {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED}, nil
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
}
type countingFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
lists atomic.Int32
}
func (f *countingFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets"}, nil
}
func (f *countingFiler) ListEntries(*filer_pb.ListEntriesRequest, grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
f.lists.Add(1)
return nil
}
func serveGrpc(t *testing.T, register func(*grpc.Server)) string {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
s := grpc.NewServer()
register(s)
go s.Serve(lis)
t.Cleanup(s.Stop)
return lis.Addr().String()
}
func startFront(t *testing.T, f *testFront) string {
return serveGrpc(t, func(s *grpc.Server) { s3_lifecycle_pb.RegisterSeaweedS3LifecycleInternalServer(s, f) })
}
func setWorkerKey(t *testing.T, key string) {
t.Helper()
v := util.GetViper()
prev := v.GetString("jwt.filer_signing.key")
v.Set("jwt.filer_signing.key", key)
t.Cleanup(func() { v.Set("jwt.filer_signing.key", prev) })
}
func newTestHandler() *Handler {
return NewHandler(grpc.WithTransportCredentials(insecure.NewCredentials()))
}
func assertNoSecrets(t *testing.T, msg string) {
t.Helper()
for _, secret := range []string{frontKey, otherKey, "Bearer", "eyJ"} {
if strings.Contains(msg, secret) {
t.Fatalf("error exposes %q: %s", secret, msg)
}
}
}
func TestSelectS3Front_SharedKeyPassesWithoutDeletes(t *testing.T) {
setWorkerKey(t, frontKey)
front := &testFront{key: frontKey}
addr := startFront(t, front)
conn, got, skipped := newTestHandler().selectS3Front(context.Background(), []string{addr})
if conn == nil {
t.Fatalf("expected a ready front, skipped: %v", skipped)
}
conn.Close()
if got != addr || len(skipped) != 0 {
t.Fatalf("got front %q skipped %v, want %q and none", got, skipped, addr)
}
if front.deletes.Load() != 0 {
t.Fatalf("readiness check sent %d LifecycleDelete calls", front.deletes.Load())
}
}
func TestSelectS3Front_KeyProblemsNameTheConfig(t *testing.T) {
cases := []struct {
name, workerKey, wantState string
}{
{"missing worker key", "", "is not set"},
{"mismatched worker key", otherKey, "is set"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
setWorkerKey(t, tc.workerKey)
addr := startFront(t, &testFront{key: frontKey})
conn, _, skipped := newTestHandler().selectS3Front(context.Background(), []string{addr})
if conn != nil {
conn.Close()
t.Fatal("front with a different key was selected")
}
if len(skipped) != 1 || status.Code(errors.Unwrap(skipped[0])) != codes.Unauthenticated {
t.Fatalf("want one Unauthenticated skip, got %v", skipped)
}
msg := noReadyS3Error(skipped).Error()
for _, want := range []string{addr, "jwt.filer_signing.key " + tc.wantState, "security.toml"} {
if !strings.Contains(msg, want) {
t.Fatalf("error %q does not mention %q", msg, want)
}
}
assertNoSecrets(t, msg)
})
}
}
func TestSelectS3Front_SkipsFrontWithOtherKey(t *testing.T) {
setWorkerKey(t, frontKey)
bad := &testFront{key: otherKey}
good := &testFront{key: frontKey}
badAddr, goodAddr := startFront(t, bad), startFront(t, good)
conn, got, skipped := newTestHandler().selectS3Front(context.Background(), []string{badAddr, goodAddr})
if conn == nil {
t.Fatalf("expected the second front, skipped: %v", skipped)
}
conn.Close()
if got != goodAddr {
t.Fatalf("selected %q, want %q", got, goodAddr)
}
if len(skipped) != 1 || !strings.Contains(skipped[0].Error(), badAddr) || !strings.Contains(skipped[0].Error(), "rejected lifecycle credentials") {
t.Fatalf("want the first front reported as a credential problem, got %v", skipped)
}
if bad.deletes.Load() != 0 || good.deletes.Load() != 0 {
t.Fatal("readiness check sent LifecycleDelete calls")
}
}
func TestSelectS3Front_OlderFrontUsesEmptyDelete(t *testing.T) {
setWorkerKey(t, frontKey)
ok := &testFront{key: frontKey, legacy: true}
okAddr := startFront(t, ok)
conn, _, skipped := newTestHandler().selectS3Front(context.Background(), []string{okAddr})
if conn == nil {
t.Fatalf("older front with the shared key was skipped: %v", skipped)
}
conn.Close()
if ok.deletes.Load() != 1 {
t.Fatalf("want one empty LifecycleDelete, got %d", ok.deletes.Load())
}
mismatched := &testFront{key: otherKey, legacy: true}
conn, _, skipped = newTestHandler().selectS3Front(context.Background(), []string{startFront(t, mismatched)})
if conn != nil {
conn.Close()
t.Fatal("older front with another key was selected")
}
if len(skipped) != 1 || !strings.Contains(skipped[0].Error(), "rejected lifecycle credentials") {
t.Fatalf("want a credential problem, got %v", skipped)
}
}
func TestSelectS3Front_TimeoutMovesOn(t *testing.T) {
setWorkerKey(t, frontKey)
prev := lifecycleReadyTimeout
lifecycleReadyTimeout = 200 * time.Millisecond
t.Cleanup(func() { lifecycleReadyTimeout = prev })
stuckAddr := startFront(t, &testFront{key: frontKey, block: true})
goodAddr := startFront(t, &testFront{key: frontKey})
start := time.Now()
conn, got, skipped := newTestHandler().selectS3Front(context.Background(), []string{stuckAddr, goodAddr})
if conn == nil {
t.Fatalf("expected the second front, skipped: %v", skipped)
}
conn.Close()
if elapsed := time.Since(start); elapsed > 5*time.Second {
t.Fatalf("readiness check took %v", elapsed)
}
if got != goodAddr || len(skipped) != 1 || status.Code(errors.Unwrap(skipped[0])) != codes.DeadlineExceeded {
t.Fatalf("got %q skipped %v, want %q after a DeadlineExceeded skip", got, skipped, goodAddr)
}
}
func TestSelectS3Front_ParentCancelStops(t *testing.T) {
setWorkerKey(t, frontKey)
next := &testFront{key: frontKey}
stuckAddr := startFront(t, &testFront{key: frontKey, block: true})
nextAddr := startFront(t, next)
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(100*time.Millisecond, cancel)
start := time.Now()
conn, _, skipped := newTestHandler().selectS3Front(ctx, []string{stuckAddr, nextAddr})
if conn != nil {
conn.Close()
t.Fatal("selected a front after the parent was cancelled")
}
if elapsed := time.Since(start); elapsed > 5*time.Second {
t.Fatalf("cancelled selection took %v", elapsed)
}
if !errors.Is(noReadyS3Error(skipped), context.Canceled) {
t.Fatalf("want context.Canceled, got %v", skipped)
}
if next.readies.Load() != 0 {
t.Fatal("tried another front after the parent was cancelled")
}
}
func TestExecute_RejectedCredentialsFailBeforeListing(t *testing.T) {
setWorkerKey(t, otherKey)
filer := &countingFiler{}
filerAddr := serveGrpc(t, func(s *grpc.Server) { filer_pb.RegisterSeaweedFilerServer(s, filer) })
front := &testFront{key: frontKey}
frontAddr := startFront(t, front)
err := newTestHandler().Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{
JobId: "j1", JobType: jobType,
Parameters: map[string]*plugin_pb.ConfigValue{
"filer_grpc_address": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: filerAddr}},
},
},
ClusterContext: &plugin_pb.ClusterContext{S3GrpcAddresses: []string{frontAddr}},
}, &recordingExecSender{})
if err == nil || !strings.Contains(err.Error(), "jwt.filer_signing.key") {
t.Fatalf("want a signing-key error, got %v", err)
}
assertNoSecrets(t, err.Error())
if filer.lists.Load() != 0 || front.deletes.Load() != 0 {
t.Fatalf("pass started anyway: %d listings, %d deletes", filer.lists.Load(), front.deletes.Load())
}
}
@@ -0,0 +1,142 @@
package s3_lifecycle
import (
"fmt"
"sort"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
"google.golang.org/protobuf/types/known/durationpb"
)
const (
runStatusComplete = "complete"
runStatusPartial = "partial"
runStatusFailed = "failed"
runStatusCanceled = "canceled"
)
const maxReportedInvalidPolicies = 10
// runReport is one pass's outcome as the job record shows it.
type runReport struct {
err error
canceled bool
elapsed time.Duration
bucketsTotal int
invalidPolicies []scheduler.ParseError
summary dailyrun.RunSummary
lastFullPass time.Time
fullPassSaveErr error
}
// Bucket walk and shard failures always surface as err. A pass without
// one is still partial when a policy could not be loaded or a shard's
// replay halted on an unresolved delete.
func (r *runReport) status() string {
switch {
case r.canceled:
return runStatusCanceled
case r.err != nil:
return runStatusFailed
case len(r.invalidPolicies) > 0, r.summary.ShardsHalted > 0:
return runStatusPartial
}
return runStatusComplete
}
// fullPass also needs every walk-only rule evaluated: a walk deferred by
// WalkerInterval is by design, but it leaves those rules unchecked.
func (r *runReport) fullPass() bool {
return r.status() == runStatusComplete && r.summary.WalksDeferred == 0
}
func (r *runReport) summaryLine() string {
verb := r.status()
if verb == runStatusComplete {
verb = "completed"
}
s := r.summary
return fmt.Sprintf("s3 lifecycle daily replay %s: buckets=%d walked=%d failed=%d skipped=%d invalid_policies=%d entries=%d events=%d rpc_done=%d rpc_errors=%d elapsed=%s",
verb, r.bucketsTotal, s.BucketsWalked, s.BucketsFailed, s.BucketsSkipped, len(r.invalidPolicies),
s.EntriesVisited, s.EventsScanned, s.Outcomes["DONE"], s.Outcomes["RPC_ERROR"], r.elapsed.Round(time.Second))
}
func (r *runReport) errorMessage() string {
if r.err == nil {
return ""
}
if n := r.summary.BucketsFailed; n > 1 {
return fmt.Sprintf("%v (%d of %d buckets failed)", r.err, n, r.bucketsTotal)
}
return r.err.Error()
}
func (r *runReport) outputValues() map[string]*plugin_pb.ConfigValue {
s := r.summary
out := map[string]*plugin_pb.ConfigValue{
"status": stringValue(r.status()),
"buckets_total": int64Value(int64(r.bucketsTotal)),
"buckets_walked": int64Value(int64(s.BucketsWalked)),
"buckets_failed": int64Value(int64(s.BucketsFailed)),
"buckets_skipped": int64Value(int64(s.BucketsSkipped)),
"invalid_policies": int64Value(int64(len(r.invalidPolicies))),
"entries_visited": int64Value(s.EntriesVisited),
"objects_visited": int64Value(s.ObjectsVisited),
"events_scanned": int64Value(s.EventsScanned),
"shard_errors": int64Value(int64(s.ShardErrors)),
"shards_halted": int64Value(int64(s.ShardsHalted)),
"walks_deferred": int64Value(int64(s.WalksDeferred)),
"full_pass": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: r.fullPass()}},
"elapsed": {Kind: &plugin_pb.ConfigValue_DurationValue{DurationValue: durationpb.New(r.elapsed.Round(time.Millisecond))}},
}
for outcome, n := range s.Outcomes {
out["rpc_"+strings.ToLower(strings.TrimPrefix(outcome, "RPC_"))] = int64Value(n)
}
if len(s.BucketFailures) > 0 {
failures := make([]string, 0, len(s.BucketFailures))
for _, f := range s.BucketFailures {
failures = append(failures, f.Bucket+": "+f.Error)
}
out["bucket_failures"] = stringListValue(failures)
}
if len(r.invalidPolicies) > 0 {
invalid := make([]string, 0, maxReportedInvalidPolicies)
for _, pe := range r.invalidPolicies {
if len(invalid) == maxReportedInvalidPolicies {
break
}
invalid = append(invalid, fmt.Sprintf("%s: %v", pe.Bucket, pe.Err))
}
sort.Strings(invalid)
out["invalid_policy_buckets"] = stringListValue(invalid)
}
if s.Phase != "" {
out["last_phase"] = stringValue(s.Phase)
}
if s.Bucket != "" {
out["last_bucket"] = stringValue(s.Bucket)
}
if r.fullPassSaveErr != nil {
out["full_pass_save_error"] = stringValue(r.fullPassSaveErr.Error())
}
if !r.lastFullPass.IsZero() {
out["last_full_pass_at"] = stringValue(r.lastFullPass.UTC().Format(time.RFC3339))
}
return out
}
func stringValue(v string) *plugin_pb.ConfigValue {
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringValue{StringValue: v}}
}
func int64Value(v int64) *plugin_pb.ConfigValue {
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: v}}
}
func stringListValue(v []string) *plugin_pb.ConfigValue {
return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringList{StringList: &plugin_pb.StringList{Values: v}}}
}