mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d57015c995 | ||
|
|
11b98ee873 | ||
|
|
0b3d50444e | ||
|
|
b85af3483e | ||
|
|
c51db540cc | ||
|
|
91bcc910eb | ||
|
|
3f4cb6d2fb | ||
|
|
122ca7c020 | ||
|
|
b2d24dd54f | ||
|
|
2b21d19e4c | ||
|
|
46bb70d93e | ||
|
|
6d12ebeefe | ||
|
|
514ba7a233 | ||
|
|
defe047e1a | ||
|
|
6001d65206 | ||
|
|
a64483885c | ||
|
|
ac65c6c2ca | ||
|
|
b456628a7a | ||
|
|
8efa32258a | ||
|
|
9a70bbfcc6 | ||
|
|
4a04594826 | ||
|
|
d8bbc1d855 | ||
|
|
c917110124 | ||
|
|
926a8e9351 | ||
|
|
ca12934834 | ||
|
|
82648cca53 | ||
|
|
1b1d4aa814 | ||
|
|
c7b01c72b2 | ||
|
|
2840980c7d | ||
|
|
b740e22e63 | ||
|
|
ad77362be3 | ||
|
|
7996dc1d67 | ||
|
|
ca95d33092 |
No files matched your search
@@ -11,4 +11,4 @@ jobs:
|
||||
- name: 'Checkout Repository'
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
|
||||
- name: 'Dependency Review'
|
||||
uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48
|
||||
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294
|
||||
+34
-25
@@ -110,7 +110,9 @@ This is more state than the previous "single subscription, single cursor" claim
|
||||
|
||||
**Cursor-skip semantics.** `last_processed[filer_id]` points at the *last resolved event* for that shard. Resume must skip events with position `<= cursor[filer_id]` (using the `(ts, offset)` order per shard) — strict `<=`, not `<`, otherwise the last processed event is replayed on every resume. Equivalently: deliver events with `(event.ts, event.offset) > cursor[filer_id]`. Phase 3 introduces a new API variant that takes per-shard `MessagePosition`s and applies this comparator — see "API change" below. The existing `pb.ReadLogFileRefs` filter `logEntry.TsNs <= startTsNs` (`weed/pb/filer_pb_direct_read.go:333`) is the wrong shape because it can't disambiguate equal-ts events.
|
||||
|
||||
**Required API addition** (Phase 3 dependency): `pb.ReadLogFileRefsWithPosition` extending the current `ReadLogFileRefs`:
|
||||
> **Implementation note:** the API addition described below was not built. The shipped reader uses `SubscribeMetadata` with a single global cursor (the filer's server-side `MetaAggregator` already does the merge). The pseudocode is preserved as design context for a future per-shard architecture.
|
||||
|
||||
**~~Required API addition~~ (Phase 3 dependency, not built)**: `pb.ReadLogFileRefsWithPosition` extending the current `ReadLogFileRefs`:
|
||||
|
||||
- Take a per-shard `start_positions: map<filer_id, MessagePosition>` instead of a single `startTsNs`.
|
||||
- Per-event callback signature `eachLogEntry(event, filer_id, position) → CallbackResult`.
|
||||
@@ -565,6 +567,8 @@ Policy changes during a bucket bootstrap: the bootstrap is bound to a specific `
|
||||
|
||||
### Reader — single subscription, client-side merge
|
||||
|
||||
> **Implementation note (post-Phase 3):** the production reader uses `client.SubscribeMetadata(...)` directly with a single global cursor. The filer's `SubscribeMetadata` server (`weed/server/filer_grpc_server_sub_meta.go`) already aggregates across peer filers — it reads disk-persisted logs from every filer via `sendLogFileRefs` then drains `MetaAggregator.MetaLogBuffer` for the in-memory tail — so the worker doesn't have to assemble its own multi-filer merge. The per-filer-shard cursor model below was designed before this was wired and was not built; the proto fields (`last_processed_original` map keyed by `filer_id`, `tail_drained_streams`) remain as forward-compat stubs. The pseudocode below describes the alternative the design considered, kept here for context. See "Multi-filer durability" and the obsoleted Phase 6 section.
|
||||
|
||||
The reader is one cluster-singleton task subscribed to one filer at a time. `Filer.CollectLogFileRefs(start_position, stop_ts)` returns chunk refs from log files in directory order. The worker passes those refs to `pb.ReadLogFileRefsWithPosition` (the new API — see Task #19), which heap-merges per-filer chunks by event ts client-side and applies the per-shard `(ts, offset)` skip filter. Chunk *bodies* are read in parallel from volume servers via the returned fileIds.
|
||||
|
||||
Cursors are per-filer-shard. `last_processed_original[D.seconds]` is `map<filer_id, MessagePosition>`; `MessagePosition = {ts_ns, offset}` disambiguates equal-ts events within a per-filer chunk. Resume skips events with `(event.ts, event.offset) <= cursor[filer_id]` — strict `<=` so the last resolved event isn't replayed.
|
||||
@@ -1394,6 +1398,8 @@ Why a separate lane matters here:
|
||||
|
||||
### Multi-filer durability
|
||||
|
||||
> **Implementation note (post-Phase 3):** the worker did not end up building its own multi-filer merge. `SubscribeMetadata` on the filer server (`weed/server/filer_grpc_server_sub_meta.go:154`) routes through `MetaAggregator` when peer filers exist: it reads from every filer's disk-persisted logs first (via `sendLogFileRefs`/`Filer.CollectLogFileRefs`), then drains the aggregator's in-memory tail. Workers get an aggregated, durable stream from a single subscription. The per-filer-shard cursor architecture below describes what would be needed if the worker had to assemble the merge itself; we kept it here as design context and as a reference for the proto stubs (`LOST_LOG`, `tail_drained_streams`) that remain forward-compatible if the architecture ever changes. The genuine residual gap — auto-degrading the worker on `ResumeFromDiskError` — is tracked separately as a narrow follow-up rather than a Phase.
|
||||
|
||||
`MetaAggregator` is **in-memory only** — `weed/filer/meta_aggregator.go:39`: *"MetaAggregator only aggregates data 'on the fly'. The logs are not re-persisted to disk. The old data comes from what each LocalMetadata persisted on disk."*
|
||||
|
||||
So the aggregator can't be the worker's source of truth: a worker restart, a crash, or a peer outage all lose unpersisted aggregated events. The persistent source is per-filer logs at `/topics/.system/log/<date>/<hour-min>.<filerId>` — written by each filer for its own events, durable, and queryable via `Filer.CollectLogFileRefs` and `Filer.ReadPersistedLogBuffer`.
|
||||
@@ -1904,11 +1910,13 @@ Phasing changed: **the back-stamp cannot be removed until the worker can take ov
|
||||
|
||||
## Phase 3 — Shared cluster reader + delay-group sweeps (non-versioned)
|
||||
|
||||
- Implement `s3.lifecycle.read` task: cluster singleton, subscribed to one filer at a time. `Filer.CollectLogFileRefs` returns chunk refs in directory order; the worker uses `pb.ReadLogFileRefsWithPosition` (Task #19) to heap-merge per-filer chunks by event ts client-side, with per-shard `MessagePosition` skip filtering. Worker reads chunk bodies in parallel from volume servers. Cursors are per-filer-shard: `last_processed_original: map<delay_seconds, map<filer_id, MessagePosition>>` and `last_processed_predicate: map<filer_id, MessagePosition>` — `LogEntry.Offset` is per-buffer (per filerId), not globally unique, so per-shard cursors are required. Resume skips events with `(ts, offset) <= cursor[filer_id]` (strict `<=`). Listing uses the low-water-mark across per-filer cursors. New shards seeded lazily via `seedNewlyDiscoveredShardsLazily` using `EarliestRetainedPositionPerShard` (Task #19), and seeding clears any matching `tail_drained_streams` marker. Tail-drain GC at task entry uses `RetainedLogRangePerShard` (Task #19) to remove cursor entries where `cursor >= range.latest`, record the matching `tail_drained_streams` key, and downgrade to `scan_only` with `LOST_LOG` if logs vanished before a stream caught up. Failover to another filer endpoint on connection error; per-filer cursor map is portable. Periodic checkpointing (default every 1000 events or 5s) bounds crash redo.
|
||||
- **Tail-drain tests required in this phase**: (a) cursor at exactly `range.latest` for a shard → tail-drained, entry GC'd, matching `tail_drained_streams` key updated, low-water-mark recovers; (b) cursor before `range.latest` → not GC'd, entry preserved; (c) shard removed from cluster but logs still retained → not GC'd until each stream cursor catches up to `range.latest`; (d) verify low-water-mark advances after GC (otherwise the tail-drain wasn't effective); (e) **lost-log**: shard's logs pruned with a stream cursor still behind `range.latest` and no matching `tail_drained_streams[...]` marker → cursor NOT GC'd, all reader-driven rules promoted to `mode = scan_only` with `degraded_reason = LOST_LOG`, `lifecycle_lost_log_total{filer_id}` increments, warning log emitted; verify `s3.lifecycle.reseed -ack-lost-log --reason <text>` is the only path that clears the lost-log cursor entries and degraded flag together; (f) cross-stream guard: a tail-drained 30-day original stream does not permit GC of the same filer's 60-day original stream or predicate stream; (g) rejoin guard: when a previously tail-drained shard reappears and is lazily seeded, the matching `tail_drained_streams` marker is cleared.
|
||||
> **Implementation note:** the shipped reader uses `client.SubscribeMetadata(...)` with a single global `(ts_ns, offset)` cursor (`weed/s3api/s3lifecycle/reader/reader.go`). The filer's `SubscribeMetadata` server already aggregates persisted + in-memory logs across peer filers, so the per-filer-shard cursor map and the `RetainedLogRangePerShard` / `EarliestRetainedPositionPerShard` filer RPCs (Task #19) were not built. The tail-drain matrix and lost-log tests below were written against that unbuilt architecture and are obsoleted; the only residual gap — auto-degrading on `ResumeFromDiskError` — is tracked as a separate narrow follow-up. The retention mode-gate, engine routing, predicate-change pass, SKIPPED_OBJECT_LOCK, TRANSPORT_ERROR, and cursor-trail tests remain valid and were exercised against the production reader/router/engine stack.
|
||||
|
||||
- Implement `s3.lifecycle.read` task: cluster singleton, subscribed to one filer at a time. ~~`Filer.CollectLogFileRefs` returns chunk refs in directory order; the worker uses `pb.ReadLogFileRefsWithPosition` (Task #19) to heap-merge per-filer chunks by event ts client-side, with per-shard `MessagePosition` skip filtering.~~ The shipped task uses a direct `SubscribeMetadata` subscription; the filer server-side does the multi-filer merge. Cursor is one global `(ts_ns, offset)` position resumed via `SinceNs`. Failover to another filer endpoint on connection error; cursor is portable (one ts). Periodic checkpointing bounds crash redo.
|
||||
- ~~**Tail-drain tests required in this phase**~~ — obsoleted by the single-cursor architecture; see Phase 6 for context.
|
||||
- **Retention mode-gate tests** (per `eventLogHorizon` table, kinds beyond age-based): inject a rule of each reader-driven kind and toggle `metaLogRetention` above and below `eventLogHorizon(rule) + bootstrapLookbackMin`; verify the rule is `event_driven` above and `scan_only` with `degraded_reason = RETENTION_BELOW_HORIZON` below. Cover `EXPIRATION_DAYS`, `NONCURRENT_DAYS`, `ABORT_MPU`, `NEWER_NONCURRENT`, `EXPIRED_DELETE_MARKER`. Verify `EXPIRATION_DATE` bypasses the gate regardless of retention.
|
||||
- Engine drives event routing: `engine.MatchOriginalWrite(event, delay=D)` and `engine.MatchPredicateChange(event)`.
|
||||
- **One sweep per delay group** (e.g. `1d`, `30d`, `60d`, `90d`); each sweep advances `reader_state.last_processed_original[D.seconds]` (a `map<filer_id, MessagePosition>` — per-shard cursors, not a single position). Single predicate-change sweep clamped to `min(now - smallDelay, now - flushSafetyLag)` advances `reader_state.last_processed_predicate` (also per-shard).
|
||||
- **One sweep per delay group** (e.g. `1d`, `30d`, `60d`, `90d`); each sweep advances `reader_state.last_processed_original[D.seconds]` (a single global `(ts_ns, offset)` `MessagePosition`). Single predicate-change sweep clamped to `min(now - smallDelay, now - flushSafetyLag)` advances `reader_state.last_processed_predicate` (also a single global position).
|
||||
- One filer fetch per event (`fetchLiveEntryOnce`), reused across all candidate rules.
|
||||
- Per-event resolution-or-stop: `Resolved` outcomes advance the cursor; `TRANSPORT_ERROR` halts the batch and the cursor stays.
|
||||
- Engine refreshes when the reader observes a lifecycle-xattr `UpdateEntry` event.
|
||||
@@ -1941,20 +1949,26 @@ Phasing changed: **the back-stamp cannot be removed until the worker can take ov
|
||||
- `AbortIncompleteMultipartUpload` driven by events under `.uploads/`.
|
||||
- Tests covering: new version PUT, delete marker creation, non-current expiration, expired-delete-marker, MPU abort.
|
||||
|
||||
## Phase 6 — Multi-filer durable replay (mostly done in Phase 3)
|
||||
## Phase 6 — Multi-filer durable replay (obsoleted)
|
||||
|
||||
The shared-reader design (Phase 3) already reads from the shared filer namespace, so multi-filer correctness is largely subsumed. This phase fills in:
|
||||
**Status: not built. Architecture moved on; the production reader uses the filer's existing aggregation surface.**
|
||||
|
||||
- Per-shard cursors keyed by `filerId` are already in the reader-state proto (Phase 3).
|
||||
- Filer-set discovery: list `/topics/.system/log/<date>/` and observe filerId suffixes (Phase 3).
|
||||
- Tail-drain GC implementation using `RetainedLogRangePerShard` (Task #19): cursor entries where `cursor >= range.latest` are removed at task entry AND the stream-specific key is recorded in `reader_state.tail_drained_streams`. Phase 3 tests verify single-shard tail-drain; Phase 6 adds multi-filer convergence tests:
|
||||
- Two filers actively writing, racing writes against the same key — events from both shards merged correctly, per-shard cursors advance independently.
|
||||
- Filer A departs (stops writing); its logs are still retained → cursor for A continues to advance until A's `range.latest`; not GC'd before then.
|
||||
- Filer A reaches `range.latest` for one stream (e.g. original delay 30d), then its logs are pruned: probe returns no range, but the matching `tail_drained_streams[(ORIGINAL,30d,A)]` entry is set → that stream cursor is GC'd as safe; no degradation.
|
||||
- Filer A later reappears and writes retained logs for that same stream: lazy seeding creates a new cursor and clears `tail_drained_streams[(ORIGINAL,30d,A)]`, so the old safe-drain marker cannot mask a future lost-log event.
|
||||
- **Lost-log: Filer A's logs are pruned BEFORE another stream cursor reaches `range.latest`** (probe returns no range AND the matching `tail_drained_streams[...]` entry is unset): the reader does NOT GC that cursor; instead, all reader-driven rules are promoted to `mode = scan_only` with `degraded_reason = LOST_LOG`; `lifecycle_lost_log_total{filer_id="A"}` increments; warning logged. Verify cursor stays put until `s3.lifecycle.reseed -ack-lost-log --reason <text>` clears the lost-log cursor entries and degraded flag.
|
||||
- Worker restart mid-merge → resumes per-filer cursors correctly; both shards continue from their persisted positions; `tail_drained_streams` survives restart.
|
||||
- Failover to a different primary filer mid-batch — cursor portable, no events skipped or replayed.
|
||||
What the original Phase 6 set out to add — per-filer-shard cursor maps, `EarliestRetainedPositionPerShard` and `RetainedLogRangePerShard` filer RPCs, `tail_drained_streams` GC, `CollectLogFileRefs` heap-merge, lost-log degraded promotion — was designed under the assumption that the lifecycle worker would have to assemble its own multi-filer view because `MetaAggregator` is in-memory only.
|
||||
|
||||
`SubscribeMetadata` already does that work server-side: when the filer has peer filers it reads disk-persisted logs from every filer first (via `sendLogFileRefs` → `Filer.CollectLogFileRefs`) and only then drains the in-memory aggregator. A single subscription returns a durable, multi-filer-merged stream. The Phase 3 shipped reader (`weed/s3api/s3lifecycle/reader/reader.go`) consumes that stream with one global `(ts_ns, offset)` cursor and never needed the per-shard cursor map.
|
||||
|
||||
What the design's per-shard architecture would have bought us, and why each piece is no longer required:
|
||||
|
||||
| Phase 6 mechanism | Why it's no longer required |
|
||||
|---|---|
|
||||
| Per-filer-shard cursor map | Single global cursor suffices because the filer presents one merged stream. Resume-replay overhead is bounded by `LogFlushInterval` (~1m) and the dispatcher's tick interval (~200ms), so the worst-case redundant work per batch is one minute of events that the cursor compare immediately skips. |
|
||||
| `RetainedLogRangePerShard` / `EarliestRetainedPositionPerShard` filer RPCs | No per-shard cursor → no need for per-shard probe. `SubscribeMetadata` already returns `ResumeFromDiskError` when the cursor predates retained logs. |
|
||||
| Tail-drain GC + `tail_drained_streams` | No per-shard cursor → no entries to GC. Departed filers' events are absorbed into the aggregated stream and the global cursor advances past them. |
|
||||
| Lazy seeding `seedNewlyDiscoveredShardsLazily` | No per-shard cursor → no shards to seed. New filers' events appear automatically through the aggregator. |
|
||||
|
||||
Forward-compat stubs that stay in the proto: `LifecycleState.DegradedReason.LOST_LOG`, `ReaderState.tail_drained_streams`, `last_processed_original` keyed by `filer_id`. They cost nothing and keep the on-disk state file readable if a future deployment ever needs a per-shard architecture.
|
||||
|
||||
The single residual gap — and the only piece worth building — is auto-degrading the reader when `SubscribeMetadata` returns `ResumeFromDiskError`. Tracked as a separate narrow follow-up (catch the error in `reader.Run`, mark reader-driven actions `scan_only` with `degraded_reason = LOST_LOG`, increment the counter, advance the cursor to retained-earliest, expose `s3.lifecycle.reseed -ack-lost-log` to flip back to event_driven once safety scans cover the gap). It is a ~50-line change, not a Phase.
|
||||
|
||||
## Phase 7 — Observability
|
||||
|
||||
@@ -1979,7 +1993,7 @@ The shared-reader design (Phase 3) already reads from the shared filer namespace
|
||||
- Date-rule deletions (`SCAN_AT_DATE` mode: a single scheduled bucket-level bootstrap at `rule.date` deletes all matches inline).
|
||||
- Periodic safety scans (re-run bootstrap on the per-kind cadence) catch drift over time.
|
||||
Not-yet-due age-based discovery via meta-log events arrives in Phase 3 (the reader). Versioned buckets remain unhandled until Phase 5; the worker skips them with a logged warning until then. The existing back-stamp keeps simple `Expiration.Days` working in parallel.
|
||||
- Phase 3 brings steady-state event-driven expiration. The reader is a cluster singleton subscribed to one filer; the worker heap-merges per-filer log chunks client-side via `pb.ReadLogFileRefsWithPosition` (Task #19) with per-shard `MessagePosition` cursors. Multi-filer clusters work the same as single-filer clusters from this point forward.
|
||||
- Phase 3 brings steady-state event-driven expiration. The reader is a cluster singleton subscribed to one filer via `SubscribeMetadata`, which the filer's `MetaAggregator` already merges across peer filers. Single global `(ts_ns, offset)` cursor; multi-filer clusters work the same as single-filer clusters from this point forward.
|
||||
- Phase 4 makes `PUT` constant-time. Required dependency: Phase 2 + Phase 3 shipped and stable.
|
||||
- Phases 5–8 complete the surface.
|
||||
|
||||
@@ -2073,16 +2087,11 @@ test-fast: build-weed-10sec
|
||||
|
||||
Run: `make -C test/s3/lifecycle test-with-server`. Phase mapping: end-to-end tests land in the same phase as the capability they cover.
|
||||
|
||||
## Layer 4 — Multi-filer convergence (Phase 6 only)
|
||||
## Layer 4 — Multi-filer convergence (obsoleted)
|
||||
|
||||
Location: `test/plugin_workers/lifecycle/multi_filer_test.go` (component) plus a multi-filer scenario in `test/s3/lifecycle/` if needed.
|
||||
**Not built.** Phase 6 was obsoleted by `SubscribeMetadata`'s server-side aggregation (see the Phase 6 section). With a single global cursor on a server-merged stream, there are no per-filer-shard convergence properties for the worker to test — any merge correctness lives inside the filer's `MetaAggregator`, which has its own coverage in `weed/filer/`.
|
||||
|
||||
Patterns to copy: `test/multi_master/`, `test/metadata_subscribe/` — both spin up multi-node clusters in-process.
|
||||
|
||||
Cases:
|
||||
- Racing writes to the same key on different filers, **including events with identical `event.ts`** — reader merges per-filer logs by `(event.ts, filer_id, event.offset)` (deterministic ordering across shards because `event.offset` is per-buffer/per-filer and not globally unique). Test asserts the same merge order across runs and that equal-ts events from different filers don't swap relative position.
|
||||
- Worker restart mid-merge → resumes per-filer watermarks correctly.
|
||||
- Filer leaves cluster → topology refresh skips it; remaining filers' logs continue.
|
||||
If `ResumeFromDiskError` auto-degrade lands as a follow-up (task #21), its tests live with the reader package, not in a separate multi-filer harness.
|
||||
|
||||
## CI gating
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
// Bootstrap-walk integration scenario: lifecycle config added AFTER the
|
||||
// objects exist must still expire them on the first sweep.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleBootstrapWalkOnExistingObjects: PUT a batch of objects
|
||||
// FIRST, backdate them, THEN configure the lifecycle rule, THEN run
|
||||
// the worker. The worker must discover the pre-existing objects via
|
||||
// the bootstrap walk (BucketBootstrapper) — there were no meta-log
|
||||
// events the reader could have observed because the objects predate
|
||||
// the rule.
|
||||
//
|
||||
// Production scenario: an operator enables lifecycle on a bucket that
|
||||
// already holds a million objects from before the policy. Without a
|
||||
// bootstrap walk, only NEW writes would ever match; the existing
|
||||
// content would never expire.
|
||||
func TestLifecycleBootstrapWalkOnExistingObjects(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("bootstrap")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
|
||||
// 5 objects so the test exercises the walker iterating multiple
|
||||
// entries in the same bucket directory. PUT FIRST, before any
|
||||
// lifecycle config is set, so the meta-log doesn't carry events
|
||||
// that match any rule.
|
||||
const total = 5
|
||||
keys := make([]string, total)
|
||||
for i := 0; i < total; i++ {
|
||||
keys[i] = fmt.Sprintf("preexisting/obj-%02d.txt", i)
|
||||
putObject(t, c, bucket, keys[i], "content")
|
||||
backdateMtime(t, fc, bucket, keys[i], 30)
|
||||
}
|
||||
|
||||
// One out-of-prefix object that must NOT be expired. Same
|
||||
// pre-existing PUT timing.
|
||||
const survivor = "other/keep.txt"
|
||||
putObject(t, c, bucket, survivor, "keep")
|
||||
backdateMtime(t, fc, bucket, survivor, 30)
|
||||
|
||||
// NOW set the rule. Up to this point the worker (if it were
|
||||
// running event-driven only) would have nothing matching to do.
|
||||
putExpirationLifecycle(t, c, bucket, "preexisting/", 1)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// Every pre-existing in-prefix object must be expired by the
|
||||
// bootstrap walk's discovery + dispatch.
|
||||
for _, k := range keys {
|
||||
k := k
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(k),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond,
|
||||
"pre-existing %s/%s must be discovered + expired by bootstrap walk", bucket, k)
|
||||
}
|
||||
|
||||
// Out-of-prefix object stays — pin that the bootstrap walk
|
||||
// doesn't ignore the rule's prefix filter.
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(survivor),
|
||||
})
|
||||
require.NoError(t, err, "out-of-prefix object must survive the bootstrap walk")
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Lifecycle config update across sweeps.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleConfigUpdateBetweenSweeps: an operator changes the
|
||||
// lifecycle rule between two shell-driven sweeps. The second sweep
|
||||
// must respect the NEW rule, not a cached version of the old one.
|
||||
//
|
||||
// Each `runLifecycleShard` invocation spawns a fresh `weed shell`
|
||||
// subprocess, so cached engine state from a previous sweep doesn't
|
||||
// persist across runs. This test pins that the freshly-loaded config
|
||||
// actually changes routing — under the new prefix only matching
|
||||
// objects expire, even if there are still backdated objects sitting
|
||||
// under the old prefix.
|
||||
func TestLifecycleConfigUpdateBetweenSweeps(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("config-update")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
|
||||
// Sweep 1: rule expires anything under "first/".
|
||||
putExpirationLifecycle(t, c, bucket, "first/", 1)
|
||||
|
||||
const firstKey = "first/initial.txt"
|
||||
putObject(t, c, bucket, firstKey, "first")
|
||||
backdateMtime(t, fc, bucket, firstKey, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("sweep 1 output:\n%s", out)
|
||||
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(firstKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "sweep 1 must expire %s", firstKey)
|
||||
|
||||
// Update the rule to a different prefix. The old "first/" prefix
|
||||
// is no longer covered by any rule; objects under it must NOT be
|
||||
// expired by sweep 2 even when backdated.
|
||||
putExpirationLifecycle(t, c, bucket, "second/", 1)
|
||||
|
||||
const secondKey = "second/new.txt"
|
||||
const oldPrefixKey = "first/post-update.txt"
|
||||
putObject(t, c, bucket, secondKey, "second")
|
||||
putObject(t, c, bucket, oldPrefixKey, "stale rule")
|
||||
backdateMtime(t, fc, bucket, secondKey, 30)
|
||||
backdateMtime(t, fc, bucket, oldPrefixKey, 30)
|
||||
|
||||
out = runLifecycleShard(t)
|
||||
t.Logf("sweep 2 output:\n%s", out)
|
||||
|
||||
// Sweep 2 expires the new-prefix object.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(secondKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "sweep 2 must expire %s under the new rule", secondKey)
|
||||
|
||||
// Sweep 2 must NOT expire the old-prefix object — the rule was
|
||||
// replaced, not merged. A regression that caches old rules across
|
||||
// PutBucketLifecycleConfiguration calls would fail here.
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(oldPrefixKey),
|
||||
})
|
||||
require.NoError(t, err, "old-prefix object must survive after rule update — config replacement, not merge")
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Operator-removes-lifecycle-config integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleDeleteBucketLifecycleStopsDispatching: when an operator
|
||||
// runs DeleteBucketLifecycle, subsequent sweeps must NOT continue
|
||||
// expiring objects under the now-removed rule. The worker reads each
|
||||
// bucket's XML config from filer state on every run; if it cached the
|
||||
// previous config across PutBucketLifecycleConfiguration → DeleteBucket
|
||||
// Lifecycle the bucket would keep losing objects.
|
||||
//
|
||||
// Setup: positive control (rule active, backdated obj expires), then
|
||||
// DeleteBucketLifecycle, then PUT + backdate a fresh object, run the
|
||||
// worker again. The fresh object must remain — no rule, no dispatch.
|
||||
func TestLifecycleDeleteBucketLifecycleStopsDispatching(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("delete-config")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putExpirationLifecycle(t, c, bucket, "x/", 1)
|
||||
|
||||
const firstKey = "x/initial.txt"
|
||||
putObject(t, c, bucket, firstKey, "first")
|
||||
backdateMtime(t, fc, bucket, firstKey, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("sweep 1 output (rule active):\n%s", out)
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(firstKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "positive control: %s should expire while rule is active", firstKey)
|
||||
|
||||
// Now remove the rule. The worker must observe the removal on the
|
||||
// next sweep.
|
||||
_, err := c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{
|
||||
Bucket: aws.String(bucket),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const survivorKey = "x/post-delete.txt"
|
||||
putObject(t, c, bucket, survivorKey, "should-stay")
|
||||
backdateMtime(t, fc, bucket, survivorKey, 30)
|
||||
|
||||
out = runLifecycleShard(t)
|
||||
t.Logf("sweep 2 output (rule deleted):\n%s", out)
|
||||
|
||||
// Wait the same window; survivor MUST still exist after the worker
|
||||
// has had every opportunity to (incorrectly) act on it.
|
||||
time.Sleep(2 * time.Second)
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(survivorKey),
|
||||
})
|
||||
require.NoError(t, err, "after DeleteBucketLifecycle, sweeps must not expire %s", survivorKey)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Empty bucket sweep — no-op safety integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleEmptyBucketSweepIsNoOp: a bucket carrying lifecycle
|
||||
// config but no objects must produce a successful sweep — no hangs,
|
||||
// no errors, no dispatches. Pinned because the bootstrap walker
|
||||
// iterates bucket directories, and an empty directory is a corner of
|
||||
// that traversal that's easy to break (e.g. a slice-bounds bug on
|
||||
// the first listing returning zero entries).
|
||||
func TestLifecycleEmptyBucketSweepIsNoOp(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
_, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("empty")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putExpirationLifecycle(t, c, bucket, "anywhere/", 1)
|
||||
|
||||
// No PUTs. The bucket is empty.
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("sweep output:\n%s", out)
|
||||
|
||||
// Sanity: the worker must report it loaded the bucket's config and
|
||||
// completed without errors. The runLifecycleShard helper already
|
||||
// fails on FATAL; pin the success markers here too so a regression
|
||||
// that produces a half-shaped output (no completion) is caught.
|
||||
require.Contains(t, out, "loaded lifecycle for", "worker must report config load")
|
||||
require.Contains(t, out, "shards 0-15 complete", "worker must complete all shards")
|
||||
require.False(t, strings.Contains(out, "FATAL"), "worker must not produce FATAL output")
|
||||
|
||||
// Bucket still exists after the sweep — the worker doesn't drop
|
||||
// empty buckets as a side effect.
|
||||
_, err := c.HeadBucket(context.Background(), &s3.HeadBucketInput{Bucket: aws.String(bucket)})
|
||||
require.NoError(t, err, "empty bucket must still exist after sweep")
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// ExpirationDate (date-based, not Days) integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleExpirationDateInThePast: an Expiration{Date: <past>} rule
|
||||
// routes through the engine's ScanAtDate mode rather than the
|
||||
// EventDriven delay-group path. The worker's dispatcher must still fire
|
||||
// when the date has already passed at the time the worker runs. Pinning
|
||||
// this path because most tests use Days-based rules; ScanAtDate is a
|
||||
// separate compile + dispatch branch (engine.decideMode case
|
||||
// ActionKindExpirationDate) that wouldn't be exercised otherwise.
|
||||
func TestLifecycleExpirationDateInThePast(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("expdate")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
|
||||
// Date in the past: AWS rejects ExpirationDate in the future from
|
||||
// being processed early but a past date is the natural integration
|
||||
// test — every object hit by the rule is immediately eligible.
|
||||
pastDate := time.Now().Add(-7 * 24 * time.Hour).UTC().Truncate(24 * time.Hour)
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{{
|
||||
ID: aws.String("expire-by-date"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("d/")},
|
||||
Expiration: &types.LifecycleExpiration{
|
||||
Date: aws.Time(pastDate),
|
||||
},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const oldKey = "d/in-prefix.txt"
|
||||
const otherKey = "other/skip.txt"
|
||||
putObject(t, c, bucket, oldKey, "old")
|
||||
putObject(t, c, bucket, otherKey, "other")
|
||||
|
||||
// Backdate oldKey too — defense-in-depth so the test doesn't
|
||||
// depend on whether the worker also considers MinTriggerAge for
|
||||
// date kinds; a fresh object with a past date should still expire,
|
||||
// but aging it locks the assertion either way.
|
||||
backdateMtime(t, fc, bucket, oldKey, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(oldKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "%s/%s must be expired by past-date rule", bucket, oldKey)
|
||||
|
||||
// Out-of-prefix object stays — the rule's Filter.Prefix gates this.
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(otherKey),
|
||||
})
|
||||
require.NoError(t, err, "object outside the rule's prefix must remain")
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// AbortIncompleteMultipartUpload integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// putAbortMPULifecycle wires AbortIncompleteMultipartUpload on a prefix.
|
||||
// AWS rejects DaysAfterInitiation < 1, so the test backdates the upload
|
||||
// directory to age it past the threshold.
|
||||
func putAbortMPULifecycle(t *testing.T, c *s3.Client, bucket, prefix string, days int32) {
|
||||
t.Helper()
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{
|
||||
{
|
||||
ID: aws.String("abort-stale-mpu"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
|
||||
AbortIncompleteMultipartUpload: &types.AbortIncompleteMultipartUpload{
|
||||
DaysAfterInitiation: aws.Int32(days),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// backdateUploadDir ages the .uploads/<uploadID>/ directory entry, which is
|
||||
// what the lifecycle worker keys ABORT_MPU off of (the upload's init-time
|
||||
// directory carries the destination key in Extended).
|
||||
func backdateUploadDir(t *testing.T, fc filer_pb.SeaweedFilerClient, bucket, uploadID string, daysOld int) {
|
||||
t.Helper()
|
||||
dir := bucketsPath + "/" + bucket + "/.uploads"
|
||||
resp, err := fc.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir, Name: uploadID,
|
||||
})
|
||||
require.NoError(t, err, "lookup .uploads/%s", uploadID)
|
||||
require.NotNil(t, resp.Entry)
|
||||
require.NotNil(t, resp.Entry.Attributes)
|
||||
require.True(t, resp.Entry.IsDirectory, ".uploads/%s should be a directory", uploadID)
|
||||
|
||||
resp.Entry.Attributes.Mtime = time.Now().Add(-time.Duration(daysOld) * 24 * time.Hour).Unix()
|
||||
resp.Entry.Attributes.MtimeNs = 0
|
||||
_, err = fc.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: dir, Entry: resp.Entry,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// TestLifecycleAbortIncompleteMultipartUpload: an MPU left incomplete past
|
||||
// the AbortIncompleteMultipartUpload.DaysAfterInitiation threshold must be
|
||||
// aborted by the lifecycle worker. Exercises the lifecycleAbortMPU handler
|
||||
// path which is otherwise unreachable from the prefix-based expiration
|
||||
// tests (the routing keys off of `.uploads/<id>/` directory events, not
|
||||
// regular object events).
|
||||
func TestLifecycleAbortIncompleteMultipartUpload(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("abort-mpu")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putAbortMPULifecycle(t, c, bucket, "uploads/", 1)
|
||||
|
||||
// Initiate an MPU, upload a single part, then leave it. CompleteMultipart
|
||||
// would consume the upload; AbortMultipart would explicitly abort. We do
|
||||
// neither so the lifecycle worker is the path that ends it.
|
||||
const key = "uploads/big.bin"
|
||||
createOut, err := c.CreateMultipartUpload(context.Background(), &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
uploadID := aws.ToString(createOut.UploadId)
|
||||
require.NotEmpty(t, uploadID)
|
||||
|
||||
// Upload one part so the directory carries the right shape.
|
||||
_, err = c.UploadPart(context.Background(), &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int32(1),
|
||||
Body: strings.NewReader("part 1 contents"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Sanity: ListMultipartUploads sees our pending upload before the
|
||||
// worker runs.
|
||||
listOut, err := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{
|
||||
Bucket: aws.String(bucket),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var foundBefore bool
|
||||
for _, u := range listOut.Uploads {
|
||||
if aws.ToString(u.UploadId) == uploadID {
|
||||
foundBefore = true
|
||||
break
|
||||
}
|
||||
}
|
||||
require.True(t, foundBefore, "upload %s should be visible before the worker runs", uploadID)
|
||||
|
||||
// Backdate the upload directory entry so the rule's DaysAfterInitiation
|
||||
// threshold is satisfied. The router walks .uploads/ and emits an
|
||||
// MPU-init event for each entry.
|
||||
backdateUploadDir(t, fc, bucket, uploadID, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// The upload must no longer appear in ListMultipartUploads.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
listOut, err := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{
|
||||
Bucket: aws.String(bucket),
|
||||
})
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, u := range listOut.Uploads {
|
||||
if aws.ToString(u.UploadId) == uploadID {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}, 30*time.Second, 500*time.Millisecond, "upload %s must be aborted by the lifecycle worker", uploadID)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Multiple-bucket integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// isS3NotFound recognizes a NotFound (NoSuchKey/404) response from the
|
||||
// AWS SDK. Treating any HeadObject error as "deleted" lets a transport
|
||||
// failure or dead endpoint mask a real bug, so callers that need to
|
||||
// prove deletion specifically should use this.
|
||||
func isS3NotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var nsk *types.NoSuchKey
|
||||
if errors.As(err, &nsk) {
|
||||
return true
|
||||
}
|
||||
var notFound *types.NotFound
|
||||
if errors.As(err, ¬Found) {
|
||||
return true
|
||||
}
|
||||
var apiErr *smithyhttp.ResponseError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr.HTTPStatusCode() == 404
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestLifecycleMultipleBucketsInOneSweep: a single shell-driven shard
|
||||
// sweep must process every bucket carrying lifecycle config, not just
|
||||
// the first one alphabetically. Pinned because the scheduler iterates
|
||||
// the buckets directory and a regression that returns early after the
|
||||
// first match would silently disable lifecycle for every later bucket.
|
||||
//
|
||||
// Two buckets, each with its own 1-day prefix-expiration rule and one
|
||||
// backdated object. After the worker runs, both objects must be gone.
|
||||
func TestLifecycleMultipleBucketsInOneSweep(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucketA := uniqueBucket("multi-a")
|
||||
bucketB := uniqueBucket("multi-b")
|
||||
mustCreateBucket(t, c, bucketA)
|
||||
mustCreateBucket(t, c, bucketB)
|
||||
|
||||
putExpirationLifecycle(t, c, bucketA, "exp/", 1)
|
||||
putExpirationLifecycle(t, c, bucketB, "exp/", 1)
|
||||
|
||||
const keyA = "exp/a.txt"
|
||||
const keyB = "exp/b.txt"
|
||||
putObject(t, c, bucketA, keyA, "a")
|
||||
putObject(t, c, bucketB, keyB, "b")
|
||||
backdateMtime(t, fc, bucketA, keyA, 30)
|
||||
backdateMtime(t, fc, bucketB, keyB, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// Both buckets must have their objects expired in this single sweep.
|
||||
for _, c2 := range []struct {
|
||||
bucket, key string
|
||||
}{
|
||||
{bucketA, keyA},
|
||||
{bucketB, keyB},
|
||||
} {
|
||||
c2 := c2
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(c2.bucket), Key: aws.String(c2.key),
|
||||
})
|
||||
// Pin: only count 404 / NoSuchKey as deletion. Any other
|
||||
// error (transport failure, dead endpoint, auth) would
|
||||
// otherwise mask a real bug as a "passed" test.
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond,
|
||||
"%s/%s must be expired by the multi-bucket sweep", c2.bucket, c2.key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Multiple-rules-per-bucket integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleMultipleRulesInOneBucket: a single bucket carries two
|
||||
// independent Expiration rules with disjoint prefix filters and
|
||||
// different Days thresholds. Each rule must fire only on its prefix
|
||||
// and ignore the other; objects outside both prefixes must survive.
|
||||
//
|
||||
// Pinned because compile.Compile builds one CompiledAction per rule
|
||||
// per kind, all sharing the same bucket index. A bug that lets one
|
||||
// rule's prefix or threshold leak into the other (e.g. last-write-
|
||||
// wins on a shared map) would silently expire wrong objects.
|
||||
func TestLifecycleMultipleRulesInOneBucket(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("multi-rule")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{
|
||||
{
|
||||
ID: aws.String("logs-1d"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("logs/")},
|
||||
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
|
||||
},
|
||||
{
|
||||
ID: aws.String("tmp-7d"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("tmp/")},
|
||||
Expiration: &types.LifecycleExpiration{Days: aws.Int32(7)},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const logsKey = "logs/access.log"
|
||||
const tmpKey = "tmp/scratch.bin"
|
||||
const otherKey = "data/keep.bin"
|
||||
|
||||
putObject(t, c, bucket, logsKey, "log entry")
|
||||
putObject(t, c, bucket, tmpKey, "scratch")
|
||||
putObject(t, c, bucket, otherKey, "important")
|
||||
|
||||
// Backdate logs/ past the 1d rule, tmp/ past the 7d rule, data/
|
||||
// past both thresholds — but data/ matches no rule, so it must
|
||||
// survive regardless of age.
|
||||
backdateMtime(t, fc, bucket, logsKey, 30)
|
||||
backdateMtime(t, fc, bucket, tmpKey, 30)
|
||||
backdateMtime(t, fc, bucket, otherKey, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// logs/ rule fires.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(logsKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "logs/ rule must expire %s", logsKey)
|
||||
|
||||
// tmp/ rule fires.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(tmpKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "tmp/ rule must expire %s", tmpKey)
|
||||
|
||||
// data/ matches NEITHER rule and must survive — pinning that the
|
||||
// per-rule prefix gate is independent and additive, not a global
|
||||
// "any rule's prefix" check.
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(otherKey),
|
||||
})
|
||||
require.NoError(t, err, "object outside both rule prefixes must survive")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// NewerNoncurrentVersions integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// putNewerNoncurrentLifecycle keeps the N most recent noncurrent versions
|
||||
// and expires the rest. NoncurrentDays is required by the AWS XML schema
|
||||
// alongside NewerNoncurrentVersions; keeping it at 1 means the rule fires
|
||||
// as soon as a version moves past the keep-count and is older than 1 day.
|
||||
func putNewerNoncurrentLifecycle(t *testing.T, c *s3.Client, bucket, prefix string, keep int32) {
|
||||
t.Helper()
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{
|
||||
{
|
||||
ID: aws.String("keep-newest-noncurrent"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
|
||||
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
|
||||
NewerNoncurrentVersions: aws.Int32(keep),
|
||||
NoncurrentDays: aws.Int32(1),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// TestLifecycleNewerNoncurrentVersions: NewerNoncurrentVersions=1 keeps
|
||||
// only the most recent noncurrent version; older noncurrent versions
|
||||
// must be deleted. PUT v1, v2, v3, v4 (v4 current; v1-v3 noncurrent),
|
||||
// backdate v1, v2, v3, run the worker, expect v3 (newest noncurrent)
|
||||
// and v4 (current) to remain, v1 and v2 to be removed.
|
||||
//
|
||||
// This routes through routePointerTransition's "needs full expansion"
|
||||
// path — distinct from the per-version NoncurrentDays path because
|
||||
// the rule depends on per-version rank, not just per-version age.
|
||||
func TestLifecycleNewerNoncurrentVersions(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("newer-nc")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putVersioningEnabled(t, c, bucket)
|
||||
putNewerNoncurrentLifecycle(t, c, bucket, "n/", 1)
|
||||
|
||||
const key = "n/obj.txt"
|
||||
puts := make([]string, 4) // versionIds in PUT order
|
||||
for i := range puts {
|
||||
out, err := c.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
Body: strings.NewReader(time.Now().Format(time.RFC3339Nano) + "-" + string(rune('a'+i))),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
puts[i] = aws.ToString(out.VersionId)
|
||||
require.NotEmpty(t, puts[i])
|
||||
}
|
||||
v1, v2, v3, v4 := puts[0], puts[1], puts[2], puts[3]
|
||||
require.NotEqual(t, v1, v2)
|
||||
require.NotEqual(t, v3, v4)
|
||||
|
||||
// Backdate every noncurrent (v1, v2, v3) so all three satisfy the
|
||||
// NoncurrentDays>=1 floor; the keep-newest-1 logic then chooses
|
||||
// which to drop.
|
||||
for _, vid := range []string{v1, v2, v3} {
|
||||
backdateVersionedMtime(t, fc, bucket, key, vid, 30)
|
||||
}
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// v1 and v2 (older noncurrent) must be expired.
|
||||
for _, vid := range []string{v1, v2} {
|
||||
vid := vid
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(vid),
|
||||
})
|
||||
return err != nil
|
||||
}, 30*time.Second, 500*time.Millisecond, "older noncurrent version %s must be expired", vid)
|
||||
}
|
||||
|
||||
// v3 (newest noncurrent within the keep=1 window) must remain.
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v3),
|
||||
})
|
||||
require.NoError(t, err, "v3 (newest noncurrent within keep=1) must survive")
|
||||
|
||||
// v4 (current) must remain — current versions are immune to
|
||||
// NoncurrentVersionExpiration regardless of how the keep-count
|
||||
// arithmetic plays out.
|
||||
currentHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err, "current version v4 must remain")
|
||||
require.Equal(t, v4, aws.ToString(currentHead.VersionId))
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Object Lock + lifecycle integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleSkipsObjectLockedObjects: an object under Object Lock
|
||||
// retention must NOT be expired by the lifecycle worker. The handler's
|
||||
// enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
|
||||
// returns an error which the dispatcher classifies as
|
||||
// SKIPPED_OBJECT_LOCK. Pinning the integration end-to-end so a
|
||||
// regression in either the lock state lookup or the dispatcher's
|
||||
// outcome handling is caught.
|
||||
//
|
||||
// Companion positive control: a second object in the same bucket
|
||||
// without retention is expired by the same sweep — proves the rule
|
||||
// is firing AND that the lock check is selective, not a blanket skip.
|
||||
func TestLifecycleSkipsObjectLockedObjects(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("objlock")
|
||||
// Object Lock requires the bucket to be created with the flag set;
|
||||
// it can't be enabled retroactively on an existing bucket. Use the
|
||||
// raw API rather than mustCreateBucket here so we can pass the
|
||||
// ObjectLockEnabledForBucket option.
|
||||
_, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{
|
||||
Bucket: aws.String(bucket),
|
||||
ObjectLockEnabledForBucket: aws.Bool(true),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
// Best-effort cleanup mirrors mustCreateBucket; locked objects
|
||||
// may resist deletion but the test process continues regardless.
|
||||
c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{Bucket: aws.String(bucket)})
|
||||
listOut, _ := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)})
|
||||
if listOut != nil {
|
||||
for _, v := range listOut.Versions {
|
||||
// Bypass governance retention to free the bucket for delete.
|
||||
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: v.Key,
|
||||
VersionId: v.VersionId,
|
||||
BypassGovernanceRetention: aws.Bool(true),
|
||||
})
|
||||
}
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket), Key: m.Key, VersionId: m.VersionId,
|
||||
})
|
||||
}
|
||||
}
|
||||
c.DeleteBucket(context.Background(), &s3.DeleteBucketInput{Bucket: aws.String(bucket)})
|
||||
})
|
||||
|
||||
putExpirationLifecycle(t, c, bucket, "lock/", 1)
|
||||
|
||||
const lockedKey = "lock/protected.txt"
|
||||
const freeKey = "lock/free.txt"
|
||||
|
||||
// Locked object: PUT with GOVERNANCE retention until 1h from now.
|
||||
lockedPut, err := c.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(lockedKey),
|
||||
Body: strings.NewReader("locked"),
|
||||
ObjectLockMode: types.ObjectLockModeGovernance,
|
||||
ObjectLockRetainUntilDate: aws.Time(time.Now().Add(time.Hour)),
|
||||
})
|
||||
require.NoError(t, err, "PUT with retention must succeed on a lock-enabled bucket")
|
||||
require.NotEmpty(t, aws.ToString(lockedPut.VersionId))
|
||||
|
||||
// Free object: PUT without retention. Object Lock requires
|
||||
// versioning, so the bucket is implicitly versioned and every PUT
|
||||
// produces a versionId. Capture both for the version-aware
|
||||
// backdate path.
|
||||
freePut, err := c.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(freeKey), Body: strings.NewReader("free"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
freeVersionID := aws.ToString(freePut.VersionId)
|
||||
require.NotEmpty(t, freeVersionID)
|
||||
|
||||
// Backdate both so they would otherwise both expire under the
|
||||
// 1-day rule. The lock check is what distinguishes them.
|
||||
// Versioning-enabled buckets store entries under .versions/v_<id>,
|
||||
// not at the bare key path, so use backdateVersionedMtime.
|
||||
backdateVersionedMtime(t, fc, bucket, lockedKey, aws.ToString(lockedPut.VersionId), 30)
|
||||
backdateVersionedMtime(t, fc, bucket, freeKey, freeVersionID, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// Free object expires (positive control).
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(freeKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "unlocked object must expire (control)")
|
||||
|
||||
// Locked object survives — Object Lock retention overrides the
|
||||
// lifecycle rule. HEAD without versionId returns the still-current
|
||||
// object data, not a 404.
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(lockedKey),
|
||||
})
|
||||
require.NoError(t, err, "object under GOVERNANCE retention must survive the sweep")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Size-filter integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestLifecycleSizeFilterGreaterThan: ObjectSizeGreaterThan is a strict >
|
||||
// gate (filterAllows in match.go uses ev.Size <= rule.FilterSizeGreaterThan
|
||||
// to reject). Two backdated objects on the same prefix — only the one
|
||||
// strictly larger than the threshold is expired.
|
||||
func TestLifecycleSizeFilterGreaterThan(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("size-filter")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
|
||||
const threshold = 100
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{{
|
||||
ID: aws.String("size-gt"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{
|
||||
And: &types.LifecycleRuleAndOperator{
|
||||
Prefix: aws.String("sz/"),
|
||||
ObjectSizeGreaterThan: aws.Int64(threshold),
|
||||
},
|
||||
},
|
||||
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const smallKey = "sz/small.txt" // size <= threshold → must remain
|
||||
const largeKey = "sz/large.txt" // size > threshold → must expire
|
||||
putObject(t, c, bucket, smallKey, strings.Repeat("a", threshold)) // exactly at boundary; gate is strictly >, so rejects
|
||||
putObject(t, c, bucket, largeKey, strings.Repeat("a", threshold+50))
|
||||
|
||||
backdateMtime(t, fc, bucket, smallKey, 30)
|
||||
backdateMtime(t, fc, bucket, largeKey, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// Larger-than-threshold object expired.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(largeKey),
|
||||
})
|
||||
return err != nil
|
||||
}, 30*time.Second, 500*time.Millisecond, "object larger than threshold must expire")
|
||||
|
||||
// Boundary object (size == threshold) survives — strictly-greater gate.
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(smallKey),
|
||||
})
|
||||
require.NoError(t, err, "object at exact threshold must remain (gate is strictly >)")
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// Suspended-versioning Expiration integration scenario.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// putVersioningSuspended flips Status=Suspended. PUTs after this point
|
||||
// overwrite the null version in place rather than creating new versionIds.
|
||||
func putVersioningSuspended(t *testing.T, c *s3.Client, bucket string) {
|
||||
t.Helper()
|
||||
_, err := c.PutBucketVersioning(context.Background(), &s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(bucket),
|
||||
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusSuspended},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// TestLifecycleSuspendedVersioningExpiration: on a suspended-versioning
|
||||
// bucket, Expiration takes a different code path than the Enabled and
|
||||
// Off cases. lifecycleDispatch's VersioningSuspended branch first
|
||||
// deletes the null version (via deleteSpecificObjectVersion(versionId="null"))
|
||||
// and then writes a fresh delete marker on top.
|
||||
//
|
||||
// Setup: enable then suspend versioning so any noncurrent versions can
|
||||
// exist alongside the null one; PUT once-with-versioning + once-after-
|
||||
// suspend (so we have a noncurrent version + a null version), backdate
|
||||
// the null, run the worker. The null must be deleted and replaced by a
|
||||
// delete marker; the prior noncurrent version stays addressable.
|
||||
func TestLifecycleSuspendedVersioningExpiration(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("suspended")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putVersioningEnabled(t, c, bucket)
|
||||
|
||||
const key = "s/obj.txt"
|
||||
// First PUT under Enabled: produces a real versionId.
|
||||
putObject(t, c, bucket, key, "v1")
|
||||
headEnabled, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
v1 := aws.ToString(headEnabled.VersionId)
|
||||
require.NotEmpty(t, v1)
|
||||
require.NotEqual(t, "null", v1)
|
||||
|
||||
// Suspend versioning, then PUT again. The new write becomes the
|
||||
// "null" version that overwrites the bare-key entry; v1 demotes to
|
||||
// a noncurrent version.
|
||||
putVersioningSuspended(t, c, bucket)
|
||||
putObject(t, c, bucket, key, "null-version")
|
||||
|
||||
// Set the Expiration rule AFTER the writes so the rule
|
||||
// configuration race against PUTs is deterministic. Days=1 for
|
||||
// AWS-spec compliance; backdating the null entry makes the worker
|
||||
// fire immediately.
|
||||
putExpirationLifecycle(t, c, bucket, "s/", 1)
|
||||
|
||||
// Backdate the bare-key entry (the null version): on suspended
|
||||
// buckets the null lives at the bare path, NOT under .versions/.
|
||||
backdateMtime(t, fc, bucket, key, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// HEAD without versionId hits the latest, which after the worker
|
||||
// runs should be a delete marker (404 NoSuchKey).
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
return err != nil
|
||||
}, 30*time.Second, 500*time.Millisecond, "delete marker must dominate latest after suspended-versioning expiration")
|
||||
|
||||
// The noncurrent v1 (created under Enabled) must remain — Expiration
|
||||
// in the suspended branch only touches the null version, not other
|
||||
// versions in the .versions/ folder.
|
||||
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v1),
|
||||
})
|
||||
require.NoError(t, err, "noncurrent v1 must survive — suspended Expiration only touches the null")
|
||||
require.NotNil(t, directHead)
|
||||
|
||||
// ListObjectVersions must show: v1 still present, a fresh delete
|
||||
// marker as latest, and no more "null" version.
|
||||
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucket), Prefix: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var sawV1, sawMarker bool
|
||||
for _, v := range listOut.Versions {
|
||||
if aws.ToString(v.Key) == key {
|
||||
vid := aws.ToString(v.VersionId)
|
||||
if vid == v1 {
|
||||
sawV1 = true
|
||||
}
|
||||
require.NotEqual(t, "null", vid, "null version must have been removed")
|
||||
}
|
||||
}
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
if aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) {
|
||||
sawMarker = true
|
||||
}
|
||||
}
|
||||
require.True(t, sawV1, "v1 must still appear in ListObjectVersions")
|
||||
require.True(t, sawMarker, "fresh delete marker must dominate latest")
|
||||
}
|
||||
@@ -90,13 +90,50 @@ func mustCreateBucket(t *testing.T, c *s3.Client, name string) {
|
||||
_, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{Bucket: aws.String(name)})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
// Best effort: empty + delete.
|
||||
listOut, _ := c.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(name)})
|
||||
// Drop the lifecycle configuration first so any subsequent
|
||||
// shell-driven shard sweep stops loading rules for this bucket
|
||||
// — without this, a later test's run-shard would pick up the
|
||||
// dead bucket's config and produce phantom dispatches.
|
||||
c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{Bucket: aws.String(name)})
|
||||
|
||||
// Empty every version + delete marker (versioning-aware buckets
|
||||
// hold state that ListObjectsV2 doesn't surface). Best-effort:
|
||||
// errors are tolerated because the bucket might already be
|
||||
// half-torn-down.
|
||||
listOut, _ := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{Bucket: aws.String(name)})
|
||||
if listOut != nil {
|
||||
for _, o := range listOut.Contents {
|
||||
for _, v := range listOut.Versions {
|
||||
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(name), Key: v.Key, VersionId: v.VersionId,
|
||||
})
|
||||
}
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(name), Key: m.Key, VersionId: m.VersionId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Catch any non-versioned objects ListObjectVersions missed.
|
||||
objs, _ := c.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(name)})
|
||||
if objs != nil {
|
||||
for _, o := range objs.Contents {
|
||||
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{Bucket: aws.String(name), Key: o.Key})
|
||||
}
|
||||
}
|
||||
|
||||
// Abort any in-flight multipart uploads — the AbortMPU lifecycle
|
||||
// test leaves these intentionally; without an explicit Abort the
|
||||
// bucket DELETE refuses with NotEmpty.
|
||||
mpus, _ := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{Bucket: aws.String(name)})
|
||||
if mpus != nil {
|
||||
for _, u := range mpus.Uploads {
|
||||
c.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
|
||||
Bucket: aws.String(name), Key: u.Key, UploadId: u.UploadId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
c.DeleteBucket(context.Background(), &s3.DeleteBucketInput{Bucket: aws.String(name)})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
// Versioning + delete-marker + noncurrent integration scenarios for the
|
||||
// event-driven lifecycle worker. Same backdating trick as the base test:
|
||||
// AWS rejects Days < 1, so the test ages the object via the filer's
|
||||
// UpdateEntry RPC and runs the shell command once with -runtime 10s.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// putVersioningEnabled flips Status=Enabled on the bucket so subsequent
|
||||
// PUTs produce versioned siblings rather than overwriting.
|
||||
func putVersioningEnabled(t *testing.T, c *s3.Client, bucket string) {
|
||||
t.Helper()
|
||||
_, err := c.PutBucketVersioning(context.Background(), &s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(bucket),
|
||||
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// putNoncurrentExpirationLifecycle sets a NoncurrentVersionExpiration rule
|
||||
// targeting a prefix. Days=1 because AWS rejects 0; the test backdates
|
||||
// the noncurrent version.
|
||||
func putNoncurrentExpirationLifecycle(t *testing.T, c *s3.Client, bucket, prefix string, days int32) {
|
||||
t.Helper()
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{
|
||||
{
|
||||
ID: aws.String("expire-noncurrent"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
|
||||
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
|
||||
NoncurrentDays: aws.Int32(days),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// backdateVersionedMtime ages a specific .versions/v_<id> entry. The
|
||||
// version files live under <buckets>/<bucket>/<key>.versions/v_<versionId>.
|
||||
//
|
||||
// Also clears the ExtNoncurrentSinceNsKey stamp if present. The stamp
|
||||
// records when this version was demoted by its successor's PUT; tests
|
||||
// that backdate a version's own mtime aren't expressing a coherent claim
|
||||
// about the demotion moment, so leaving a real-now stamp would let it
|
||||
// dominate the backdated mtime and stop the rule from firing. Clearing
|
||||
// makes the lifecycle engine fall back to the sibling-mtime derivation,
|
||||
// which is what these tests were originally written against. Production
|
||||
// PUTs always write a stamp; this is a test-only escape hatch.
|
||||
func backdateVersionedMtime(t *testing.T, fc filer_pb.SeaweedFilerClient, bucket, key, versionID string, daysOld int) {
|
||||
t.Helper()
|
||||
dir := bucketsPath + "/" + bucket + "/" + key + ".versions"
|
||||
name := "v_" + versionID
|
||||
resp, err := fc.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir, Name: name,
|
||||
})
|
||||
require.NoError(t, err, "lookup version %s/%s", dir, name)
|
||||
require.NotNil(t, resp.Entry)
|
||||
require.NotNil(t, resp.Entry.Attributes)
|
||||
|
||||
resp.Entry.Attributes.Mtime = time.Now().Add(-time.Duration(daysOld) * 24 * time.Hour).Unix()
|
||||
resp.Entry.Attributes.MtimeNs = 0
|
||||
delete(resp.Entry.Extended, s3_constants.ExtNoncurrentSinceNsKey)
|
||||
_, err = fc.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: dir, Entry: resp.Entry,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func runLifecycleShard(t *testing.T) string {
|
||||
t.Helper()
|
||||
out := runShellCommand(t, fmt.Sprintf(
|
||||
"s3.lifecycle.run-shard -shards 0-15 -s3 %s -events 0 -dispatch 200ms -checkpoint 5s -runtime 10s",
|
||||
envOr("S3_GRPC_ENDPOINT", defaultS3GrpcEndpoint),
|
||||
))
|
||||
require.NotContains(t, out, "FATAL", "shell output:\n%s", out)
|
||||
return out
|
||||
}
|
||||
|
||||
// TestLifecycleVersionedBucketCreatesDeleteMarker: an Expiration rule on a
|
||||
// versioned bucket must produce a delete marker (latest version after
|
||||
// expiration) rather than removing the version itself. Pre-fix this would
|
||||
// have unconditionally deleted the live version.
|
||||
func TestLifecycleVersionedBucketCreatesDeleteMarker(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("vexp")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putVersioningEnabled(t, c, bucket)
|
||||
putExpirationLifecycle(t, c, bucket, "expire/", 1)
|
||||
|
||||
const key = "expire/old.txt"
|
||||
putObject(t, c, bucket, key, "v1")
|
||||
|
||||
// Look up the version we just created so we can backdate it. The bare
|
||||
// filer entry under <bucket>/<key> is the latest-version pointer in
|
||||
// SeaweedFS's versioned layout.
|
||||
headOut, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, headOut.VersionId)
|
||||
versionID := aws.ToString(headOut.VersionId)
|
||||
require.NotEmpty(t, versionID)
|
||||
backdateVersionedMtime(t, fc, bucket, key, versionID, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// HEAD without versionId returns the latest version. After the worker
|
||||
// runs, the latest must be a delete marker (NoSuchKey on plain HEAD).
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "expected delete marker to become latest for %s/%s", bucket, key)
|
||||
|
||||
// The original version must still be addressable directly — Expiration
|
||||
// on a versioned bucket creates a marker, it doesn't drop the version.
|
||||
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(versionID),
|
||||
})
|
||||
require.NoError(t, err, "original version must still exist")
|
||||
require.NotNil(t, directHead)
|
||||
|
||||
// ListObjectVersions should now show a delete marker dominating the
|
||||
// version. The IsLatest=true marker proves the worker created a fresh
|
||||
// marker rather than aging the existing version.
|
||||
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucket), Prefix: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var sawMarker bool
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
if aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) {
|
||||
sawMarker = true
|
||||
break
|
||||
}
|
||||
}
|
||||
require.True(t, sawMarker, "ListObjectVersions must show a delete marker as latest for %s", key)
|
||||
}
|
||||
|
||||
// TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
|
||||
// only fires on noncurrent versions. PUT v1, PUT v2 (so v1 → noncurrent),
|
||||
// backdate v1, run worker. v1 must be removed; v2 stays current.
|
||||
func TestLifecycleNoncurrentVersionExpiration(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("noncurrent")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putVersioningEnabled(t, c, bucket)
|
||||
putNoncurrentExpirationLifecycle(t, c, bucket, "v/", 1)
|
||||
|
||||
const key = "v/obj.txt"
|
||||
// First PUT.
|
||||
put1, err := c.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v1"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
v1 := aws.ToString(put1.VersionId)
|
||||
|
||||
// Second PUT promotes v1 to noncurrent.
|
||||
put2, err := c.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v2"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
v2 := aws.ToString(put2.VersionId)
|
||||
require.NotEqual(t, v1, v2)
|
||||
|
||||
// NoncurrentDays is clocked from the SUCCESSOR's mtime — i.e. when
|
||||
// the version became noncurrent — not from the displaced version's
|
||||
// own mtime. Backdating only v1 leaves the noncurrent clock (v2's
|
||||
// mtime) at "now" and the rule never fires. Age both with v1 older
|
||||
// than v2 so the ordering is realistic.
|
||||
backdateVersionedMtime(t, fc, bucket, key, v1, 31)
|
||||
backdateVersionedMtime(t, fc, bucket, key, v2, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// v1 must be gone.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v1),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "noncurrent v1 must be expired")
|
||||
|
||||
// v2 must still be addressable BY VERSION ID — pinning that the
|
||||
// noncurrent dispatch didn't accidentally remove the current
|
||||
// version's file.
|
||||
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v2),
|
||||
})
|
||||
require.NoError(t, err, "current version v2 (versionId=%s) must still be addressable directly", v2)
|
||||
|
||||
// And HEAD without versionId (i.e., the latest) must hit v2 — pinning
|
||||
// that the bare-key pointer wasn't removed and a delete marker
|
||||
// wasn't fabricated as a side effect of the noncurrent delete. On
|
||||
// failure we dump ListObjectVersions so the failure log shows
|
||||
// exactly what's there (versions vs delete markers vs bare).
|
||||
currentHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
listOut, listErr := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucket), Prefix: aws.String(key),
|
||||
})
|
||||
if listErr != nil || listOut == nil {
|
||||
t.Logf("HeadObject(latest) failed: %v\nListObjectVersions err=%v", err, listErr)
|
||||
} else {
|
||||
t.Logf("HeadObject(latest) failed: %v\nListObjectVersions err=%v versions=%d markers=%d", err, listErr, len(listOut.Versions), len(listOut.DeleteMarkers))
|
||||
for _, v := range listOut.Versions {
|
||||
t.Logf(" version key=%s id=%s isLatest=%v", aws.ToString(v.Key), aws.ToString(v.VersionId), aws.ToBool(v.IsLatest))
|
||||
}
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
t.Logf(" marker key=%s id=%s isLatest=%v", aws.ToString(m.Key), aws.ToString(m.VersionId), aws.ToBool(m.IsLatest))
|
||||
}
|
||||
}
|
||||
require.NoError(t, err, "HEAD(latest) on %s/%s must succeed; v2 (%s) must remain current", bucket, key, v2)
|
||||
}
|
||||
require.Equal(t, v2, aws.ToString(currentHead.VersionId), "latest pointer must still resolve to v2")
|
||||
_ = directHead
|
||||
}
|
||||
|
||||
// TestLifecycleExpiredDeleteMarkerCleanup: a sole-survivor delete marker
|
||||
// must be removed by an ExpiredObjectDeleteMarker=true rule. Setup: PUT v1,
|
||||
// DELETE (creates a marker that becomes latest, with v1 as noncurrent),
|
||||
// expire v1 via NoncurrentVersionExpiration so the marker is alone, then
|
||||
// the marker rule fires.
|
||||
//
|
||||
// We exercise this in two passes: pass 1 (Noncurrent rule on a sibling
|
||||
// prefix) cleans v1; pass 2 (ExpiredObjectDeleteMarker rule, also on the
|
||||
// same prefix) removes the now-orphaned marker. Since the lifecycle XML
|
||||
// only carries one set of rules per bucket, we wire both.
|
||||
func TestLifecycleExpiredDeleteMarkerCleanup(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("marker")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
putVersioningEnabled(t, c, bucket)
|
||||
|
||||
// Combined rule: noncurrent expiration + delete-marker cleanup, both
|
||||
// on the same prefix.
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{
|
||||
{
|
||||
ID: aws.String("expire-noncurrent"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("m/")},
|
||||
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
|
||||
NoncurrentDays: aws.Int32(1),
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: aws.String("expire-marker"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("m/")},
|
||||
Expiration: &types.LifecycleExpiration{
|
||||
ExpiredObjectDeleteMarker: aws.Bool(true),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const key = "m/obj.txt"
|
||||
put1, err := c.PutObject(context.Background(), &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v1"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
v1 := aws.ToString(put1.VersionId)
|
||||
|
||||
// Plain DELETE with versioning on creates a marker; the marker becomes
|
||||
// latest, v1 demotes to noncurrent.
|
||||
_, err = c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Backdate v1 so the noncurrent rule expires it.
|
||||
backdateVersionedMtime(t, fc, bucket, key, v1, 30)
|
||||
|
||||
// Backdate the delete marker too. ListObjectVersions tells us the
|
||||
// marker's versionId.
|
||||
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucket), Prefix: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var markerID string
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
if aws.ToString(m.Key) == key {
|
||||
markerID = aws.ToString(m.VersionId)
|
||||
break
|
||||
}
|
||||
}
|
||||
require.NotEmpty(t, markerID, "expected to find the delete marker we just created")
|
||||
backdateVersionedMtime(t, fc, bucket, key, markerID, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// Both v1 and the marker must be gone — the .versions/<key>/ folder
|
||||
// should hold nothing for this key.
|
||||
require.Eventuallyf(t, func() bool {
|
||||
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
|
||||
Bucket: aws.String(bucket), Prefix: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, v := range listOut.Versions {
|
||||
if aws.ToString(v.Key) == key {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, m := range listOut.DeleteMarkers {
|
||||
if aws.ToString(m.Key) == key {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}, 30*time.Second, 500*time.Millisecond, "every version and marker for %s must be gone", key)
|
||||
}
|
||||
|
||||
// TestLifecycleDisabledRuleSkipsObject: a rule with Status=Disabled must
|
||||
// not produce dispatches, even on a backdated object that would otherwise
|
||||
// match. Negative test for the engine's enabled-status gate.
|
||||
func TestLifecycleDisabledRuleSkipsObject(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("disabled")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{{
|
||||
ID: aws.String("disabled-rule"),
|
||||
Status: types.ExpirationStatusDisabled,
|
||||
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("d/")},
|
||||
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const key = "d/obj.txt"
|
||||
putObject(t, c, bucket, key, "still-here")
|
||||
backdateMtime(t, fc, bucket, key, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
// Wait the same window; the object MUST still exist after.
|
||||
time.Sleep(2 * time.Second) // give the worker a chance to (incorrectly) act
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key),
|
||||
})
|
||||
require.NoError(t, err, "Disabled rule must not delete the object")
|
||||
}
|
||||
|
||||
// TestLifecycleTagFilter: a rule with a tag filter must only match objects
|
||||
// carrying that tag. Two backdated objects, one tagged, one not — only the
|
||||
// tagged one is removed.
|
||||
func TestLifecycleTagFilter(t *testing.T) {
|
||||
c := s3Client(t)
|
||||
fc, fcClose := filerClient(t)
|
||||
defer fcClose()
|
||||
|
||||
bucket := uniqueBucket("tagfilter")
|
||||
mustCreateBucket(t, c, bucket)
|
||||
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
|
||||
Bucket: aws.String(bucket),
|
||||
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
|
||||
Rules: []types.LifecycleRule{{
|
||||
ID: aws.String("tag-only"),
|
||||
Status: types.ExpirationStatusEnabled,
|
||||
Filter: &types.LifecycleRuleFilter{
|
||||
And: &types.LifecycleRuleAndOperator{
|
||||
Prefix: aws.String("t/"),
|
||||
Tags: []types.Tag{
|
||||
{Key: aws.String("env"), Value: aws.String("temp")},
|
||||
},
|
||||
},
|
||||
},
|
||||
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
|
||||
}},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const taggedKey = "t/tagged.txt"
|
||||
const untaggedKey = "t/untagged.txt"
|
||||
putObject(t, c, bucket, taggedKey, "tagged")
|
||||
putObject(t, c, bucket, untaggedKey, "untagged")
|
||||
|
||||
// Stamp the tag on one of them.
|
||||
_, err = c.PutObjectTagging(context.Background(), &s3.PutObjectTaggingInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(taggedKey),
|
||||
Tagging: &types.Tagging{TagSet: []types.Tag{
|
||||
{Key: aws.String("env"), Value: aws.String("temp")},
|
||||
}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
backdateMtime(t, fc, bucket, taggedKey, 30)
|
||||
backdateMtime(t, fc, bucket, untaggedKey, 30)
|
||||
|
||||
out := runLifecycleShard(t)
|
||||
t.Logf("shell output:\n%s", out)
|
||||
|
||||
require.Eventuallyf(t, func() bool {
|
||||
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(taggedKey),
|
||||
})
|
||||
return isS3NotFound(err)
|
||||
}, 30*time.Second, 500*time.Millisecond, "tagged object must be expired")
|
||||
|
||||
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(untaggedKey),
|
||||
})
|
||||
require.NoError(t, err, "untagged object must remain")
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
)
|
||||
|
||||
// Job types whose ExecuteJobRequest needs per-worker rate-allocation
|
||||
// metadata injected. Keyed by the job-type string so plugin.go's
|
||||
// generic dispatch path stays job-agnostic.
|
||||
//
|
||||
// To add a new job type to the share-allocation pipeline: register an
|
||||
// entry here that knows how to read its admin-config field(s) and
|
||||
// produce the metadata keys/values the worker reads.
|
||||
|
||||
// s3LifecycleClusterDeletesPerSecondKey, s3LifecycleClusterDeletesBurstKey,
|
||||
// s3LifecycleMetadataDeletesPerSecond, and s3LifecycleMetadataDeletesBurst
|
||||
// are the contract between admin and worker. The values must match the
|
||||
// constants exported from weed/worker/tasks/s3_lifecycle/cluster_rate_limit.go
|
||||
// — duplicated here as plain strings rather than imported so the admin
|
||||
// plugin package doesn't pull a dependency on the worker handler
|
||||
// package. A mismatch on either side would silently disable rate
|
||||
// limiting; tests pin the constants in both packages against the same
|
||||
// values.
|
||||
const (
|
||||
s3LifecycleJobType = "s3_lifecycle"
|
||||
s3LifecycleClusterDeletesPerSecondKey = "cluster_deletes_per_second"
|
||||
s3LifecycleClusterDeletesBurstKey = "cluster_deletes_burst"
|
||||
s3LifecycleMetadataDeletesPerSecond = "s3_lifecycle.deletes_per_second"
|
||||
s3LifecycleMetadataDeletesBurst = "s3_lifecycle.deletes_burst"
|
||||
)
|
||||
|
||||
// decorateClusterContextForJob returns a new ClusterContext with any
|
||||
// per-job-type metadata the admin needs to inject before the
|
||||
// ExecuteJobRequest is sent. Returns the input cc unchanged when no
|
||||
// decoration applies.
|
||||
//
|
||||
// Today only s3_lifecycle decorates; the function exists so a future
|
||||
// job type's plumbing slots in alongside without touching
|
||||
// executeJobWithExecutor.
|
||||
//
|
||||
// maxJobsPerDetection is the job-type's AdminRuntimeConfig.MaxJobsPerDetection
|
||||
// — the cap on how many parallel instances of this job the scheduler will
|
||||
// dispatch per detection cycle. For singleton jobs (s3_lifecycle has
|
||||
// MaxJobsPerDetection=1) only one worker is ever active, so the cluster
|
||||
// budget must go to that worker undivided. For parallel-dispatch jobs the
|
||||
// budget divides across the actually-running set, not across every
|
||||
// capable worker. The divisor is min(executors, maxJobsPerDetection),
|
||||
// clamped to ≥1.
|
||||
func (r *Plugin) decorateClusterContextForJob(cc *plugin_pb.ClusterContext, jobType string, adminConfigValues map[string]*plugin_pb.ConfigValue, maxJobsPerDetection int) *plugin_pb.ClusterContext {
|
||||
if cc == nil {
|
||||
return cc
|
||||
}
|
||||
if jobType != s3LifecycleJobType {
|
||||
return cc
|
||||
}
|
||||
rps := readNonNegativeInt(adminConfigValues, s3LifecycleClusterDeletesPerSecondKey)
|
||||
burst := readNonNegativeInt(adminConfigValues, s3LifecycleClusterDeletesBurstKey)
|
||||
if rps <= 0 {
|
||||
// Operator hasn't configured a cluster cap; nothing to allocate.
|
||||
// The worker treats missing metadata keys as "unlimited," which
|
||||
// is the legacy behavior.
|
||||
return cc
|
||||
}
|
||||
executors := r.registry.CountCapableExecutors(jobType)
|
||||
if executors <= 0 {
|
||||
// No executors means the job won't dispatch at all; metadata
|
||||
// would be discarded. Log so the case is visible in ops.
|
||||
glog.V(2).Infof("decorateClusterContext: %s rps=%d but no execute-capable workers; skipping allocation", jobType, rps)
|
||||
return cc
|
||||
}
|
||||
// Divide by the number of *concurrently-running* workers, not the
|
||||
// number of capable ones. A singleton job (maxJobs=1) gets the full
|
||||
// budget on its single active worker.
|
||||
activeWorkers := executors
|
||||
if maxJobsPerDetection > 0 && maxJobsPerDetection < activeWorkers {
|
||||
activeWorkers = maxJobsPerDetection
|
||||
}
|
||||
perWorkerRps := float64(rps) / float64(activeWorkers)
|
||||
perWorkerBurst := 0
|
||||
if burst > 0 {
|
||||
perWorkerBurst = burst / activeWorkers
|
||||
if perWorkerBurst < 1 {
|
||||
perWorkerBurst = 1
|
||||
}
|
||||
}
|
||||
|
||||
// Clone so we don't mutate the shared base context. The metadata
|
||||
// map is small; a fresh allocation per ExecuteJob is fine.
|
||||
out := cloneClusterContext(cc)
|
||||
if out.Metadata == nil {
|
||||
out.Metadata = map[string]string{}
|
||||
}
|
||||
out.Metadata[s3LifecycleMetadataDeletesPerSecond] = strconv.FormatFloat(perWorkerRps, 'f', -1, 64)
|
||||
if perWorkerBurst > 0 {
|
||||
out.Metadata[s3LifecycleMetadataDeletesBurst] = strconv.Itoa(perWorkerBurst)
|
||||
}
|
||||
glog.V(3).Infof("decorateClusterContext: %s rps=%d burst=%d executors=%d maxJobs=%d active=%d -> per-worker rps=%g burst=%d",
|
||||
jobType, rps, burst, executors, maxJobsPerDetection, activeWorkers, perWorkerRps, perWorkerBurst)
|
||||
return out
|
||||
}
|
||||
|
||||
// cloneClusterContext returns a shallow-but-safe copy: the top-level
|
||||
// fields are reassigned, and the Metadata map is duplicated so the
|
||||
// caller can mutate it without racing other consumers of the input.
|
||||
// Slices of strings (master/filer/volume/s3 addresses) are copied by
|
||||
// reference — those are treated as immutable elsewhere in the codebase.
|
||||
func cloneClusterContext(in *plugin_pb.ClusterContext) *plugin_pb.ClusterContext {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := &plugin_pb.ClusterContext{
|
||||
MasterGrpcAddresses: in.MasterGrpcAddresses,
|
||||
FilerGrpcAddresses: in.FilerGrpcAddresses,
|
||||
VolumeGrpcAddresses: in.VolumeGrpcAddresses,
|
||||
S3GrpcAddresses: in.S3GrpcAddresses,
|
||||
}
|
||||
if in.Metadata != nil {
|
||||
out.Metadata = make(map[string]string, len(in.Metadata))
|
||||
for k, v := range in.Metadata {
|
||||
out.Metadata[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// readNonNegativeInt reads an int64 admin config value, treating
|
||||
// missing fields and non-int kinds as 0. Negative values are clamped
|
||||
// to 0 since the AdminConfigForm declares MinValue=0 on both fields.
|
||||
func readNonNegativeInt(values map[string]*plugin_pb.ConfigValue, field string) int {
|
||||
v, ok := values[field]
|
||||
if !ok || v == nil {
|
||||
return 0
|
||||
}
|
||||
switch k := v.Kind.(type) {
|
||||
case *plugin_pb.ConfigValue_Int64Value:
|
||||
if k.Int64Value < 0 {
|
||||
return 0
|
||||
}
|
||||
return int(k.Int64Value)
|
||||
case *plugin_pb.ConfigValue_DoubleValue:
|
||||
if k.DoubleValue < 0 {
|
||||
return 0
|
||||
}
|
||||
return int(k.DoubleValue)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// pluginWithExecutors returns a Plugin whose registry contains n
|
||||
// non-stale execute-capable workers for jobType. Helper for the
|
||||
// allocator tests. Bypasses UpsertFromHello so tests don't have to
|
||||
// build a full Hello message.
|
||||
func pluginWithExecutors(t *testing.T, jobType string, n int) *Plugin {
|
||||
t.Helper()
|
||||
reg := NewRegistry()
|
||||
now := time.Now()
|
||||
for i := 0; i < n; i++ {
|
||||
id := "worker-" + string(rune('a'+i))
|
||||
reg.sessions[id] = &WorkerSession{
|
||||
WorkerID: id,
|
||||
LastSeenAt: now,
|
||||
ConnectedAt: now,
|
||||
Capabilities: map[string]*plugin_pb.JobTypeCapability{
|
||||
jobType: {CanExecute: true},
|
||||
},
|
||||
}
|
||||
}
|
||||
return &Plugin{registry: reg}
|
||||
}
|
||||
|
||||
// adminConfig builds an int64 admin config map for the given fields.
|
||||
func adminConfig(pairs ...interface{}) map[string]*plugin_pb.ConfigValue {
|
||||
if len(pairs)%2 != 0 {
|
||||
panic("adminConfig expects key/value pairs")
|
||||
}
|
||||
out := map[string]*plugin_pb.ConfigValue{}
|
||||
for i := 0; i < len(pairs); i += 2 {
|
||||
key := pairs[i].(string)
|
||||
switch v := pairs[i+1].(type) {
|
||||
case int:
|
||||
out[key] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(v)}}
|
||||
case int64:
|
||||
out[key] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: v}}
|
||||
case float64:
|
||||
out[key] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_DoubleValue{DoubleValue: v}}
|
||||
default:
|
||||
panic("adminConfig: unsupported value type")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_NonS3LifecycleIsPassThrough(t *testing.T) {
|
||||
// Any job type other than s3_lifecycle gets the input cc back
|
||||
// unchanged. Future allocators add their own branch; the default
|
||||
// is pass-through.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{Metadata: map[string]string{"unrelated": "v"}}
|
||||
out := r.decorateClusterContextForJob(in, "some_other_job", adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
|
||||
assert.Same(t, in, out, "non-allocator job type must return the same pointer")
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_RpsZeroSkipsAllocation(t *testing.T) {
|
||||
// rps=0 means "operator hasn't configured a cap"; the worker
|
||||
// treats missing keys as unlimited. We must NOT inject any
|
||||
// metadata (in particular, not "0") because that would force the
|
||||
// worker into a no-throughput state on a misconfigured cluster.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType, adminConfig(s3LifecycleClusterDeletesPerSecondKey, 0), 1)
|
||||
if out.Metadata != nil {
|
||||
_, hasRps := out.Metadata[s3LifecycleMetadataDeletesPerSecond]
|
||||
assert.False(t, hasRps, "rps=0 must not write a deletes_per_second key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_NoExecutorsSkipsAllocation(t *testing.T) {
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 0)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType, adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
|
||||
if out.Metadata != nil {
|
||||
_, hasRps := out.Metadata[s3LifecycleMetadataDeletesPerSecond]
|
||||
assert.False(t, hasRps, "0 executors must not write share metadata (would divide by zero)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_SingletonJobGetsFullBudget(t *testing.T) {
|
||||
// s3_lifecycle has MaxJobsPerDetection=1: only ONE worker runs the
|
||||
// job at a time. The cluster budget must go to that worker undivided
|
||||
// — dividing by N capable executors would starve the active worker
|
||||
// to 1/N of the configured rps. Pin the singleton behavior.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
|
||||
require.NotNil(t, out.Metadata)
|
||||
assert.Equal(t, "100", out.Metadata[s3LifecycleMetadataDeletesPerSecond], "singleton job: full budget to the single active worker")
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_SharedEvenlyWhenParallelLimited(t *testing.T) {
|
||||
// Hypothetical parallel-dispatch job type (maxJobs=4): budget
|
||||
// divides across the running-set, which equals min(executors,
|
||||
// maxJobs)=4. 100/4=25.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 4)
|
||||
require.NotNil(t, out.Metadata)
|
||||
assert.Equal(t, "25", out.Metadata[s3LifecycleMetadataDeletesPerSecond], "maxJobs=4 across 4 executors = 25/worker")
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_MaxJobsExceedsExecutors(t *testing.T) {
|
||||
// maxJobs=10 but only 4 executors exist — the divisor is the
|
||||
// smaller value (executors) since you can't run more jobs in
|
||||
// parallel than there are workers to run them.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 10)
|
||||
require.NotNil(t, out.Metadata)
|
||||
assert.Equal(t, "25", out.Metadata[s3LifecycleMetadataDeletesPerSecond])
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_BurstSharedWhenParallel(t *testing.T) {
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 2)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100, s3LifecycleClusterDeletesBurstKey, 20), 2)
|
||||
require.NotNil(t, out.Metadata)
|
||||
assert.Equal(t, "50", out.Metadata[s3LifecycleMetadataDeletesPerSecond])
|
||||
assert.Equal(t, "10", out.Metadata[s3LifecycleMetadataDeletesBurst])
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_BurstZeroOmitsKey(t *testing.T) {
|
||||
// burst=0 means "let the worker default it." Don't write the key —
|
||||
// the worker's parsePositiveInt would then take the unset path
|
||||
// and compute 2 × rps automatically.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100, s3LifecycleClusterDeletesBurstKey, 0), 4)
|
||||
_, hasBurst := out.Metadata[s3LifecycleMetadataDeletesBurst]
|
||||
assert.False(t, hasBurst, "burst=0 must NOT write the burst key (worker default kicks in)")
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_BurstFloorIsOneWhenDividesBelowOne(t *testing.T) {
|
||||
// burst=1 across 4 active workers would round to 0; clamp to 1 so
|
||||
// the limiter doesn't become "single-token bucket that never refills."
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
in := &plugin_pb.ClusterContext{}
|
||||
out := r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100, s3LifecycleClusterDeletesBurstKey, 1), 4)
|
||||
assert.Equal(t, "1", out.Metadata[s3LifecycleMetadataDeletesBurst])
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_DoesNotMutateInput(t *testing.T) {
|
||||
// The same base ClusterContext is shared across many parallel
|
||||
// ExecuteJob calls. The decorator must produce a fresh map so it
|
||||
// can't race / leak per-job metadata into the base.
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
baseMeta := map[string]string{"existing": "value"}
|
||||
in := &plugin_pb.ClusterContext{Metadata: baseMeta}
|
||||
_ = r.decorateClusterContextForJob(in, s3LifecycleJobType,
|
||||
adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
|
||||
_, leaked := baseMeta[s3LifecycleMetadataDeletesPerSecond]
|
||||
assert.False(t, leaked, "decorator must not mutate the input metadata map")
|
||||
assert.Equal(t, "value", baseMeta["existing"])
|
||||
}
|
||||
|
||||
func TestDecorateClusterContext_NilInputPassesThrough(t *testing.T) {
|
||||
r := pluginWithExecutors(t, s3LifecycleJobType, 4)
|
||||
out := r.decorateClusterContextForJob(nil, s3LifecycleJobType, adminConfig(s3LifecycleClusterDeletesPerSecondKey, 100), 1)
|
||||
assert.Nil(t, out)
|
||||
}
|
||||
@@ -649,6 +649,14 @@ func (r *Plugin) executeJobWithExecutor(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply per-job-type cluster-allocation decoration (e.g. s3_lifecycle
|
||||
// divides cluster_deletes_per_second by min(workers, maxJobsPerDetection)
|
||||
// and ships the share via ClusterContext.Metadata). No-op for job
|
||||
// types without an allocator registered. MaxJobsPerDetection caps
|
||||
// the divisor so a singleton job (maxJobs=1) gets the full budget on
|
||||
// the single active worker, not 1/N of it.
|
||||
clusterContext = r.decorateClusterContextForJob(clusterContext, job.JobType, adminConfigValues, int(adminRuntime.GetMaxJobsPerDetection()))
|
||||
|
||||
completedCh := make(chan *plugin_pb.JobCompleted, 1)
|
||||
r.pendingExecutionMu.Lock()
|
||||
r.pendingExecution[requestID] = completedCh
|
||||
|
||||
@@ -142,6 +142,31 @@ func (r *Registry) HasCapableWorker(jobType string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// CountCapableExecutors returns the number of non-stale workers that
|
||||
// can EXECUTE the given job type. Used by per-job-type cluster
|
||||
// allocators (e.g. the s3_lifecycle delete-rate divider) to compute a
|
||||
// per-worker share at dispatch time. Returns 0 when no executor is
|
||||
// available — callers should treat that as "skip allocation" rather
|
||||
// than dividing by zero.
|
||||
func (r *Registry) CountCapableExecutors(jobType string) int {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
now := time.Now()
|
||||
n := 0
|
||||
for _, session := range r.sessions {
|
||||
if r.isSessionStaleLocked(session, now) {
|
||||
continue
|
||||
}
|
||||
capability := session.Capabilities[jobType]
|
||||
if capability == nil || !capability.CanExecute {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// DetectableJobTypes returns sorted job types that currently have at least one detect-capable worker.
|
||||
func (r *Registry) DetectableJobTypes() []string {
|
||||
r.mu.RLock()
|
||||
|
||||
@@ -583,16 +583,15 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, fuse.Status)
|
||||
// our IsDirectoryCached check and FindEntry (e.g. markDirectoryReadThrough).
|
||||
// If it's no longer cached, fall through to the filer lookup below.
|
||||
if wfs.metaCache.IsDirectoryCached(dirPath) {
|
||||
// If the kernel is still tracking this path's inode, the entry
|
||||
// was known to exist recently; a cached-dir miss here suggests
|
||||
// metaCache/parent-cache coherence drift. Log visibly so the
|
||||
// next occurrence shows up in mount.log without -v=4.
|
||||
if _, inodeFound := wfs.inodeToPath.GetInode(fullpath); inodeFound {
|
||||
glog.Warningf("lookupEntry: %s missing from cache while parent %s is cached; inode still tracked (possible coherence bug)", fullpath, dirPath)
|
||||
} else {
|
||||
// Authoritative ENOENT only if inodeToPath also has no record.
|
||||
// If the kernel still tracks this inode, the three layers
|
||||
// disagree; trust the filer over the local cache (the
|
||||
// filer-ErrNotFound branch below logs the confirmed drift).
|
||||
if _, inodeFound := wfs.inodeToPath.GetInode(fullpath); !inodeFound {
|
||||
glog.V(4).Infof("lookupEntry cache miss (dir cached) %s", fullpath)
|
||||
return nil, fuse.ENOENT
|
||||
}
|
||||
return nil, fuse.ENOENT
|
||||
glog.V(2).Infof("lookupEntry: %s missing from cache while parent %s is cached; inode tracked, consulting filer", fullpath, dirPath)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -81,7 +82,15 @@ func init() {
|
||||
// GrpcDial to host:grpcPort (or to a loopback alias of host on the same
|
||||
// port) is routed through the Unix socket. Dials to any other host on the
|
||||
// same port still go over TCP.
|
||||
//
|
||||
// No-op on Windows: the /tmp/...sock paths callers pass are POSIX-only and
|
||||
// the listen/dial would fail at runtime, taking gRPC down with it (#9430).
|
||||
// Skipping registration leaves the maps empty, so ServeGrpcOnLocalSocket
|
||||
// and resolveLocalGrpcSocket short-circuit and same-host RPCs go over TCP.
|
||||
func RegisterLocalGrpcSocket(host string, grpcPort int, socketPath string) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return
|
||||
}
|
||||
localGrpcSocketsLock.Lock()
|
||||
defer localGrpcSocketsLock.Unlock()
|
||||
localGrpcSockets[grpcPort] = socketPath
|
||||
|
||||
@@ -2,6 +2,7 @@ package pb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -74,6 +75,9 @@ func TestIsClientSideMarshalError_RequiresGrpcStatus(t *testing.T) {
|
||||
// continue out over TCP — they must NOT be hijacked into host A's local
|
||||
// socket on the basis of port match alone.
|
||||
func TestResolveLocalGrpcSocket_RemotePortCollision(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix-socket routing is disabled on Windows (#9430)")
|
||||
}
|
||||
// Snapshot and restore global state so the test does not leak into others.
|
||||
localGrpcSocketsLock.Lock()
|
||||
prevSockets := localGrpcSockets
|
||||
|
||||
@@ -19,6 +19,12 @@ const (
|
||||
ExtLatestVersionOwnerKey = "Seaweed-X-Amz-Latest-Version-Owner"
|
||||
ExtLatestVersionIsDeleteMarker = "Seaweed-X-Amz-Latest-Version-Is-Delete-Marker"
|
||||
ExtMultipartObjectKey = "key"
|
||||
// Wall-clock nanoseconds (int64 as decimal string) captured at the
|
||||
// moment a versioned entry was demoted from current to noncurrent
|
||||
// by a later PUT or delete marker. Read by the s3 lifecycle engine
|
||||
// to compute NoncurrentDays due time; zero/missing falls back to
|
||||
// the entry's own mtime so legacy data still expires.
|
||||
ExtNoncurrentSinceNsKey = "Seaweed-X-Amz-Noncurrent-Since-Ns"
|
||||
|
||||
// S3 checksum storage keys (use x-seaweedfs- prefix to avoid leaking in generic header loop)
|
||||
ExtChecksumAlgorithm = "x-seaweedfs-checksum-algorithm"
|
||||
|
||||
@@ -56,12 +56,7 @@ func (s3a *S3ApiServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_p
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest, entry *filer_pb.Entry) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
// metadataOnly: skip per-chunk DeleteFile RPCs because the volume's TTL
|
||||
// will reclaim chunks on its own. Per-write TTL stamping (PR 9377) sets
|
||||
// Attributes.TtlSec on every entry whose lifecycle rule fits within
|
||||
// volume TTL — observing a non-zero TtlSec on the live entry is the
|
||||
// authoritative signal.
|
||||
metadataOnly := entry != nil && entry.Attributes != nil && entry.Attributes.TtlSec > 0
|
||||
metadataOnly := entryUsesMetadataOnlyDelete(entry)
|
||||
switch req.ActionKind {
|
||||
case s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE:
|
||||
// Current-version expiration: Enabled -> delete marker; Suspended
|
||||
@@ -347,6 +342,17 @@ func identityMatches(live, want *s3_lifecycle_pb.EntryIdentity) bool {
|
||||
return bytes.Equal(live.ExtendedHash, want.ExtendedHash)
|
||||
}
|
||||
|
||||
// entryUsesMetadataOnlyDelete reports whether the lifecycle delete path
|
||||
// can skip per-chunk DeleteFile RPCs and rely on the volume's TTL to
|
||||
// reclaim chunks. Per-write TTL stamping (PR 9377) sets Attributes.TtlSec
|
||||
// on every entry whose lifecycle rule fits within volume TTL — observing
|
||||
// a non-zero TtlSec on the live entry is the authoritative signal.
|
||||
// Defensive nil-checks because the caller may be racing a concurrent
|
||||
// rewrite that nil-ed Attributes briefly during meta-log replay.
|
||||
func entryUsesMetadataOnlyDelete(entry *filer_pb.Entry) bool {
|
||||
return entry != nil && entry.Attributes != nil && entry.Attributes.TtlSec > 0
|
||||
}
|
||||
|
||||
// recordMetadataOnlyIf bumps the metadata-only counter when on=true.
|
||||
// Skipped when off so callers don't need a guard at every call site.
|
||||
// rule_hash is hex-encoded so operators can group by rule when
|
||||
|
||||
@@ -241,6 +241,47 @@ func contains(haystack, needle string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func TestEntryUsesMetadataOnlyDelete(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
entry *filer_pb.Entry
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "nil entry",
|
||||
entry: nil,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "nil attributes",
|
||||
entry: &filer_pb.Entry{},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "TtlSec=0 (no per-write stamp)",
|
||||
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: 0}},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "TtlSec>0 (PR 9377 stamped a fast-path TTL)",
|
||||
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: 86400}},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "TtlSec<0 should not happen but must not flip the path on",
|
||||
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: -1}},
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := entryUsesMetadataOnlyDelete(c.entry); got != c.want {
|
||||
t.Fatalf("want %v, got %v", c.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordMetadataOnlyIf_OnlyFiresWhenOn(t *testing.T) {
|
||||
// Counter must increment exactly once per (bucket, hex(rule_hash))
|
||||
// when on=true, and not at all when on=false. Other lifecycle paths
|
||||
|
||||
@@ -1053,7 +1053,20 @@ func (s3a *S3ApiServer) copySingleChunk(chunk *filer_pb.FileChunk, dstPath strin
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Download and upload the chunk
|
||||
// Stream the chunk through io.Pipe when no in-transit transformation is
|
||||
// required; this holds only ~32 KiB per copy in flight, vs. the
|
||||
// chunk-sized buffers the buffered path needs. isFullChunk=true asks
|
||||
// the source volume for compressed bytes, so a gzipped chunk is
|
||||
// forwarded to the destination without anyone having to decompress.
|
||||
if canStreamCopyChunk(chunk) {
|
||||
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, 0, int64(chunk.Size), true /*isFullChunk*/, assignResult); err != nil {
|
||||
return nil, fmt.Errorf("stream chunk: %w", err)
|
||||
}
|
||||
return dstChunk, nil
|
||||
}
|
||||
|
||||
// SSE / per-chunk-cipher: bytes need to be transformed in transit, so
|
||||
// download into a buffer first.
|
||||
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, 0, int64(chunk.Size), chunk.CipherKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download chunk data: %w", err)
|
||||
@@ -1088,6 +1101,25 @@ func (s3a *S3ApiServer) copySingleChunkForRange(originalChunk, rangeChunk *filer
|
||||
overlapStart := max(rangeStart, chunkStart)
|
||||
offsetInChunk := overlapStart - chunkStart
|
||||
|
||||
// Stream the byte range through io.Pipe when there's no in-transit
|
||||
// transformation required (see canStreamCopyChunk for the eligibility
|
||||
// rules); this is the dominant path for Harbor-style multipart
|
||||
// assemble loads, which use UploadPartCopy with a CopySourceRange.
|
||||
//
|
||||
// When the requested range happens to cover the entire source chunk
|
||||
// exactly, switch to the full-chunk fetch mode: that asks the source
|
||||
// volume for compressed bytes (Accept-Encoding: gzip) and forwards
|
||||
// them as-is, avoiding the volume-side decompression that a Range
|
||||
// fetch on a gzipped chunk would otherwise pay. Harbor's typical
|
||||
// part-size = chunk-size assemble pattern hits this branch.
|
||||
if canStreamCopyChunk(originalChunk) {
|
||||
isFullChunk := offsetInChunk == 0 && rangeChunk.Size == originalChunk.Size
|
||||
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), isFullChunk, assignResult); err != nil {
|
||||
return nil, fmt.Errorf("stream chunk range: %w", err)
|
||||
}
|
||||
return dstChunk, nil
|
||||
}
|
||||
|
||||
// Download and upload the chunk portion
|
||||
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), originalChunk.CipherKey)
|
||||
if err != nil {
|
||||
@@ -1379,16 +1411,7 @@ func (s3a *S3ApiServer) prepareChunkCopy(sourceFileId, dstPath string, expectedD
|
||||
// uploadChunkData uploads chunk data to the destination using common upload logic
|
||||
// isCompressed indicates if the data is already compressed and should not be compressed again
|
||||
func (s3a *S3ApiServer) uploadChunkData(chunkData []byte, assignResult *filer_pb.AssignVolumeResponse, isCompressed bool) error {
|
||||
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
|
||||
|
||||
uploadOption := &operation.UploadOption{
|
||||
UploadUrl: dstUrl,
|
||||
Cipher: false, // Data is already encrypted if source had CipherKey; don't re-encrypt
|
||||
IsInputCompressed: isCompressed,
|
||||
MimeType: "",
|
||||
PairMap: nil,
|
||||
Jwt: security.EncodedJwt(assignResult.Auth),
|
||||
}
|
||||
uploadOption := newChunkUploadOption(chunkData, assignResult, isCompressed)
|
||||
uploader, err := operation.NewUploader()
|
||||
if err != nil {
|
||||
return fmt.Errorf("create uploader: %w", err)
|
||||
@@ -1401,6 +1424,33 @@ func (s3a *S3ApiServer) uploadChunkData(chunkData []byte, assignResult *filer_pb
|
||||
return nil
|
||||
}
|
||||
|
||||
// multipartFramingOverhead reserves space for the multipart wrapper
|
||||
// upload_content writes around chunkData (boundary + Content-Disposition +
|
||||
// optional Content-Type/Content-Encoding/Content-MD5 headers + trailing
|
||||
// boundary). Real-world overhead is a few hundred bytes; rounding to 1 KiB
|
||||
// avoids a single grow on the buffer we hand to the multipart writer.
|
||||
const multipartFramingOverhead = 1024
|
||||
|
||||
// newChunkUploadOption builds the operation.UploadOption used by every
|
||||
// chunk-copy upload. It always sets BytesBuffer to a fresh, per-call buffer
|
||||
// so upload_content does not fall back to the package-global
|
||||
// valyala/bytebufferpool — that pool retains every high-water buffer for the
|
||||
// process's lifetime, and under concurrent UploadPartCopy load it hoarded
|
||||
// one chunk-sized buffer per concurrent upload (see #6541). The per-call
|
||||
// buffer is GC'd as soon as the upload returns.
|
||||
func newChunkUploadOption(chunkData []byte, assignResult *filer_pb.AssignVolumeResponse, isCompressed bool) *operation.UploadOption {
|
||||
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
|
||||
return &operation.UploadOption{
|
||||
UploadUrl: dstUrl,
|
||||
Cipher: false, // Data is already encrypted if source had CipherKey; don't re-encrypt
|
||||
IsInputCompressed: isCompressed,
|
||||
MimeType: "",
|
||||
PairMap: nil,
|
||||
Jwt: security.EncodedJwt(assignResult.Auth),
|
||||
BytesBuffer: bytes.NewBuffer(make([]byte, 0, len(chunkData)+multipartFramingOverhead)),
|
||||
}
|
||||
}
|
||||
|
||||
// downloadChunkData downloads chunk data from the source URL
|
||||
func (s3a *S3ApiServer) downloadChunkData(srcUrl, fileId string, offset, size int64, cipherKey []byte) ([]byte, error) {
|
||||
jwt := filer.JwtForVolumeServer(fileId)
|
||||
@@ -1434,7 +1484,13 @@ func (s3a *S3ApiServer) downloadChunkData(srcUrl, fileId string, offset, size in
|
||||
return nil, fmt.Errorf("chunk size %d exceeds maximum int32 size", size)
|
||||
}
|
||||
sizeInt := int(size)
|
||||
var chunkData []byte
|
||||
// Pre-size the receive buffer to the known chunk size so the streaming
|
||||
// callback below does not trigger geometric `append`-grow on a nil slice.
|
||||
// Receiving a 64 MiB chunk through 256 KiB callback ticks would otherwise
|
||||
// allocate ~2x the chunk size, and with concurrent UploadPartCopy requests
|
||||
// (Harbor-style assemble loops) this caused the runaway-RSS pattern in
|
||||
// https://github.com/seaweedfs/seaweedfs/issues/6541.
|
||||
chunkData := make([]byte, 0, sizeInt)
|
||||
shouldRetry, err := util_http.ReadUrlAsStream(context.Background(), srcUrl, jwt, nil, false, false, offset, sizeInt, func(data []byte) {
|
||||
chunkData = append(chunkData, data...)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// TestDownloadChunkData_AllocationBound is a regression guard for
|
||||
// https://github.com/seaweedfs/seaweedfs/issues/6541.
|
||||
//
|
||||
// downloadChunkData previously accumulated streamed bytes via
|
||||
//
|
||||
// var chunkData []byte
|
||||
// ... fn := func(data []byte) { chunkData = append(chunkData, data...) }
|
||||
//
|
||||
// The callback fires once per ReadUrlAsStream pump (256 KiB), so a 16 MiB
|
||||
// chunk grew the slice geometrically (256K -> 512K -> 1M -> ... -> 32M),
|
||||
// allocating ~2x the chunk size for every transferred byte. Combined with
|
||||
// the 4-way per-request concurrency in copyChunks/copyChunksForRange and
|
||||
// any number of in-flight UploadPartCopy calls (Harbor multipart assemble),
|
||||
// this produced the runaway RSS reported in the issue.
|
||||
//
|
||||
// We assert that downloading a chunkSize-byte chunk allocates at most
|
||||
// 1.5 * chunkSize bytes on the heap. The pre-fix nil-append pattern blows
|
||||
// past that bound; the fixed (`make([]byte, 0, sizeInt)`) version stays
|
||||
// well under it.
|
||||
func TestDownloadChunkData_AllocationBound(t *testing.T) {
|
||||
// downloadChunkData drives the package-level global HTTP client. Tests
|
||||
// don't go through the normal `weed` startup that does this, so call it
|
||||
// here. Idempotent on subsequent test runs.
|
||||
util_http.InitGlobalHttpClient()
|
||||
|
||||
const chunkSize = 16 << 20 // 16 MiB
|
||||
payload := make([]byte, chunkSize)
|
||||
for i := range payload {
|
||||
payload[i] = byte(i)
|
||||
}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(payload)))
|
||||
// Write in 64 KiB increments so the body is delivered to the client
|
||||
// reader in many small reads, mirroring real volume-server streaming
|
||||
// behavior. The exact step does not matter as long as the body comes
|
||||
// through the client in multiple Read() calls.
|
||||
const step = 64 * 1024
|
||||
for i := 0; i < len(payload); i += step {
|
||||
end := i + step
|
||||
if end > len(payload) {
|
||||
end = len(payload)
|
||||
}
|
||||
if _, err := w.Write(payload[i:end]); err != nil {
|
||||
return
|
||||
}
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
s3a := &S3ApiServer{}
|
||||
|
||||
// Warm up the global HTTP client and any package-level pools so they
|
||||
// don't show up in the measured allocation window.
|
||||
if _, err := s3a.downloadChunkData(srv.URL, "1,0", 0, int64(chunkSize), nil); err != nil {
|
||||
t.Fatalf("warm-up downloadChunkData: %v", err)
|
||||
}
|
||||
|
||||
runtime.GC()
|
||||
var before, after runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
|
||||
data, err := s3a.downloadChunkData(srv.URL, "1,0", 0, int64(chunkSize), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("downloadChunkData: %v", err)
|
||||
}
|
||||
|
||||
runtime.ReadMemStats(&after)
|
||||
allocated := after.TotalAlloc - before.TotalAlloc
|
||||
|
||||
// Correctness check happens after the alloc measurement so bytes.Equal
|
||||
// doesn't pollute the window. A pre-sized buffer that silently truncates
|
||||
// or corrupts the chunk would still pass the bound — assert content too.
|
||||
if !bytes.Equal(data, payload) {
|
||||
t.Fatalf("downloaded data does not match payload (len got=%d want=%d)",
|
||||
len(data), len(payload))
|
||||
}
|
||||
|
||||
// The output slice itself is chunkSize bytes; the streaming pump uses a
|
||||
// pooled 256 KiB read buffer and doesn't otherwise accumulate. A 1.5x
|
||||
// bound is comfortably above the steady-state cost and well below the
|
||||
// pre-fix geometric-grow cost (~2x).
|
||||
maxAllowed := uint64(chunkSize) * 3 / 2
|
||||
if allocated > maxAllowed {
|
||||
t.Fatalf("downloadChunkData allocated %d bytes for a %d-byte chunk; bound is %d "+
|
||||
"(regression: unbounded append in callback?)",
|
||||
allocated, chunkSize, maxAllowed)
|
||||
}
|
||||
t.Logf("allocated=%d bytes, bound=%d, output=%d", allocated, maxAllowed, chunkSize)
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// benchEnv stands up a fake source volume (returns N bytes on GET) and a
|
||||
// fake destination volume (parses an incoming multipart POST and discards
|
||||
// the body, asserting the data arrived intact via SHA-256). It returns the
|
||||
// URLs and an AssignVolumeResponse pointing at the destination.
|
||||
type benchEnv struct {
|
||||
srcSrv *httptest.Server
|
||||
dstSrv *httptest.Server
|
||||
payload []byte
|
||||
dstHash [32]byte
|
||||
assign *filer_pb.AssignVolumeResponse
|
||||
}
|
||||
|
||||
func newBenchEnv(b *testing.B, payloadSize int) *benchEnv {
|
||||
b.Helper()
|
||||
payload := make([]byte, payloadSize)
|
||||
for i := range payload {
|
||||
payload[i] = byte(i*31 + 7) // arbitrary repeatable pattern
|
||||
}
|
||||
wantHash := sha256.Sum256(payload)
|
||||
|
||||
srcSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Honor Range header if present (UploadPartCopy passes one).
|
||||
start, end := int64(0), int64(len(payload)-1)
|
||||
if rng := r.Header.Get("Range"); rng != "" {
|
||||
var s, e int64
|
||||
if _, err := fmt.Sscanf(rng, "bytes=%d-%d", &s, &e); err == nil {
|
||||
start, end = s, e
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(payload[start : end+1])
|
||||
}))
|
||||
|
||||
dstSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mr, err := r.MultipartReader()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
part, err := mr.NextPart()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, part); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var got [32]byte
|
||||
copy(got[:], h.Sum(nil))
|
||||
if got != wantHash {
|
||||
http.Error(w, "hash mismatch", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = io.WriteString(w, `{"size":`+strconv.Itoa(payloadSize)+`}`)
|
||||
}))
|
||||
|
||||
dstURL, _ := neturl(dstSrv.URL)
|
||||
assign := &filer_pb.AssignVolumeResponse{
|
||||
FileId: "1,benchmark",
|
||||
Location: &filer_pb.Location{
|
||||
Url: dstURL,
|
||||
PublicUrl: dstURL,
|
||||
},
|
||||
Auth: "",
|
||||
}
|
||||
|
||||
return &benchEnv{
|
||||
srcSrv: srcSrv,
|
||||
dstSrv: dstSrv,
|
||||
payload: payload,
|
||||
dstHash: wantHash,
|
||||
assign: assign,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *benchEnv) close() {
|
||||
e.srcSrv.Close()
|
||||
e.dstSrv.Close()
|
||||
}
|
||||
|
||||
// neturl extracts host:port from "http://host:port".
|
||||
func neturl(rawURL string) (string, error) {
|
||||
const prefix = "http://"
|
||||
if len(rawURL) < len(prefix) || rawURL[:len(prefix)] != prefix {
|
||||
return "", fmt.Errorf("unexpected URL: %q", rawURL)
|
||||
}
|
||||
host := rawURL[len(prefix):]
|
||||
if _, _, err := net.SplitHostPort(host); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return host, nil
|
||||
}
|
||||
|
||||
// BenchmarkCopyChunk_Buffered measures the cost of the existing buffered
|
||||
// chunk-copy path (downloadChunkData + uploadChunkData). The path
|
||||
// allocates one chunk-sized []byte and one multipart-encoded buffer per
|
||||
// call.
|
||||
func BenchmarkCopyChunk_Buffered(b *testing.B) {
|
||||
for _, size := range []int{1 << 20, 8 << 20, 64 << 20} {
|
||||
b.Run(humanByteName(size), func(b *testing.B) {
|
||||
util_http.InitGlobalHttpClient()
|
||||
env := newBenchEnv(b, size)
|
||||
defer env.close()
|
||||
|
||||
s3a := &S3ApiServer{}
|
||||
b.ResetTimer()
|
||||
b.SetBytes(int64(size))
|
||||
b.ReportAllocs()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
data, err := s3a.downloadChunkData(env.srcSrv.URL, env.assign.FileId, 0, int64(size), nil)
|
||||
if err != nil {
|
||||
b.Fatalf("download: %v", err)
|
||||
}
|
||||
if err := s3a.uploadChunkData(data, env.assign, false); err != nil {
|
||||
b.Fatalf("upload: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkCopyChunk_Streamed measures the cost of the io.Pipe streaming
|
||||
// chunk-copy path. The path holds only the pipe's hand-off buffer (~32
|
||||
// KiB) plus http transport buffers per call, regardless of chunk size.
|
||||
func BenchmarkCopyChunk_Streamed(b *testing.B) {
|
||||
for _, size := range []int{1 << 20, 8 << 20, 64 << 20} {
|
||||
b.Run(humanByteName(size), func(b *testing.B) {
|
||||
util_http.InitGlobalHttpClient()
|
||||
env := newBenchEnv(b, size)
|
||||
defer env.close()
|
||||
|
||||
s3a := &S3ApiServer{}
|
||||
b.ResetTimer()
|
||||
b.SetBytes(int64(size))
|
||||
b.ReportAllocs()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := s3a.streamCopyChunkRange(context.Background(),
|
||||
env.srcSrv.URL, env.assign.FileId, 0, int64(size),
|
||||
true /*isFullChunk*/, env.assign); err != nil {
|
||||
b.Fatalf("stream: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func humanByteName(n int) string {
|
||||
switch {
|
||||
case n >= 1<<30:
|
||||
return strconv.Itoa(n>>30) + "GiB"
|
||||
case n >= 1<<20:
|
||||
return strconv.Itoa(n>>20) + "MiB"
|
||||
case n >= 1<<10:
|
||||
return strconv.Itoa(n>>10) + "KiB"
|
||||
default:
|
||||
return strconv.Itoa(n) + "B"
|
||||
}
|
||||
}
|
||||
|
||||
// Compile-time sanity: ensure the multipart library version we depend on
|
||||
// is the one whose framing we mirror in streamCopyChunkRange.
|
||||
var _ = multipart.NewWriter
|
||||
@@ -0,0 +1,77 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// TestNewChunkUploadOption_AvoidsBytePool is a regression guard for the
|
||||
// s3-side retention amplifier in https://github.com/seaweedfs/seaweedfs/issues/6541.
|
||||
//
|
||||
// operation.upload_content falls back to the package-global
|
||||
// valyala/bytebufferpool (which retains high-water buffers for the
|
||||
// process's lifetime) whenever UploadOption.BytesBuffer is nil. Concurrent
|
||||
// UploadPartCopy calls then hoard one chunk-sized buffer per concurrent
|
||||
// upload in that pool, and RSS never recedes. The chunk-copy path must
|
||||
// therefore always provide its own buffer; this test pins that contract.
|
||||
func TestNewChunkUploadOption_AvoidsBytePool(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
chunkLen int
|
||||
}{
|
||||
{"empty chunk", 0},
|
||||
{"small chunk", 1024},
|
||||
{"typical 8 MiB chunk", 8 * 1024 * 1024},
|
||||
{"large 64 MiB chunk", 64 * 1024 * 1024},
|
||||
}
|
||||
|
||||
assign := &filer_pb.AssignVolumeResponse{
|
||||
FileId: "1,foo",
|
||||
Location: &filer_pb.Location{
|
||||
Url: "127.0.0.1:8080",
|
||||
PublicUrl: "127.0.0.1:8080",
|
||||
},
|
||||
Auth: "",
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
data := make([]byte, c.chunkLen)
|
||||
opt := newChunkUploadOption(data, assign, false)
|
||||
|
||||
if opt.BytesBuffer == nil {
|
||||
t.Fatalf("BytesBuffer must be non-nil so chunk uploads bypass " +
|
||||
"the package-global bytebufferpool (regression: #6541)")
|
||||
}
|
||||
if got, want := opt.BytesBuffer.Cap(), c.chunkLen+multipartFramingOverhead; got < want {
|
||||
t.Errorf("BytesBuffer cap=%d, want >=%d (one alloc-and-grow "+
|
||||
"per upload defeats the purpose of pre-sizing)", got, want)
|
||||
}
|
||||
if opt.BytesBuffer.Len() != 0 {
|
||||
t.Errorf("BytesBuffer not empty: len=%d", opt.BytesBuffer.Len())
|
||||
}
|
||||
if opt.Cipher {
|
||||
t.Errorf("Cipher must be false: chunk-copy data is already " +
|
||||
"encrypted if the source had a CipherKey")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewChunkUploadOption_PerCallIsolation verifies each call returns a
|
||||
// distinct buffer. Sharing one buffer across concurrent uploads would
|
||||
// corrupt the multipart bodies under concurrent UploadPartCopy.
|
||||
func TestNewChunkUploadOption_PerCallIsolation(t *testing.T) {
|
||||
assign := &filer_pb.AssignVolumeResponse{
|
||||
FileId: "1,foo",
|
||||
Location: &filer_pb.Location{Url: "127.0.0.1:8080"},
|
||||
}
|
||||
|
||||
o1 := newChunkUploadOption(nil, assign, false)
|
||||
o2 := newChunkUploadOption(nil, assign, false)
|
||||
if o1.BytesBuffer == o2.BytesBuffer {
|
||||
t.Fatalf("newChunkUploadOption must hand each caller a distinct buffer; " +
|
||||
"sharing one across concurrent uploads would corrupt the multipart bodies")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// canStreamCopyChunk reports whether the chunk-copy fast path can use the
|
||||
// io.Pipe streaming variant. The streaming path bypasses both the s3-side
|
||||
// download buffer and the s3-side multipart-encode buffer, holding only the
|
||||
// io.Pipe internal buffer (~32 KiB) per copy in flight. It does not work
|
||||
// when bytes need to be transformed in transit:
|
||||
//
|
||||
// - SSE-C / SSE-KMS / SSE-S3: bytes need to be re-encrypted with a
|
||||
// different key on the destination, so they have to land in memory.
|
||||
// - Per-chunk CipherKey (per-chunk encryption from the source): the
|
||||
// source bytes need to be decrypted before being re-uploaded.
|
||||
//
|
||||
// In both cases the caller falls back to the buffered copySingleChunk path,
|
||||
// which already handles those transformations correctly. The streaming
|
||||
// path is still safe for IsCompressed chunks — gzip is end-to-end and we
|
||||
// just forward the wire bytes (with the destination Content-Encoding
|
||||
// header set to whatever the source actually returned).
|
||||
func canStreamCopyChunk(chunk *filer_pb.FileChunk) bool {
|
||||
if len(chunk.CipherKey) > 0 {
|
||||
return false
|
||||
}
|
||||
if chunk.GetSseType() != filer_pb.SSEType_NONE {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// streamCopyChunkRange copies size bytes starting at offset from srcUrl to
|
||||
// the destination volume identified by assignResult, using io.Pipe to avoid
|
||||
// buffering the chunk in memory. The destination volume server expects the
|
||||
// same multipart wire format that operation.upload_content writes — see
|
||||
// upload_content.go for the canonical version; we mirror its part headers
|
||||
// here so the volume's needle.parseUpload accepts the request.
|
||||
//
|
||||
// isFullChunk is the load-bearing distinction:
|
||||
//
|
||||
// - false (partial range): a Range header is sent to the source volume,
|
||||
// which serves the requested byte range. For compressed chunks the
|
||||
// volume internally decompresses to satisfy the range, then returns
|
||||
// raw bytes (no Content-Encoding); we forward those raw bytes.
|
||||
// - true (full chunk): we ask the source volume to send compressed
|
||||
// bytes via Accept-Encoding: gzip, bypass Go's auto-decompression on
|
||||
// resp.Body, and forward whatever wire bytes arrived to the
|
||||
// destination. When the chunk is stored gzipped that means we never
|
||||
// decompress on either the source-volume or s3-server side; the
|
||||
// destination receives gzipped bytes and stores them as-is.
|
||||
//
|
||||
// For the Harbor-style assemble repro (where each UploadPartCopy range
|
||||
// matches a source chunk boundary), the full-chunk path eliminates the
|
||||
// "bytes.growSlice from util.DecompressData" cost that dominates the
|
||||
// volume-side heap profile after the s3-side fixes.
|
||||
//
|
||||
// The destination's Content-Encoding header is set from the source's
|
||||
// response Content-Encoding only — never from a caller-supplied hint.
|
||||
// Trusting a hint that disagrees with the wire bytes (e.g. caller says
|
||||
// "compressed" but the volume returned raw bytes for a partial range)
|
||||
// would label raw bytes as gzip and corrupt reads on the destination.
|
||||
func (s3a *S3ApiServer) streamCopyChunkRange(
|
||||
ctx context.Context,
|
||||
srcUrl, srcFileId string,
|
||||
offset, size int64,
|
||||
isFullChunk bool,
|
||||
assignResult *filer_pb.AssignVolumeResponse,
|
||||
) error {
|
||||
// Range header takes int64, but mirror the int32 bound from
|
||||
// downloadChunkData so the two paths reject the same inputs.
|
||||
if size > int64(math.MaxInt32) {
|
||||
return fmt.Errorf("chunk size %d exceeds maximum int32 size", size)
|
||||
}
|
||||
// Child context so a terminal error here unblocks both legs
|
||||
// immediately. Without this, a failed POST closes pipeReader
|
||||
// (which only fails the producer's writes), but the source GET's
|
||||
// read loop would keep draining srcResp.Body in the background
|
||||
// until EOF — wasting source-volume bandwidth and CPU on a copy
|
||||
// that's already failed. Cancelling streamCtx tears down both the
|
||||
// source GET and the destination POST when this function returns.
|
||||
streamCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
|
||||
dstJwt := security.EncodedJwt(assignResult.Auth)
|
||||
srcJwt := filer.JwtForVolumeServer(srcFileId)
|
||||
|
||||
// Source GET: built directly (not through ReadUrlAsStream) because that
|
||||
// helper auto-decompresses gzipped responses, which would defeat the
|
||||
// whole-chunk pass-through optimization. We want the wire bytes.
|
||||
srcReq, err := http.NewRequestWithContext(streamCtx, http.MethodGet, srcUrl, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create source GET: %w", err)
|
||||
}
|
||||
if srcJwt != "" {
|
||||
srcReq.Header.Set("Authorization", "BEARER "+srcJwt)
|
||||
}
|
||||
if isFullChunk {
|
||||
// Manually setting Accept-Encoding tells Go's http.Transport that
|
||||
// the user wants raw bytes back — Go's automatic decompression is
|
||||
// only applied when it adds the header itself. The server may or
|
||||
// may not actually gzip; the response Content-Encoding header is
|
||||
// authoritative.
|
||||
srcReq.Header.Set("Accept-Encoding", "gzip")
|
||||
} else {
|
||||
srcReq.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+size-1))
|
||||
}
|
||||
|
||||
srcResp, err := util_http.GetGlobalHttpClient().Do(srcReq)
|
||||
if err != nil {
|
||||
return fmt.Errorf("source GET: %w", err)
|
||||
}
|
||||
// CloseResponse drains and closes resp.Body for keepalive.
|
||||
defer util_http.CloseResponse(srcResp)
|
||||
|
||||
if srcResp.StatusCode >= 400 {
|
||||
return fmt.Errorf("source GET %s: %s", srcUrl, srcResp.Status)
|
||||
}
|
||||
|
||||
// What's actually on the wire — trust this over caller hints. For range
|
||||
// fetches the volume always returns raw bytes (no Content-Encoding); for
|
||||
// full-chunk fetches it depends on whether the chunk is stored gzipped.
|
||||
bodyIsGzipped := srcResp.Header.Get("Content-Encoding") == "gzip"
|
||||
|
||||
// io.Pipe gives us a synchronous handoff: the producer goroutine builds
|
||||
// the multipart body, the consumer (HTTP transport) reads it. Writes
|
||||
// block until reads consume them, so the in-flight footprint is the
|
||||
// pipe's hand-off buffer — not the chunk size.
|
||||
pipeReader, pipeWriter := io.Pipe()
|
||||
mw := multipart.NewWriter(pipeWriter)
|
||||
contentType := mw.FormDataContentType()
|
||||
|
||||
go func() {
|
||||
// CloseWithError on the writer end propagates the failure to the
|
||||
// HTTP transport reading from pipeReader, which then aborts the
|
||||
// POST. Plain Close (with err==nil) sends EOF normally.
|
||||
var producerErr error
|
||||
defer func() {
|
||||
pipeWriter.CloseWithError(producerErr)
|
||||
}()
|
||||
|
||||
h := make(textproto.MIMEHeader)
|
||||
h.Set("Content-Disposition", mime.FormatMediaType("form-data",
|
||||
map[string]string{"name": "file", "filename": ""}))
|
||||
h.Set("Idempotency-Key", dstUrl)
|
||||
if bodyIsGzipped {
|
||||
h.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
|
||||
fw, err := mw.CreatePart(h)
|
||||
if err != nil {
|
||||
producerErr = fmt.Errorf("multipart create part: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := io.Copy(fw, srcResp.Body); err != nil {
|
||||
if shouldLogStreamError(err) {
|
||||
glog.V(2).Infof("stream copy %s offset=%d size=%d: %v",
|
||||
srcUrl, offset, size, err)
|
||||
}
|
||||
producerErr = fmt.Errorf("stream copy: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := mw.Close(); err != nil {
|
||||
producerErr = fmt.Errorf("multipart close: %w", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
req, err := http.NewRequestWithContext(streamCtx, http.MethodPost, dstUrl, pipeReader)
|
||||
if err != nil {
|
||||
pipeReader.CloseWithError(err)
|
||||
return fmt.Errorf("create POST request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
if dstJwt != "" {
|
||||
req.Header.Set("Authorization", "BEARER "+string(dstJwt))
|
||||
}
|
||||
|
||||
resp, err := util_http.GetGlobalHttpClient().Do(req)
|
||||
if err != nil {
|
||||
// Closing the reader unblocks the producer if it was still mid-write;
|
||||
// the deferred cancel above also stops any in-flight source read.
|
||||
pipeReader.CloseWithError(err)
|
||||
return fmt.Errorf("POST: %w", err)
|
||||
}
|
||||
defer util_http.CloseResponse(resp)
|
||||
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("POST %s: %s", dstUrl, resp.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func shouldLogStreamError(err error) bool {
|
||||
// io.ErrClosedPipe shows up when the HTTP transport closed pipeReader
|
||||
// after the POST failed; the underlying error is reported via the POST
|
||||
// path, no need to log twice.
|
||||
return err != nil && err != io.ErrClosedPipe
|
||||
}
|
||||
@@ -1274,19 +1274,25 @@ func (s3a *S3ApiServer) putSuspendedVersioningObject(r *http.Request, bucket, ob
|
||||
// Upload the file using putToFiler - this will create the file with version metadata.
|
||||
// Versioned/suspended bucket → resolver returns 0 by construction;
|
||||
// pass 0 directly so the path is explicit at the call site.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, nil)
|
||||
//
|
||||
// Clear the prior latest-version pointer (and stamp the displaced
|
||||
// entry with NoncurrentSinceNs) inside the afterCreate callback so
|
||||
// it runs while withObjectWriteLock is still held in putToFiler.
|
||||
// Doing it after putToFiler returns would race a concurrent PUT
|
||||
// promoting a newer latest, which we'd then incorrectly wipe.
|
||||
etag, errCode, sseMetadata = s3a.putToFiler(r, filePath, body, bucket, normalizedObject, 1, 0, func(_ *filer_pb.Entry) s3err.ErrorCode {
|
||||
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject); err != nil {
|
||||
// Best-effort: a stale IsLatest flag is recoverable on the
|
||||
// next list-versions resync, so don't fail the PUT.
|
||||
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
|
||||
}
|
||||
return s3err.ErrNone
|
||||
})
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.Errorf("putSuspendedVersioningObject: failed to upload object: %v", errCode)
|
||||
return "", errCode, SSEResponseMetadata{}
|
||||
}
|
||||
|
||||
// Update all existing versions/delete markers to set IsLatest=false since "null" is now latest
|
||||
err = s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, normalizedObject)
|
||||
if err != nil {
|
||||
glog.Warningf("putSuspendedVersioningObject: failed to update IsLatest flags: %v", err)
|
||||
// Don't fail the request, but log the warning
|
||||
}
|
||||
|
||||
glog.V(2).Infof("putSuspendedVersioningObject: successfully created null version for %s/%s", bucket, object)
|
||||
|
||||
return etag, s3err.ErrNone, sseMetadata
|
||||
@@ -1341,6 +1347,21 @@ func (s3a *S3ApiServer) updateIsLatestFlagsForSuspendedVersioning(bucket, object
|
||||
// Clear the latest version metadata from .versions directory since "null" is now latest
|
||||
versionsEntry, err := s3a.getEntry(bucketDir, versionsObjectPath)
|
||||
if err == nil && versionsEntry.Extended != nil {
|
||||
// Capture previously-latest filename before clearing the pointer.
|
||||
prevLatestFileName := string(versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
|
||||
|
||||
// Stamp the demoted version BEFORE the .versions/ pointer
|
||||
// clear. The pointer clear emits a meta-log event the lifecycle
|
||||
// router consumes, then looks up the demoted version. If the
|
||||
// stamp isn't already on the entry, the router falls back to a
|
||||
// sibling-mtime derivation that can be wrong (versioned COPY
|
||||
// in particular keeps the source's mtime). Best-effort:
|
||||
// transient stamp-write failures are logged, lifecycle then
|
||||
// falls back to the legacy derivation.
|
||||
if prevLatestFileName != "" {
|
||||
s3a.markVersionNoncurrent(bucketDir, versionsObjectPath, prevLatestFileName, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
// Remove latest version metadata so all versions show IsLatest=false.
|
||||
// Also wipe cached list-metadata (size/mtime/etag/owner/delete-marker):
|
||||
// they were stamped from the prior latest, and stale cached mtime
|
||||
@@ -1480,6 +1501,28 @@ func (s3a *S3ApiServer) updateLatestVersionInDirectory(bucket, object, versionId
|
||||
if versionsEntry.Extended == nil {
|
||||
versionsEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
// Capture the previously-latest version's filename before overwriting
|
||||
// the pointer so the lifecycle engine can stamp NoncurrentSinceNs on
|
||||
// the demoted entry. Same-file overwrites (idempotent retries) are
|
||||
// detected by filename equality and skip the stamp.
|
||||
prevLatestFileName := string(versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey])
|
||||
|
||||
// Stamp the demoted entry BEFORE updating the .versions/ directory
|
||||
// pointer. The pointer-flip emits a meta-log event that the
|
||||
// lifecycle router consumes; that router then looks up the demoted
|
||||
// version. If the stamp isn't on the entry yet, the router falls
|
||||
// back to a sibling-mtime derivation that can be arbitrarily wrong
|
||||
// — versioned COPY is the clean break, since the new latest keeps
|
||||
// the source object's mtime instead of recording the demotion
|
||||
// moment. Stamping first closes that race.
|
||||
//
|
||||
// Best-effort: a transient stamp-write failure is logged but not
|
||||
// fatal; the lifecycle engine still falls back to the legacy
|
||||
// derivation in that case.
|
||||
if prevLatestFileName != "" && prevLatestFileName != versionFileName {
|
||||
s3a.markVersionNoncurrent(bucketDir, versionsObjectPath, prevLatestFileName, time.Now().UnixNano())
|
||||
}
|
||||
|
||||
versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey] = []byte(versionId)
|
||||
versionsEntry.Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte(versionFileName)
|
||||
|
||||
|
||||
@@ -38,6 +38,37 @@ func clearCachedVersionMetadata(extended map[string][]byte) {
|
||||
delete(extended, s3_constants.ExtLatestVersionIsDeleteMarker)
|
||||
}
|
||||
|
||||
// markVersionNoncurrent stamps ExtNoncurrentSinceNsKey on the named entry
|
||||
// inside .versions/. Called when a PUT or delete-marker demotes that entry
|
||||
// from current to noncurrent so the s3 lifecycle engine can compute
|
||||
// NoncurrentDays due time directly from the stamp instead of deriving it
|
||||
// from the next-newer sibling's mtime. demotionNs is captured once per
|
||||
// demotion event by the caller (typically time.Now().UnixNano()) and
|
||||
// passed in so concurrent demotions on the same object don't race for
|
||||
// a wall-clock read inside the helper.
|
||||
//
|
||||
// Idempotent on retries: if the key is already present, it is overwritten
|
||||
// with the new value. Out-of-order overwrites are bounded by the caller's
|
||||
// single-timestamp-per-event contract.
|
||||
func (s3a *S3ApiServer) markVersionNoncurrent(bucketDir, versionsObjectPath, fileName string, demotionNs int64) {
|
||||
if fileName == "" || demotionNs <= 0 {
|
||||
return
|
||||
}
|
||||
versionsDir := bucketDir + "/" + versionsObjectPath
|
||||
entry, err := s3a.getEntry(versionsDir, fileName)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("markVersionNoncurrent: skip %s/%s: %v", versionsDir, fileName, err)
|
||||
return
|
||||
}
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
entry.Extended[s3_constants.ExtNoncurrentSinceNsKey] = []byte(strconv.FormatInt(demotionNs, 10))
|
||||
if err := s3a.updateEntry(versionsDir, entry); err != nil {
|
||||
glog.V(2).Infof("markVersionNoncurrent: update %s/%s: %v", versionsDir, fileName, err)
|
||||
}
|
||||
}
|
||||
|
||||
// setCachedListMetadata caches list metadata in the .versions directory entry for single-scan efficiency
|
||||
func setCachedListMetadata(versionsEntry, versionEntry *filer_pb.Entry) {
|
||||
if versionEntry == nil || versionsEntry == nil {
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
# S3 Lifecycle (Design)
|
||||
|
||||
Replaces the current streaming + heap design with a daily meta-log replay. The worker becomes "start, do today's work, stop" — matching the operator's mental model and removing the per-shard heap that grows O(events × TTL_days).
|
||||
|
||||
## Goal
|
||||
|
||||
For each bucket lifecycle rule with TTL `D` days, delete every object whose age exceeds `D`, exactly once per day, with the worker exiting when the pass completes. No future-buffered Matches in memory. No tick-driven dispatch loop. Cluster-wide delete rate cap allocated per worker.
|
||||
|
||||
## Algorithm
|
||||
|
||||
One pass per day, per shard:
|
||||
|
||||
```text
|
||||
daily_run(shardID):
|
||||
persisted = load_cursor(shardID) // { TsNs, rule_set_hash, promoted_hash }
|
||||
earliest_available = metalog.EarliestAvailableTsNs(shardID)
|
||||
retention_window = duration(now - earliest_available) // time.Duration; sole window input to engine
|
||||
snap = engine.CurrentSnapshot() // base; per-action active/Mode reflect compile-time state, not partition
|
||||
replay, walk = snap.RulesForShard(shardID, retention_window)
|
||||
if replay == nil and walk == nil: return // bucket has no rules
|
||||
rsh = engine.ReplayContentHash(snap) // content over ExpirationDays/NoncurrentDays/AbortMPU rules; partition-independent
|
||||
promoted = engine.PromotedHash(snap, retention_window) // rules currently in walk due to scan_only
|
||||
|
||||
needs_recovery_walk = (
|
||||
persisted is fresh // cold start
|
||||
or persisted.rule_set_hash != rsh // replay-rule edit
|
||||
or persisted.promoted_hash != promoted // partition flip in either direction
|
||||
or (replay != nil and persisted.TsNs < earliest_available) // retention loss; meaningless if pure walker bucket
|
||||
)
|
||||
|
||||
if needs_recovery_walk:
|
||||
// Catch already-due objects across ALL rules — both walker-bound and
|
||||
// replay-bound. Replay-bound rules may have objects whose mtime is
|
||||
// older than (now - max_ttl) that the steady-state replay window cannot
|
||||
// reach. The recovery view force-activates every action so the walker
|
||||
// doesn't skip event-driven rules that the base snapshot has marked
|
||||
// inactive (e.g., pre-BootstrapComplete).
|
||||
walker.RunForShard(ctx, shardID, engine.RecoveryView(snap), limiter)
|
||||
if replay == nil:
|
||||
save_cursor(shardID, { TsNs: 0, rule_set_hash: rsh, promoted_hash: promoted })
|
||||
else:
|
||||
save_cursor(shardID, { TsNs: now - engine.MaxEffectiveTTL(replay), rule_set_hash: rsh, promoted_hash: promoted })
|
||||
return
|
||||
|
||||
// --- Steady-state path. ----------------------------------------------
|
||||
if walk != nil:
|
||||
walker.RunForShard(ctx, shardID, walk, limiter) // walker-bound actions only
|
||||
|
||||
if replay == nil:
|
||||
save_cursor(shardID, { TsNs: 0, rule_set_hash: rsh, promoted_hash: promoted })
|
||||
return
|
||||
|
||||
max_ttl = engine.MaxEffectiveTTL(replay)
|
||||
cursor = max(persisted.TsNs, now - max_ttl)
|
||||
done = {r: false for r in replay.activeRules()}
|
||||
last_ok = persisted.TsNs
|
||||
|
||||
for ev in metalog.from(shardID, cursor): // ascending TsNs
|
||||
if all(done.values()): break
|
||||
halt = false
|
||||
matches = router.Route(ctx, replay, ev, now, lister) // existing signature; replay is *engine.Snapshot
|
||||
for m in matches:
|
||||
r = replay.lookup(m.RuleHash)
|
||||
if r == nil or done[r]: continue
|
||||
if m.DueTime > now:
|
||||
done[r] = true // monotonic for replay kinds
|
||||
continue
|
||||
limiter.wait()
|
||||
outcome = dispatch_delete(m.Bucket, m.ObjectKey, m.VersionID,
|
||||
expected_mtime=m.Identity.mtime, ruleHash=m.RuleHash)
|
||||
if outcome is unresolved (RETRY_LATER, transport error after in-run retries, BLOCKED):
|
||||
halt = true; break
|
||||
if halt: break
|
||||
last_ok = ev.TsNs
|
||||
|
||||
save_cursor(shardID, { TsNs: last_ok, rule_set_hash: rsh, promoted_hash: promoted })
|
||||
```
|
||||
|
||||
Two distinct walker invocations, deliberately:
|
||||
|
||||
| Branch | Walker input | Why |
|
||||
|---|---|---|
|
||||
| Recovery (cold-start, replay-rule edit, retention loss, partition flip) | `engine.RecoveryView(snap)` — every action clone force-`markActive()`'d, `Mode` preserved | Catch already-due objects across all rules — including replay-bound rules whose subjects are older than `max_ttl` (replay scan window cannot reach), *and* event-driven rules the base snapshot may mark inactive (`compile.go:73-74` requires `BootstrapComplete`). |
|
||||
| Steady-state | `walk` (walker-only actions) | Replay handles its own rules via the meta-log scan. Walker only runs for actions that have no replay path. |
|
||||
|
||||
`router.Route` and `walker.RunForShard` keep their existing `*engine.Snapshot` parameter; `replay`, `walk`, and `snap` are all `*Snapshot` values.
|
||||
|
||||
The single API surface is:
|
||||
|
||||
```go
|
||||
// In engine:
|
||||
func CurrentSnapshot() *Snapshot // base
|
||||
func (s *Snapshot) RulesForShard(shardID int, retentionWindow time.Duration) (replay, walk *Snapshot)
|
||||
func RecoveryView(s *Snapshot) *Snapshot // every action force-activated; recovery walker only
|
||||
func ReplayContentHash(s *Snapshot) [32]byte // content over replay-eligible rules; partition-independent
|
||||
func PromotedHash(s *Snapshot, retentionWindow time.Duration) [32]byte // hash of replay-eligible rules currently in walk (scan_only)
|
||||
func MaxEffectiveTTL(s *Snapshot) time.Duration // max over active replay actions
|
||||
```
|
||||
|
||||
`RulesForShard` and `RecoveryView` both return new `*Snapshot` instances with cloned `*CompiledAction` objects and shared (by pointer) rule definitions. The fields that differ from the base are:
|
||||
|
||||
- **`active`** (per clone) — set per view.
|
||||
- **`Mode`** (per clone) — rewritten to `ModeEventDriven` on `replay` clones; preserved as-is on `walk` and `recovery` clones. The rewrite is required because `router.Route` gates on `Mode == ModeEventDriven` (`router.go:134, 253, 413, 479, 566, 623, 844`), and today's compile preserves a persistent `prior.Mode = ModeScanOnly` that would otherwise lock the action out of replay even after retention rehabilitates it.
|
||||
- **Action-map membership** — `replay`'s map contains only replay-eligible clones; `walk`'s contains only walker-bound clones; `recovery`'s contains every action.
|
||||
|
||||
Per-view settings are summarized in the table under "`router.Route` integration."
|
||||
|
||||
`router.Route` is the existing entry point — it computes `ComputeDueAt`, applies predicate filters, expands one event into 0+ `Match`es (e.g., a demoting PUT produces one for the new version's lifecycle and another for the displaced version's `NoncurrentDays`). The replay path delegates due-time math to the engine so all replay-eligible action kinds (`ExpirationDays`, `NoncurrentDays`, `AbortMPU`) are handled uniformly.
|
||||
|
||||
### `router.Route` integration
|
||||
|
||||
Today's `router.Route(ctx, snap *engine.Snapshot, ev, now, lister)` iterates every action with `IsActive() == true` in the snapshot. `IsActive` is **instance-level state on `*CompiledAction`** (`engine/compile.go:73-85`, `ca.markActive()`), so two snapshots can't disagree on activation if they share the same `*CompiledAction` pointers.
|
||||
|
||||
**Approach: views are independent `*Snapshot` instances with cloned `CompiledAction` objects.**
|
||||
|
||||
Two gating fields are instance-level on `*CompiledAction` and must both match what the downstream call site expects:
|
||||
|
||||
- `active` (`engine/compile.go:73-85`) — gates routing and walker iteration.
|
||||
- `Mode` — `router.Route` requires `Mode == engine.ModeEventDriven` at every emit site (`router.go:134, 253, 413, 479, 566, 623, 844`); the walker rejects only `Mode == engine.ModeDisabled` (`walker.go:147`). Today's compile preserves `prior.Mode`, so a rule previously promoted to `ModeScanOnly` will still be skipped by `router.Route` even if `active=true`.
|
||||
|
||||
`engine.Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)` returns two new `*Snapshot` instances. Each has its own `actions map[ActionKey]*CompiledAction` containing *clones* of the originals with **both `active` and `Mode` rewritten** per view. The partition predicate is "TTL ≤ retentionWindow" for replay membership; the engine does no clock arithmetic of its own — `retentionWindow` is the only window input it receives:
|
||||
|
||||
| View | Clone settings | Why |
|
||||
|---|---|---|
|
||||
| `replay` | `active = true`, `Mode = ModeEventDriven` | `router.Route` requires `ModeEventDriven`. Forced regardless of `prior.Mode`, so a rule previously stuck in `ModeScanOnly` is rehabilitated when retention now fits its TTL. |
|
||||
| `walk` | `active = true`, `Mode` preserved from original (any non-`ModeDisabled` is accepted by the walker) | Walker doesn't gate on a specific Mode value, so no rewrite needed beyond ensuring `active`. |
|
||||
| `recovery` (see below) | `active = true`, `Mode` preserved | Recovery walker iterates all action clones; preserving `Mode` lets each rule's evaluator do its normal predicate work. |
|
||||
|
||||
Shared-by-pointer with the base: `Rule` definitions, predicate maps, `RuleHash` table, and other immutable data — memory overhead is one `CompiledAction` struct per action per view (tens of bytes × dozens of actions, not megabytes).
|
||||
|
||||
Membership:
|
||||
|
||||
- `replay`: clones of `ExpirationDays`, `NoncurrentDays`, `AbortMPU` actions whose TTL ≤ `retentionWindow`. The Mode rewrite is what makes "rehabilitation" work — retention recovers, a previously `ModeScanOnly`-stuck rule clone now reads as `ModeEventDriven` in the replay view.
|
||||
- `walk`: clones of `ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, plus `scan_only`-promoted clones whose TTL exceeds `retentionWindow`.
|
||||
- Either return value may be `nil` if its partition is empty.
|
||||
|
||||
The daily replay loop calls `router.Route(ctx, replay, ev, now, lister)`. Steady-state walker calls `walker.RunForShard(ctx, shardID, walk, limiter)`. Both call sites are drop-in — they see the correct, per-partition set with the correct `(active, Mode)` for their gating logic.
|
||||
|
||||
**Recovery view (separate).** The recovery branch needs the walker to see **all** replay-eligible + walker-eligible actions as active, including event-driven actions that the base snapshot may have marked inactive (`compile.go:73-74`: event-driven actions require `BootstrapComplete`). Add:
|
||||
|
||||
```go
|
||||
func RecoveryView(s *Snapshot) *Snapshot
|
||||
```
|
||||
|
||||
`RecoveryView` is a third `*Snapshot` instance whose action clones are all `markActive()`'d, with `Mode` preserved from the original. The walker accepts any non-`ModeDisabled` Mode, so no rewrite is needed. The recovery branch calls `walker.RunForShard(ctx, shardID, engine.RecoveryView(snap), limiter)`. Without this, recovery would silently skip any rule the base snapshot considers inactive — defeating the recovery branch's purpose of catching already-due objects across the full rule set.
|
||||
|
||||
`RecoveryView` does not participate in steady-state. It exists only for the recovery walker invocation.
|
||||
|
||||
**`scan_only` input path.** The retention boundary used for promotion is supplied explicitly via `retentionWindow time.Duration`, not derived inside the engine. `daily_run` computes it once at run start (`retention_window = duration(now - metalog.EarliestAvailableTsNs(shardID))`) and passes it to `RulesForShard` and `PromotedHash`. The promotion decision is therefore stable across one `daily_run` invocation — a rule that flips between `replay` and `walk` mid-run does not re-route; it gets its new bucket on the next day's `RulesForShard` call. `RecoveryView` takes only the base snapshot — it activates everything, partition-independent.
|
||||
|
||||
This approach keeps `router.Route` and `walker.Run` signatures unchanged. The trade-off is cloning `CompiledAction` per view (and rewriting `Mode` in the replay view); the alternative (adding a filter parameter to `Route` or restructuring `IsActive`/`Mode` to be view-scoped) would force every call site — including the streaming dispatcher during Phase 2/3 — to thread the filter, while clone-per-view localizes the partition decision to the engine. The Mode rewrite also bypasses today's persistent `prior.Mode = ModeScanOnly` lock-in, which is now obsoleted by the new partition logic.
|
||||
|
||||
Why correct:
|
||||
|
||||
- Meta-log is TsNs-ordered. For any rule `R`, `due_time` is also monotonic in TsNs (see "Due-time source"), so the first not-yet-due event for `R` proves every later event is also not-yet-due. Hence the `done` flag.
|
||||
- Multiple rules fan out on the same scan: one meta-log read, N predicate checks per event.
|
||||
- Identity drift (object overwritten between event and delete) is caught at the RPC by the existing `LifecycleDelete` identity-CAS, which returns `NOOP_RESOLVED` for stale events. The algorithm dispatches optimistically and lets the server filter.
|
||||
|
||||
### Action kinds and dispatch paths
|
||||
|
||||
The engine defines six action kinds (`weed/s3api/s3lifecycle/action_kind.go`). Each has a distinct trigger and due-time semantics, and they split into two dispatch paths. Replay path uses meta-log iteration with the `done` early-stop; walker path lists current bucket state.
|
||||
|
||||
| ActionKind | Trigger | Due time | Path | Early-stop? |
|
||||
|---|---|---|---|---|
|
||||
| `ExpirationDays` | Latest-version PUT | `ev.TsNs + r.ExpirationDays` | Replay | Yes — `due` strictly increasing in iteration order |
|
||||
| `NoncurrentDays` | Demotion (next PUT for same key) | `entry.noncurrent_since + r.NoncurrentDays` | Replay | Yes — `noncurrent_since` is the demoting event's TsNs (see "`noncurrent_since`" below), monotonic |
|
||||
| `AbortMPU` | MPU init | `mpu_init.TsNs + r.AbortMPUDaysAfterInitiation` | Replay | Yes — same monotonicity as `ExpirationDays` |
|
||||
| `ExpirationDate` | Latest-version PUT, fired on `now >= r.ExpirationDate` | `r.ExpirationDate` (constant) | Walker | n/a — fixed wall-clock date, fires once per object |
|
||||
| `ExpiredDeleteMarker` | Delete marker with `NumVersions == 1` (no remaining siblings) | "now if orphaned, else never" — depends on current bucket state, not event age | Walker | n/a — requires sibling lookup, not derivable from event TsNs |
|
||||
| `NewerNoncurrent` | Version becomes noncurrent AND total noncurrents > `r.NewerNoncurrentVersions` | "now if over the count cap, else never" — count is current state | Walker | n/a — requires version-list lookup |
|
||||
|
||||
Why `ExpiredDeleteMarker` and `NewerNoncurrent` are walker-only:
|
||||
|
||||
Both rules' "due time" depends on the *current* state of sibling versions, not on any single event's timestamp. Modeling them as replay would force a sibling-list lookup on every meta-log event for the matching keys (today's `router.Route` does exactly this), and the `done` early-stop would never engage because the trigger condition isn't event-time-monotonic. They fit the walker far better: list each key's versions once per day, evaluate the rule against current state, emit deletes. Today's `bootstrap/walker.go` already handles them via `EvaluateAction`.
|
||||
|
||||
`expected_mtime` passed to `LifecycleDelete` is always the entry's original mtime (used for identity CAS), regardless of action kind. The TTL clock and the CAS identity are separate concerns.
|
||||
|
||||
### Rule changes
|
||||
|
||||
Rule changes invalidate the persisted cursor's assumption that "everything older has already been processed under the same rules." The algorithm tracks `rule_set_hash` alongside the cursor and forces a bootstrap walk on mismatch. Cases this covers:
|
||||
|
||||
- New rule added → walker discovers existing objects under the new rule.
|
||||
- TTL increased (e.g. 30d → 60d) → walker discovers objects in `[now-60d, now-30d]` that were skipped while the old rule ran.
|
||||
- Predicate widened (prefix/tag filter change) → walker re-evaluates everything.
|
||||
- TTL decreased / predicate narrowed → walker still runs (harmless re-evaluation), but the next daily run picks up steady-state quickly.
|
||||
|
||||
Bootstrap walker on rule change is a one-shot full bucket list. Cost is proportional to bucket size, not history; acceptable as an infrequent event.
|
||||
|
||||
### Bootstrap retention window
|
||||
|
||||
The walker only deletes objects whose age already exceeds their TTL. Not-yet-due objects are intentionally left for the meta-log path. If the post-walker cursor were set to `now`, the next daily replay would scan from `now` forward and never see the PUT event for, say, a 20-day-old object under a 30-day rule — that event sits at `TsNs ≈ now - 20d`, before the cursor.
|
||||
|
||||
The cursor is therefore reset to `now - max_ttl` (excluding `ScanAtDate` rules from `max_ttl`, since those don't use the replay path). The clamp `max(persisted, now - max_ttl)` in the steady-state algorithm preserves the sliding window: each day the effective scan range is `[now - max_ttl, now]`, and not-yet-due events surface naturally as they age in.
|
||||
|
||||
Invariant this depends on: **meta-log retention ≥ max_ttl**. If retention is shorter, events for some still-pending objects age out before they become due. Detected at run start by comparing the meta-log's earliest available TsNs against `now - max_ttl`; if the gap is non-empty, the affected rules are flagged `scan_only` for that run and routed to the walker (see "Scan-at-date and scan-only paths").
|
||||
|
||||
### Replay vs walker: single source of truth
|
||||
|
||||
`Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)` is the **only** place that decides which path each compiled action takes during steady state. Both return values are new `*Snapshot` instances containing cloned `*CompiledAction` values with per-partition `active` flags (see "`router.Route` integration" for why cloning is required); either may be `nil` when its partition is empty. Every other component (`daily_run`, the walker invocation, the cursor's `RuleSetHash`, the `max_ttl` calculation) reads through these views. A given compiled action's clone has `active=true` in exactly one of `replay` or `walk`:
|
||||
|
||||
| Reason for walker | Engine signal |
|
||||
|---|---|
|
||||
| `ExpirationDate` (`ModeScanAtDate`) | `compile.go:73` sets `mode == ModeScanAtDate` |
|
||||
| `ExpiredDeleteMarker` | Action kind requires sibling count |
|
||||
| `NewerNoncurrent` | Action kind requires version count |
|
||||
| `scan_only` (TTL > meta-log retention) | `event_log_horizon.go` check against earliest available TsNs at run start |
|
||||
|
||||
Everything else (`ExpirationDays`, `NoncurrentDays`, `AbortMPU` when TTL fits in retention) is on the replay list.
|
||||
|
||||
The `effective_ttl` per active replay action — used by `engine.MaxEffectiveTTL(replay)` — is:
|
||||
|
||||
- `ExpirationDays.ExpirationDays`
|
||||
- `NoncurrentDays.NoncurrentDays`
|
||||
- `AbortMPU.AbortMPUDaysAfterInitiation`
|
||||
|
||||
Walker actions don't appear as active in `replay`, so they naturally contribute nothing to `MaxEffectiveTTL` — the cursor sliding window only governs replay.
|
||||
|
||||
If `snap.replay` is empty (e.g., a bucket whose only rule is `ExpirationDate`), the cursor's `TsNs` is recorded as `0` (or any sentinel) and never read; only `RuleSetHash` matters, so a future addition of a replay rule is detected and triggers the rewind branch. The walker still runs every day for the walker rules.
|
||||
|
||||
### Cursor hashes: `RuleSetHash` and `PromotedHash`
|
||||
|
||||
The cursor stores two hashes. Together they detect every situation that invalidates the cursor's "everything before persisted.TsNs has been processed under the same rules" assumption.
|
||||
|
||||
**`RuleSetHash = engine.ReplayContentHash(snap)`** — content over the rule definitions (action kind, predicate, TTL value) of replay-eligible action kinds (`ExpirationDays`, `NoncurrentDays`, `AbortMPU`) in the base snapshot. Partition-independent.
|
||||
|
||||
**`PromotedHash = engine.PromotedHash(snap, retentionWindow)`** — hash of the set of replay-eligible rules that are currently classified as `walk` due to `scan_only` (their TTL exceeds `retentionWindow`). Changes when retention shifts move rules between partitions, even if XML rules and their content are unchanged.
|
||||
|
||||
Why two hashes: a replay-cursor rewind is needed when either the rule definitions change *or* when a rule transitions between partitions in either direction.
|
||||
|
||||
- Promotion (replay → walk, retention dropped): the promoted rule's meta-log events for in-flight objects are no longer reachable. Walker must take over for that rule. Cursor for other replay rules is fine, but the recovery branch's full-rule-set walk is still the safest catch-up — `PromotedHash` change triggers it.
|
||||
- Demotion (walk → replay, retention recovered): the rule's events are now reachable again in meta-log. **But persisted.TsNs may be forward of where the rule's relevant events live**, because other replay rules kept the cursor advancing while this rule was in walk. The `persisted.TsNs < earliest_available` check does not catch this — that check fires only on retention regression. Demotion is detected by `PromotedHash` change.
|
||||
|
||||
Recovery triggers, complete list:
|
||||
|
||||
| Trigger | Detection | Why |
|
||||
|---|---|---|
|
||||
| Cold start | No persisted cursor | First run |
|
||||
| Replay-rule edit | `RuleSetHash` mismatch | Content of replay-eligible rules changed |
|
||||
| Retention loss | `replay != nil && persisted.TsNs < earliest_available` | Worker was down or retention shrank past cursor. Gated on `replay != nil` so the TsNs sentinel (`0`) used by pure walker buckets doesn't perpetually trigger recovery. |
|
||||
| Partition flip | `PromotedHash` mismatch | A replay-eligible rule moved between `replay` and `walk` |
|
||||
|
||||
Walker-only rule edits (`ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, or any rule with no replay-eligible action kind) do not change either hash. They are picked up by the steady-state `walk` invocation; replay cursor is untouched.
|
||||
|
||||
Practical consequences:
|
||||
|
||||
- Adding/removing/modifying a walker-only rule: both hashes unchanged, replay cursor untouched.
|
||||
- Retention drops (replay rule promotes to walk): `RuleSetHash` unchanged, `PromotedHash` changes → recovery fires. Walker over base catches already-due objects; cursor rewinds for replay continuity.
|
||||
- Retention recovers (rule demotes back to replay): `RuleSetHash` unchanged, `PromotedHash` changes → recovery fires. The demoted rule's events get a fresh scan window via the rewind.
|
||||
- Editing a replay-eligible XML rule: `RuleSetHash` changes → recovery fires. Walker covers the full rule set; already-due objects under the new rule are caught.
|
||||
|
||||
### Shard-aware walker
|
||||
|
||||
Today's walker (`bootstrap/walker.go`) is bucket-wide: it lists every entry under a bucket and emits matches regardless of `ShardID`. Shards are derived as `sha256(bucket||"/"||key) >> 252` (`weed/s3api/s3lifecycle/shard.go:23`), so a single bucket's objects spread across all 16 shards.
|
||||
|
||||
Daily replay is per-shard, so a per-shard `daily_run(shardID)` invoking the bucket-wide walker would have all 16 shards re-walk every bucket — 16× the filer listing cost, 16× the duplicate delete RPCs (idempotent but wasteful and noisy in metrics).
|
||||
|
||||
Two paths are workable; the design picks the simpler one and notes the optimization:
|
||||
|
||||
1. **Shard-filtering walker (chosen).** Add `walker.RunForShard(shardID int, ...)`. The walker still does one full bucket listing, but for each entry it computes `ShardID(bucket, key)` and skips entries not in the target shard. Cost: still 1 listing per shard per bucket = 16× listing total. Simpler; no coordination across workers. Acceptable for buckets up to ~100M entries where listing is cheap relative to deletes.
|
||||
2. **Bucket-coordinated walker (future).** A separate coordinator (e.g., the worker that owns shard 0 for that bucket) runs the walker once, routing emitted matches to each shard's local injection point. 1 listing per bucket total. Requires a coordination layer that today's plugin/worker model doesn't have. Tracked as an optimization, not blocking.
|
||||
|
||||
Path #1 is wire-compatible with today's walker — only the iteration filter changes. `RunForShard` is a thin wrapper that takes a shard predicate; the existing `Run(bucket)` becomes `RunForShard(shard, bucket)` with `shard == any`.
|
||||
|
||||
### Delete failure handling
|
||||
|
||||
Cursor advance is gated on success. The cursor only moves past events whose deletes returned `DONE`, `NOOP_RESOLVED`, or `SKIPPED_OBJECT_LOCK` (lock-protected, but rule semantics are satisfied). Any other outcome — `RETRY_LATER`, `BLOCKED`, or transport error after in-run retries — halts the run and persists the cursor at the last fully-processed event.
|
||||
|
||||
Semantics:
|
||||
|
||||
- **Head-of-line blocking is intentional.** A transient filer error stalls the rest of today's pass; tomorrow's run resumes at the same cursor and retries from the failing event. This is loud — operator sees a stuck cursor in metrics — and idempotent (identity-CAS makes any redundant delete a no-op).
|
||||
- **In-run retry with backoff** for transport errors only (default 3 attempts, exponential backoff). Server-side outcomes (`RETRY_LATER`, `BLOCKED`) are not retried in-run; the server already classified them as "wait until next run."
|
||||
- **No separate retry queue.** Removing the per-key freeze state was the whole point — adding it back would re-introduce the state machine this design replaces.
|
||||
|
||||
## Data model changes
|
||||
|
||||
### `noncurrent_since` on version entries
|
||||
|
||||
A non-current version's TTL clock starts when the next version was written, not at its own mtime. Today there's no field for that timestamp; the engine has to derive it by joining successive PUTs for the same key.
|
||||
|
||||
Change: at the S3 PUT handler that demotes a prior version (current → noncurrent), write `noncurrent_since` on the demoted entry **to the TsNs of the demoting event**, not local wall-clock. The demoting event is itself a meta-log PUT with a well-defined TsNs; using that value keeps `noncurrent_since` strictly monotonic in meta-log order across all replicas and immune to wall-clock skew between S3 handler nodes.
|
||||
|
||||
The lifecycle evaluator uses `ev.TsNs` for current-version rules and `entry.noncurrent_since` for noncurrent rules — both monotonic in the iteration order, so the algorithm's `done` flag still holds. `expected_mtime` (passed to `LifecycleDelete` for identity CAS) remains the entry's own mtime; CAS identity and TTL clock are kept separate.
|
||||
|
||||
### Cursor
|
||||
|
||||
Per-shard cursor is `{ TsNs int64, RuleSetHash [32]byte, PromotedHash [32]byte }`. No frozen-cursor set, no per-key freeze state — failed deletes halt the run and leave the cursor at the last successful event (see "Delete failure handling"). `RuleSetHash` and `PromotedHash` together gate recovery — mismatch on either triggers the recovery branch on the next run. See "Cursor hashes."
|
||||
|
||||
## Components
|
||||
|
||||
| Component | Status |
|
||||
|---|---|
|
||||
| `engine/` (rule compilation, snapshot) | Keep |
|
||||
| `evaluate.go`, `due_at.go`, `rule_hash.go`, `tags.go` | Keep |
|
||||
| `reader/` (meta-log subscribe) | Keep, used once per daily pass instead of continuously |
|
||||
| `router/router.go` (rule evaluation per event) | Keep, callable in the per-event loop |
|
||||
| `router/schedule.go` (heap) | **Remove** |
|
||||
| `dispatcher/dispatcher.go` (tick, retries, freeze) | **Remove**; per-call `LifecycleDelete` moves into the daily loop |
|
||||
| `dispatcher/pipeline.go` | **Replace** with `daily_run` per shard |
|
||||
| `scheduler/scheduler.go` (long-running goroutines + refresh ticker) | **Replace** with one-shot per-shard fan-out |
|
||||
| `bootstrap/walker.go` | Keep, with shard filter added (`RunForShard`). Two invocation modes: (a) **steady-state daily** against the `walk` view (`ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, `scan_only` rules); (b) **recovery** against `engine.RecoveryView(snap)` (cold start, replay-rule edit, retention loss, partition flip). No longer feeds an in-memory schedule. |
|
||||
|
||||
## Rate limiting
|
||||
|
||||
Cluster-wide deletes-per-second cap, set as admin config. Admin computes per-worker share at job-dispatch time:
|
||||
|
||||
- Admin counts workers capable of `s3_lifecycle` from the registry, divides `cluster_deletes_per_second` by the count, writes the share into `ExecuteJobRequest.ClusterContext.Metadata["s3_lifecycle.deletes_per_second"]`.
|
||||
- Worker reads the share and constructs one `golang.org/x/time/rate.Limiter` shared across all shard goroutines. `dispatch_delete` calls `limiter.Wait(ctx)` before each RPC.
|
||||
- Brief over/undershoot during worker join/leave is acceptable for a bulk workload.
|
||||
|
||||
No proto changes: `ClusterContext.Metadata` already exists.
|
||||
|
||||
## Failure & recovery
|
||||
|
||||
- **Worker crashes mid-run.** Cursor advances only past successfully-deleted events (see "Delete failure handling"); on restart the next run resumes at the same cursor and re-attempts. Identity-CAS makes redundant deletes no-ops.
|
||||
- **Transient delete failure.** Run halts at the failing event, cursor stays. Tomorrow's run retries from the same point. Stuck cursor is visible in metrics — operators see head-of-line blocking and address root cause.
|
||||
Four triggers route into the same **recovery branch** (cold-start, replay-rule edit, retention loss, partition flip). All four run the walker against `engine.RecoveryView(snap)` (every action force-`markActive()`'d, regardless of compile-time `IsActive`/`BootstrapComplete`) to catch already-due objects across the full rule set, then rewind the cursor to `now - MaxEffectiveTTL(replay)` (or sentinel `0` if replay is empty). The merge is by design: distinguishing the four would require independent state that isn't worth the complexity, and the walker is idempotent.
|
||||
|
||||
- **Cold start (no persisted cursor).** Recovery branch.
|
||||
- **Replay-rule edit** (new/removed/changed `ExpirationDays`, `NoncurrentDays`, or `AbortMPU` rule). Detected by `RuleSetHash` mismatch. Recovery branch.
|
||||
- **Retention loss** (`replay != nil && persisted.TsNs < earliest_available`). Worker was down longer than meta-log retention, or retention itself shrunk. Gated on `replay != nil` so the sentinel `TsNs=0` used by pure walker buckets doesn't perpetually re-trigger recovery. Recovery branch.
|
||||
- **Partition flip** (`PromotedHash` mismatch — a replay-eligible rule moved between `replay` and `walk` since last run). Covers both directions:
|
||||
- Promotion (replay → walk, retention dropped): walker takes over for that rule. Recovery fires to refresh state.
|
||||
- Demotion (walk → replay, retention recovered): persisted.TsNs is likely forward of the rule's relevant events (other replay rules kept advancing during the walk era). Recovery rewinds the cursor so the demoted rule's events get a fresh scan window.
|
||||
- **Walker-only rule edit** (added/removed/modified `ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, or any rule with no replay-eligible action kind). Not a recovery trigger — both hashes unchanged, cursor untouched. Walker re-reads `walk` on every steady-state run and applies the new rule automatically.
|
||||
- **`ExpirationDate` rules.** Always routed to the walker — fixed wall-clock due time can't be derived from event TsNs, and objects created before the date may have aged out of meta-log. See "Replay vs walker."
|
||||
- **Identity drift.** Handled by `LifecycleDelete` RPC as today. No worker-side state needed.
|
||||
|
||||
## Comparison
|
||||
|
||||
| | Streaming (today) | Daily replay (this design) |
|
||||
|---|---|---|
|
||||
| Worker lifetime | Long-running, capped by `MaxRuntime` | Starts, completes pass, exits |
|
||||
| Memory | O(events with DueTime in `[now, now+TTL]`) | O(in-flight delete RPCs) |
|
||||
| Disk reads | Continuous meta-log subscribe + periodic bootstrap | One meta-log scan per day, length ≤ max_ttl |
|
||||
| Latency | DispatchTick (~1 min) | Up to 24h |
|
||||
| Future-buffering | Yes, in heap | No |
|
||||
| State persisted | Cursor + frozen set + heap (rebuilt from meta-log on restart) | Cursor only |
|
||||
| Dispatch tick / checkpoint tick / refresh tick | Required | Removed |
|
||||
| Bootstrap walker | Hot path (every run, feeds heap) | Daily for `walk` rules; recovery for full rule set |
|
||||
| Failure recovery | Heap rebuild from meta-log replay | Cursor advance |
|
||||
|
||||
## Configuration changes
|
||||
|
||||
The admin and worker forms collapse significantly. New worker config:
|
||||
|
||||
```text
|
||||
deletes_per_run_concurrency // optional, in-pass parallelism (default 1)
|
||||
max_runtime_minutes // safety cap; default 1440 (24h)
|
||||
```
|
||||
|
||||
Removed worker config (no longer meaningful):
|
||||
|
||||
```text
|
||||
dispatch_tick_minutes
|
||||
checkpoint_tick_seconds
|
||||
refresh_interval_minutes
|
||||
bootstrap_interval_minutes
|
||||
```
|
||||
|
||||
New admin config (added to the existing form):
|
||||
|
||||
```text
|
||||
cluster_deletes_per_second // 0 = unlimited
|
||||
cluster_deletes_burst // 0 = 2× rps
|
||||
```
|
||||
|
||||
Admin runtime stays at `DetectionIntervalMinutes=1440` (daily detection produces one execution per worker).
|
||||
|
||||
---
|
||||
|
||||
## Implementation phases
|
||||
|
||||
Sequenced so each phase compiles and ships independently. Phase 1 lands first because it's a prerequisite the algorithm relies on; phases 2–4 can be authored in parallel but should merge in order.
|
||||
|
||||
### Phase 1 — `noncurrent_since` on version entries
|
||||
|
||||
Smallest, isolated, prerequisite.
|
||||
|
||||
- Add `NoncurrentSinceNs int64` to the filer entry extended attributes (or as a top-level field if the proto allows non-breaking add).
|
||||
- At the S3 PUT handler in `weed/s3api/s3api_object_handlers_put.go` (or whichever site demotes the prior current version), set `NoncurrentSinceNs` to the **TsNs of the demoting meta-log event**, not `time.Now().UnixNano()`. Read the value from the in-flight write's TsNs (the filer assigns this) — coordinate with the filer write API to make that value available to the demotion path. If the API can't surface it cleanly, fall back to a single `time.Now().UnixNano()` captured at the start of the demoting RPC, accepting that this introduces sub-millisecond skew relative to meta-log TsNs (still monotonic per node, weakly monotonic across nodes within clock-sync tolerance).
|
||||
- Backfill: nil/zero on existing entries — the lifecycle evaluator treats `NoncurrentSinceNs == 0` as "fall back to entry mtime" so legacy data still expires, just with the old (slightly looser) semantics.
|
||||
- Unit tests in the s3api package covering PUT-over-existing and PUT-with-versioning-suspended.
|
||||
- Verify with a clock-skew test: two S3 nodes with ±5s clock drift produce a sequence of PUT/demotion events; assert `noncurrent_since` is non-decreasing in meta-log iteration order.
|
||||
|
||||
### Phase 2 — Daily-replay worker (parallel to today's, behind a flag)
|
||||
|
||||
Add the new code path without disturbing the existing one. Allows side-by-side smoke testing.
|
||||
|
||||
- New file `weed/s3api/s3lifecycle/dailyrun/dailyrun.go` with `func Run(ctx, shardID, ...) error` implementing the algorithm.
|
||||
- Reuses `engine.Snapshot`, `evaluate.go`, `due_at.go`, the existing `reader.Reader`, and the existing `LifecycleDelete` RPC. No new RPCs.
|
||||
- Per-shard cursor type `dailyrun.Cursor { TsNs int64; RuleSetHash [32]byte; PromotedHash [32]byte }`, JSON-persisted under the same filer path as today's cursor, keyed by `daily/` prefix to avoid collision. Cursor load returns `(cursor, isFresh bool)` so the algorithm can distinguish first-run from a rule-change rewrite. In Phase 2 (no walker plumbing), `PromotedHash` is always the empty hash; Phase 4 wires `engine.PromotedHash(snap, retentionWindow)` and the partition-flip recovery trigger.
|
||||
- **Replay/walker partition**: full `RulesForShard` / `RecoveryView` plumbing lands in Phase 4. For Phase 2 alone, since walker rules are rejected (next bullet), Phase 2 is **replay-only**: pass the **base snapshot** directly to `router.Route` (no view, no clone, no Mode rewrite). This is acceptable for Phase 2 because the unsupported-rule check guarantees no walker-bound actions are present, and the absence of walker rules means there's no risk of router.Route emitting walker-bound matches. Mode rewrite is also unnecessary in Phase 2: any rule that compiled to `ModeScanOnly` (legacy persistent state) falls into the unsupported-rule path along with `scan_only`-promoted rules. Phase 4 then introduces clone-per-view (including Mode rewrite) and the recovery branch.
|
||||
- **Refuse to run on unsupported rule sets.** Before invoking the replay loop, `dailyrun.Run` checks the compiled rules for any action of kind `ExpirationDate`, `ExpiredDeleteMarker`, `NewerNoncurrent`, or any rule promoted to `scan_only`. If any are present, the handler:
|
||||
- Logs at error level which rules are unsupported.
|
||||
- Returns a typed error from `Execute` so admin marks the run failed (visible in the activity log).
|
||||
- Does **not** advance the cursor.
|
||||
This makes flipping `algorithm: daily_replay` before Phase 4 a loud failure, not a silent dropped rule. Operators see the error and either revert to `streaming` or wait for Phase 4.
|
||||
- **Rule-change handling**: compute `rsh = engine.ReplayContentHash(snap)` at run start (partition-independent — see "Cursor hashes"). If `rsh != cursor.RuleSetHash` and `replay` is non-`nil`, persist `{ TsNs: now - MaxEffectiveTTL(replay), RuleSetHash: rsh, PromotedHash: promoted }` and return. If `replay` is `nil`, persist `{ TsNs: 0, RuleSetHash: rsh, PromotedHash: promoted }` and return. In Phase 2, `promoted` is the empty hash (no walker plumbing); Phase 4 wires real values. All cursor writes carry all three fields so Phase 4 doesn't have to migrate existing Phase 2 cursors. Tested explicitly: add a replay-eligible rule mid-test, assert cursor TsNs rewinds to `now - max_ttl` and `RuleSetHash` updates.
|
||||
- **Delete failure handling**: track `last_ok TsNs` as the algorithm progresses; only set `last_ok = ev.TsNs` after a successful or `NOOP_RESOLVED` outcome for *all* matches produced from that event. On any unresolved outcome (`RETRY_LATER`, `BLOCKED`, transport error after in-run retries), break the loop and persist `{ TsNs: last_ok, RuleSetHash: rsh, PromotedHash: promoted }`. In-run retry policy for transport errors: 3 attempts with exponential backoff capped at 5s.
|
||||
- **Match expansion**: invoke `router.Route(ctx, snap, ev, now, lister)` per event, where `snap` is the **base snapshot** directly (Phase 2 is replay-only — see "Replay/walker partition" bullet above; the view-based call site `router.Route(ctx, replay, ev, ...)` lands in Phase 4 when the partition is wired). Handles `ExpirationDays`, `NoncurrentDays`, `AbortMPU` correctly out of the box (already in `due_at.go`).
|
||||
- Rate limiter accepted as a parameter; constructed once per `Execute()` and shared across all shard goroutines.
|
||||
- New admin config flag `algorithm: streaming | daily_replay` in `weed/worker/tasks/s3_lifecycle/handler.go`. When `daily_replay`, the handler invokes `dailyrun.Run` and exits. When `streaming` (default), today's code path runs unchanged.
|
||||
- Unit tests:
|
||||
- Per-rule `done` flag correctness (single rule, multi-rule).
|
||||
- Multiple-match fan-out from one event (PUT-over-existing emits both `ExpirationDays` for the new version and `NoncurrentDays` for the displaced one).
|
||||
- Cursor advance halts at the first unresolved failure; subsequent run resumes there.
|
||||
- Identity-CAS skip path (event mtime stale → `NOOP_RESOLVED` still advances cursor).
|
||||
- Rule-set-hash mismatch rewinds cursor to `now - max_ttl` (Phase 4 adds the walker call on this path; Phase 2 just rewinds).
|
||||
- `replay` empty case: cursor persists `{ TsNs: 0, RuleSetHash: rsh, PromotedHash: <empty in Phase 2> }`, no meta-log read attempted.
|
||||
- `NoncurrentDays` rule uses `entry.noncurrent_since`, `ExpirationDays` rule uses `ev.TsNs`; both monotonic in iteration order.
|
||||
- `AbortMPU` test: MPU init event ages past `AbortMPUDaysAfterInitiation`, delete emitted.
|
||||
- **Unsupported-rule rejection**: bucket has an `ExpirationDate` (or `ExpiredDeleteMarker` or `NewerNoncurrent`) rule and the flag is set to `daily_replay`. Assert `Execute` returns the typed unsupported-rule error, the cursor is not advanced, and the streaming code path was not invoked. Repeat for a rule promoted to `scan_only`.
|
||||
|
||||
### Phase 3 — Cluster rate limit allocation
|
||||
|
||||
Admin-side share computation. Lands once Phase 2 has a working `Limiter` parameter to receive it.
|
||||
|
||||
- `weed/worker/tasks/s3_lifecycle/handler.go`: add `cluster_deletes_per_second`, `cluster_deletes_burst` to `AdminConfigForm.Sections["scope"]`.
|
||||
- `weed/admin/plugin/plugin.go` near `RunDetectionRequest`/`ExecuteJobRequest` build sites: count capable workers, divide rps, write `s3_lifecycle.deletes_per_second` and `s3_lifecycle.deletes_burst` into `ClusterContext.Metadata`.
|
||||
- Worker `Execute`: parse metadata keys, build `rate.Limiter`, pass to `dailyrun.Run`.
|
||||
- New histogram `S3LifecycleDispatchLimiterWaitSeconds` for operator visibility.
|
||||
- Tests: admin allocation math under join/leave, worker correctly slows under low share.
|
||||
|
||||
### Phase 4 — Shard-aware walker + scan-at-date / scan-only routing
|
||||
|
||||
Reposition the walker and add shard-filtering + per-rule routing.
|
||||
|
||||
- **Shard filter on the walker.** Add `walker.RunForShard(ctx context.Context, shardID int, view *engine.Snapshot, limiter *rate.Limiter) error`. `view` is one of `walk`/`replay`/`recovery` views — its action set already filters to the right partition (via per-clone `active` flags), so the walker iterates the bucket and evaluates each entry against `view` exactly as today's `Run` does, with the only added step being `if ShardID(bucket, entry.Name) != shardID { continue }`. The existing bucket-wide `Run` becomes `RunForShard` with `shardID = -1` (any) for backward compatibility, or is deleted outright in Phase 5.
|
||||
- **Engine surface.** Four new exports on the engine package, all consumed by `daily_run`:
|
||||
- `func (s *Snapshot) RulesForShard(shardID int, retentionWindow time.Duration) (replay, walk *Snapshot)`. Returns two new `*Snapshot` instances with **cloned `*CompiledAction`** values; per-view `active` flags (and `Mode` rewrite on `replay`) determine partition membership. Shared-by-pointer with the base: `Rule` definitions, predicate maps, `RuleHash` table. Either return value may be `nil` when its partition is empty. The retention window is an explicit input — `daily_run` computes it once at run start as `duration(now - metalog.EarliestAvailableTsNs(shardID))` and passes it in. The engine does no clock arithmetic of its own. The partition is stable across one `daily_run` invocation. Membership:
|
||||
- **`replay`**: cloned `ExpirationDays`, `NoncurrentDays`, `AbortMPU` actions, `active=true`, where the action's TTL ≤ `retentionWindow`.
|
||||
- **`walk`**: cloned `ExpirationDate` (`ModeScanAtDate`), `ExpiredDeleteMarker`, `NewerNoncurrent` actions, plus any of the above promoted to `scan_only` because their TTL exceeds the retention boundary. All `active=true`.
|
||||
- A single XML rule that compiles to multiple action kinds (e.g., `ExpirationDays` + `NewerNoncurrent` on the same rule) is split: each compiled action lands in `replay` or `walk` independently. `ReplayContentHash` only hashes replay-eligible rule definitions from the base snapshot, so neither the `NewerNoncurrent` action nor any walker-only edit affects the hash.
|
||||
- `func RecoveryView(s *Snapshot) *Snapshot`. Returns a third `*Snapshot` instance with every action cloned and `markActive()`'d — regardless of `Mode` or prior `BootstrapComplete` state. The recovery walker uses this view to see all replay-eligible + walker-eligible rules. Without it, recovery would skip event-driven actions the base snapshot marks inactive (`compile.go:73-74`).
|
||||
- `func ReplayContentHash(s *Snapshot) [32]byte`. Stable across reorderings, partition-independent. Used as `RuleSetHash = ReplayContentHash(snap)`. Returns the empty hash when no replay-eligible rules exist. See "Cursor hashes."
|
||||
- `func PromotedHash(s *Snapshot, retentionWindow time.Duration) [32]byte`. Hash of the set of replay-eligible rules currently classified as `walk` due to `scan_only` (TTL > `retentionWindow`). Detects partition flips in either direction. Takes the same `retentionWindow` value as `RulesForShard` so the two cannot disagree about partition membership. See "Cursor hashes."
|
||||
- `func MaxEffectiveTTL(s *Snapshot) time.Duration`. Max over active replay actions; returns `0` for `nil` or empty replay (caller must already be in the empty-replay branch).
|
||||
- `func CurrentSnapshot() *Snapshot`. The base snapshot before partitioning. Recovery branch passes this to `RecoveryView`.
|
||||
- **`dailyrun.Run` flow.** Cold-start, replay-rule edit (`RuleSetHash` mismatch), retention loss, and partition flip (`PromotedHash` mismatch) all route into the **recovery branch**: walker over `engine.RecoveryView(snap)` so already-due objects across all rules are caught (including event-driven actions the base snapshot may mark inactive), then cursor rewinds. Steady-state path runs walker over `walk` only, then replay over `replay`. Cursor stores `{ TsNs, RuleSetHash, PromotedHash }`; steady-state writes both hashes through unchanged.
|
||||
- **Recovery branch.** Triggered by any of: no persisted cursor, `RuleSetHash` mismatch, `PromotedHash` mismatch, or `replay != nil && persisted.TsNs < earliest_available`. The retention-loss trigger uses the **absolute** `earliest_available` TsNs (the oldest available meta-log TsNs from `metalog.EarliestAvailableTsNs(shardID)`), not the `retentionWindow` duration that `RulesForShard`/`PromotedHash` consume — they're different shapes for different purposes: the retention check on the cursor compares two absolute timestamps, while the engine partition check compares a per-action TTL to a duration. Gated on `replay != nil` because pure walker buckets persist a sentinel `TsNs=0` that would otherwise re-fire recovery every run. Invokes `walker.RunForShard(ctx, shardID, engine.RecoveryView(snap), limiter)`. Persists cursor at:
|
||||
- `{ TsNs: now - engine.MaxEffectiveTTL(replay), RuleSetHash: rsh, PromotedHash: promoted }` if `replay` is non-`nil`.
|
||||
- `{ TsNs: 0, RuleSetHash: rsh, PromotedHash: promoted }` if `replay` is `nil` (pure walker bucket).
|
||||
`MaxEffectiveTTL` is undefined over an empty set, so the sentinel form is required when `replay` is `nil`. **Both hashes are written on every recovery persistence** — failing to update `PromotedHash` here would cause the partition-flip trigger to re-fire on every subsequent run. See "Bootstrap retention window."
|
||||
- **Steady-state walker invocation.** Distinct from recovery: `walker.RunForShard(ctx, shardID, walk, limiter)`. `walk`'s cloned actions are masked to walker-bound kinds only, so the walker doesn't re-process replay rules that the meta-log scan already handles on the same run.
|
||||
- Drop the bootstrap walker's call from `scheduler.go` (removed entirely in Phase 5).
|
||||
- Tests:
|
||||
- Cold start with mixed walker-only + replay rules in same bucket: recovery branch fires once (walker over `engine.RecoveryView(snap)`, then cursor rewind). Next day's run is steady-state (walker over `walk` only, replay over `replay`).
|
||||
- `ExpirationDate` rule fires only on/after the date (walker path).
|
||||
- `ExpiredDeleteMarker` rule deletes orphaned markers (walker path, sibling-aware).
|
||||
- `NewerNoncurrent` count rule deletes oldest noncurrent versions beyond the cap (walker path, version-list-aware).
|
||||
- Bucket with only walker rules (e.g., pure `ExpirationDate`): `replay` is `nil`, cursor persisted with sentinel `TsNs=0`, no meta-log subscribe attempted. Critically — assert that across 5 consecutive daily runs, recovery fires exactly once (on the first run); subsequent runs see no recovery despite `persisted.TsNs (0) < earliest_available`, because the retention-loss check is gated on `replay != nil`.
|
||||
- Replay-rule edit triggers recovery: walker runs over `RecoveryView(snap)` (catches an object already 60d old under a brand-new 30d rule), then cursor rewinds. Object aged 20d at edit time is later deleted at age 30 via the replay path.
|
||||
- `RecoveryView` activates event-driven actions: simulate a base snapshot where an `ExpirationDays` action has `IsActive=false` (e.g., `BootstrapComplete=false`); assert the recovery walker still sees and evaluates the rule via the recovery view, while the steady-state walker over `walk` does not.
|
||||
- **Replay view rewrites Mode**: simulate a base snapshot with a `ModeScanOnly`-locked `ExpirationDays` action (carried over from `prior.Mode`); assert that `replay`'s clone of the action has `Mode == ModeEventDriven`, and that `router.Route(ctx, replay, ev, ...)` emits a Match for it. The test should fail if Mode rewrite is skipped — confirming the rehabilitation path is wired.
|
||||
- Cursor persistence after recovery: assert `PromotedHash` is written through on every recovery branch persistence; simulate a partition flip across two runs and verify the second run does not re-fire recovery because the prior `promoted_hash` was correctly stored.
|
||||
- Adding a walker-only rule to an existing replay-only bucket: `ReplayContentHash(snap)` is unchanged, replay cursor TsNs unchanged, walker picks up the new rule on its next steady-state pass.
|
||||
- `scan_only` promotion (retention drops, replay-eligible rule moves to `walk`): `ReplayContentHash` unchanged, **`PromotedHash` changes** → recovery branch fires. Walker over base catches in-flight objects under the promoted rule; cursor rewinds; `PromotedHash` is persisted.
|
||||
- Retention recovery (`scan_only` rule demotes back to `replay` while other replay rules' cursor has advanced past the rule's relevant events): `ReplayContentHash` unchanged, `persisted.TsNs > earliest_available` so retention-loss check does NOT fire, **`PromotedHash` changes** → recovery branch fires. Asserts the demoted rule's older events get processed (this is the test that would have failed before adding `PromotedHash`).
|
||||
- `PromotedHash` persistence: simulate a partition flip in either direction across two runs, assert cursor's `promoted_hash` field carries through and gates the next run's recovery decision correctly.
|
||||
- Shard filter: 2 shards × 1 bucket walker run leaves no double-deletes (assert via RPC counter).
|
||||
- `scan_only` promotion: rule with TTL > meta-log retention moves from `replay` to `walk` at run start.
|
||||
|
||||
### Phase 5 — Switch default and delete streaming path
|
||||
|
||||
Cut over and clean up. Should be a single PR that's mostly deletions.
|
||||
|
||||
- Default `algorithm: daily_replay` and remove the streaming alternative from the descriptor.
|
||||
- Delete:
|
||||
- `weed/s3api/s3lifecycle/router/schedule.go` (+ tests)
|
||||
- `weed/s3api/s3lifecycle/dispatcher/dispatcher.go` (+ tests), `freeze`-related code, retry state
|
||||
- `weed/s3api/s3lifecycle/dispatcher/pipeline.go`
|
||||
- `weed/s3api/s3lifecycle/scheduler/scheduler.go` (+ tests), refresh ticker
|
||||
- Removed worker config fields and their `ParseConfig` handling
|
||||
- Rewrite `weed/s3api/s3lifecycle/DESIGN.md` to remove "streaming" sections.
|
||||
- One full end-to-end test on a bucket with 1M objects, mixed-TTL rules, with cluster rate cap engaged.
|
||||
|
||||
### Phase 6 — Observability polish
|
||||
|
||||
After cutover, before announcing.
|
||||
|
||||
- Daily-run summary log line: shard, rules-touched, events-scanned, deletes-issued, walker-fallback (y/n), duration.
|
||||
- Prometheus: `S3LifecycleDailyRunDurationSeconds`, `S3LifecycleDailyRunEventsScanned`, `S3LifecycleDailyRunDeletesIssued`, all labelled by `shard_id` and `outcome`.
|
||||
- Admin UI: a single "Last Run" card per bucket showing the above summary line. Removes the now-meaningless "Next Run / Detection Results" widgets we already hid for `s3_lifecycle`.
|
||||
|
||||
## Open questions
|
||||
|
||||
1. **In-pass concurrency.** Today's worker has 1–16 shard goroutines via `workers` config. Daily replay can either (a) keep that knob, fanning out shard scans across goroutines that share the limiter, or (b) drop it since the limiter is now the throughput governor. Lean toward (a) — shards are independent meta-log subscriptions and parallel reads cut wall-clock significantly.
|
||||
2. **Cursor format compatibility.** Worth deciding whether the new cursor coexists at a separate filer path (clean cutover, no migration) or overwrites the old one (single source of truth, requires a one-time read-then-rewrite during cutover). Lean toward separate paths during phases 2–4, unified at Phase 5.
|
||||
3. **Per-shard rule snapshots vs. global.** Engine snapshots are bucket-scoped today; Phase 4 adds `Snapshot.RulesForShard(shardID, retentionWindow) (replay, walk *Snapshot)`. Open: should `RulesForShard` also gate by which buckets a shard "owns" (every bucket is on every shard via `ShardID(bucket, key)`), or just return the global rule set partitioned by mode? Current lean: return global partition, since every shard worker runs against every bucket and the actual shard filter happens at the entry-iteration site (meta-log subscription and walker entry loop).
|
||||
6. **Bucket-coordinated walker.** Phase 4 has each shard walk the full bucket and filter by `ShardID` — simple, but 16× the listing cost. A future optimization is a per-bucket coordinator (the worker owning shard 0 for that bucket lists once, routes matches to other shards via the existing injection point). Worth doing if listing cost becomes the bottleneck for very large buckets. Not blocking initial cutover.
|
||||
4. **`noncurrent_since` source from filer write API.** Phase 1 prefers the demoting event's TsNs over wall-clock. Whether the existing filer write path surfaces that TsNs to the S3 handler without a proto change is a Phase 1 design decision; the fallback (handler-local `time.Now()`) is documented but loses cross-node monotonicity guarantees and should be a temporary measure.
|
||||
5. **Retry budget for `RETRY_LATER`.** The current dispatcher tracks per-key retry counts; this design removes that state and lets head-of-line blocking surface the issue. Worth confirming that operators are OK with a stuck cursor as the failure signal vs. silent retry. If not, add a bounded retry counter on the cursor (one per stuck event) — small state, but inches back toward the model we're replacing.
|
||||
@@ -0,0 +1,33 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// HasPrefix is a thin wrapper around strings.HasPrefix exported by the
|
||||
// bootstrap package so call sites can avoid pulling strings just to do
|
||||
// a prefix check. Trivial but at 0% coverage — pin it.
|
||||
|
||||
func TestHasPrefix(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
prefix string
|
||||
want bool
|
||||
}{
|
||||
{"matching prefix", "logs/2026/01/01", "logs/", true},
|
||||
{"exact match", "logs/", "logs/", true},
|
||||
{"non-matching prefix", "metrics/x", "logs/", false},
|
||||
{"shorter than prefix", "logs", "logs/", false},
|
||||
{"empty prefix matches all", "anything", "", true},
|
||||
{"both empty", "", "", true},
|
||||
{"empty input non-empty prefix", "", "x", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, HasPrefix(c.path, c.prefix))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -135,10 +135,16 @@ func walkEntry(ctx context.Context, snap *engine.Snapshot, bucket string, entry
|
||||
if action == nil {
|
||||
continue
|
||||
}
|
||||
// SCAN_AT_DATE runs its own date-triggered bootstrap. DISABLED can
|
||||
// be flipped at runtime independent of XML Status, so skip it even
|
||||
// though EvaluateAction would also reject.
|
||||
if action.Mode == engine.ModeScanAtDate || action.Mode == engine.ModeDisabled {
|
||||
// DISABLED can be flipped at runtime independent of XML Status,
|
||||
// so skip it even though EvaluateAction would also reject.
|
||||
// SCAN_AT_DATE actions are processed here too — the date check
|
||||
// in EvaluateAction (now.Before(rule.ExpirationDate)) gates the
|
||||
// dispatch, so pre-date walks are no-ops and post-date walks
|
||||
// expire eligible objects. The earlier "scan-at-date runs its
|
||||
// own bootstrap" plan was never wired; until that lands, the
|
||||
// regular bootstrap walk is the only path that fires
|
||||
// ExpirationDate rules.
|
||||
if action.Mode == engine.ModeDisabled {
|
||||
continue
|
||||
}
|
||||
// (kind, info) shape gate: ABORT_MPU only on MPU init records,
|
||||
|
||||
@@ -164,9 +164,10 @@ func TestWalk_NotYetDueSkipped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalk_DateActionsSkipped(t *testing.T) {
|
||||
// Date kind is handled by its own SCAN_AT_DATE bootstrap, not by the
|
||||
// regular bootstrap walker.
|
||||
func TestWalk_DateActionFiresAfterDate(t *testing.T) {
|
||||
// The dedicated SCAN_AT_DATE bootstrap was never wired; until it
|
||||
// lands, the regular bootstrap walker is the only path that fires
|
||||
// ExpirationDate rules. Entries past the rule's date must dispatch.
|
||||
date := mustTime(t, "2025-06-15T00:00:00Z")
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "d",
|
||||
@@ -181,8 +182,30 @@ func TestWalk_DateActionsSkipped(t *testing.T) {
|
||||
}), rec, WalkOptions{Now: date.AddDate(0, 1, 0)}); err != nil {
|
||||
t.Fatalf("Walk: %v", err)
|
||||
}
|
||||
if len(rec.calls) != 1 || rec.calls[0].path != "x/a" {
|
||||
t.Fatalf("date kind past the rule date must dispatch, got %v", rec.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalk_DateActionSkippedBeforeDate(t *testing.T) {
|
||||
// Pre-date walks are no-ops: EvaluateAction returns ActionNone when
|
||||
// now is before rule.ExpirationDate.
|
||||
date := mustTime(t, "2025-06-15T00:00:00Z")
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "d",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDate: date,
|
||||
}
|
||||
snap := compileEvDriven(t, "bk", rule)
|
||||
|
||||
rec := &recorder{}
|
||||
if _, err := Walk(context.Background(), snap, "bk", EntryCallback([]*Entry{
|
||||
{Path: "x/a", IsLatest: true, ModTime: mustTime(t, "2024-01-01T00:00:00Z")},
|
||||
}), rec, WalkOptions{Now: date.AddDate(0, -1, 0)}); err != nil {
|
||||
t.Fatalf("Walk: %v", err)
|
||||
}
|
||||
if len(rec.calls) != 0 {
|
||||
t.Fatalf("date kind should not dispatch from walker, got %v", rec.calls)
|
||||
t.Fatalf("pre-date walk must not dispatch, got %v", rec.calls)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// Package dailyrun implements the daily-replay s3 lifecycle worker
|
||||
// described in weed/s3api/s3lifecycle/DESIGN.md. One pass per day per
|
||||
// shard reads the meta-log forward from the persisted cursor, drains
|
||||
// every event whose due_time is past now, and exits — replacing the
|
||||
// streaming + heap pipeline with a bounded, idempotent scan.
|
||||
//
|
||||
// Phase 2 (this file's first version): replay-only. Buckets whose
|
||||
// compiled rules include walker-bound action kinds (ExpirationDate,
|
||||
// ExpiredDeleteMarker, NewerNoncurrent) or any scan_only promotion are
|
||||
// refused with a typed error so flipping the algorithm flag is a loud
|
||||
// failure rather than silent data loss. Phase 4 wires the walker and
|
||||
// the recovery branch.
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
|
||||
)
|
||||
|
||||
// CursorDir is the filer directory holding per-shard daily-replay
|
||||
// cursor files. Kept distinct from dispatcher.CursorDir so a deployment
|
||||
// running both algorithms during cutover doesn't have one trample the
|
||||
// other's persisted state.
|
||||
const CursorDir = "/etc/s3/lifecycle/daily-cursors"
|
||||
|
||||
// cursorFileVersion bumps when the on-disk shape changes. Phase 2
|
||||
// writes version 1; Phase 4 will continue writing version 1 since the
|
||||
// schema (TsNs + RuleSetHash + PromotedHash) is already final.
|
||||
const cursorFileVersion = 1
|
||||
|
||||
// Cursor captures everything daily_run needs to decide whether to
|
||||
// recover (Phase 4) or continue steady-state. TsNs is the latest
|
||||
// meta-log event whose Matches all dispatched successfully (or as
|
||||
// NOOP_RESOLVED); RuleSetHash is the content hash of the replay-eligible
|
||||
// rules from the run that wrote this cursor; PromotedHash is the hash
|
||||
// of replay-eligible rules currently in scan_only.
|
||||
//
|
||||
// In Phase 2 PromotedHash is always the empty hash because the walker
|
||||
// path isn't wired yet — any rule that would land in walk causes the
|
||||
// run to refuse. Phase 4 starts writing a real value.
|
||||
type Cursor struct {
|
||||
TsNs int64
|
||||
RuleSetHash [32]byte
|
||||
PromotedHash [32]byte
|
||||
}
|
||||
|
||||
// cursorFile is the on-disk JSON shape. Bytes are base64-encoded by
|
||||
// encoding/json automatically.
|
||||
type cursorFile struct {
|
||||
Version int `json:"version"`
|
||||
ShardID int `json:"shard_id"`
|
||||
TsNs int64 `json:"ts_ns"`
|
||||
RuleSetHash []byte `json:"rule_set_hash"`
|
||||
PromotedHash []byte `json:"promoted_hash"`
|
||||
}
|
||||
|
||||
// CursorPersister loads and saves daily-replay cursors. The Phase 2
|
||||
// production implementation is FilerCursorPersister; tests inject a
|
||||
// fake.
|
||||
type CursorPersister interface {
|
||||
Load(ctx context.Context, shardID int) (Cursor, bool, error) // (cursor, found, err)
|
||||
Save(ctx context.Context, shardID int, c Cursor) error
|
||||
}
|
||||
|
||||
// FilerCursorPersister writes cursors to CursorDir as one JSON file per
|
||||
// shard. Reuses dispatcher.FilerStore for the actual filer I/O so both
|
||||
// algorithms share the same minimal storage abstraction.
|
||||
type FilerCursorPersister struct {
|
||||
Store dispatcher.FilerStore
|
||||
}
|
||||
|
||||
func cursorFileName(shardID int) string {
|
||||
return fmt.Sprintf("shard-%02d.json", shardID)
|
||||
}
|
||||
|
||||
// Load returns (zero-Cursor, false, nil) only when the cursor file
|
||||
// does not exist yet (cold start). Every other failure mode — empty
|
||||
// file, malformed JSON, wrong version, wrong shard, hash slices not
|
||||
// exactly 32 bytes — returns an error so the daily run halts and is
|
||||
// fixed by an operator rather than silently re-scanning from time zero.
|
||||
//
|
||||
// Strict shape validation is load-bearing because the cursor is
|
||||
// load → mutate → save in a single run: a partial-truncate that
|
||||
// silently zero-padded the rule_set_hash would be persisted back as a
|
||||
// real-looking hash, masking the corruption forever.
|
||||
func (p *FilerCursorPersister) Load(ctx context.Context, shardID int) (Cursor, bool, error) {
|
||||
if p.Store == nil {
|
||||
return Cursor{}, false, errors.New("FilerCursorPersister: nil Store")
|
||||
}
|
||||
content, err := p.Store.Read(ctx, CursorDir, cursorFileName(shardID))
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return Cursor{}, false, nil
|
||||
}
|
||||
return Cursor{}, false, fmt.Errorf("cursor read shard=%d: %w", shardID, err)
|
||||
}
|
||||
if len(content) == 0 {
|
||||
return Cursor{}, false, fmt.Errorf("cursor shard=%d: file exists but is empty (partial write or external truncation)", shardID)
|
||||
}
|
||||
var cf cursorFile
|
||||
if err := json.Unmarshal(content, &cf); err != nil {
|
||||
return Cursor{}, false, fmt.Errorf("cursor decode shard=%d: %w", shardID, err)
|
||||
}
|
||||
if cf.Version != cursorFileVersion {
|
||||
return Cursor{}, false, fmt.Errorf("cursor version shard=%d: got %d, want %d", shardID, cf.Version, cursorFileVersion)
|
||||
}
|
||||
if cf.ShardID != shardID {
|
||||
return Cursor{}, false, fmt.Errorf("cursor shard mismatch: file declares shard=%d, requested shard=%d", cf.ShardID, shardID)
|
||||
}
|
||||
if len(cf.RuleSetHash) != 32 {
|
||||
return Cursor{}, false, fmt.Errorf("cursor rule_set_hash shard=%d: got %d bytes, want 32", shardID, len(cf.RuleSetHash))
|
||||
}
|
||||
if len(cf.PromotedHash) != 32 {
|
||||
return Cursor{}, false, fmt.Errorf("cursor promoted_hash shard=%d: got %d bytes, want 32", shardID, len(cf.PromotedHash))
|
||||
}
|
||||
c := Cursor{TsNs: cf.TsNs}
|
||||
copy(c.RuleSetHash[:], cf.RuleSetHash)
|
||||
copy(c.PromotedHash[:], cf.PromotedHash)
|
||||
return c, true, nil
|
||||
}
|
||||
|
||||
func (p *FilerCursorPersister) Save(ctx context.Context, shardID int, c Cursor) error {
|
||||
if p.Store == nil {
|
||||
return errors.New("FilerCursorPersister: nil Store")
|
||||
}
|
||||
cf := cursorFile{
|
||||
Version: cursorFileVersion,
|
||||
ShardID: shardID,
|
||||
TsNs: c.TsNs,
|
||||
RuleSetHash: c.RuleSetHash[:],
|
||||
PromotedHash: c.PromotedHash[:],
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(cf); err != nil {
|
||||
return fmt.Errorf("cursor encode shard=%d: %w", shardID, err)
|
||||
}
|
||||
if err := p.Store.Save(ctx, CursorDir, cursorFileName(shardID), buf.Bytes()); err != nil {
|
||||
return fmt.Errorf("cursor save shard=%d: %w", shardID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// fakeStore is a minimal in-memory dispatcher.FilerStore for cursor tests.
|
||||
type fakeStore struct {
|
||||
mu sync.Mutex
|
||||
files map[string][]byte
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{files: map[string][]byte{}}
|
||||
}
|
||||
|
||||
func (s *fakeStore) key(dir, name string) string { return dir + "/" + name }
|
||||
|
||||
func (s *fakeStore) Read(_ context.Context, dir, name string) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
b, ok := s.files[s.key(dir, name)]
|
||||
if !ok {
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
return append([]byte(nil), b...), nil
|
||||
}
|
||||
|
||||
func (s *fakeStore) Save(_ context.Context, dir, name string, content []byte) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.files[s.key(dir, name)] = append([]byte(nil), content...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_EmptyLoadReturnsNotFound(t *testing.T) {
|
||||
p := &FilerCursorPersister{Store: newFakeStore()}
|
||||
c, found, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, found)
|
||||
assert.Equal(t, Cursor{}, c)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_SaveLoadRoundTrip(t *testing.T) {
|
||||
p := &FilerCursorPersister{Store: newFakeStore()}
|
||||
in := Cursor{
|
||||
TsNs: 1700000000_000000123,
|
||||
}
|
||||
for i := range in.RuleSetHash {
|
||||
in.RuleSetHash[i] = byte(i + 1)
|
||||
}
|
||||
for i := range in.PromotedHash {
|
||||
in.PromotedHash[i] = byte(0xff - i)
|
||||
}
|
||||
require.NoError(t, p.Save(context.Background(), 3, in))
|
||||
|
||||
out, found, err := p.Load(context.Background(), 3)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
assert.Equal(t, in, out)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_IsolatesShards(t *testing.T) {
|
||||
p := &FilerCursorPersister{Store: newFakeStore()}
|
||||
a := Cursor{TsNs: 100}
|
||||
b := Cursor{TsNs: 200}
|
||||
require.NoError(t, p.Save(context.Background(), 0, a))
|
||||
require.NoError(t, p.Save(context.Background(), 1, b))
|
||||
|
||||
got0, _, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
got1, _, err := p.Load(context.Background(), 1)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(100), got0.TsNs)
|
||||
assert.Equal(t, int64(200), got1.TsNs)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_CorruptDataReturnsError(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
store.files[store.key(CursorDir, "shard-00.json")] = []byte("not json")
|
||||
p := &FilerCursorPersister{Store: store}
|
||||
_, _, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_EmptyFileReturnsError(t *testing.T) {
|
||||
// A cursor file that exists but is empty signals a partial write
|
||||
// or external truncation. Treating it as "cold start" would silently
|
||||
// re-scan from time zero and burn through a meta-log window for no
|
||||
// reason. Pin that we error instead.
|
||||
store := newFakeStore()
|
||||
store.files[store.key(CursorDir, "shard-00.json")] = []byte{}
|
||||
p := &FilerCursorPersister{Store: store}
|
||||
_, _, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_WrongVersionReturnsError(t *testing.T) {
|
||||
// Future schema bumps must not silently overwrite a cursor written
|
||||
// by a newer worker. Pin that contract here.
|
||||
store := newFakeStore()
|
||||
store.files[store.key(CursorDir, "shard-00.json")] = []byte(`{"version":42,"shard_id":0,"ts_ns":0,"rule_set_hash":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","promoted_hash":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`)
|
||||
p := &FilerCursorPersister{Store: store}
|
||||
_, _, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_ShardIDMismatchReturnsError(t *testing.T) {
|
||||
// A file declaring shard=1 read by a shard=0 caller is corruption
|
||||
// (or a misroute); applying that cursor would advance the wrong
|
||||
// shard's state. Reject loudly.
|
||||
store := newFakeStore()
|
||||
// Build a valid v1 payload but with shard_id=1 in the body.
|
||||
in := Cursor{TsNs: 42}
|
||||
for i := range in.RuleSetHash {
|
||||
in.RuleSetHash[i] = byte(i + 1)
|
||||
}
|
||||
for i := range in.PromotedHash {
|
||||
in.PromotedHash[i] = byte(i)
|
||||
}
|
||||
p := &FilerCursorPersister{Store: store}
|
||||
require.NoError(t, p.Save(context.Background(), 1, in))
|
||||
// Reparent that file as if it lived at shard 0 — the test's fake
|
||||
// store only keys by name, so we copy the bytes manually.
|
||||
store.mu.Lock()
|
||||
store.files[store.key(CursorDir, "shard-00.json")] = store.files[store.key(CursorDir, "shard-01.json")]
|
||||
store.mu.Unlock()
|
||||
_, _, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_HashLengthMismatchReturnsError(t *testing.T) {
|
||||
// Hand-rolled JSON with hashes shorter than 32 bytes. copy() would
|
||||
// silently zero-pad which makes the hash comparison match a value
|
||||
// that doesn't actually exist on disk. Reject loudly so an operator
|
||||
// fixes the persisted state.
|
||||
store := newFakeStore()
|
||||
store.files[store.key(CursorDir, "shard-00.json")] = []byte(`{"version":1,"shard_id":0,"ts_ns":0,"rule_set_hash":"AA==","promoted_hash":"AA=="}`)
|
||||
p := &FilerCursorPersister{Store: store}
|
||||
_, _, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestFilerCursorPersister_NilStoreErrors(t *testing.T) {
|
||||
p := &FilerCursorPersister{}
|
||||
_, _, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
require.Error(t, p.Save(context.Background(), 0, Cursor{}))
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
)
|
||||
|
||||
// transportRetryAttempts is the in-run retry budget for transport
|
||||
// errors (RPC dial failures, stream resets). Server-side outcomes
|
||||
// (RETRY_LATER, BLOCKED) are NOT retried in-run — the server already
|
||||
// classified them as "wait until next run." The retry exists only to
|
||||
// paper over a single flake from the network.
|
||||
const transportRetryAttempts = 3
|
||||
|
||||
// transportRetryInitial is the first sleep after a failed attempt.
|
||||
// Doubled per attempt up to transportRetryMax. Phase 2 keeps these
|
||||
// small because the daily run's own MaxRuntime is the larger cap.
|
||||
const (
|
||||
transportRetryInitial = 200 * time.Millisecond
|
||||
transportRetryMax = 5 * time.Second
|
||||
)
|
||||
|
||||
// dispatchWithRetry sends one LifecycleDelete request, retrying on
|
||||
// transport errors up to transportRetryAttempts times with exponential
|
||||
// backoff. Returns the server's outcome on success, or an error if all
|
||||
// retries exhausted. Server outcomes (RETRY_LATER / BLOCKED) bypass
|
||||
// the retry — the daily run's halt-on-failure semantics handles them.
|
||||
func dispatchWithRetry(ctx context.Context, client LifecycleClient, m router.Match) (s3_lifecycle_pb.LifecycleDeleteOutcome, error) {
|
||||
req := buildDeleteRequest(m)
|
||||
backoff := transportRetryInitial
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= transportRetryAttempts; attempt++ {
|
||||
resp, err := client.LifecycleDelete(ctx, req)
|
||||
if err == nil {
|
||||
return resp.Outcome, nil
|
||||
}
|
||||
// Context cancellation is shutdown, not a transport flake.
|
||||
// Surface it immediately so the caller halts and tomorrow
|
||||
// resumes from the same cursor.
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return s3_lifecycle_pb.LifecycleDeleteOutcome_LIFECYCLE_DELETE_OUTCOME_UNSPECIFIED, err
|
||||
}
|
||||
lastErr = err
|
||||
if attempt == transportRetryAttempts {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return s3_lifecycle_pb.LifecycleDeleteOutcome_LIFECYCLE_DELETE_OUTCOME_UNSPECIFIED, ctx.Err()
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
backoff *= 2
|
||||
if backoff > transportRetryMax {
|
||||
backoff = transportRetryMax
|
||||
}
|
||||
}
|
||||
return s3_lifecycle_pb.LifecycleDeleteOutcome_LIFECYCLE_DELETE_OUTCOME_UNSPECIFIED, lastErr
|
||||
}
|
||||
|
||||
// buildDeleteRequest constructs the LifecycleDelete RPC payload for a
|
||||
// router Match. Mirrors dispatcher.dispatchOne's request shape — both
|
||||
// targets the same server-side handler and the proto encoding must
|
||||
// match exactly. Duplicated rather than shared because Phase 5
|
||||
// deletes the dispatcher's call site and the cross-package dependency
|
||||
// would just create a temporary import.
|
||||
func buildDeleteRequest(m router.Match) *s3_lifecycle_pb.LifecycleDeleteRequest {
|
||||
rh := m.Key.RuleHash
|
||||
return &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: m.Bucket,
|
||||
ObjectPath: m.ObjectKey,
|
||||
VersionId: m.VersionID,
|
||||
RuleHash: rh[:],
|
||||
ActionKind: toProtoActionKind(m.Key.ActionKind),
|
||||
ExpectedIdentity: toProtoIdentity(m.Identity),
|
||||
}
|
||||
}
|
||||
|
||||
func toProtoActionKind(k s3lifecycle.ActionKind) s3_lifecycle_pb.ActionKind {
|
||||
switch k {
|
||||
case s3lifecycle.ActionKindExpirationDays:
|
||||
return s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS
|
||||
case s3lifecycle.ActionKindExpirationDate:
|
||||
return s3_lifecycle_pb.ActionKind_EXPIRATION_DATE
|
||||
case s3lifecycle.ActionKindNoncurrentDays:
|
||||
return s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS
|
||||
case s3lifecycle.ActionKindNewerNoncurrent:
|
||||
return s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT
|
||||
case s3lifecycle.ActionKindAbortMPU:
|
||||
return s3_lifecycle_pb.ActionKind_ABORT_MPU
|
||||
case s3lifecycle.ActionKindExpiredDeleteMarker:
|
||||
return s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER
|
||||
}
|
||||
return s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED
|
||||
}
|
||||
|
||||
func toProtoIdentity(id *router.EntryIdentity) *s3_lifecycle_pb.EntryIdentity {
|
||||
if id == nil {
|
||||
return nil
|
||||
}
|
||||
return &s3_lifecycle_pb.EntryIdentity{
|
||||
MtimeNs: id.MtimeNs,
|
||||
Size: id.Size,
|
||||
HeadFid: id.HeadFid,
|
||||
ExtendedHash: id.ExtendedHash,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// fakeLifecycleClient is the test double for LifecycleClient. It
|
||||
// returns a scripted sequence of (outcome, error) pairs and counts
|
||||
// invocations so retry behavior can be pinned exactly.
|
||||
type fakeLifecycleClient struct {
|
||||
scripted []scriptedResp
|
||||
calls int32
|
||||
}
|
||||
|
||||
type scriptedResp struct {
|
||||
outcome s3_lifecycle_pb.LifecycleDeleteOutcome
|
||||
err error
|
||||
}
|
||||
|
||||
func (c *fakeLifecycleClient) LifecycleDelete(_ context.Context, _ *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
idx := int(atomic.AddInt32(&c.calls, 1)) - 1
|
||||
if idx >= len(c.scripted) {
|
||||
// Default to the last scripted response if the test under-specifies.
|
||||
idx = len(c.scripted) - 1
|
||||
}
|
||||
r := c.scripted[idx]
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: r.outcome}, nil
|
||||
}
|
||||
|
||||
func sampleMatch() router.Match {
|
||||
return router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "b", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
Bucket: "b",
|
||||
ObjectKey: "obj",
|
||||
}
|
||||
}
|
||||
|
||||
// Speed up dispatch retries inside tests so the suite stays fast.
|
||||
// The defaults (200ms initial, 5s max) make exponential backoff cases
|
||||
// take seconds; tests shrink to microseconds via a separate helper.
|
||||
func dispatchWithRetryFast(t *testing.T, ctx context.Context, c LifecycleClient, m router.Match) (s3_lifecycle_pb.LifecycleDeleteOutcome, error) {
|
||||
t.Helper()
|
||||
// We can't override the package-private constants, but every test
|
||||
// path here uses small attempt counts so even the production
|
||||
// backoff is fine.
|
||||
return dispatchWithRetry(ctx, c, m)
|
||||
}
|
||||
|
||||
func TestDispatch_FirstAttemptSucceeds(t *testing.T) {
|
||||
c := &fakeLifecycleClient{scripted: []scriptedResp{
|
||||
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE},
|
||||
}}
|
||||
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, out)
|
||||
assert.Equal(t, int32(1), c.calls)
|
||||
}
|
||||
|
||||
func TestDispatch_TransportRetryThenSucceed(t *testing.T) {
|
||||
// Two transport flakes then a success. The retry loop tries 3 times
|
||||
// by default; we expect 3 calls and the final outcome.
|
||||
c := &fakeLifecycleClient{scripted: []scriptedResp{
|
||||
{err: errors.New("transport boom")},
|
||||
{err: errors.New("transport boom")},
|
||||
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED},
|
||||
}}
|
||||
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED, out)
|
||||
assert.Equal(t, int32(3), c.calls)
|
||||
}
|
||||
|
||||
func TestDispatch_ExhaustsRetriesReturnsError(t *testing.T) {
|
||||
// All N attempts fail with transport errors. Caller must see an
|
||||
// error and the call count must equal transportRetryAttempts.
|
||||
failing := errors.New("transport persistent")
|
||||
c := &fakeLifecycleClient{scripted: []scriptedResp{
|
||||
{err: failing}, {err: failing}, {err: failing},
|
||||
}}
|
||||
_, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, int32(transportRetryAttempts), c.calls)
|
||||
}
|
||||
|
||||
func TestDispatch_ServerOutcomeRetryLaterIsNotRetried(t *testing.T) {
|
||||
// RETRY_LATER is a SERVER outcome; the daily run's halt-on-failure
|
||||
// caller handles it. dispatchWithRetry must surface it on the first
|
||||
// successful RPC and NOT retry in-run.
|
||||
c := &fakeLifecycleClient{scripted: []scriptedResp{
|
||||
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER},
|
||||
}}
|
||||
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, out)
|
||||
assert.Equal(t, int32(1), c.calls, "server outcome must not trigger transport retry")
|
||||
}
|
||||
|
||||
func TestDispatch_ServerOutcomeBlockedNotRetried(t *testing.T) {
|
||||
c := &fakeLifecycleClient{scripted: []scriptedResp{
|
||||
{outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED},
|
||||
}}
|
||||
out, err := dispatchWithRetryFast(t, context.Background(), c, sampleMatch())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, out)
|
||||
assert.Equal(t, int32(1), c.calls)
|
||||
}
|
||||
|
||||
func TestDispatch_ContextCancelledShortCircuits(t *testing.T) {
|
||||
// Context cancellation must surface immediately, not consume the
|
||||
// retry budget. Cursor-staying semantics in the caller depends on
|
||||
// this distinction.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
c := &fakeLifecycleClient{scripted: []scriptedResp{
|
||||
{err: context.Canceled},
|
||||
}}
|
||||
_, err := dispatchWithRetryFast(t, ctx, c, sampleMatch())
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
assert.Equal(t, int32(1), c.calls, "context cancellation must not consume the retry budget")
|
||||
}
|
||||
|
||||
func TestBuildDeleteRequest_RuleHashAndIdentity(t *testing.T) {
|
||||
// Pin the request shape so a future Match-struct refactor doesn't
|
||||
// silently drop the identity-CAS witness or the rule hash slice.
|
||||
m := router.Match{
|
||||
Bucket: "bucket",
|
||||
ObjectKey: "obj.txt",
|
||||
VersionID: "v_1",
|
||||
Key: s3lifecycle.ActionKey{
|
||||
Bucket: "bucket",
|
||||
RuleHash: [8]byte{1, 2, 3, 4, 5, 6, 7, 8},
|
||||
ActionKind: s3lifecycle.ActionKindNoncurrentDays,
|
||||
},
|
||||
Identity: &router.EntryIdentity{
|
||||
MtimeNs: time.Unix(1700000000, 12345).UnixNano(),
|
||||
Size: 42,
|
||||
HeadFid: "1,abc",
|
||||
ExtendedHash: []byte{0xaa, 0xbb},
|
||||
},
|
||||
}
|
||||
req := buildDeleteRequest(m)
|
||||
assert.Equal(t, "bucket", req.Bucket)
|
||||
assert.Equal(t, "obj.txt", req.ObjectPath)
|
||||
assert.Equal(t, "v_1", req.VersionId)
|
||||
assert.Equal(t, []byte{1, 2, 3, 4, 5, 6, 7, 8}, req.RuleHash)
|
||||
assert.Equal(t, s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS, req.ActionKind)
|
||||
require.NotNil(t, req.ExpectedIdentity)
|
||||
assert.Equal(t, int64(42), req.ExpectedIdentity.Size)
|
||||
assert.Equal(t, "1,abc", req.ExpectedIdentity.HeadFid)
|
||||
assert.Equal(t, []byte{0xaa, 0xbb}, req.ExpectedIdentity.ExtendedHash)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"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"
|
||||
)
|
||||
|
||||
// recordingClient captures every LifecycleDelete request the
|
||||
// daily-run path emits. Default outcome is DONE; tests that need
|
||||
// other outcomes set responses by index.
|
||||
type recordingClient struct {
|
||||
mu sync.Mutex
|
||||
requests []*s3_lifecycle_pb.LifecycleDeleteRequest
|
||||
responses []s3_lifecycle_pb.LifecycleDeleteOutcome
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (c *recordingClient) LifecycleDelete(_ context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
c.mu.Lock()
|
||||
c.requests = append(c.requests, req)
|
||||
idx := int(c.calls.Add(1)) - 1
|
||||
c.mu.Unlock()
|
||||
out := s3_lifecycle_pb.LifecycleDeleteOutcome_DONE
|
||||
if idx < len(c.responses) {
|
||||
out = c.responses[idx]
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out}, nil
|
||||
}
|
||||
|
||||
func (c *recordingClient) seenObjects() []string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
out := make([]string, 0, len(c.requests))
|
||||
for _, r := range c.requests {
|
||||
out = append(out, r.ObjectPath)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Phase 2's processMatches must NOT use a per-rule done flag.
|
||||
// routePointerTransitionExpand can return multiple matches for the
|
||||
// same ActionKey on different objects, each with its own
|
||||
// SuccessorModTime from a distinct demoting event. A not-yet-due
|
||||
// sibling must never gate a sibling that's already past its DueTime.
|
||||
// Pin that here.
|
||||
func TestProcessMatches_NotYetDueDoesNotSuppressDueOnSameRule(t *testing.T) {
|
||||
runNow := time.Now()
|
||||
rh := [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
|
||||
rule := s3lifecycle.ActionKey{
|
||||
Bucket: "b",
|
||||
RuleHash: rh,
|
||||
ActionKind: s3lifecycle.ActionKindNoncurrentDays,
|
||||
}
|
||||
// Three matches for the same ActionKey, different objects, mixed
|
||||
// due-times. Order intentionally puts the not-yet-due match first
|
||||
// so a buggy per-rule done flag would suppress the others.
|
||||
matches := []router.Match{
|
||||
{Key: rule, Bucket: "b", ObjectKey: "future-sibling", DueTime: runNow.Add(48 * time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "due-sibling-a", DueTime: runNow.Add(-48 * time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "due-sibling-b", DueTime: runNow.Add(-24 * time.Hour)},
|
||||
}
|
||||
client := &recordingClient{}
|
||||
cfg := Config{Client: client}
|
||||
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{TsNs: runNow.UnixNano()}, matches)
|
||||
require.NoError(t, err)
|
||||
require.False(t, halted)
|
||||
require.True(t, skipped, "at least one future-DueTime match must flag skippedAny")
|
||||
|
||||
// Both due siblings must have been dispatched.
|
||||
seen := client.seenObjects()
|
||||
assert.ElementsMatch(t, []string{"due-sibling-a", "due-sibling-b"}, seen,
|
||||
"due matches must dispatch regardless of where the future-sibling sits in the slice")
|
||||
}
|
||||
|
||||
func TestProcessMatches_OrderingDoesNotMatter(t *testing.T) {
|
||||
runNow := time.Now()
|
||||
rh := [8]byte{0xaa}
|
||||
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
matches := []router.Match{
|
||||
{Key: rule, Bucket: "b", ObjectKey: "a", DueTime: runNow.Add(-2 * time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "b", DueTime: runNow.Add(-1 * time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "future", DueTime: runNow.Add(time.Hour)},
|
||||
}
|
||||
client := &recordingClient{}
|
||||
cfg := Config{Client: client}
|
||||
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, matches)
|
||||
require.NoError(t, err)
|
||||
require.False(t, halted)
|
||||
require.True(t, skipped)
|
||||
assert.ElementsMatch(t, []string{"a", "b"}, client.seenObjects())
|
||||
}
|
||||
|
||||
func TestProcessMatches_HaltOnServerOutcomeStopsRemaining(t *testing.T) {
|
||||
runNow := time.Now()
|
||||
rh := [8]byte{0xbb}
|
||||
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
matches := []router.Match{
|
||||
{Key: rule, Bucket: "b", ObjectKey: "ok", DueTime: runNow.Add(-time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "blocked", DueTime: runNow.Add(-time.Hour)},
|
||||
{Key: rule, Bucket: "b", ObjectKey: "would-be-next", DueTime: runNow.Add(-time.Hour)},
|
||||
}
|
||||
client := &recordingClient{responses: []s3_lifecycle_pb.LifecycleDeleteOutcome{
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, // would be a bug if reached
|
||||
}}
|
||||
cfg := Config{Client: client}
|
||||
_, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, matches)
|
||||
require.NoError(t, err)
|
||||
require.True(t, halted, "BLOCKED outcome must halt the event loop")
|
||||
assert.Equal(t, []string{"ok", "blocked"}, client.seenObjects(),
|
||||
"would-be-next must NOT be dispatched after the halt")
|
||||
}
|
||||
|
||||
func TestProcessMatches_EmptyMatchesIsNoop(t *testing.T) {
|
||||
runNow := time.Now()
|
||||
client := &recordingClient{}
|
||||
cfg := Config{Client: client}
|
||||
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, nil)
|
||||
require.NoError(t, err)
|
||||
require.False(t, halted)
|
||||
require.False(t, skipped)
|
||||
assert.Empty(t, client.seenObjects())
|
||||
}
|
||||
|
||||
func TestProcessMatches_AllDueNoSkippedFlag(t *testing.T) {
|
||||
// All matches past their DueTime — skippedAny must be false so the
|
||||
// caller can advance the cursor past this event.
|
||||
runNow := time.Now()
|
||||
rh := [8]byte{0xcc}
|
||||
rule := s3lifecycle.ActionKey{Bucket: "b", RuleHash: rh, 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(-30 * time.Minute)},
|
||||
}
|
||||
client := &recordingClient{}
|
||||
cfg := Config{Client: client}
|
||||
skipped, halted, err := processMatches(context.Background(), cfg, runNow, &reader.Event{}, matches)
|
||||
require.NoError(t, err)
|
||||
require.False(t, halted)
|
||||
require.False(t, skipped, "every match was past DueTime; skippedAny must be false")
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
|
||||
)
|
||||
|
||||
// UnsupportedRuleError is returned by Run when the bucket's compiled
|
||||
// rules include any action kind Phase 2 cannot service. The handler
|
||||
// surfaces this so admin marks the run failed in the activity log;
|
||||
// flipping the algorithm flag to daily_replay on a bucket with these
|
||||
// rules is a loud failure rather than a silent dropped rule.
|
||||
type UnsupportedRuleError struct {
|
||||
Bucket string
|
||||
Kind s3lifecycle.ActionKind
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (e *UnsupportedRuleError) Error() string {
|
||||
return fmt.Sprintf("daily_replay: unsupported action kind %s on bucket %q: %s", e.Kind, e.Bucket, e.Reason)
|
||||
}
|
||||
|
||||
// IsUnsupportedRule reports whether err is or wraps an
|
||||
// UnsupportedRuleError. Callers (the worker handler) use this to
|
||||
// classify the run outcome.
|
||||
func IsUnsupportedRule(err error) bool {
|
||||
var u *UnsupportedRuleError
|
||||
return errors.As(err, &u)
|
||||
}
|
||||
|
||||
// isReplayEligibleKind reports whether the engine's daily-replay path
|
||||
// can service action kind k. Mirror this list when adding new kinds.
|
||||
func isReplayEligibleKind(k s3lifecycle.ActionKind) bool {
|
||||
switch k {
|
||||
case s3lifecycle.ActionKindExpirationDays,
|
||||
s3lifecycle.ActionKindNoncurrentDays,
|
||||
s3lifecycle.ActionKindAbortMPU:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkSnapshotForUnsupported walks every active CompiledAction in snap
|
||||
// and returns the first kind that isn't replay-eligible OR is in a Mode
|
||||
// other than ModeEventDriven. router.Route gates dispatch on
|
||||
// `Mode == ModeEventDriven` (see weed/s3api/s3lifecycle/router/router.go),
|
||||
// so a replay-kind action that's been promoted to ModeScanOnly would
|
||||
// silently get no matches at all — the daily run must reject it loudly
|
||||
// so admin sees the failure in the activity log. Phase 4 partitions
|
||||
// these into walk-bound actions and runs them through the walker,
|
||||
// removing the gate.
|
||||
func checkSnapshotForUnsupported(snap *engine.Snapshot) *UnsupportedRuleError {
|
||||
if snap == nil {
|
||||
return nil
|
||||
}
|
||||
for _, a := range snap.AllActions() {
|
||||
if a == nil || !a.IsActive() {
|
||||
continue
|
||||
}
|
||||
if !isReplayEligibleKind(a.Key.ActionKind) {
|
||||
return &UnsupportedRuleError{
|
||||
Bucket: a.Bucket,
|
||||
Kind: a.Key.ActionKind,
|
||||
Reason: "Phase 2 only routes ExpirationDays / NoncurrentDays / AbortMPU; ExpirationDate, ExpiredDeleteMarker, NewerNoncurrent land in Phase 4",
|
||||
}
|
||||
}
|
||||
if a.Mode != engine.ModeEventDriven {
|
||||
return &UnsupportedRuleError{
|
||||
Bucket: a.Bucket,
|
||||
Kind: a.Key.ActionKind,
|
||||
Reason: fmt.Sprintf("action is in Mode=%v (router.Route only dispatches ModeEventDriven); scan_only promotions land in Phase 4", a.Mode),
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// localReplayContentHash hashes the rule definitions of replay-eligible
|
||||
// actions in snap. Stable across reorderings — actions are sorted by
|
||||
// (bucket, rule_hash, action_kind) before mixing. Phase 4 replaces
|
||||
// this with engine.ReplayContentHash; both must produce the same value
|
||||
// on a snapshot that's already fully replay-eligible (which Phase 2
|
||||
// enforces via checkSnapshotForUnsupported).
|
||||
//
|
||||
// Includes the effective TTL in the hash so a TTL change (e.g. 30 → 60
|
||||
// days) is detected as a rule-content change, even though the rule's
|
||||
// RuleHash also captures it — defense in depth against any future
|
||||
// RuleHash collision and an explicit dependency for the cursor
|
||||
// rewind decision.
|
||||
func localReplayContentHash(snap *engine.Snapshot) [32]byte {
|
||||
if snap == nil {
|
||||
return [32]byte{}
|
||||
}
|
||||
type rec struct {
|
||||
bucket string
|
||||
ruleHash [8]byte
|
||||
actionKind s3lifecycle.ActionKind
|
||||
ttlNs int64
|
||||
}
|
||||
var recs []rec
|
||||
for _, a := range snap.AllActions() {
|
||||
if a == nil || !a.IsActive() {
|
||||
continue
|
||||
}
|
||||
if !isReplayEligibleKind(a.Key.ActionKind) {
|
||||
continue
|
||||
}
|
||||
recs = append(recs, rec{
|
||||
bucket: a.Bucket,
|
||||
ruleHash: a.Key.RuleHash,
|
||||
actionKind: a.Key.ActionKind,
|
||||
ttlNs: int64(effectiveTTL(a)),
|
||||
})
|
||||
}
|
||||
if len(recs) == 0 {
|
||||
return [32]byte{}
|
||||
}
|
||||
sort.Slice(recs, func(i, j int) bool {
|
||||
if recs[i].bucket != recs[j].bucket {
|
||||
return recs[i].bucket < recs[j].bucket
|
||||
}
|
||||
if recs[i].ruleHash != recs[j].ruleHash {
|
||||
for k := 0; k < len(recs[i].ruleHash); k++ {
|
||||
if recs[i].ruleHash[k] != recs[j].ruleHash[k] {
|
||||
return recs[i].ruleHash[k] < recs[j].ruleHash[k]
|
||||
}
|
||||
}
|
||||
}
|
||||
return int(recs[i].actionKind) < int(recs[j].actionKind)
|
||||
})
|
||||
h := sha256.New()
|
||||
var scratch [16]byte
|
||||
for _, r := range recs {
|
||||
h.Write([]byte(r.bucket))
|
||||
h.Write([]byte{0})
|
||||
h.Write(r.ruleHash[:])
|
||||
binary.LittleEndian.PutUint64(scratch[:8], uint64(r.actionKind))
|
||||
binary.LittleEndian.PutUint64(scratch[8:], uint64(r.ttlNs))
|
||||
h.Write(scratch[:])
|
||||
}
|
||||
var out [32]byte
|
||||
copy(out[:], h.Sum(nil))
|
||||
return out
|
||||
}
|
||||
|
||||
// effectiveTTL returns the per-action TTL the lifecycle engine clocks
|
||||
// against. Walker-bound kinds (ExpirationDate, ExpiredDeleteMarker,
|
||||
// NewerNoncurrent) return 0 — they don't participate in the replay
|
||||
// sliding window so they don't contribute to MaxEffectiveTTL or the
|
||||
// content hash. Phase 2 guarantees those kinds never reach here via
|
||||
// checkSnapshotForUnsupported, but the switch stays exhaustive so a
|
||||
// future kind addition is a compile-time prompt to decide.
|
||||
func effectiveTTL(a *engine.CompiledAction) time.Duration {
|
||||
if a == nil || a.Rule == nil {
|
||||
return 0
|
||||
}
|
||||
switch a.Key.ActionKind {
|
||||
case s3lifecycle.ActionKindExpirationDays:
|
||||
return s3lifecycle.DaysToDuration(a.Rule.ExpirationDays)
|
||||
case s3lifecycle.ActionKindNoncurrentDays:
|
||||
return s3lifecycle.DaysToDuration(a.Rule.NoncurrentVersionExpirationDays)
|
||||
case s3lifecycle.ActionKindAbortMPU:
|
||||
return s3lifecycle.DaysToDuration(a.Rule.AbortMPUDaysAfterInitiation)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// localMaxEffectiveTTL returns the largest effective TTL across active
|
||||
// replay-eligible actions. Returns zero when snap is empty/nil — caller
|
||||
// is responsible for routing through the empty-replay branch in that
|
||||
// case. Phase 4 replaces this with engine.MaxEffectiveTTL.
|
||||
func localMaxEffectiveTTL(snap *engine.Snapshot) time.Duration {
|
||||
if snap == nil {
|
||||
return 0
|
||||
}
|
||||
var max time.Duration
|
||||
for _, a := range snap.AllActions() {
|
||||
if a == nil || !a.IsActive() {
|
||||
continue
|
||||
}
|
||||
if !isReplayEligibleKind(a.Key.ActionKind) {
|
||||
continue
|
||||
}
|
||||
if d := effectiveTTL(a); d > max {
|
||||
max = d
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newSnapshotWith(t *testing.T, inputs []engine.CompileInput) *engine.Snapshot {
|
||||
t.Helper()
|
||||
e := engine.New()
|
||||
e.Compile(inputs, engine.CompileOptions{})
|
||||
snap := e.Snapshot()
|
||||
// Mark every action active so isActive checks fire as expected; the
|
||||
// production compile path also marks them active for replay-eligible
|
||||
// kinds when prior.BootstrapComplete is true. Tests just need them
|
||||
// visible to AllActions().
|
||||
for _, a := range snap.AllActions() {
|
||||
snap.MarkActive(a.Key)
|
||||
}
|
||||
return snap
|
||||
}
|
||||
|
||||
func ruleExpirationDays(days int) *s3lifecycle.Rule {
|
||||
return &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: days}
|
||||
}
|
||||
|
||||
func ruleExpirationDate(t time.Time) *s3lifecycle.Rule {
|
||||
return &s3lifecycle.Rule{ID: "r-date", Status: s3lifecycle.StatusEnabled, ExpirationDate: t}
|
||||
}
|
||||
|
||||
func ruleNoncurrentDays(days int) *s3lifecycle.Rule {
|
||||
return &s3lifecycle.Rule{ID: "r-nc", Status: s3lifecycle.StatusEnabled, NoncurrentVersionExpirationDays: days}
|
||||
}
|
||||
|
||||
func ruleAbortMPU(days int) *s3lifecycle.Rule {
|
||||
return &s3lifecycle.Rule{ID: "r-mpu", Status: s3lifecycle.StatusEnabled, AbortMPUDaysAfterInitiation: days}
|
||||
}
|
||||
|
||||
func ruleNewerNoncurrent(n int) *s3lifecycle.Rule {
|
||||
return &s3lifecycle.Rule{ID: "r-newer", Status: s3lifecycle.StatusEnabled, NewerNoncurrentVersions: n}
|
||||
}
|
||||
|
||||
func ruleExpiredDeleteMarker() *s3lifecycle.Rule {
|
||||
return &s3lifecycle.Rule{ID: "r-edm", Status: s3lifecycle.StatusEnabled, ExpiredObjectDeleteMarker: true}
|
||||
}
|
||||
|
||||
func TestCheckSnapshotForUnsupported_AllReplayKindsAccepted(t *testing.T) {
|
||||
snap := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{
|
||||
ruleExpirationDays(30),
|
||||
ruleNoncurrentDays(7),
|
||||
ruleAbortMPU(7),
|
||||
}},
|
||||
})
|
||||
require.Nil(t, checkSnapshotForUnsupported(snap))
|
||||
}
|
||||
|
||||
func TestCheckSnapshotForUnsupported_ExpirationDateRejected(t *testing.T) {
|
||||
snap := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDate(time.Now().Add(48 * time.Hour))}},
|
||||
})
|
||||
err := checkSnapshotForUnsupported(snap)
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, s3lifecycle.ActionKindExpirationDate, err.Kind)
|
||||
assert.Equal(t, "b1", err.Bucket)
|
||||
}
|
||||
|
||||
func TestCheckSnapshotForUnsupported_NewerNoncurrentRejected(t *testing.T) {
|
||||
snap := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleNewerNoncurrent(2)}},
|
||||
})
|
||||
err := checkSnapshotForUnsupported(snap)
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, s3lifecycle.ActionKindNewerNoncurrent, err.Kind)
|
||||
}
|
||||
|
||||
func TestCheckSnapshotForUnsupported_ExpiredDeleteMarkerRejected(t *testing.T) {
|
||||
snap := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpiredDeleteMarker()}},
|
||||
})
|
||||
err := checkSnapshotForUnsupported(snap)
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, s3lifecycle.ActionKindExpiredDeleteMarker, err.Kind)
|
||||
}
|
||||
|
||||
func TestCheckSnapshotForUnsupported_NonEventDrivenModeRejected(t *testing.T) {
|
||||
// A replay-eligible action whose Mode isn't ModeEventDriven (e.g.
|
||||
// promoted to ModeScanOnly by retention checks) is silently
|
||||
// ignored by router.Route. Phase 2 must catch this loudly. Build a
|
||||
// snapshot with one ExpirationDays action and mutate its Mode to
|
||||
// ModeScanOnly directly — there's no production path that produces
|
||||
// this without retention plumbing we don't have here, but the gate
|
||||
// must still reject it.
|
||||
snap := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDays(30)}},
|
||||
})
|
||||
// Mutate the compiled action to ModeScanOnly. AllActions returns
|
||||
// the live snapshot's actions; this is safe in a test where no
|
||||
// concurrent worker is reading.
|
||||
for _, a := range snap.AllActions() {
|
||||
if a.Key.ActionKind == s3lifecycle.ActionKindExpirationDays {
|
||||
a.Mode = engine.ModeScanOnly
|
||||
}
|
||||
}
|
||||
err := checkSnapshotForUnsupported(snap)
|
||||
require.NotNil(t, err, "ModeScanOnly on a replay-kind action must be rejected")
|
||||
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, err.Kind)
|
||||
assert.Contains(t, err.Reason, "ModeEventDriven")
|
||||
}
|
||||
|
||||
func TestIsUnsupportedRule_TypeCheck(t *testing.T) {
|
||||
var u error = &UnsupportedRuleError{Bucket: "b", Kind: s3lifecycle.ActionKindExpirationDate, Reason: "x"}
|
||||
assert.True(t, IsUnsupportedRule(u))
|
||||
assert.False(t, IsUnsupportedRule(nil))
|
||||
assert.False(t, IsUnsupportedRule(assertNonNilError()))
|
||||
}
|
||||
|
||||
// assertNonNilError returns a plain non-nil error of a different type
|
||||
// so IsUnsupportedRule's errors.As check has a negative case to refuse.
|
||||
func assertNonNilError() error { return errPlain }
|
||||
|
||||
type plainErr struct{}
|
||||
|
||||
func (plainErr) Error() string { return "plain" }
|
||||
|
||||
var errPlain = plainErr{}
|
||||
|
||||
func TestLocalReplayContentHash_StableAcrossReorderings(t *testing.T) {
|
||||
// Compile the same rules in two snapshots and verify the hash is
|
||||
// identical — sort order in AllActions() is implementation detail
|
||||
// and must not affect the cursor's content hash.
|
||||
rules := []*s3lifecycle.Rule{ruleExpirationDays(30), ruleNoncurrentDays(7), ruleAbortMPU(7)}
|
||||
snapA := newSnapshotWith(t, []engine.CompileInput{{Bucket: "b1", Rules: rules}})
|
||||
// Build snapB with the same rules in reverse order; hash must match.
|
||||
rev := []*s3lifecycle.Rule{rules[2], rules[1], rules[0]}
|
||||
snapB := newSnapshotWith(t, []engine.CompileInput{{Bucket: "b1", Rules: rev}})
|
||||
assert.Equal(t, localReplayContentHash(snapA), localReplayContentHash(snapB))
|
||||
}
|
||||
|
||||
func TestLocalReplayContentHash_ChangesOnTTLEdit(t *testing.T) {
|
||||
snap30 := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDays(30)}},
|
||||
})
|
||||
snap60 := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{ruleExpirationDays(60)}},
|
||||
})
|
||||
assert.NotEqual(t, localReplayContentHash(snap30), localReplayContentHash(snap60))
|
||||
}
|
||||
|
||||
func TestLocalReplayContentHash_EmptyIsZero(t *testing.T) {
|
||||
snap := newSnapshotWith(t, nil)
|
||||
var zero [32]byte
|
||||
assert.Equal(t, zero, localReplayContentHash(snap))
|
||||
}
|
||||
|
||||
func TestLocalMaxEffectiveTTL_PicksLargest(t *testing.T) {
|
||||
snap := newSnapshotWith(t, []engine.CompileInput{
|
||||
{Bucket: "b1", Rules: []*s3lifecycle.Rule{
|
||||
ruleExpirationDays(7),
|
||||
ruleNoncurrentDays(30),
|
||||
ruleAbortMPU(14),
|
||||
}},
|
||||
})
|
||||
got := localMaxEffectiveTTL(snap)
|
||||
assert.Equal(t, s3lifecycle.DaysToDuration(30), got)
|
||||
}
|
||||
|
||||
func TestLocalMaxEffectiveTTL_EmptyReturnsZero(t *testing.T) {
|
||||
snap := newSnapshotWith(t, nil)
|
||||
assert.Equal(t, time.Duration(0), localMaxEffectiveTTL(snap))
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
package dailyrun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"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/engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
"github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
// LifecycleClient is the same RPC contract the streaming dispatcher
|
||||
// uses. Replicated here to avoid an import cycle with dispatcher; both
|
||||
// shapes target s3_lifecycle_pb.SeaweedS3LifecycleInternalClient and
|
||||
// neither owns the protobuf interface.
|
||||
type LifecycleClient interface {
|
||||
LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error)
|
||||
}
|
||||
|
||||
// Config bundles everything daily_run needs to make one shard-fan-out
|
||||
// pass over the meta-log. Fields with zero values use documented
|
||||
// defaults; required fields are checked at the top of Run.
|
||||
type Config struct {
|
||||
Shards []int
|
||||
BucketsPath string
|
||||
Engine *engine.Engine
|
||||
FilerClient filer_pb.SeaweedFilerClient
|
||||
Client LifecycleClient
|
||||
Persister CursorPersister
|
||||
Lister router.SiblingLister
|
||||
|
||||
// Workers caps how many shards run in parallel. Each shard owns its
|
||||
// own meta-log subscription and rate limiter is shared across all
|
||||
// of them, so the cap is about filer-side concurrency rather than
|
||||
// throughput. Zero or negative → 1 (serial, the legacy default).
|
||||
Workers int
|
||||
|
||||
// Limiter is the optional per-worker rate.Limiter shared across all
|
||||
// shard goroutines on this worker. nil = no rate limit (the legacy
|
||||
// "drain as fast as the filer can" behavior). Phase 3 wires the
|
||||
// per-worker share from ClusterContext.Metadata into this field.
|
||||
Limiter *rate.Limiter
|
||||
|
||||
// ClientName / ClientID identify this worker on the meta-log
|
||||
// subscription. ClientID 0 randomizes per-run.
|
||||
ClientName string
|
||||
ClientID int32
|
||||
|
||||
// Now overrides time.Now for tests. nil = production wall clock.
|
||||
Now func() time.Time
|
||||
|
||||
// EventBudget caps how many meta-log events each shard's reader
|
||||
// consumes before returning. Zero = unbounded (the run-until-now
|
||||
// behavior — see "stop condition" below). Tests set a small value
|
||||
// to bound deterministic runs.
|
||||
EventBudget int
|
||||
}
|
||||
|
||||
// Run executes the daily replay for every shard in cfg.Shards
|
||||
// concurrently. Returns the first non-nil error from any shard; other
|
||||
// shards still run to completion so a transient filer error on one
|
||||
// shard doesn't lose progress on the others.
|
||||
//
|
||||
// Phase 2 scope: replay only. A bucket whose compiled rules require
|
||||
// walker-bound dispatch (ExpirationDate, ExpiredDeleteMarker,
|
||||
// NewerNoncurrent) or any rule promoted to scan_only fails the whole
|
||||
// run with an UnsupportedRuleError — the handler reports this so admin
|
||||
// can either revert algorithm=streaming or wait for Phase 4.
|
||||
func Run(ctx context.Context, cfg Config) error {
|
||||
if err := validate(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
now := cfg.Now
|
||||
if now == nil {
|
||||
now = func() time.Time { return time.Now().UTC() }
|
||||
}
|
||||
// Freeze "now" at the start of the run. Every shard, every match's
|
||||
// DueTime comparison, and every cursor-floor calculation uses the
|
||||
// same instant so a long-running shard doesn't see the boundary
|
||||
// drift relative to a short-running peer.
|
||||
runNow := now()
|
||||
|
||||
// Refuse runs whose snapshot includes a walker-bound action kind
|
||||
// or any rule the router won't route. Done once against an
|
||||
// immutable snapshot — every shard reuses this exact value so a
|
||||
// mid-execution Compile can't make shards disagree about the rule
|
||||
// set or the hash.
|
||||
snap := cfg.Engine.Snapshot()
|
||||
if unsupported := checkSnapshotForUnsupported(snap); unsupported != nil {
|
||||
return unsupported
|
||||
}
|
||||
|
||||
// Concurrency cap. cfg.Workers controls how many shards run in
|
||||
// parallel; the rate limiter (Phase 3) governs throughput. With
|
||||
// Workers=1 (the legacy default) the 16 shards process serially.
|
||||
workers := cfg.Workers
|
||||
if workers <= 0 {
|
||||
workers = 1
|
||||
}
|
||||
if workers > len(cfg.Shards) {
|
||||
workers = len(cfg.Shards)
|
||||
}
|
||||
sem := make(chan struct{}, workers)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, len(cfg.Shards))
|
||||
for _, sh := range cfg.Shards {
|
||||
sh := sh
|
||||
wg.Add(1)
|
||||
sem <- struct{}{}
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
if err := runShard(ctx, cfg, snap, runNow, sh); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
// Return the first error; the rest are logged at glog level so
|
||||
// they're recoverable in the operational stream.
|
||||
var first error
|
||||
for err := range errCh {
|
||||
if first == nil {
|
||||
first = err
|
||||
} else {
|
||||
glog.V(1).Infof("daily_run: additional shard error: %v", err)
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
func validate(cfg Config) error {
|
||||
if cfg.Engine == nil {
|
||||
return errors.New("daily_run: nil Engine")
|
||||
}
|
||||
if cfg.FilerClient == nil {
|
||||
return errors.New("daily_run: nil FilerClient")
|
||||
}
|
||||
if cfg.Client == nil {
|
||||
return errors.New("daily_run: nil Client (LifecycleDelete RPC)")
|
||||
}
|
||||
if cfg.Persister == nil {
|
||||
return errors.New("daily_run: nil Persister")
|
||||
}
|
||||
if cfg.Lister == nil {
|
||||
return errors.New("daily_run: nil Lister")
|
||||
}
|
||||
if cfg.BucketsPath == "" {
|
||||
return errors.New("daily_run: empty BucketsPath")
|
||||
}
|
||||
for _, sh := range cfg.Shards {
|
||||
if sh < 0 || sh >= s3lifecycle.ShardCount {
|
||||
return fmt.Errorf("daily_run: shard %d out of [0, %d)", sh, s3lifecycle.ShardCount)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runShard executes the daily replay loop for a single shard. The
|
||||
// algorithm is documented in DESIGN.md ("Algorithm" section).
|
||||
//
|
||||
// Phase 2 omissions vs. the full design:
|
||||
// - No walker invocation on rule-change / cold-start / retention
|
||||
// loss. The cursor is rewritten and the worker exits; Phase 4
|
||||
// wires the walker over engine.RecoveryView(snap) on these
|
||||
// branches.
|
||||
// - PromotedHash is always the empty hash. The partition-flip
|
||||
// trigger is dormant until Phase 4.
|
||||
// - All walker-bound action kinds and scan_only-promoted rules are
|
||||
// refused at validate-time (see checkSnapshotForUnsupported), so
|
||||
// replay only ever sees ExpirationDays / NoncurrentDays / AbortMPU.
|
||||
//
|
||||
// snap is the engine snapshot captured at the top of Run; reusing the
|
||||
// same value across shards guarantees they observe identical rules and
|
||||
// hashes. runNow is the frozen instant for due-time comparisons.
|
||||
func runShard(ctx context.Context, cfg Config, snap *engine.Snapshot, runNow time.Time, shardID int) error {
|
||||
persisted, found, err := cfg.Persister.Load(ctx, shardID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("shard=%d: load cursor: %w", shardID, err)
|
||||
}
|
||||
|
||||
rsh := localReplayContentHash(snap)
|
||||
maxTTL := localMaxEffectiveTTL(snap)
|
||||
|
||||
// Empty-replay sentinel: no replay-eligible active rules in the
|
||||
// snapshot. We persist the hash so a future rule addition is
|
||||
// detected as a content change. Use the hash rather than maxTTL
|
||||
// here as the explicit "no replay state" signal — both fire on
|
||||
// the same set in practice (action_kind.go only emits actions
|
||||
// when their Days field is > 0), but the hash captures intent.
|
||||
if rsh == [32]byte{} {
|
||||
return cfg.Persister.Save(ctx, shardID, Cursor{
|
||||
TsNs: 0,
|
||||
RuleSetHash: rsh,
|
||||
PromotedHash: [32]byte{}, // Phase 2: always empty
|
||||
})
|
||||
}
|
||||
|
||||
// Rule-change branch: hash mismatch (and a persisted cursor exists)
|
||||
// rewinds to now - max_ttl. Phase 4 adds the walker call here.
|
||||
if found && persisted.RuleSetHash != rsh {
|
||||
next := Cursor{
|
||||
TsNs: runNow.Add(-maxTTL).UnixNano(),
|
||||
RuleSetHash: rsh,
|
||||
// PromotedHash stays empty in Phase 2.
|
||||
}
|
||||
return cfg.Persister.Save(ctx, shardID, next)
|
||||
}
|
||||
|
||||
// Cold start with no prior cursor: start scanning from now - max_ttl
|
||||
// so a freshly-installed worker still expires already-due objects
|
||||
// whose PUT events sit within meta-log retention. Phase 4 would
|
||||
// invoke the walker here for the longer-than-retention case; Phase 2
|
||||
// trusts that retention >= max_ttl in the deployments this code is
|
||||
// enabled on.
|
||||
startTsNs := persisted.TsNs
|
||||
floor := runNow.Add(-maxTTL).UnixNano()
|
||||
if startTsNs < floor {
|
||||
startTsNs = floor
|
||||
}
|
||||
|
||||
lastOK, _, drainErr := drainShardEvents(ctx, cfg, runNow, shardID, snap, startTsNs)
|
||||
if drainErr != nil {
|
||||
// Drain failed (transport, ctx cancel, or limiter shutdown):
|
||||
// persist whatever progress we have so subsequent runs don't
|
||||
// re-process the events we already dispatched, then propagate
|
||||
// the error. Cursor save uses ctx — if ctx is already cancelled
|
||||
// the save will fail too; that's fine, we still surface the
|
||||
// underlying drain error.
|
||||
_ = cfg.Persister.Save(ctx, shardID, Cursor{TsNs: lastOK, RuleSetHash: rsh})
|
||||
return fmt.Errorf("shard=%d: drain: %w", shardID, drainErr)
|
||||
}
|
||||
|
||||
// drainShardEvents stops advancing lastOK at the first event with a
|
||||
// skipped (not-yet-due) match. Persisting that value means the next
|
||||
// run resumes from before the skipped event and re-scans it —
|
||||
// without that, future-DueTime matches would be lost. halted=true
|
||||
// adds nothing here because lastOK already reflects the
|
||||
// stuck-at-failure boundary.
|
||||
return cfg.Persister.Save(ctx, shardID, Cursor{
|
||||
TsNs: lastOK,
|
||||
RuleSetHash: rsh,
|
||||
// PromotedHash stays empty in Phase 2.
|
||||
})
|
||||
}
|
||||
|
||||
// drainShardEvents subscribes to the meta-log starting at startTsNs,
|
||||
// routes every event through router.Route, and dispatches each Match
|
||||
// whose due_time is past runNow. Returns (cursorAdvanceTo, halted, error):
|
||||
// - cursorAdvanceTo: the highest TsNs the persisted cursor may safely
|
||||
// advance to. Equals the TsNs of the last event whose matches were
|
||||
// ALL dispatched (DONE/NOOP_RESOLVED/SKIPPED_OBJECT_LOCK) AND every
|
||||
// prior event was likewise fully processed. Once an event with a
|
||||
// not-yet-due match is encountered, cursorAdvanceTo stops growing —
|
||||
// so subsequent runs re-scan that event and any after it.
|
||||
// - halted: true when an unresolved dispatch outcome (RETRY_LATER /
|
||||
// BLOCKED / transport error after in-run retries) stopped the loop.
|
||||
// - error: stream/setup failure or context cancellation; caller
|
||||
// persists cursorAdvanceTo and propagates the error so the run is
|
||||
// marked as interrupted rather than successful.
|
||||
func drainShardEvents(ctx context.Context, cfg Config, runNow time.Time, shardID int, snap *engine.Snapshot, startTsNs int64) (int64, bool, error) {
|
||||
clientName := cfg.ClientName
|
||||
if clientName == "" {
|
||||
clientName = "worker-s3-lifecycle-daily"
|
||||
}
|
||||
clientID := cfg.ClientID
|
||||
if clientID == 0 {
|
||||
clientID = int32(util.RandomInt32())
|
||||
}
|
||||
runUpTo := runNow.UnixNano()
|
||||
if startTsNs >= runUpTo {
|
||||
// Nothing to do — cursor already at or past the run boundary.
|
||||
return startTsNs, false, nil
|
||||
}
|
||||
|
||||
events := make(chan *reader.Event, 64)
|
||||
rd := &reader.Reader{
|
||||
ShardID: shardID,
|
||||
BucketsPath: cfg.BucketsPath,
|
||||
StartTsNs: startTsNs,
|
||||
Events: events,
|
||||
EventBudget: cfg.EventBudget,
|
||||
}
|
||||
|
||||
readerCtx, cancelReader := context.WithCancel(ctx)
|
||||
defer cancelReader()
|
||||
|
||||
readerDone := make(chan error, 1)
|
||||
go func() {
|
||||
readerDone <- rd.Run(readerCtx, cfg.FilerClient, clientName, clientID)
|
||||
}()
|
||||
|
||||
cursorAdvanceTo := startTsNs
|
||||
// stuck flips to true at the first event with a skipped (not-yet-due)
|
||||
// match. From that event onward, cursorAdvanceTo no longer rises —
|
||||
// future runs must re-scan everything from cursorAdvanceTo + 1 onward
|
||||
// so the future-due matches get re-evaluated when they age in.
|
||||
stuck := false
|
||||
halted := false
|
||||
|
||||
drain:
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// Parent context cancellation (worker shutdown, MaxRuntime).
|
||||
// Return whatever progress was made so far and propagate the
|
||||
// error so the caller marks the run as interrupted.
|
||||
cancelReader()
|
||||
<-readerDone
|
||||
return cursorAdvanceTo, true, ctx.Err()
|
||||
case ev, ok := <-events:
|
||||
if !ok {
|
||||
break drain
|
||||
}
|
||||
if ev == nil {
|
||||
continue
|
||||
}
|
||||
if ev.TsNs > runUpTo {
|
||||
// Reached the run boundary: events past now belong to
|
||||
// tomorrow's pass. Cancel the reader so it doesn't keep
|
||||
// pulling live events, then exit.
|
||||
cancelReader()
|
||||
break drain
|
||||
}
|
||||
matches := router.Route(ctx, snap, ev, runNow, cfg.Lister)
|
||||
eventSkipped, eventHalted, eventErr := processMatches(ctx, cfg, runNow, ev, matches)
|
||||
if eventErr != nil {
|
||||
// A non-dispatch error (e.g. limiter wait cancelled by
|
||||
// shutdown). Cursor stays at the last fully-processed
|
||||
// event; surface the error so the caller treats it as
|
||||
// an interrupt.
|
||||
cancelReader()
|
||||
<-readerDone
|
||||
return cursorAdvanceTo, true, eventErr
|
||||
}
|
||||
if eventHalted {
|
||||
halted = true
|
||||
break drain
|
||||
}
|
||||
if eventSkipped {
|
||||
// First event with a not-yet-due match. Don't advance
|
||||
// the cursor past it; keep processing later events to
|
||||
// dispatch any due ones, but the persisted cursor stays
|
||||
// at the previous cursorAdvanceTo so this event is
|
||||
// re-scanned tomorrow.
|
||||
stuck = true
|
||||
continue
|
||||
}
|
||||
if !stuck {
|
||||
cursorAdvanceTo = ev.TsNs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for reader to drain so its goroutine doesn't outlive us.
|
||||
cancelReader()
|
||||
if rerr := <-readerDone; rerr != nil && !errors.Is(rerr, context.Canceled) {
|
||||
glog.V(2).Infof("daily_run shard=%d: reader returned: %v", shardID, rerr)
|
||||
}
|
||||
return cursorAdvanceTo, halted, nil
|
||||
}
|
||||
|
||||
// processMatches dispatches every match emitted from one event. Returns
|
||||
// (skippedAny, halted, error):
|
||||
// - skippedAny=true if at least one match had a DueTime past runNow.
|
||||
// The caller must NOT advance the persisted cursor past this event
|
||||
// so the skipped match gets re-scanned in a later run.
|
||||
// - halted=true on an unresolved outcome (RETRY_LATER / BLOCKED /
|
||||
// transport error after in-run retries). Caller exits the drain
|
||||
// loop.
|
||||
// - error: propagated from limiter.Wait when ctx is cancelled.
|
||||
//
|
||||
// A future-DueTime match is silently skipped — it does NOT terminate
|
||||
// the loop or get cached as "done for this rule." A single event can
|
||||
// produce multiple matches for the same ActionKey against different
|
||||
// objects (routePointerTransitionExpand emits one match per noncurrent
|
||||
// sibling, each with its own SuccessorModTime derived from a different
|
||||
// demoting event), so a not-yet-due sibling must never gate a sibling
|
||||
// that's already past its DueTime. Without per-object state the only
|
||||
// safe behavior is per-match independence; the cursor-advance gate
|
||||
// upstream handles re-scanning the skipped events tomorrow.
|
||||
//
|
||||
// runNow is the frozen run-start instant. Using it (rather than a
|
||||
// fresh now() per call) keeps the boundary stable across all matches
|
||||
// in this run.
|
||||
func processMatches(ctx context.Context, cfg Config, runNow time.Time, ev *reader.Event, matches []router.Match) (skippedAny, halted bool, err error) {
|
||||
for _, m := range matches {
|
||||
if m.DueTime.After(runNow) {
|
||||
skippedAny = true
|
||||
continue
|
||||
}
|
||||
if cfg.Limiter != nil {
|
||||
waitStart := time.Now()
|
||||
if waitErr := cfg.Limiter.Wait(ctx); waitErr != nil {
|
||||
return skippedAny, true, waitErr
|
||||
}
|
||||
stats.S3LifecycleDispatchLimiterWaitSeconds.Observe(time.Since(waitStart).Seconds())
|
||||
}
|
||||
outcome, dispatchErr := dispatchWithRetry(ctx, cfg.Client, m)
|
||||
if dispatchErr != nil {
|
||||
// Exhausted in-run transport retries: halt; tomorrow retries
|
||||
// from the same cursor.
|
||||
glog.V(1).Infof("daily_run: transport error on %s/%s %s: %v",
|
||||
m.Bucket, m.ObjectKey, m.Key.ActionKind, dispatchErr)
|
||||
return skippedAny, true, nil
|
||||
}
|
||||
switch outcome {
|
||||
case s3_lifecycle_pb.LifecycleDeleteOutcome_DONE,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK:
|
||||
// Cursor advances. The dispatch's own metric (in the RPC
|
||||
// server) records the outcome; the daily-run side stays
|
||||
// metric-quiet to avoid double-counting.
|
||||
case s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED:
|
||||
glog.V(1).Infof("daily_run: %s on %s/%s %s",
|
||||
outcome, m.Bucket, m.ObjectKey, m.Key.ActionKind)
|
||||
return skippedAny, true, nil
|
||||
default:
|
||||
glog.V(1).Infof("daily_run: unknown outcome %v on %s/%s", outcome, m.Bucket, m.ObjectKey)
|
||||
return skippedAny, true, nil
|
||||
}
|
||||
_ = ev // ev kept available for future per-event logging
|
||||
}
|
||||
return skippedAny, false, nil
|
||||
}
|
||||
@@ -98,10 +98,16 @@ func (d *Dispatcher) Tick(ctx context.Context, now time.Time) int {
|
||||
d.retries = map[retryKey]int{}
|
||||
}
|
||||
due := d.Schedule.Drain(now)
|
||||
for _, m := range due {
|
||||
for i, m := range due {
|
||||
if err := ctx.Err(); err != nil {
|
||||
// Re-queue and return; the caller is shutting down.
|
||||
d.Schedule.Add(m)
|
||||
// Caller is shutting down. Re-queue every remaining drained
|
||||
// Match (current and any not yet visited) so they're not
|
||||
// lost across the worker restart — the schedule already
|
||||
// popped them all out, so the dispatcher owns putting them
|
||||
// back.
|
||||
for _, rem := range due[i:] {
|
||||
d.Schedule.Add(rem)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
d.dispatchOne(ctx, m, now)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Direct coverage for dispatcher pure helpers (keyOf, budget, backoff)
|
||||
// and the retryKey identity that drives the retry-budget map. The
|
||||
// existing dispatcher tests exercise these only through Tick; pinning
|
||||
// each one separately makes a regression in the helper itself fail at
|
||||
// the helper level.
|
||||
|
||||
func TestKeyOf_DerivesIdentityFromMatch(t *testing.T) {
|
||||
hash := [8]byte{0xde, 0xad, 0xbe, 0xef, 1, 2, 3, 4}
|
||||
m := router.Match{
|
||||
Key: s3lifecycle.ActionKey{
|
||||
Bucket: "bk",
|
||||
RuleHash: hash,
|
||||
ActionKind: s3lifecycle.ActionKindExpirationDays,
|
||||
},
|
||||
ObjectKey: "obj.txt",
|
||||
VersionID: "v_abc",
|
||||
}
|
||||
got := keyOf(m)
|
||||
assert.Equal(t, "bk", got.bucket)
|
||||
assert.Equal(t, hash, got.ruleHash)
|
||||
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, got.kind)
|
||||
assert.Equal(t, "obj.txt", got.objectKey)
|
||||
assert.Equal(t, "v_abc", got.versionID)
|
||||
}
|
||||
|
||||
func TestKeyOf_EqualMatchesProduceEqualKeys(t *testing.T) {
|
||||
// retryKey is used as a map key in the retry budget; equality must
|
||||
// hold between two Match values with identical fields so the second
|
||||
// dispatch finds the first's retry counter.
|
||||
hash := [8]byte{0xde, 0xad, 0xbe, 0xef}
|
||||
m1 := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
ObjectKey: "obj",
|
||||
VersionID: "v_x",
|
||||
}
|
||||
m2 := m1
|
||||
assert.Equal(t, keyOf(m1), keyOf(m2))
|
||||
}
|
||||
|
||||
func TestKeyOf_DistinctVersionIDsProduceDistinctKeys(t *testing.T) {
|
||||
// Two versions of the same logical object must NOT share a retry
|
||||
// budget; otherwise a noisy version could starve a healthy one.
|
||||
base := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
|
||||
ObjectKey: "obj",
|
||||
VersionID: "v_a",
|
||||
}
|
||||
other := base
|
||||
other.VersionID = "v_b"
|
||||
assert.NotEqual(t, keyOf(base), keyOf(other))
|
||||
}
|
||||
|
||||
func TestKeyOf_DistinctActionKindsProduceDistinctKeys(t *testing.T) {
|
||||
// The same (bucket, object, version) hit by two different action
|
||||
// kinds must each have their own retry budget.
|
||||
base := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
ObjectKey: "obj",
|
||||
}
|
||||
other := base
|
||||
other.Key.ActionKind = s3lifecycle.ActionKindNoncurrentDays
|
||||
assert.NotEqual(t, keyOf(base), keyOf(other))
|
||||
}
|
||||
|
||||
func TestDispatcherBudget_ReturnsConfiguredValueWhenSet(t *testing.T) {
|
||||
d := &Dispatcher{RetryBudget: 9}
|
||||
assert.Equal(t, 9, d.budget())
|
||||
}
|
||||
|
||||
func TestDispatcherBudget_FallsBackToDefaultWhenZero(t *testing.T) {
|
||||
// Operators leaving the budget at zero opt into the documented
|
||||
// default. A regression that returns 0 would NOOP every retry.
|
||||
d := &Dispatcher{}
|
||||
assert.Equal(t, defaultRetryBudget, d.budget())
|
||||
}
|
||||
|
||||
func TestDispatcherBudget_NegativeFallsBackToDefault(t *testing.T) {
|
||||
// budget() guards on > 0, so a negative value falls back rather
|
||||
// than producing nonsense. Pin the contract so a refactor that
|
||||
// flips the comparison is caught.
|
||||
d := &Dispatcher{RetryBudget: -1}
|
||||
assert.Equal(t, defaultRetryBudget, d.budget())
|
||||
}
|
||||
|
||||
func TestDispatcherBackoff_ReturnsConfiguredValueWhenSet(t *testing.T) {
|
||||
d := &Dispatcher{RetryBackoff: 5 * time.Second}
|
||||
assert.Equal(t, 5*time.Second, d.backoff())
|
||||
}
|
||||
|
||||
func TestDispatcherBackoff_FallsBackToDefaultWhenZero(t *testing.T) {
|
||||
d := &Dispatcher{}
|
||||
assert.Equal(t, defaultRetryBackoff, d.backoff())
|
||||
}
|
||||
|
||||
func TestDispatcherBackoff_NegativeFallsBackToDefault(t *testing.T) {
|
||||
d := &Dispatcher{RetryBackoff: -time.Second}
|
||||
assert.Equal(t, defaultRetryBackoff, d.backoff())
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// errFilerStore satisfies FilerStore with a forced Read error so the
|
||||
// Load path's "non-NotFound transport error" branch is reachable.
|
||||
// Save mirrors the pattern; tests for the nil-Store branch don't need
|
||||
// a stub at all.
|
||||
type errFilerStore struct {
|
||||
readErr error
|
||||
saveErr error
|
||||
readData []byte
|
||||
}
|
||||
|
||||
func (e *errFilerStore) Read(_ context.Context, _, _ string) ([]byte, error) {
|
||||
if e.readErr != nil {
|
||||
return nil, e.readErr
|
||||
}
|
||||
return e.readData, nil
|
||||
}
|
||||
func (e *errFilerStore) Save(_ context.Context, _, _ string, _ []byte) error {
|
||||
return e.saveErr
|
||||
}
|
||||
|
||||
// ---------- FilerPersister edges ----------
|
||||
|
||||
func TestFilerPersisterLoad_NilStoreErrors(t *testing.T) {
|
||||
// The persister's Store dependency is required; loading with a nil
|
||||
// Store must error rather than panic on the Read call.
|
||||
p := &FilerPersister{}
|
||||
_, err := p.Load(context.Background(), 0)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "nil Store")
|
||||
}
|
||||
|
||||
func TestFilerPersisterSave_NilStoreErrors(t *testing.T) {
|
||||
p := &FilerPersister{}
|
||||
err := p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "nil Store")
|
||||
}
|
||||
|
||||
func TestFilerPersisterLoad_NonNotFoundErrorIsWrapped(t *testing.T) {
|
||||
// A transport-level error (anything that isn't ErrNotFound) wraps
|
||||
// with the shard ID context so operators can attribute it. Pin
|
||||
// both that the error surfaces and that the original is recoverable
|
||||
// via errors.Is so a caller can distinguish.
|
||||
want := errors.New("filer-side bang")
|
||||
p := &FilerPersister{Store: &errFilerStore{readErr: want}}
|
||||
_, err := p.Load(context.Background(), 3)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, want)
|
||||
assert.Contains(t, err.Error(), "shard=3")
|
||||
}
|
||||
|
||||
func TestFilerPersisterLoad_EmptyContentReturnsEmptyMap(t *testing.T) {
|
||||
// Read returning a successful empty []byte means "file exists but
|
||||
// is zero length"; the persister must treat this as "no entries"
|
||||
// rather than try to JSON-decode an empty slice and return an
|
||||
// error.
|
||||
p := &FilerPersister{Store: &errFilerStore{readData: []byte{}}}
|
||||
got, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, got)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
// ---------- Tick edges ----------
|
||||
|
||||
func TestTick_InitializesRetriesMapOnFirstCall(t *testing.T) {
|
||||
// retries is a lazy map; a Dispatcher constructed without it must
|
||||
// not panic on the first Tick. Pin that handleRetryLater can write
|
||||
// into the map afterwards (proven by the dispatcher returning an
|
||||
// integer rather than crashing).
|
||||
d, sched := newDispatcher(&fakeClient{
|
||||
respond: func(int) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
},
|
||||
})
|
||||
require.Nil(t, d.retries, "preconditions: retries map starts nil")
|
||||
t0 := time.Now()
|
||||
sched.Add(router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
ObjectKey: "k",
|
||||
DueTime: t0,
|
||||
})
|
||||
processed := d.Tick(context.Background(), t0.Add(time.Hour))
|
||||
assert.Equal(t, 1, processed)
|
||||
assert.NotNil(t, d.retries, "Tick must initialize the retries map")
|
||||
}
|
||||
|
||||
func TestTick_CtxShutdownMidLoopRequeuesAndReturnsZero(t *testing.T) {
|
||||
// If ctx is canceled before Tick starts dispatching, the entire
|
||||
// drained batch must be re-queued. Drain pops ALL due matches at
|
||||
// once, so a naive "re-add the current Match only" would silently
|
||||
// lose every Match past the cancellation point. Three matches
|
||||
// here exercises that the loop re-queues the current AND every
|
||||
// remaining drained entry.
|
||||
calls := 0
|
||||
client := &fakeClient{
|
||||
respond: func(int) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
calls++
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
},
|
||||
}
|
||||
d, sched := newDispatcher(client)
|
||||
t0 := time.Now()
|
||||
for _, k := range []string{"k1", "k2", "k3"} {
|
||||
sched.Add(router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
ObjectKey: k,
|
||||
DueTime: t0,
|
||||
})
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // shutdown before Tick even starts dispatching
|
||||
|
||||
processed := d.Tick(ctx, t0.Add(time.Hour))
|
||||
assert.Equal(t, 0, processed, "shutdown must report zero processed")
|
||||
assert.Equal(t, 0, calls, "shutdown must skip every dispatch call")
|
||||
assert.Equal(t, 3, sched.Len(), "every drained Match must be re-queued — none lost")
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// Direct tests for dispatcher / pipeline pure helpers and their side
|
||||
// effects on the Prometheus surface. The Tick + Run integration tests
|
||||
// drive these only as one slice of a larger flow; pinning each helper
|
||||
// individually makes a regression in the helper itself fail at the
|
||||
// helper level.
|
||||
|
||||
// ---------- observeScheduleDepth ----------
|
||||
|
||||
func TestObserveScheduleDepth_ReportsScheduleLen(t *testing.T) {
|
||||
// observeScheduleDepth sets the gauge to the current Schedule.Len.
|
||||
// The dispatcher calls it on every Tick so operators can see how
|
||||
// far behind schedule the worker is. Use a distinct shard label so
|
||||
// other tests sharing the global gauge don't bleed in.
|
||||
const shard = 137
|
||||
d := &Dispatcher{ShardID: shard, Schedule: router.NewSchedule()}
|
||||
g := stats_collect.S3LifecycleScheduleDepthGauge.WithLabelValues(strconv.Itoa(shard))
|
||||
// Drop the label series at end of test so the global registry
|
||||
// doesn't accumulate stale entries across test runs in the same
|
||||
// process.
|
||||
defer stats_collect.S3LifecycleScheduleDepthGauge.DeleteLabelValues(strconv.Itoa(shard))
|
||||
|
||||
// Empty schedule -> 0.
|
||||
d.observeScheduleDepth()
|
||||
assert.Equal(t, float64(0), testutil.ToFloat64(g))
|
||||
|
||||
// Adding two matches lifts the gauge to 2 on the next observe.
|
||||
t0 := time.Now()
|
||||
d.Schedule.Add(router.Match{DueTime: t0})
|
||||
d.Schedule.Add(router.Match{DueTime: t0.Add(time.Second)})
|
||||
d.observeScheduleDepth()
|
||||
assert.Equal(t, float64(2), testutil.ToFloat64(g))
|
||||
|
||||
// Draining drops it back to 0; Tick would re-call but observe is a
|
||||
// pure setter so we drive it manually here.
|
||||
_ = d.Schedule.Drain(t0.Add(2 * time.Second))
|
||||
d.observeScheduleDepth()
|
||||
assert.Equal(t, float64(0), testutil.ToFloat64(g))
|
||||
}
|
||||
|
||||
// ---------- ensureEventsChan ----------
|
||||
|
||||
func TestEnsureEventsChan_HonorsEventBuffer(t *testing.T) {
|
||||
p := &Pipeline{EventBuffer: 7}
|
||||
p.ensureEventsChan()
|
||||
require.NotNil(t, p.events)
|
||||
assert.Equal(t, 7, cap(p.events), "EventBuffer must size the channel")
|
||||
require.NotNil(t, p.eventsReady)
|
||||
}
|
||||
|
||||
func TestEnsureEventsChan_FallsBackToDefault(t *testing.T) {
|
||||
// EventBuffer=0 means "use the default"; non-positive must not
|
||||
// produce a zero-sized channel that would block every InjectEvent.
|
||||
p := &Pipeline{}
|
||||
p.ensureEventsChan()
|
||||
assert.Equal(t, defaultEventBuffer, cap(p.events))
|
||||
}
|
||||
|
||||
func TestEnsureEventsChan_NegativeFallsBackToDefault(t *testing.T) {
|
||||
p := &Pipeline{EventBuffer: -1}
|
||||
p.ensureEventsChan()
|
||||
assert.Equal(t, defaultEventBuffer, cap(p.events))
|
||||
}
|
||||
|
||||
func TestEnsureEventsChan_IdempotentAcrossConcurrentCallers(t *testing.T) {
|
||||
// sync.Once must guarantee a single channel allocation under
|
||||
// concurrent calls; otherwise a races would create two channels
|
||||
// and lose events on the discarded one.
|
||||
p := &Pipeline{EventBuffer: 4}
|
||||
const N = 32
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(N)
|
||||
for i := 0; i < N; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
p.ensureEventsChan()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
require.NotNil(t, p.events)
|
||||
assert.Equal(t, 4, cap(p.events))
|
||||
}
|
||||
|
||||
// ---------- InjectEvent ----------
|
||||
|
||||
func TestInjectEvent_DeliversToEventsChannel(t *testing.T) {
|
||||
p := &Pipeline{EventBuffer: 1}
|
||||
ev := &reader.Event{Bucket: "bk", Key: "k"}
|
||||
require.NoError(t, p.InjectEvent(context.Background(), ev))
|
||||
|
||||
select {
|
||||
case got := <-p.events:
|
||||
assert.Same(t, ev, got, "InjectEvent must deliver the same pointer")
|
||||
default:
|
||||
t.Fatal("event was not enqueued")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectEvent_ReturnsCtxErrWhenCanceled(t *testing.T) {
|
||||
// A canceled context must propagate the cancellation; otherwise
|
||||
// the bootstrap walker could keep injecting after the worker is
|
||||
// shutting down. ensureEventsChan clamps EventBuffer<=0 to the
|
||||
// default, so to force the select to actually block we pre-fill
|
||||
// the buffer (size 1) and then send into the canceled context.
|
||||
p := &Pipeline{EventBuffer: 1}
|
||||
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
err := p.InjectEvent(ctx, &reader.Event{})
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
func TestInjectEvent_EnsureEventsChanCalledIfFirstCall(t *testing.T) {
|
||||
// InjectEvent must call ensureEventsChan internally so a caller can
|
||||
// inject before Run starts (e.g. bootstrap walks that fire before
|
||||
// the reader is up). Pin that the channel exists post-call.
|
||||
p := &Pipeline{}
|
||||
require.Nil(t, p.events, "preconditions: events not yet allocated")
|
||||
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
|
||||
require.NotNil(t, p.events, "InjectEvent must allocate the channel via ensureEventsChan")
|
||||
}
|
||||
|
||||
// ---------- isCtxShutdown ----------
|
||||
|
||||
func TestIsCtxShutdown_NilIsNotShutdown(t *testing.T) {
|
||||
assert.False(t, isCtxShutdown(nil))
|
||||
}
|
||||
|
||||
func TestIsCtxShutdown_ContextCanceledIsShutdown(t *testing.T) {
|
||||
assert.True(t, isCtxShutdown(context.Canceled))
|
||||
assert.True(t, isCtxShutdown(context.DeadlineExceeded))
|
||||
}
|
||||
|
||||
func TestIsCtxShutdown_GRPCCanceledStatusIsShutdown(t *testing.T) {
|
||||
// Filer / S3 RPCs can come back wrapped as gRPC status codes; the
|
||||
// helper must recognize Canceled / DeadlineExceeded by code so a
|
||||
// shutdown doesn't get misclassified as a transport failure.
|
||||
assert.True(t, isCtxShutdown(status.Error(codes.Canceled, "client closed")))
|
||||
assert.True(t, isCtxShutdown(status.Error(codes.DeadlineExceeded, "stream timeout")))
|
||||
}
|
||||
|
||||
func TestIsCtxShutdown_OtherErrorsAreNotShutdown(t *testing.T) {
|
||||
// A garden-variety transport error must NOT classify as shutdown;
|
||||
// otherwise the worker would silently swallow real failures.
|
||||
assert.False(t, isCtxShutdown(errors.New("connection refused")))
|
||||
assert.False(t, isCtxShutdown(status.Error(codes.Unavailable, "filer down")))
|
||||
assert.False(t, isCtxShutdown(status.Error(codes.Internal, "boom")))
|
||||
}
|
||||
|
||||
// ---------- cursorFileName ----------
|
||||
|
||||
func TestCursorFileName_PadsShardIDToTwoDigits(t *testing.T) {
|
||||
// The persister stores per-shard cursor files at predictable paths
|
||||
// so a manual operator inspection finds them sorted by shard. Pin
|
||||
// the zero-padded form so a refactor that drops %02d doesn't break
|
||||
// existing on-disk filenames.
|
||||
cases := map[int]string{
|
||||
0: "shard-00.json",
|
||||
1: "shard-01.json",
|
||||
9: "shard-09.json",
|
||||
10: "shard-10.json",
|
||||
15: "shard-15.json",
|
||||
}
|
||||
for shard, want := range cases {
|
||||
t.Run(want, func(t *testing.T) {
|
||||
assert.Equal(t, want, cursorFileName(shard))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,15 @@ type filerSiblingLister struct {
|
||||
bucketsPath string
|
||||
}
|
||||
|
||||
// NewFilerSiblingLister returns a router.SiblingLister backed by the
|
||||
// filer client. Exported so the daily-replay worker (and any future
|
||||
// non-dispatcher caller) can reuse the same .versions/ + null-bare
|
||||
// lookup logic without re-implementing it. Phase 5 deletes the
|
||||
// dispatcher's internal use; this constructor stays.
|
||||
func NewFilerSiblingLister(client filer_pb.SeaweedFilerClient, bucketsPath string) router.SiblingLister {
|
||||
return &filerSiblingLister{client: client, bucketsPath: bucketsPath}
|
||||
}
|
||||
|
||||
func (l *filerSiblingLister) Survivors(ctx context.Context, bucket, objectKey string) (router.Survivors, error) {
|
||||
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
|
||||
versionsDir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
|
||||
|
||||
@@ -64,7 +64,14 @@ func (e *Engine) Compile(inputs []CompileInput, opts CompileOptions) *Snapshot {
|
||||
if !hasPrior || mode == ModeUnspecified {
|
||||
mode = decideMode(rule, kind, opts.MetaLogRetention, opts.BootstrapLookbackMin)
|
||||
}
|
||||
active := prior.BootstrapComplete && mode == ModeEventDriven
|
||||
// Active gates routing: MatchPath / MatchOriginalWrite skip
|
||||
// !IsActive actions. ScanAtDate's only dispatch path is the
|
||||
// bootstrap walk's MatchPath call, so the action must be
|
||||
// considered active there or its rule is silently a no-op.
|
||||
// Bootstrap-completion state is per-action and event-driven-
|
||||
// shaped; date-based actions don't need a bootstrap rendezvous.
|
||||
active := mode == ModeScanAtDate ||
|
||||
(prior.BootstrapComplete && mode == ModeEventDriven)
|
||||
|
||||
ca := &CompiledAction{
|
||||
Rule: rule,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// rulePredicateSensitive's non-nil branches are exercised by the
|
||||
// existing Compile tests; this test pins the defensive nil-rule
|
||||
// branch directly. Compile shouldn't ever pass a nil rule, but a
|
||||
// future caller that does shouldn't panic.
|
||||
|
||||
func TestRulePredicateSensitive_NilRuleReturnsFalse(t *testing.T) {
|
||||
assert.False(t, rulePredicateSensitive(nil))
|
||||
}
|
||||
|
||||
func TestRulePredicateSensitive_NoFilterTagsReturnsFalse(t *testing.T) {
|
||||
// A rule without FilterTags is not predicate-sensitive; the
|
||||
// router's MatchPredicateChange path skips actions whose rule
|
||||
// returns false here.
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
assert.False(t, rulePredicateSensitive(rule))
|
||||
}
|
||||
|
||||
func TestRulePredicateSensitive_EmptyFilterTagsReturnsFalse(t *testing.T) {
|
||||
// An empty (non-nil) FilterTags map must classify as non-sensitive
|
||||
// — the function checks len, so empty == 0 == false.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
FilterTags: map[string]string{},
|
||||
}
|
||||
assert.False(t, rulePredicateSensitive(rule))
|
||||
}
|
||||
|
||||
func TestRulePredicateSensitive_PopulatedFilterTagsReturnsTrue(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
FilterTags: map[string]string{"env": "prod"},
|
||||
}
|
||||
assert.True(t, rulePredicateSensitive(rule))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -322,3 +323,60 @@ func TestEngine_SnapshotAtomicSwap(t *testing.T) {
|
||||
t.Fatalf("Engine.Snapshot should return the latest")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCompile_DelayGroupsDedupeAcrossBuckets pins the scaling property
|
||||
// the dispatcher relies on: originalDelayGroups is keyed by Delay, so N
|
||||
// rules sharing the same Days threshold across M buckets collapse into
|
||||
// one delay group with N*M action keys — not N*M groups. The dispatch
|
||||
// path can then index by delay group rather than per-rule.
|
||||
func TestCompile_DelayGroupsDedupeAcrossBuckets(t *testing.T) {
|
||||
const buckets = 100
|
||||
const rulesPerBucket = 5
|
||||
// Five rules per bucket, but only three distinct day values, so two
|
||||
// pairs of rules per bucket share a delay group.
|
||||
dayValues := []int{1, 1, 7, 7, 30}
|
||||
distinctDays := map[int]bool{}
|
||||
for _, d := range dayValues {
|
||||
distinctDays[d] = true
|
||||
}
|
||||
|
||||
inputs := make([]CompileInput, buckets)
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{}
|
||||
for b := 0; b < buckets; b++ {
|
||||
bucket := "b" + strconv.Itoa(b)
|
||||
rules := make([]*s3lifecycle.Rule, rulesPerBucket)
|
||||
for r, days := range dayValues {
|
||||
rule := ruleExpDays("r"+strconv.Itoa(r), "p"+strconv.Itoa(r)+"/", days)
|
||||
rules[r] = rule
|
||||
prior[s3lifecycle.ActionKey{
|
||||
Bucket: bucket,
|
||||
RuleHash: s3lifecycle.RuleHash(rule),
|
||||
ActionKind: s3lifecycle.ActionKindExpirationDays,
|
||||
}] = PriorState{BootstrapComplete: true}
|
||||
}
|
||||
inputs[b] = CompileInput{Bucket: bucket, Rules: rules}
|
||||
}
|
||||
|
||||
e := New()
|
||||
snap := e.Compile(inputs, CompileOptions{PriorStates: prior})
|
||||
|
||||
if got := len(snap.actions); got != buckets*rulesPerBucket {
|
||||
t.Fatalf("want %d actions (no collapse), got %d", buckets*rulesPerBucket, got)
|
||||
}
|
||||
if got := len(snap.originalDelayGroups); got != len(distinctDays) {
|
||||
t.Fatalf("want %d delay groups (one per distinct Days), got %d",
|
||||
len(distinctDays), got)
|
||||
}
|
||||
// Per-group key count: each distinct day appears in `count` rules per
|
||||
// bucket, so the group holds count*buckets keys.
|
||||
wantPerGroup := map[time.Duration]int{}
|
||||
for _, d := range dayValues {
|
||||
wantPerGroup[s3lifecycle.DaysToDuration(d)] += buckets
|
||||
}
|
||||
for delay, want := range wantPerGroup {
|
||||
if got := len(snap.originalDelayGroups[delay]); got != want {
|
||||
t.Fatalf("delay %v: want %d action keys, got %d", delay, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"hash"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
)
|
||||
|
||||
// hashItem pairs a ruleset member with its parent action so the
|
||||
// sort+hash helpers below can be type-agnostic. Internal type — every
|
||||
// hash callsite collects items into a slice, then hands it off.
|
||||
type hashItem struct {
|
||||
key s3lifecycle.ActionKey
|
||||
action *CompiledAction
|
||||
}
|
||||
|
||||
// sortHashItems orders items by (RuleHash, ActionKind, Bucket). The
|
||||
// composition matches the ActionKey identity model: RuleHash is the
|
||||
// primary content-derived identifier, ActionKind disambiguates siblings
|
||||
// of one rule, Bucket scopes by bucket so the same XML in two buckets
|
||||
// hashes distinctly. Shared between ReplayContentHash and PromotedHash
|
||||
// so the two helpers agree on the on-wire ordering — if one drifted,
|
||||
// the cursor could see "rule changed" on a no-op snapshot rebuild.
|
||||
func sortHashItems(items []hashItem) {
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if c := bytes.Compare(items[i].key.RuleHash[:], items[j].key.RuleHash[:]); c != 0 {
|
||||
return c < 0
|
||||
}
|
||||
if items[i].key.ActionKind != items[j].key.ActionKind {
|
||||
return items[i].key.ActionKind < items[j].key.ActionKind
|
||||
}
|
||||
return items[i].key.Bucket < items[j].key.Bucket
|
||||
})
|
||||
}
|
||||
|
||||
// hashWriter is the small varint-tagged writer the hash helpers use.
|
||||
// Each field gets a one-byte tag so a future schema change (new field)
|
||||
// can extend the on-wire format without colliding with existing values.
|
||||
type hashWriter struct {
|
||||
h hash.Hash
|
||||
lenbuf [binary.MaxVarintLen64]byte
|
||||
}
|
||||
|
||||
func newHashWriter() *hashWriter {
|
||||
return &hashWriter{h: sha256.New()}
|
||||
}
|
||||
|
||||
// writeField writes a length-prefixed byte field under tag.
|
||||
func (w *hashWriter) writeField(tag byte, b []byte) {
|
||||
_, _ = w.h.Write([]byte{tag})
|
||||
n := binary.PutUvarint(w.lenbuf[:], uint64(len(b)))
|
||||
_, _ = w.h.Write(w.lenbuf[:n])
|
||||
_, _ = w.h.Write(b)
|
||||
}
|
||||
|
||||
// writeInt writes a varint-encoded signed integer under tag.
|
||||
func (w *hashWriter) writeInt(tag byte, v int64) {
|
||||
_, _ = w.h.Write([]byte{tag})
|
||||
n := binary.PutVarint(w.lenbuf[:], v)
|
||||
_, _ = w.h.Write(w.lenbuf[:n])
|
||||
}
|
||||
|
||||
func (w *hashWriter) sum() [32]byte {
|
||||
var out [32]byte
|
||||
copy(out[:], w.h.Sum(nil))
|
||||
return out
|
||||
}
|
||||
|
||||
// ReplayContentHash hashes the content (action kind, predicate, TTL value)
|
||||
// of every replay-eligible compiled action in the base snapshot, returning
|
||||
// the empty hash when no replay-eligible action exists. The hash is:
|
||||
// - Partition-independent. A retention-driven scan_only promotion does
|
||||
// NOT change this hash; only the dispatch path changes, not the rule
|
||||
// content. (PromotedHash exists to catch partition flips separately.)
|
||||
// - Stable across snapshot reorderings. Actions are pre-sorted by
|
||||
// RuleHash + ActionKind + Bucket so two snapshots with the same rules
|
||||
// compiled in any order hash identically.
|
||||
// - Disabled-rule-aware. ModeDisabled actions are excluded so disabling
|
||||
// a rule changes the hash (it changed the rule set the worker is
|
||||
// scanning under).
|
||||
//
|
||||
// Used as cursor.RuleSetHash. A mismatch between persisted and current
|
||||
// triggers the recovery branch on next daily_run.
|
||||
func ReplayContentHash(s *Snapshot) [32]byte {
|
||||
var empty [32]byte
|
||||
if s == nil {
|
||||
return empty
|
||||
}
|
||||
var items []hashItem
|
||||
for k, a := range s.actions {
|
||||
if a == nil || a.Mode == ModeDisabled {
|
||||
continue
|
||||
}
|
||||
if !isReplayKind(k.ActionKind) {
|
||||
continue
|
||||
}
|
||||
items = append(items, hashItem{key: k, action: a})
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return empty
|
||||
}
|
||||
sortHashItems(items)
|
||||
|
||||
w := newHashWriter()
|
||||
for _, it := range items {
|
||||
w.writeField(0x01, []byte(it.key.Bucket))
|
||||
w.writeField(0x02, it.key.RuleHash[:])
|
||||
w.writeInt(0x03, int64(it.key.ActionKind))
|
||||
// RuleHash already covers the predicate (Prefix + FilterTags + size
|
||||
// filters) and per-kind TTLs, so we don't need to re-canonicalise
|
||||
// the *Rule. But we also include the action's effective TTL
|
||||
// directly so that an "effective TTL of 0" (a malformed rule where
|
||||
// the kind doesn't match the populated field) is distinguishable
|
||||
// from a valid one.
|
||||
w.writeInt(0x04, int64(effectiveTTL(it.action)))
|
||||
}
|
||||
return w.sum()
|
||||
}
|
||||
|
||||
// PromotedHash hashes the set of replay-eligible actions that *would* land
|
||||
// in walk (rather than replay) for the given retentionWindow, due to TTL >
|
||||
// retentionWindow. Empty hash when no rules are promoted. Takes the SAME
|
||||
// retentionWindow value as RulesForShard so the two helpers cannot disagree
|
||||
// about partition membership.
|
||||
//
|
||||
// Detects partition flips in either direction:
|
||||
// - replay → walk (retention dropped): rule appears in this hash but
|
||||
// didn't before.
|
||||
// - walk → replay (retention recovered): rule used to appear here but no
|
||||
// longer does.
|
||||
//
|
||||
// In both cases the persisted hash differs from the freshly computed one,
|
||||
// firing the recovery branch.
|
||||
//
|
||||
// A mismatch with the persisted PromotedHash triggers recovery even when
|
||||
// rule content is unchanged.
|
||||
func PromotedHash(s *Snapshot, retentionWindow time.Duration) [32]byte {
|
||||
var empty [32]byte
|
||||
if s == nil {
|
||||
return empty
|
||||
}
|
||||
var items []hashItem
|
||||
for k, a := range s.actions {
|
||||
if a == nil || a.Mode == ModeDisabled {
|
||||
continue
|
||||
}
|
||||
if !isReplayKind(k.ActionKind) {
|
||||
continue
|
||||
}
|
||||
ttl := effectiveTTL(a)
|
||||
// Mirror RulesForShard's partition predicate exactly: a replay
|
||||
// kind lands in walk when ttl is 0 (malformed) or ttl >
|
||||
// retentionWindow. PromotedHash hashes that walk-bound subset.
|
||||
if ttl > 0 && ttl <= retentionWindow {
|
||||
continue
|
||||
}
|
||||
items = append(items, hashItem{key: k, action: a})
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return empty
|
||||
}
|
||||
sortHashItems(items)
|
||||
|
||||
w := newHashWriter()
|
||||
for _, it := range items {
|
||||
w.writeField(0x01, []byte(it.key.Bucket))
|
||||
w.writeField(0x02, it.key.RuleHash[:])
|
||||
w.writeInt(0x03, int64(it.key.ActionKind))
|
||||
}
|
||||
return w.sum()
|
||||
}
|
||||
|
||||
// MaxEffectiveTTL returns the maximum effective TTL across the *active*
|
||||
// replay-eligible actions in s. Returns 0 for a nil snapshot or one with no
|
||||
// active replay actions; the caller is expected to be in the empty-replay
|
||||
// branch already (per the design's sentinel-cursor logic).
|
||||
//
|
||||
// "Effective TTL" mirrors the partition predicate in views.go: derived from
|
||||
// the rule field that matches the action kind. Walker-only action kinds
|
||||
// (ExpirationDate / ExpiredDeleteMarker / NewerNoncurrent) contribute
|
||||
// nothing — they're either not replay-eligible or, in a walk view, not
|
||||
// active in the replay sense.
|
||||
func MaxEffectiveTTL(s *Snapshot) time.Duration {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
var max time.Duration
|
||||
for k, a := range s.actions {
|
||||
if a == nil || !a.IsActive() {
|
||||
continue
|
||||
}
|
||||
if !isReplayKind(k.ActionKind) {
|
||||
continue
|
||||
}
|
||||
if ttl := effectiveTTL(a); ttl > max {
|
||||
max = ttl
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestReplayContentHash_EmptyWhenNoReplayActions(t *testing.T) {
|
||||
var empty [32]byte
|
||||
// Nil snapshot.
|
||||
assert.Equal(t, empty, ReplayContentHash(nil))
|
||||
|
||||
// Walker-only rule: ExpirationDate compiles to a single ScanAtDate
|
||||
// action which is excluded from ReplayContentHash.
|
||||
when := time.Now().Add(24 * time.Hour)
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "d",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDate: when,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
assert.Equal(t, empty, ReplayContentHash(snap))
|
||||
}
|
||||
|
||||
func TestReplayContentHash_PartitionIndependent(t *testing.T) {
|
||||
// Critical invariant: a retention shift that promotes a rule from
|
||||
// replay to walk (or back) MUST NOT change ReplayContentHash. The hash
|
||||
// is over the rule content as it appears in the base snapshot, not
|
||||
// over the partition it ends up in.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "shift",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
hashWithLargeRetention := ReplayContentHash(snap)
|
||||
|
||||
// Whether retention is 1d (promotes to walk) or 365d (stays in
|
||||
// replay), the base snapshot's rule content didn't move — only its
|
||||
// partition did. ReplayContentHash hashes the base, so this is
|
||||
// trivially constant. We re-call here to pin the contract.
|
||||
_, walkSmall := snap.RulesForShard(0, s3lifecycle.DaysToDuration(1))
|
||||
require.NotNil(t, walkSmall, "precondition: 1d retention promotes 30d rule to walk")
|
||||
replayLarge, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(365))
|
||||
require.NotNil(t, replayLarge, "precondition: 365d retention keeps 30d rule in replay")
|
||||
|
||||
hashAgain := ReplayContentHash(snap)
|
||||
assert.Equal(t, hashWithLargeRetention, hashAgain,
|
||||
"ReplayContentHash must be partition-independent")
|
||||
}
|
||||
|
||||
func TestReplayContentHash_ChangesOnRuleContentEdit(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
snap1 := buildSnapshotForViews(t, "b1", rule)
|
||||
h1 := ReplayContentHash(snap1)
|
||||
|
||||
// Edit the TTL — RuleHash changes, so the action's key changes, and
|
||||
// the content hash must move.
|
||||
rule2 := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 60,
|
||||
}
|
||||
snap2 := buildSnapshotForViews(t, "b1", rule2)
|
||||
h2 := ReplayContentHash(snap2)
|
||||
|
||||
assert.NotEqual(t, h1, h2, "TTL edit must change ReplayContentHash")
|
||||
}
|
||||
|
||||
func TestReplayContentHash_StableAcrossRuleReorder(t *testing.T) {
|
||||
r1 := &s3lifecycle.Rule{ID: "a", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7, Prefix: "a/"}
|
||||
r2 := &s3lifecycle.Rule{ID: "b", Status: s3lifecycle.StatusEnabled, ExpirationDays: 14, Prefix: "b/"}
|
||||
snapAB := buildSnapshotForViews(t, "b1", r1, r2)
|
||||
snapBA := buildSnapshotForViews(t, "b1", r2, r1)
|
||||
assert.Equal(t, ReplayContentHash(snapAB), ReplayContentHash(snapBA),
|
||||
"reordering rules at compile time must not change ReplayContentHash")
|
||||
}
|
||||
|
||||
func TestReplayContentHash_ExcludesWalkerOnlyAndDisabled(t *testing.T) {
|
||||
// Walker-only kinds and disabled rules don't affect ReplayContentHash;
|
||||
// only replay-eligible action kinds count.
|
||||
replayRule := &s3lifecycle.Rule{
|
||||
ID: "rep",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
snapOnlyReplay := buildSnapshotForViews(t, "b1", replayRule)
|
||||
baseline := ReplayContentHash(snapOnlyReplay)
|
||||
|
||||
walkerRule := &s3lifecycle.Rule{
|
||||
ID: "walker",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
}
|
||||
disabledRule := &s3lifecycle.Rule{
|
||||
ID: "off",
|
||||
Status: s3lifecycle.StatusDisabled,
|
||||
ExpirationDays: 90,
|
||||
}
|
||||
snapMixed := buildSnapshotForViews(t, "b1", replayRule, walkerRule, disabledRule)
|
||||
mixed := ReplayContentHash(snapMixed)
|
||||
|
||||
assert.Equal(t, baseline, mixed,
|
||||
"adding walker-only and disabled rules must not change ReplayContentHash")
|
||||
}
|
||||
|
||||
func TestPromotedHash_EmptyWhenNoneAreInWalk(t *testing.T) {
|
||||
var empty [32]byte
|
||||
assert.Equal(t, empty, PromotedHash(nil, 0))
|
||||
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "fits",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
// Large retention → rule stays in replay → no promotion.
|
||||
assert.Equal(t, empty, PromotedHash(snap, s3lifecycle.DaysToDuration(365)))
|
||||
}
|
||||
|
||||
func TestPromotedHash_ChangesOnReplayToWalkPromotion(t *testing.T) {
|
||||
// Retention drops below the rule's TTL → rule promotes from replay to
|
||||
// walk → PromotedHash changes from empty to non-empty.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "long",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
|
||||
before := PromotedHash(snap, s3lifecycle.DaysToDuration(365)) // replay
|
||||
after := PromotedHash(snap, s3lifecycle.DaysToDuration(7)) // promoted to walk
|
||||
|
||||
var empty [32]byte
|
||||
assert.Equal(t, empty, before)
|
||||
assert.NotEqual(t, empty, after)
|
||||
assert.NotEqual(t, before, after, "promotion must change PromotedHash")
|
||||
}
|
||||
|
||||
func TestPromotedHash_ChangesOnWalkToReplayDemotion(t *testing.T) {
|
||||
// Retention recovers from < TTL to >= TTL → rule demotes from walk to
|
||||
// replay → PromotedHash changes from non-empty to empty.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "demo",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
|
||||
before := PromotedHash(snap, s3lifecycle.DaysToDuration(7)) // walk
|
||||
after := PromotedHash(snap, s3lifecycle.DaysToDuration(365)) // demoted back to replay
|
||||
|
||||
var empty [32]byte
|
||||
assert.NotEqual(t, empty, before)
|
||||
assert.Equal(t, empty, after)
|
||||
assert.NotEqual(t, before, after, "demotion must change PromotedHash")
|
||||
}
|
||||
|
||||
func TestPromotedHash_StableWhenContentUnchangedAndPartitionStays(t *testing.T) {
|
||||
// Same snapshot + same retentionWindow → same PromotedHash.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "stable",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
rw := s3lifecycle.DaysToDuration(7) // promoted
|
||||
assert.Equal(t, PromotedHash(snap, rw), PromotedHash(snap, rw))
|
||||
}
|
||||
|
||||
func TestPromotedHash_MatchesRulesForShardWalkMembership(t *testing.T) {
|
||||
// PromotedHash must agree with RulesForShard about which replay-
|
||||
// eligible actions are in walk for the same retentionWindow.
|
||||
rules := []*s3lifecycle.Rule{
|
||||
{ID: "short", Status: s3lifecycle.StatusEnabled, ExpirationDays: 1},
|
||||
{ID: "long", Status: s3lifecycle.StatusEnabled, ExpirationDays: 90},
|
||||
{ID: "noncurrent", Status: s3lifecycle.StatusEnabled, NoncurrentVersionExpirationDays: 200},
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rules...)
|
||||
rw := s3lifecycle.DaysToDuration(30)
|
||||
|
||||
replay, walk := snap.RulesForShard(0, rw)
|
||||
require.NotNil(t, replay)
|
||||
require.NotNil(t, walk)
|
||||
|
||||
// Expected walk members (from replay-eligible kinds only): long, noncurrent.
|
||||
wantPromoted := map[s3lifecycle.ActionKey]struct{}{}
|
||||
for k := range walk.actions {
|
||||
if isReplayKind(k.ActionKind) {
|
||||
wantPromoted[k] = struct{}{}
|
||||
}
|
||||
}
|
||||
assert.Len(t, wantPromoted, 2, "two of three replay-eligible rules should promote")
|
||||
|
||||
hash := PromotedHash(snap, rw)
|
||||
var empty [32]byte
|
||||
assert.NotEqual(t, empty, hash)
|
||||
}
|
||||
|
||||
func TestMaxEffectiveTTL_NilAndEmpty(t *testing.T) {
|
||||
assert.Equal(t, time.Duration(0), MaxEffectiveTTL(nil))
|
||||
|
||||
// Snapshot with only walker-only kinds → no active replay action →
|
||||
// MaxEffectiveTTL returns 0.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "walk",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
assert.Equal(t, time.Duration(0), MaxEffectiveTTL(snap))
|
||||
}
|
||||
|
||||
func TestMaxEffectiveTTL_ReturnsMaxAcrossActiveReplay(t *testing.T) {
|
||||
// Three replay-eligible actions with mixed TTLs; MaxEffectiveTTL picks
|
||||
// the largest.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "mix",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 10,
|
||||
NoncurrentVersionExpirationDays: 60,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
got := MaxEffectiveTTL(snap)
|
||||
assert.Equal(t, s3lifecycle.DaysToDuration(60), got)
|
||||
}
|
||||
|
||||
func TestMaxEffectiveTTL_OperatesOnReplayView(t *testing.T) {
|
||||
// The caller passes the *replay* snapshot here in production. Verify
|
||||
// that on a replay view the answer is the max over the view's
|
||||
// (active) replay actions and excludes anything that was routed away
|
||||
// to walk via scan_only promotion.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "mix",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 10,
|
||||
NoncurrentVersionExpirationDays: 200, // would promote at small retention
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
// Retention 30d: ExpirationDays(10) stays in replay; NoncurrentDays(200)
|
||||
// promotes to walk. The replay view's MaxEffectiveTTL is therefore 10d.
|
||||
replay, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
require.NotNil(t, replay)
|
||||
assert.Equal(t, s3lifecycle.DaysToDuration(10), MaxEffectiveTTL(replay))
|
||||
}
|
||||
|
||||
func TestMaxEffectiveTTL_IgnoresInactiveActions(t *testing.T) {
|
||||
// Pre-BootstrapComplete event-driven action is in the snapshot but
|
||||
// inactive. MaxEffectiveTTL only counts active actions.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "pending",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{}, // no PriorState → inactive
|
||||
)
|
||||
for _, a := range snap.actions {
|
||||
require.False(t, a.IsActive(), "precondition")
|
||||
}
|
||||
assert.Equal(t, time.Duration(0), MaxEffectiveTTL(snap),
|
||||
"inactive replay actions must not contribute to MaxEffectiveTTL")
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Direct tests for Snapshot.OriginalDelayGroups / PredicateActions /
|
||||
// DateActions accessors and MarkActive/IsActive transitions. The Compile
|
||||
// tests exercise the construction path; these tests pin the read-side
|
||||
// surface the router and dispatcher reach for at runtime.
|
||||
|
||||
func TestSnapshot_OriginalDelayGroupsExposesCompiledGroups(t *testing.T) {
|
||||
// Two action kinds with different delays must land in distinct
|
||||
// delay groups so the dispatcher polls each at the right cadence.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{}
|
||||
for _, k := range s3lifecycle.RuleActionKinds(rule) {
|
||||
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
|
||||
BootstrapComplete: true,
|
||||
Mode: ModeEventDriven,
|
||||
}
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
groups := snap.OriginalDelayGroups()
|
||||
require.NotNil(t, groups)
|
||||
|
||||
// 7d expiration delay group must contain the specific expiration key.
|
||||
expirationDelay := s3lifecycle.MinTriggerAge(rule, s3lifecycle.ActionKindExpirationDays)
|
||||
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
assert.Contains(t, groups[expirationDelay], expirationKey, "expiration delay group must carry its specific key")
|
||||
|
||||
// 3d abort-mpu delay group is distinct and contains the abort key.
|
||||
abortDelay := s3lifecycle.MinTriggerAge(rule, s3lifecycle.ActionKindAbortMPU)
|
||||
assert.NotEqual(t, expirationDelay, abortDelay)
|
||||
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
|
||||
assert.Contains(t, groups[abortDelay], abortKey, "abort-mpu delay group must carry its specific key")
|
||||
}
|
||||
|
||||
func TestSnapshot_OriginalDelayGroupsScanOnlyExcluded(t *testing.T) {
|
||||
// Scan-only actions don't go through originalDelayGroups (they
|
||||
// fire from the bootstrap walk only), so the dispatcher's
|
||||
// MatchOriginalWrite path won't see them.
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
scanOnlyKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{
|
||||
scanOnlyKey: {BootstrapComplete: true, Mode: ModeScanOnly},
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
groups := snap.OriginalDelayGroups()
|
||||
for delay, keys := range groups {
|
||||
for _, k := range keys {
|
||||
assert.NotEqual(t, scanOnlyKey, k, "scan-only action leaked into delay group %v", delay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshot_PredicateActionsContainsTagSensitive(t *testing.T) {
|
||||
// A tag-sensitive rule's actions must surface in PredicateActions
|
||||
// so MatchPredicateChange routes them.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
FilterTags: map[string]string{"env": "prod"},
|
||||
}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{}
|
||||
for _, k := range s3lifecycle.RuleActionKinds(rule) {
|
||||
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
|
||||
BootstrapComplete: true,
|
||||
Mode: ModeEventDriven,
|
||||
}
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
predicates := snap.PredicateActions()
|
||||
require.NotEmpty(t, predicates, "tag-sensitive rule must populate predicateActions")
|
||||
// Verify the specific key landed (not just non-empty) so a routing
|
||||
// regression that emits a wrong ActionKey is caught.
|
||||
expectedKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
assert.Contains(t, predicates, expectedKey, "predicateActions must carry the rule's specific ActionKey")
|
||||
}
|
||||
|
||||
func TestSnapshot_PredicateActionsEmptyForNonTagSensitiveRule(t *testing.T) {
|
||||
// A rule without FilterTags is not predicate-sensitive; the
|
||||
// predicate-action list must stay empty so MatchPredicateChange
|
||||
// never routes irrelevant kinds.
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{},
|
||||
)
|
||||
assert.Empty(t, snap.PredicateActions())
|
||||
}
|
||||
|
||||
func TestSnapshot_DateActionsContainsExpirationDate(t *testing.T) {
|
||||
// EXPIRATION_DATE rules go into dateActions (not delay groups);
|
||||
// the scan-at-date scheduler reads from this map.
|
||||
when := time.Now().Add(24 * time.Hour)
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDate: when,
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{},
|
||||
)
|
||||
dateActions := snap.DateActions()
|
||||
require.NotEmpty(t, dateActions)
|
||||
for _, dt := range dateActions {
|
||||
assert.Equal(t, when, dt, "DateActions must surface the rule's ExpirationDate verbatim")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshot_DateActionsEmptyForNonDateRule(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{},
|
||||
)
|
||||
assert.Empty(t, snap.DateActions())
|
||||
}
|
||||
|
||||
func TestSnapshot_MarkActiveUnknownKeyIsNoOp(t *testing.T) {
|
||||
// MarkActive must silently skip keys that aren't in the snapshot;
|
||||
// the durable bootstrap-complete write can race with a recompile
|
||||
// that drops the rule, and a panic here would crash the worker.
|
||||
snap := New().Compile(nil, CompileOptions{})
|
||||
snap.MarkActive(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
|
||||
}
|
||||
|
||||
func TestSnapshot_MarkActiveFlipsCompiledActionToActive(t *testing.T) {
|
||||
// Bootstrap-pending actions land inactive; MarkActive transitions
|
||||
// them to active so the routing filter starts emitting matches.
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
key := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
// No prior state -> the action lands inactive (BootstrapComplete=false).
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{},
|
||||
)
|
||||
a := snap.Action(key)
|
||||
require.NotNil(t, a)
|
||||
assert.False(t, a.IsActive(), "fresh action without prior state must be inactive")
|
||||
snap.MarkActive(key)
|
||||
assert.True(t, a.IsActive(), "MarkActive must transition the action to active")
|
||||
}
|
||||
|
||||
func TestSnapshot_BucketIndexedActionKeysCoverAllKinds(t *testing.T) {
|
||||
// Cross-check that BucketActionKeys lists every kind compiled from
|
||||
// the rule, regardless of mode. The router iterates these for
|
||||
// MatchPath, so a missed kind silently disables prefix-only routing
|
||||
// for that action.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{},
|
||||
)
|
||||
keys := snap.BucketActionKeys("bk")
|
||||
wantKinds := s3lifecycle.RuleActionKinds(rule)
|
||||
require.Len(t, keys, len(wantKinds))
|
||||
|
||||
// Verify the contents, not just the count: every key must carry
|
||||
// the right bucket scope, and the kinds must match RuleActionKinds
|
||||
// element-for-element (in any order). Catches an indexing
|
||||
// regression that produces N keys but with wrong kinds.
|
||||
gotKinds := make([]s3lifecycle.ActionKind, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
assert.Equal(t, "bk", k.Bucket, "key leaked across bucket")
|
||||
gotKinds = append(gotKinds, k.ActionKind)
|
||||
}
|
||||
assert.ElementsMatch(t, wantKinds, gotKinds, "kinds must match RuleActionKinds")
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
)
|
||||
|
||||
// currentEngine is the package-level pointer the wiring will eventually
|
||||
// populate so daily_run can fetch the live snapshot through CurrentSnapshot.
|
||||
// Today the worker/scheduler owns its own *Engine and passes the snapshot
|
||||
// explicitly to its consumers; nothing calls SetCurrentEngine yet. Phase 4's
|
||||
// daily-replay caller will register the worker's engine here on startup so
|
||||
// the package-level helper resolves without threading the *Engine through
|
||||
// every layer.
|
||||
//
|
||||
// TODO(phase4-wiring): hook scheduler/worker startup to call SetCurrentEngine.
|
||||
var currentEngine atomic.Pointer[Engine]
|
||||
|
||||
// SetCurrentEngine installs e as the package-level engine returned by
|
||||
// CurrentSnapshot. Intended for the worker bootstrap path; tests may also
|
||||
// call it with a locally-constructed engine. Passing nil clears the pointer.
|
||||
func SetCurrentEngine(e *Engine) { currentEngine.Store(e) }
|
||||
|
||||
// CurrentSnapshot returns the latest *Snapshot from the package-level engine,
|
||||
// or nil if no engine has been registered yet. The caller is responsible for
|
||||
// nil-checking the return — a missing engine is treated as "no rules" so the
|
||||
// daily-run loop short-circuits cleanly instead of panicking during early
|
||||
// startup.
|
||||
//
|
||||
// TODO(phase4-wiring): SetCurrentEngine must be invoked at worker startup
|
||||
// for production callers; until then this returns nil.
|
||||
func CurrentSnapshot() *Snapshot {
|
||||
e := currentEngine.Load()
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Snapshot()
|
||||
}
|
||||
|
||||
// cloneAction makes an independent *CompiledAction for a per-view snapshot.
|
||||
// The clone shares Rule (immutable) and Key (value) with the base, but its
|
||||
// engineState (the active bit) is its own atomic — so flipping active on the
|
||||
// clone never reaches the base or any sibling view. Mode is set explicitly by
|
||||
// the caller to encode the per-view dispatch contract (replay forces
|
||||
// ModeEventDriven so router.Route's gate passes; walk and recovery preserve
|
||||
// the base Mode so the walker's "any non-Disabled" gate works as-is).
|
||||
func cloneAction(src *CompiledAction, mode RuleMode, active bool) *CompiledAction {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
dst := &CompiledAction{
|
||||
Rule: src.Rule,
|
||||
Bucket: src.Bucket,
|
||||
Key: src.Key,
|
||||
Delay: src.Delay,
|
||||
PredicateSensitive: src.PredicateSensitive,
|
||||
Mode: mode,
|
||||
}
|
||||
if active {
|
||||
dst.markActive()
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// newView constructs a *Snapshot that holds the supplied per-view action
|
||||
// clones but otherwise shares the base's immutable rule / index data by
|
||||
// pointer (see DESIGN.md "router.Route integration" — only `active` and
|
||||
// `Mode` differ per view; everything else is share-by-pointer).
|
||||
//
|
||||
// Returns nil if actions is empty: callers consume nil as "this partition
|
||||
// has no actions, skip the corresponding dispatch path."
|
||||
func newView(base *Snapshot, actions map[s3lifecycle.ActionKey]*CompiledAction) *Snapshot {
|
||||
if len(actions) == 0 {
|
||||
return nil
|
||||
}
|
||||
// allActionsSorted mirrors the base order: same comparator (Bucket,
|
||||
// RuleHash, ActionKind) so downstream iteration order is stable per view.
|
||||
sorted := make([]*CompiledAction, 0, len(actions))
|
||||
for _, a := range actions {
|
||||
sorted = append(sorted, a)
|
||||
}
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
a, b := sorted[i], sorted[j]
|
||||
if a.Bucket != b.Bucket {
|
||||
return a.Bucket < b.Bucket
|
||||
}
|
||||
if c := bytes.Compare(a.Key.RuleHash[:], b.Key.RuleHash[:]); c != 0 {
|
||||
return c < 0
|
||||
}
|
||||
return a.Key.ActionKind < b.Key.ActionKind
|
||||
})
|
||||
return &Snapshot{
|
||||
id: base.id,
|
||||
buckets: base.buckets,
|
||||
actions: actions,
|
||||
allActionsSorted: sorted,
|
||||
originalDelayGroups: base.originalDelayGroups,
|
||||
predicateActions: base.predicateActions,
|
||||
dateActions: base.dateActions,
|
||||
}
|
||||
}
|
||||
|
||||
// isReplayKind reports whether ActionKind is a candidate for the replay
|
||||
// partition: its trigger derives from a single event's TsNs (or a stamped
|
||||
// noncurrent_since), so the meta-log scan can drive dispatch directly.
|
||||
// ExpirationDate / ExpiredDeleteMarker / NewerNoncurrent are walker-only
|
||||
// because their due time depends on current bucket state, not event age.
|
||||
func isReplayKind(k s3lifecycle.ActionKind) bool {
|
||||
switch k {
|
||||
case s3lifecycle.ActionKindExpirationDays,
|
||||
s3lifecycle.ActionKindNoncurrentDays,
|
||||
s3lifecycle.ActionKindAbortMPU:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// effectiveTTL is the duration used both for partition membership
|
||||
// (TTL ≤ retentionWindow → replay) and MaxEffectiveTTL math (driving the
|
||||
// cursor's sliding scan window). Walker-only kinds return 0 so they never
|
||||
// contribute to MaxEffectiveTTL and never satisfy the partition gate when
|
||||
// retentionWindow is finite.
|
||||
func effectiveTTL(a *CompiledAction) time.Duration {
|
||||
if a == nil || a.Rule == nil {
|
||||
return 0
|
||||
}
|
||||
switch a.Key.ActionKind {
|
||||
case s3lifecycle.ActionKindExpirationDays:
|
||||
if a.Rule.ExpirationDays > 0 {
|
||||
return s3lifecycle.DaysToDuration(a.Rule.ExpirationDays)
|
||||
}
|
||||
case s3lifecycle.ActionKindNoncurrentDays:
|
||||
if a.Rule.NoncurrentVersionExpirationDays > 0 {
|
||||
return s3lifecycle.DaysToDuration(a.Rule.NoncurrentVersionExpirationDays)
|
||||
}
|
||||
case s3lifecycle.ActionKindAbortMPU:
|
||||
if a.Rule.AbortMPUDaysAfterInitiation > 0 {
|
||||
return s3lifecycle.DaysToDuration(a.Rule.AbortMPUDaysAfterInitiation)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// RulesForShard partitions the base snapshot's compiled actions into a
|
||||
// replay view and a walk view.
|
||||
//
|
||||
// shardID is **reserved for forward-compatibility** and not consumed by
|
||||
// this implementation. Every shard sees every rule today because the
|
||||
// shard filter runs at the entry-iteration site (meta-log subscription
|
||||
// per shard, walker entry-loop ShardID check) rather than at view
|
||||
// construction. Keeping the parameter in the signature preserves the
|
||||
// API surface for a future move to per-shard rule sets (e.g. when
|
||||
// bucket-shard ownership is added) — removing it now would be a
|
||||
// breaking change at that future point. See DESIGN.md "open questions
|
||||
// → per-shard rule snapshots vs. global."
|
||||
//
|
||||
// retentionWindow is the only window input the engine sees; the
|
||||
// daily_run caller computes it as `now - earliest_available` and
|
||||
// passes it in so the partition is stable across one daily_run
|
||||
// invocation.
|
||||
//
|
||||
// Membership:
|
||||
// - replay: clones of ExpirationDays / NoncurrentDays / AbortMPU actions
|
||||
// whose TTL ≤ retentionWindow. active=true, Mode forced to
|
||||
// ModeEventDriven (rehabilitating any prior ModeScanOnly lock-in so
|
||||
// router.Route's gate accepts the clone).
|
||||
// - walk: clones of ExpirationDate / ExpiredDeleteMarker / NewerNoncurrent
|
||||
// actions, plus any replay-eligible action whose TTL exceeds
|
||||
// retentionWindow (the "scan_only promotion" path). active=true, Mode
|
||||
// preserved from the base — the walker only rejects ModeDisabled.
|
||||
//
|
||||
// Either return value may be nil when its partition has no actions.
|
||||
// Disabled actions (Mode == ModeDisabled) are excluded from both views.
|
||||
func (s *Snapshot) RulesForShard(shardID int, retentionWindow time.Duration) (replay, walk *Snapshot) {
|
||||
_ = shardID
|
||||
if s == nil {
|
||||
return nil, nil
|
||||
}
|
||||
replayActions := map[s3lifecycle.ActionKey]*CompiledAction{}
|
||||
walkActions := map[s3lifecycle.ActionKey]*CompiledAction{}
|
||||
for key, a := range s.actions {
|
||||
if a == nil || a.Mode == ModeDisabled {
|
||||
continue
|
||||
}
|
||||
if isReplayKind(key.ActionKind) {
|
||||
ttl := effectiveTTL(a)
|
||||
// retentionWindow == 0 means "no retention info supplied" — the
|
||||
// caller should treat the partition as walk-only to stay safe,
|
||||
// since promoting every rule into replay without retention
|
||||
// proof would defeat the scan_only protection. ttl == 0 is a
|
||||
// malformed rule (kind says replay but no TTL): also routes to
|
||||
// walk so the walker can decide.
|
||||
if ttl > 0 && ttl <= retentionWindow {
|
||||
replayActions[key] = cloneAction(a, ModeEventDriven, true)
|
||||
} else {
|
||||
walkActions[key] = cloneAction(a, a.Mode, true)
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Walker-only kinds: preserve Mode (ModeScanAtDate for
|
||||
// ExpirationDate, ModeEventDriven for the others) so the walker's
|
||||
// per-rule evaluator runs as today.
|
||||
walkActions[key] = cloneAction(a, a.Mode, true)
|
||||
}
|
||||
return newView(s, replayActions), newView(s, walkActions)
|
||||
}
|
||||
|
||||
// RecoveryView returns a *Snapshot that contains a clone of every action in
|
||||
// the base, with active=true regardless of compile-time IsActive/
|
||||
// BootstrapComplete and Mode preserved as-is. The recovery walker uses this
|
||||
// view to catch already-due objects across the full rule set on cold start,
|
||||
// rule edit, retention loss, or partition flip. Disabled actions stay out —
|
||||
// recovery shouldn't resurrect an explicitly disabled rule.
|
||||
//
|
||||
// Unlike RulesForShard, RecoveryView takes no retentionWindow: every
|
||||
// non-disabled action is activated, partition-independent, because recovery
|
||||
// must reach rules whose subjects sit outside the replay scan window.
|
||||
func RecoveryView(s *Snapshot) *Snapshot {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
actions := map[s3lifecycle.ActionKey]*CompiledAction{}
|
||||
for key, a := range s.actions {
|
||||
if a == nil || a.Mode == ModeDisabled {
|
||||
continue
|
||||
}
|
||||
actions[key] = cloneAction(a, a.Mode, true)
|
||||
}
|
||||
return newView(s, actions)
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// buildSnapshotForViews compiles a snapshot with a single bucket containing
|
||||
// one rule per supplied factory, marking every action bootstrap_complete so
|
||||
// the base actions are active. Tests can then call RulesForShard and assert
|
||||
// the per-view clones come out independent.
|
||||
func buildSnapshotForViews(t *testing.T, bucket string, rules ...*s3lifecycle.Rule) *Snapshot {
|
||||
t.Helper()
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{}
|
||||
for _, r := range rules {
|
||||
rh := s3lifecycle.RuleHash(r)
|
||||
for _, k := range s3lifecycle.RuleActionKinds(r) {
|
||||
prior[s3lifecycle.ActionKey{Bucket: bucket, RuleHash: rh, ActionKind: k}] = PriorState{
|
||||
BootstrapComplete: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
return New().Compile(
|
||||
[]CompileInput{{Bucket: bucket, Rules: rules}},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
}
|
||||
|
||||
func TestCurrentSnapshot_NilWhenNoEngineRegistered(t *testing.T) {
|
||||
// Save and restore the package-level pointer so tests stay isolated.
|
||||
prev := currentEngine.Load()
|
||||
t.Cleanup(func() { currentEngine.Store(prev) })
|
||||
|
||||
SetCurrentEngine(nil)
|
||||
assert.Nil(t, CurrentSnapshot())
|
||||
}
|
||||
|
||||
func TestCurrentSnapshot_ReturnsRegisteredEngineSnapshot(t *testing.T) {
|
||||
prev := currentEngine.Load()
|
||||
t.Cleanup(func() { currentEngine.Store(prev) })
|
||||
|
||||
e := New()
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := e.Compile([]CompileInput{{Bucket: "b", Rules: []*s3lifecycle.Rule{rule}}}, CompileOptions{})
|
||||
SetCurrentEngine(e)
|
||||
assert.Same(t, snap, CurrentSnapshot())
|
||||
}
|
||||
|
||||
func TestRulesForShard_NilSnapshot(t *testing.T) {
|
||||
var s *Snapshot
|
||||
replay, walk := s.RulesForShard(0, 30*24*time.Hour)
|
||||
assert.Nil(t, replay)
|
||||
assert.Nil(t, walk)
|
||||
}
|
||||
|
||||
func TestRulesForShard_ReplayPartitionMembership(t *testing.T) {
|
||||
// ExpirationDays / NoncurrentDays / AbortMPU below retentionWindow all
|
||||
// land in replay; the replay map carries clones with active=true and
|
||||
// Mode=ModeEventDriven.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "all-replay",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 3,
|
||||
NoncurrentVersionExpirationDays: 5,
|
||||
AbortMPUDaysAfterInitiation: 2,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
require.NotNil(t, replay, "all three replay-eligible kinds should land in replay")
|
||||
assert.Nil(t, walk, "no walker kinds, no scan_only promotion, walk should be empty")
|
||||
assert.Len(t, replay.actions, 3)
|
||||
for k, a := range replay.actions {
|
||||
assert.True(t, a.IsActive(), "replay clone must be active for kind %v", k.ActionKind)
|
||||
assert.Equal(t, ModeEventDriven, a.Mode, "replay Mode must be ModeEventDriven for kind %v", k.ActionKind)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRulesForShard_WalkOnlyKindsRouteToWalk(t *testing.T) {
|
||||
// ExpirationDate, ExpiredObjectDeleteMarker, NewerNoncurrent are walker-
|
||||
// only and must land in walk regardless of retentionWindow.
|
||||
when := time.Now().Add(24 * time.Hour)
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "walker-mix",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDate: when,
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
NewerNoncurrentVersions: 2,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
assert.Nil(t, replay, "walker-only rule has no replay partition")
|
||||
require.NotNil(t, walk)
|
||||
assert.Len(t, walk.actions, 3, "all three walker kinds should land in walk")
|
||||
for _, a := range walk.actions {
|
||||
assert.True(t, a.IsActive())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRulesForShard_MultiActionXMLRuleSplits(t *testing.T) {
|
||||
// A single XML rule that compiles to ExpirationDays + NewerNoncurrent
|
||||
// must split: ExpirationDays → replay, NewerNoncurrent → walk.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "split",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 3,
|
||||
NewerNoncurrentVersions: 5,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
require.NotNil(t, replay)
|
||||
require.NotNil(t, walk)
|
||||
assert.Len(t, replay.actions, 1)
|
||||
assert.Len(t, walk.actions, 1)
|
||||
for k := range replay.actions {
|
||||
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, k.ActionKind)
|
||||
}
|
||||
for k := range walk.actions {
|
||||
assert.Equal(t, s3lifecycle.ActionKindNewerNoncurrent, k.ActionKind)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRulesForShard_ScanOnlyPromotionRoutesToWalk(t *testing.T) {
|
||||
// A replay-eligible kind whose TTL exceeds retentionWindow promotes to
|
||||
// walk. The clone's active=true is set; Mode is preserved as-is from
|
||||
// the base (the walker only rejects ModeDisabled).
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "long",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 90,
|
||||
AbortMPUDaysAfterInitiation: 1,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
// Retention window of 30 days promotes ExpirationDays(90d) to walk;
|
||||
// AbortMPU(1d) stays in replay.
|
||||
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
require.NotNil(t, replay)
|
||||
require.NotNil(t, walk)
|
||||
assert.Len(t, replay.actions, 1)
|
||||
assert.Len(t, walk.actions, 1)
|
||||
for k, a := range replay.actions {
|
||||
assert.Equal(t, s3lifecycle.ActionKindAbortMPU, k.ActionKind)
|
||||
assert.Equal(t, ModeEventDriven, a.Mode)
|
||||
}
|
||||
for k := range walk.actions {
|
||||
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, k.ActionKind)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRulesForShard_ReplayRewritesScanOnlyMode(t *testing.T) {
|
||||
// A base action carrying Mode=ModeScanOnly via PriorState must still
|
||||
// land in replay as ModeEventDriven once retention rehabilitates its
|
||||
// TTL. router.Route gates on ModeEventDriven, so this is the
|
||||
// rehabilitation contract.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "rehab",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 5,
|
||||
}
|
||||
rh := s3lifecycle.RuleHash(rule)
|
||||
key := s3lifecycle.ActionKey{Bucket: "b1", RuleHash: rh, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{
|
||||
PriorStates: map[s3lifecycle.ActionKey]PriorState{
|
||||
// Persistent ModeScanOnly carried over from a prior compile.
|
||||
key: {BootstrapComplete: true, Mode: ModeScanOnly},
|
||||
},
|
||||
},
|
||||
)
|
||||
// Verify the base really did keep ModeScanOnly (Compile preserves it).
|
||||
require.Equal(t, ModeScanOnly, snap.actions[key].Mode)
|
||||
|
||||
replay, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
require.NotNil(t, replay)
|
||||
clone := replay.actions[key]
|
||||
require.NotNil(t, clone)
|
||||
assert.Equal(t, ModeEventDriven, clone.Mode, "replay must force ModeEventDriven on the clone")
|
||||
assert.True(t, clone.IsActive())
|
||||
}
|
||||
|
||||
func TestRulesForShard_DisabledRuleExcludedFromBothViews(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{ID: "off", Status: s3lifecycle.StatusDisabled, ExpirationDays: 7}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
replay, walk := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
assert.Nil(t, replay)
|
||||
assert.Nil(t, walk)
|
||||
}
|
||||
|
||||
func TestRulesForShard_ClonesAreIndependentOfBase(t *testing.T) {
|
||||
// Toggling active on a view clone must never propagate to the base
|
||||
// action — that's the whole point of cloning per view.
|
||||
rule := &s3lifecycle.Rule{ID: "iso", Status: s3lifecycle.StatusEnabled, ExpirationDays: 3}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
key := s3lifecycle.ActionKey{
|
||||
Bucket: "b1",
|
||||
RuleHash: s3lifecycle.RuleHash(rule),
|
||||
ActionKind: s3lifecycle.ActionKindExpirationDays,
|
||||
}
|
||||
base := snap.Action(key)
|
||||
require.NotNil(t, base)
|
||||
baseActiveBefore := base.IsActive()
|
||||
|
||||
replay, _ := snap.RulesForShard(0, s3lifecycle.DaysToDuration(30))
|
||||
require.NotNil(t, replay)
|
||||
clone := replay.actions[key]
|
||||
require.NotNil(t, clone)
|
||||
assert.NotSame(t, base, clone, "clone must be a distinct *CompiledAction")
|
||||
|
||||
// Force the clone inactive (write directly to its atomic so we exercise
|
||||
// the active bit boundary, not just markActive's setter).
|
||||
clone.engineState.Store(engineStateInactive)
|
||||
assert.False(t, clone.IsActive())
|
||||
assert.Equal(t, baseActiveBefore, base.IsActive(),
|
||||
"toggling the clone must not perturb the base's active bit")
|
||||
}
|
||||
|
||||
func TestRulesForShard_ZeroRetentionRoutesAllReplayKindsToWalk(t *testing.T) {
|
||||
// retentionWindow == 0 (no proven retention) must route every replay-
|
||||
// eligible action into walk — the partition is "ttl > 0 && ttl <=
|
||||
// retentionWindow", and 0 fails the upper bound. This is the safe
|
||||
// default before the meta-log horizon is known.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "any",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 1,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
replay, walk := snap.RulesForShard(0, 0)
|
||||
assert.Nil(t, replay)
|
||||
require.NotNil(t, walk)
|
||||
assert.Len(t, walk.actions, 1)
|
||||
}
|
||||
|
||||
func TestRecoveryView_ActivatesEveryNonDisabledAction(t *testing.T) {
|
||||
// Base snapshot has no PriorState → event-driven actions land inactive
|
||||
// (pre-BootstrapComplete). Recovery view must clone them with active=
|
||||
// true so the recovery walker emits matches for them.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "pending",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{}, // no PriorStates → action lands inactive
|
||||
)
|
||||
key := s3lifecycle.ActionKey{
|
||||
Bucket: "b1",
|
||||
RuleHash: s3lifecycle.RuleHash(rule),
|
||||
ActionKind: s3lifecycle.ActionKindExpirationDays,
|
||||
}
|
||||
require.False(t, snap.actions[key].IsActive(), "precondition: base action must be inactive")
|
||||
|
||||
rv := RecoveryView(snap)
|
||||
require.NotNil(t, rv)
|
||||
clone := rv.actions[key]
|
||||
require.NotNil(t, clone)
|
||||
assert.True(t, clone.IsActive(), "recovery view must force-activate even pre-BootstrapComplete actions")
|
||||
assert.Equal(t, ModeEventDriven, clone.Mode, "recovery preserves base Mode")
|
||||
}
|
||||
|
||||
func TestRecoveryView_PreservesBaseModeForScanAtDate(t *testing.T) {
|
||||
// ScanAtDate actions are active at compile time (no BootstrapComplete
|
||||
// requirement). Recovery view must keep their Mode as ModeScanAtDate so
|
||||
// the walker's date evaluator runs as expected — a Mode rewrite here
|
||||
// would re-route them through the event-driven gate by mistake.
|
||||
when := time.Now().Add(48 * time.Hour)
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "d",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDate: when,
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{},
|
||||
)
|
||||
rv := RecoveryView(snap)
|
||||
require.NotNil(t, rv)
|
||||
require.Len(t, rv.actions, 1)
|
||||
for _, a := range rv.actions {
|
||||
assert.Equal(t, ModeScanAtDate, a.Mode)
|
||||
assert.True(t, a.IsActive())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoveryView_ExcludesDisabledRules(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "off",
|
||||
Status: s3lifecycle.StatusDisabled,
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
rv := RecoveryView(snap)
|
||||
assert.Nil(t, rv, "disabled rules must not surface in recovery view")
|
||||
}
|
||||
|
||||
func TestRecoveryView_ClonesAreIndependentOfBase(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{ID: "iso", Status: s3lifecycle.StatusEnabled, ExpirationDays: 3}
|
||||
snap := buildSnapshotForViews(t, "b1", rule)
|
||||
key := s3lifecycle.ActionKey{
|
||||
Bucket: "b1",
|
||||
RuleHash: s3lifecycle.RuleHash(rule),
|
||||
ActionKind: s3lifecycle.ActionKindExpirationDays,
|
||||
}
|
||||
base := snap.Action(key)
|
||||
baseActiveBefore := base.IsActive()
|
||||
|
||||
rv := RecoveryView(snap)
|
||||
require.NotNil(t, rv)
|
||||
clone := rv.actions[key]
|
||||
require.NotNil(t, clone)
|
||||
assert.NotSame(t, base, clone)
|
||||
|
||||
clone.engineState.Store(engineStateInactive)
|
||||
assert.Equal(t, baseActiveBefore, base.IsActive(),
|
||||
"flipping the recovery clone must not perturb the base")
|
||||
}
|
||||
|
||||
func TestRecoveryView_NilSnapshot(t *testing.T) {
|
||||
assert.Nil(t, RecoveryView(nil))
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package s3lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Final unit-test cleanup ahead of the integration suite. Pins the
|
||||
// remaining 0%-and-default-branch helpers in the s3lifecycle package
|
||||
// and the lifecycletest builder so a regression doesn't slip in
|
||||
// during the integration work that follows.
|
||||
|
||||
func TestActionKind_StringUnspecifiedDefault(t *testing.T) {
|
||||
// String's default branch (covers ActionKindUnspecified and any
|
||||
// future enum value not listed) must render "unspecified" rather
|
||||
// than empty or panic. Operators read this via the metrics labels
|
||||
// (see S3LifecycleDispatchCounter "kind").
|
||||
assert.Equal(t, "unspecified", ActionKindUnspecified.String())
|
||||
assert.Equal(t, "unspecified", ActionKind(99).String())
|
||||
}
|
||||
|
||||
func TestHashExtended_DirectFromLifecyclePackage(t *testing.T) {
|
||||
// HashExtended is exercised from the s3api package's identity
|
||||
// tests; pin it here so the s3lifecycle package's own coverage
|
||||
// reflects the call. A nil/empty map produces no bytes, so the
|
||||
// CAS witness collapses to "no Extended" rather than a synthetic
|
||||
// hash that would mismatch on the server.
|
||||
assert.Empty(t, HashExtended(nil))
|
||||
assert.Empty(t, HashExtended(map[string][]byte{}))
|
||||
got := HashExtended(map[string][]byte{"a": []byte("1")})
|
||||
assert.NotEmpty(t, got)
|
||||
// Same content, different literal/insertion order across multiple
|
||||
// keys: hash must be stable. A single-key check can't catch an
|
||||
// iteration-order regression — multiple keys force the helper's
|
||||
// sort path to actually do work.
|
||||
first := HashExtended(map[string][]byte{
|
||||
"a": []byte("1"),
|
||||
"b": []byte("2"),
|
||||
"c": []byte("3"),
|
||||
})
|
||||
second := HashExtended(map[string][]byte{
|
||||
"c": []byte("3"),
|
||||
"a": []byte("1"),
|
||||
"b": []byte("2"),
|
||||
})
|
||||
assert.Equal(t, first, second, "hash must be insensitive to map iteration order")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package lifecycletest
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Coverage gap-fillers for the With* options' OldEntry-only branches
|
||||
// (NewEntry==nil, OldEntry populated — i.e. Delete events). The
|
||||
// existing eventbuilder_test.go covers Create events; these tests
|
||||
// exercise the alternate fall-through path on each option.
|
||||
|
||||
func TestEventOption_WithModTime_AppliesToOldEntryOnDelete(t *testing.T) {
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
override := time.Unix(1699000000, 250)
|
||||
e := NewDelete("bk", "k", t0, WithModTime(override))
|
||||
require.Nil(t, e.NewEntry)
|
||||
require.NotNil(t, e.OldEntry)
|
||||
assert.Equal(t, override.Unix(), e.OldEntry.Attributes.Mtime)
|
||||
assert.Equal(t, int32(250), e.OldEntry.Attributes.MtimeNs)
|
||||
}
|
||||
|
||||
func TestEventOption_WithTtlSec_AppliesToOldEntryOnDelete(t *testing.T) {
|
||||
e := NewDelete("bk", "k", time.Unix(0, 0), WithTtlSec(7200))
|
||||
require.NotNil(t, e.OldEntry)
|
||||
assert.Equal(t, int32(7200), e.OldEntry.Attributes.TtlSec)
|
||||
}
|
||||
|
||||
func TestEventOption_WithVersionID_AppliesToOldEntryOnDelete(t *testing.T) {
|
||||
// VersionID-on-delete: the bootstrapper synthesizes deletes for
|
||||
// noncurrent-version sweeps and needs the version-id stamp.
|
||||
e := NewDelete("bk", "k", time.Unix(0, 0), WithVersionID("v_old"))
|
||||
require.NotNil(t, e.OldEntry)
|
||||
require.NotNil(t, e.OldEntry.Extended)
|
||||
assert.Equal(t, []byte("v_old"), e.OldEntry.Extended[s3_constants.ExtVersionIdKey])
|
||||
}
|
||||
|
||||
func TestEventOption_WithExtended_AppliesToOldEntryOnDelete(t *testing.T) {
|
||||
e := NewDelete("bk", "k", time.Unix(0, 0), WithExtended("Custom-Tag", []byte("v")))
|
||||
require.NotNil(t, e.OldEntry)
|
||||
require.NotNil(t, e.OldEntry.Extended)
|
||||
assert.Equal(t, []byte("v"), e.OldEntry.Extended["Custom-Tag"])
|
||||
}
|
||||
|
||||
func TestEventOption_WithChunks_AppliesToOldEntryOnDelete(t *testing.T) {
|
||||
c := &filer_pb.FileChunk{FileId: "1,old"}
|
||||
e := NewDelete("bk", "k", time.Unix(0, 0), WithChunks(c))
|
||||
require.NotNil(t, e.OldEntry)
|
||||
require.Len(t, e.OldEntry.Chunks, 1)
|
||||
assert.Equal(t, "1,old", e.OldEntry.Chunks[0].FileId)
|
||||
}
|
||||
|
||||
func TestEventOption_WithBootstrapVersion(t *testing.T) {
|
||||
// WithBootstrapVersion attaches a BootstrapVersion to the event;
|
||||
// the bootstrap walker uses this for per-version state the live
|
||||
// meta-log doesn't carry. Pin both create and delete shapes.
|
||||
bv := &reader.BootstrapVersion{
|
||||
LogicalKey: "obj.txt",
|
||||
VersionID: "v_aaa",
|
||||
IsLatest: true,
|
||||
IsDeleteMarker: false,
|
||||
NumVersions: 3,
|
||||
NoncurrentIndex: 2,
|
||||
}
|
||||
|
||||
create := NewCreate("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
|
||||
require.Same(t, bv, create.BootstrapVersion)
|
||||
|
||||
del := NewDelete("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
|
||||
require.Same(t, bv, del.BootstrapVersion)
|
||||
|
||||
update := NewUpdate("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
|
||||
require.Same(t, bv, update.BootstrapVersion)
|
||||
}
|
||||
|
||||
func TestEventOption_NoPanicOnEmptyEvent(t *testing.T) {
|
||||
// Defense: an event with neither NewEntry nor OldEntry must not
|
||||
// panic on any With* option, even though no constructor produces
|
||||
// this shape today. Entry-targeting options fall through silently
|
||||
// (NewEntry/OldEntry stay nil); WithBootstrapVersion targets the
|
||||
// event itself, not an entry, so it does set BootstrapVersion —
|
||||
// included here for panic safety.
|
||||
e := &reader.Event{}
|
||||
WithModTime(time.Unix(1, 0))(e)
|
||||
WithTtlSec(60)(e)
|
||||
WithVersionID("v")(e)
|
||||
WithExtended("k", []byte("v"))(e)
|
||||
WithChunks(&filer_pb.FileChunk{FileId: "x"})(e)
|
||||
WithSize(1024)(e)
|
||||
bv := &reader.BootstrapVersion{VersionID: "v"}
|
||||
WithBootstrapVersion(bv)(e)
|
||||
|
||||
assert.Nil(t, e.NewEntry, "entry-targeting options must not allocate NewEntry")
|
||||
assert.Nil(t, e.OldEntry, "entry-targeting options must not allocate OldEntry")
|
||||
assert.Same(t, bv, e.BootstrapVersion, "WithBootstrapVersion sets the field regardless of entry state")
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package s3lifecycle
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// SuccessorFromEntryStamp returns the explicit noncurrent-since timestamp
|
||||
// written by the S3 PUT handler at demotion time
|
||||
// (s3_constants.ExtNoncurrentSinceNsKey). Returns zero time if the stamp
|
||||
// is missing or unparseable — the caller falls back to derived values
|
||||
// (sibling mtime or entry mtime) for legacy entries written before the
|
||||
// stamp existed.
|
||||
//
|
||||
// The lifecycle engine prefers this stamp over the legacy
|
||||
// "next-newer sibling mtime" derivation because it records the exact
|
||||
// moment a version was demoted, immune to later mtime edits on the
|
||||
// sibling. The router and bootstrap walker both read it through this
|
||||
// helper so the parsing rules — non-positive, unparseable, missing —
|
||||
// stay in one place.
|
||||
func SuccessorFromEntryStamp(entry *filer_pb.Entry) time.Time {
|
||||
if entry == nil {
|
||||
return time.Time{}
|
||||
}
|
||||
raw, ok := entry.Extended[s3_constants.ExtNoncurrentSinceNsKey]
|
||||
if !ok || len(raw) == 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
ns, err := strconv.ParseInt(string(raw), 10, 64)
|
||||
if err != nil || ns <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Unix(0, ns)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package s3lifecycle
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Direct coverage for the parser. The router and the bootstrap walker
|
||||
// both go through this single helper to read the demotion stamp, so
|
||||
// pinning every parsing branch here keeps that contract enforced even
|
||||
// as the call sites evolve.
|
||||
|
||||
func TestSuccessorFromEntryStamp_NilOrMissingReturnsZero(t *testing.T) {
|
||||
assert.True(t, SuccessorFromEntryStamp(nil).IsZero())
|
||||
assert.True(t, SuccessorFromEntryStamp(&filer_pb.Entry{}).IsZero())
|
||||
assert.True(t, SuccessorFromEntryStamp(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{},
|
||||
}).IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorFromEntryStamp_EmptyOrInvalidReturnsZero(t *testing.T) {
|
||||
for _, raw := range [][]byte{nil, []byte(""), []byte("nope")} {
|
||||
got := SuccessorFromEntryStamp(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: raw},
|
||||
})
|
||||
assert.True(t, got.IsZero(), "value %q must produce zero time", string(raw))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessorFromEntryStamp_NonPositiveReturnsZero(t *testing.T) {
|
||||
// Stamps are wall-clock UnixNano captured at demotion time; <=0
|
||||
// signals "not set" — caller falls back to derived sibling mtime.
|
||||
for _, raw := range []string{"0", "-1"} {
|
||||
got := SuccessorFromEntryStamp(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte(raw)},
|
||||
})
|
||||
assert.True(t, got.IsZero(), "value %q must produce zero time", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessorFromEntryStamp_PositiveNanosRoundTrip(t *testing.T) {
|
||||
const ns int64 = 1700000000_123456789
|
||||
got := SuccessorFromEntryStamp(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte("1700000000123456789")},
|
||||
})
|
||||
assert.Equal(t, time.Unix(0, ns).UTC(), got.UTC())
|
||||
}
|
||||
|
||||
func TestSuccessorFromEntryStamp_OrderedNanosStayOrdered(t *testing.T) {
|
||||
// Pins the read contract: if two stamps were written in increasing
|
||||
// nanosecond order, the parser must return Times in the same order.
|
||||
// Uses fixed nanosecond values rather than time.Now().UnixNano() —
|
||||
// UnixNano() drops the monotonic component, so back-to-back calls
|
||||
// can decrease if the wall clock steps backward and the property
|
||||
// being verified would then exercise OS clock behavior, not the
|
||||
// parser.
|
||||
require := require.New(t)
|
||||
const earlier int64 = 1700000000_000000001
|
||||
const later int64 = 1700000000_000000002
|
||||
|
||||
earlierEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte(strconv.FormatInt(earlier, 10))},
|
||||
}
|
||||
laterEntry := &filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtNoncurrentSinceNsKey: []byte(strconv.FormatInt(later, 10))},
|
||||
}
|
||||
require.False(SuccessorFromEntryStamp(earlierEntry).After(SuccessorFromEntryStamp(laterEntry)),
|
||||
"parser must preserve write-order between two stamps")
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package reader
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// IsCreate / IsDelete are the small but routing-critical predicates
|
||||
// the dispatcher uses to decide which match path applies. Both were
|
||||
// previously exercised only through end-to-end Tick/Match tests; pin
|
||||
// them directly here.
|
||||
|
||||
func TestEventIsCreate_PopulatedNewEntryNoOldEntry(t *testing.T) {
|
||||
e := &Event{NewEntry: &filer_pb.Entry{Name: "k"}}
|
||||
assert.True(t, e.IsCreate())
|
||||
assert.False(t, e.IsDelete())
|
||||
}
|
||||
|
||||
func TestEventIsDelete_PopulatedOldEntryNoNewEntry(t *testing.T) {
|
||||
e := &Event{OldEntry: &filer_pb.Entry{Name: "k"}}
|
||||
assert.True(t, e.IsDelete())
|
||||
assert.False(t, e.IsCreate())
|
||||
}
|
||||
|
||||
func TestEventBothEntries_NeitherCreateNorDelete(t *testing.T) {
|
||||
// An update event carries both old and new; the predicates are
|
||||
// strict (one or the other, not both) so the router can route
|
||||
// updates through the dedicated path rather than treating them
|
||||
// as creates or deletes.
|
||||
e := &Event{
|
||||
OldEntry: &filer_pb.Entry{Name: "k"},
|
||||
NewEntry: &filer_pb.Entry{Name: "k"},
|
||||
}
|
||||
assert.False(t, e.IsCreate(), "update event must not classify as create")
|
||||
assert.False(t, e.IsDelete(), "update event must not classify as delete")
|
||||
}
|
||||
|
||||
func TestEventNoEntries_NeitherCreateNorDelete(t *testing.T) {
|
||||
// A degenerate event with neither side populated must not classify
|
||||
// as either; otherwise a metadata-only filer event with no bucket
|
||||
// payload could trigger spurious dispatches.
|
||||
e := &Event{}
|
||||
assert.False(t, e.IsCreate())
|
||||
assert.False(t, e.IsDelete())
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package reader
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// LogStartup writes a single glog line summarising the reader's
|
||||
// resume position; the only behavioral output is a side effect on the
|
||||
// log sink, but exercising both branches still pins compile-time
|
||||
// shape (e.g. that ShardPredicate-set readers don't trip on a missing
|
||||
// ShardID and vice versa) and lets coverage actually visit the code.
|
||||
|
||||
func TestLogStartup_ShardIDOnly(t *testing.T) {
|
||||
// Single-shard configuration: ShardID is set, ShardPredicate is nil,
|
||||
// no Cursor, no StartTsNs. The function must run without panic.
|
||||
r := &Reader{ShardID: 7, EventBudget: 100}
|
||||
r.LogStartup()
|
||||
}
|
||||
|
||||
func TestLogStartup_ShardPredicate(t *testing.T) {
|
||||
// ShardPredicate-set readers take a different log branch; pinning
|
||||
// the call here catches a regression that returns or panics.
|
||||
r := &Reader{
|
||||
ShardPredicate: func(int) bool { return true },
|
||||
EventBudget: 100,
|
||||
}
|
||||
r.LogStartup()
|
||||
}
|
||||
|
||||
func TestLogStartup_StartTsNsOverridesCursor(t *testing.T) {
|
||||
// Explicit StartTsNs takes precedence over Cursor.MinTsNs; this
|
||||
// branch is otherwise only hit when a worker is replaying a
|
||||
// specific position. Run it through to make sure the override is
|
||||
// honored without consulting the Cursor.
|
||||
r := &Reader{ShardID: 0, StartTsNs: 1700000000_000_000_000, Cursor: NewCursor()}
|
||||
r.LogStartup()
|
||||
}
|
||||
|
||||
func TestLogStartup_CursorMinFallback(t *testing.T) {
|
||||
// StartTsNs=0 with a non-nil Cursor falls back to Cursor.MinTsNs.
|
||||
c := NewCursor()
|
||||
r := &Reader{ShardID: 0, Cursor: c}
|
||||
r.LogStartup()
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Direct coverage for the pure helpers in router.go that the larger
|
||||
// Route* tests exercise indirectly. Pinning each one separately catches
|
||||
// regressions before they manifest as a broader Route failure that's
|
||||
// harder to diagnose.
|
||||
|
||||
// ---------- successorModTimeFromContainer ----------
|
||||
|
||||
func TestSuccessorModTimeFromContainer_MissingExtReturnsZero(t *testing.T) {
|
||||
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{}).IsZero())
|
||||
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{},
|
||||
}).IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_EmptyValueReturnsZero(t *testing.T) {
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: nil},
|
||||
})
|
||||
assert.True(t, got.IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_NonNumericReturnsZero(t *testing.T) {
|
||||
// A malformed value is the writer's bug; the helper must not
|
||||
// propagate a parse error or surface a nonsense time.
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("not-a-number")},
|
||||
})
|
||||
assert.True(t, got.IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_NonPositiveReturnsZero(t *testing.T) {
|
||||
// The container ext stores Unix seconds; <=0 means "not set" so
|
||||
// the helper falls back to zero rather than emitting 1970-01-01.
|
||||
for _, raw := range []string{"0", "-1", "-1000"} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte(raw)},
|
||||
})
|
||||
assert.True(t, got.IsZero(), "value %q must produce zero time", raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_PositiveSecondsRoundTrip(t *testing.T) {
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("1700000000")},
|
||||
})
|
||||
assert.Equal(t, time.Unix(1700000000, 0).UTC(), got.UTC())
|
||||
}
|
||||
|
||||
// ---------- logicalKeyFromVersionPath ----------
|
||||
|
||||
func TestLogicalKeyFromVersionPath_ExtractsLogicalKey(t *testing.T) {
|
||||
logical, ok := logicalKeyFromVersionPath("a/b/c.versions/v_abc")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "a/b/c", logical)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsPathWithoutVersionsParent(t *testing.T) {
|
||||
// The parent of the version file must end with .versions; otherwise
|
||||
// it's not a version path.
|
||||
_, ok := logicalKeyFromVersionPath("a/b/c/v_abc")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsRootLevelPath(t *testing.T) {
|
||||
// LastIndex returning 0 means the only "/" is at index 0, which
|
||||
// would yield an empty parent — not a real version path.
|
||||
_, ok := logicalKeyFromVersionPath("/v_abc")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsNoSlashes(t *testing.T) {
|
||||
_, ok := logicalKeyFromVersionPath("v_abc")
|
||||
assert.False(t, ok)
|
||||
_, ok = logicalKeyFromVersionPath("")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsBareVersionsContainer(t *testing.T) {
|
||||
// A path that's only the .versions container has no version-file
|
||||
// child to extract a logical key from.
|
||||
_, ok := logicalKeyFromVersionPath(s3_constants.VersionsFolder + "/v_x")
|
||||
assert.False(t, ok, "logical key cannot be empty after trim")
|
||||
}
|
||||
|
||||
// ---------- isVersionsContainerKey ----------
|
||||
|
||||
func TestIsVersionsContainerKey(t *testing.T) {
|
||||
cases := []struct {
|
||||
key string
|
||||
want bool
|
||||
}{
|
||||
{"obj" + s3_constants.VersionsFolder, true},
|
||||
{"a/b/obj" + s3_constants.VersionsFolder, true},
|
||||
// Bucket-root .versions is rejected explicitly: it has no
|
||||
// logical object key, so the router can't process it.
|
||||
{s3_constants.VersionsFolder, false},
|
||||
{"obj.versions/v_x", false}, // the version file inside, not the container
|
||||
{"obj", false},
|
||||
{"", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.key, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, isVersionsContainerKey(c.key))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- isVersionFolderPath ----------
|
||||
|
||||
func TestIsVersionFolderPath(t *testing.T) {
|
||||
// Reports whether a key sits inside a .versions/ folder, looking at
|
||||
// the parent segment specifically. The router uses this to skip
|
||||
// version-file events that need sibling state to classify.
|
||||
cases := []struct {
|
||||
key string
|
||||
want bool
|
||||
}{
|
||||
{"obj.versions/v_aaa", true},
|
||||
{"a/b/obj.versions/v_aaa", true},
|
||||
{"obj/v_aaa", false}, // parent isn't .versions
|
||||
{"obj.versions", false}, // the container itself, not a child
|
||||
// "obj.versions/" reads as the trailing-slash form of the path
|
||||
// "obj.versions" → leaf is "obj.versions" which ends with the
|
||||
// suffix → true. The router never sees this shape from the
|
||||
// reader (events carry concrete leaf names), but pin it here so
|
||||
// the contract is documented.
|
||||
{"obj.versions/", true},
|
||||
{"v_aaa", false}, // no slash at all
|
||||
{"", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.key, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, isVersionFolderPath(c.key))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- isDeleteMarkerEntry ----------
|
||||
|
||||
func TestIsDeleteMarkerEntry_NilOrEmptyExtendedReturnsFalse(t *testing.T) {
|
||||
assert.False(t, isDeleteMarkerEntry(nil))
|
||||
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{}))
|
||||
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{Extended: map[string][]byte{}}))
|
||||
}
|
||||
|
||||
func TestIsDeleteMarkerEntry_TrueOnlyForLiteralTrue(t *testing.T) {
|
||||
// The marker key must be exactly "true"; any other value is not a
|
||||
// marker. Pinning catches a regression that does case-insensitive
|
||||
// matching or treats "1" as truthy.
|
||||
mk := func(val string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte(val)}}
|
||||
}
|
||||
assert.True(t, isDeleteMarkerEntry(mk("true")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("True")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("TRUE")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("1")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("false")))
|
||||
}
|
||||
|
||||
// ---------- extractTags ----------
|
||||
|
||||
func TestExtractTags_NilOrEmptyReturnsNil(t *testing.T) {
|
||||
assert.Nil(t, extractTags(nil))
|
||||
assert.Nil(t, extractTags(map[string][]byte{}))
|
||||
}
|
||||
|
||||
func TestExtractTags_OnlyKeysWithObjectTaggingPrefix(t *testing.T) {
|
||||
// extractTags returns ExtVersionIdKey, Mime, etc. → no.
|
||||
// It only picks up keys with the AmzObjectTagging prefix and strips
|
||||
// that prefix to produce the tag map.
|
||||
prefix := s3_constants.AmzObjectTagging + "-"
|
||||
ext := map[string][]byte{
|
||||
prefix + "env": []byte("prod"),
|
||||
prefix + "team": []byte("data"),
|
||||
"X-Amz-Other": []byte("ignored"),
|
||||
"Seaweed-X-Internal": []byte("ignored"),
|
||||
}
|
||||
got := extractTags(ext)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "prod", got["env"])
|
||||
assert.Equal(t, "data", got["team"])
|
||||
}
|
||||
|
||||
func TestExtractTags_ReturnsNilWhenNoTaggingPrefixedKeys(t *testing.T) {
|
||||
// Keys with no tagging prefix produce a nil map (not an empty map);
|
||||
// the router treats nil as "no tags" without an extra branch.
|
||||
ext := map[string][]byte{
|
||||
"X-Amz-Other": []byte("ignored"),
|
||||
"Seaweed-X-Internal": []byte("ignored"),
|
||||
}
|
||||
got := extractTags(ext)
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
// ---------- hasActiveEventDrivenAction ----------
|
||||
|
||||
func TestHasActiveEventDrivenAction(t *testing.T) {
|
||||
// Build a snapshot with two action kinds and one of them set to
|
||||
// scan-only (inactive in event-driven view). hasActiveEventDrivenAction
|
||||
// must answer true only for the active event-driven kind.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
|
||||
prior := map[s3lifecycle.ActionKey]engine.PriorState{
|
||||
expirationKey: {BootstrapComplete: true, Mode: engine.ModeEventDriven},
|
||||
abortKey: {BootstrapComplete: true, Mode: engine.ModeScanOnly},
|
||||
}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
engine.CompileOptions{PriorStates: prior},
|
||||
)
|
||||
keys := []s3lifecycle.ActionKey{expirationKey, abortKey}
|
||||
|
||||
// Active event-driven kind matches.
|
||||
assert.True(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
|
||||
// Scan-only kind does NOT match — operator promoted it to scan-only
|
||||
// and the router must respect that by skipping the event-driven path.
|
||||
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindAbortMPU))
|
||||
// A kind not in the keys list is false.
|
||||
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNoncurrentDays))
|
||||
}
|
||||
|
||||
func TestHasActiveEventDrivenAction_NilActionSkipped(t *testing.T) {
|
||||
// A key the snapshot doesn't know about returns nil from Action;
|
||||
// the helper must skip rather than panic.
|
||||
snap := engine.New().Compile(nil, engine.CompileOptions{})
|
||||
keys := []s3lifecycle.ActionKey{
|
||||
{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
}
|
||||
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
|
||||
}
|
||||
|
||||
// ---------- engine.Snapshot accessors ----------
|
||||
|
||||
func TestSnapshot_BucketVersionedReportsCompiledFlag(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{
|
||||
{Bucket: "vbk", Rules: []*s3lifecycle.Rule{rule}, Versioned: true},
|
||||
{Bucket: "ubk", Rules: []*s3lifecycle.Rule{rule}, Versioned: false},
|
||||
},
|
||||
engine.CompileOptions{},
|
||||
)
|
||||
assert.True(t, snap.BucketVersioned("vbk"))
|
||||
assert.False(t, snap.BucketVersioned("ubk"))
|
||||
// Unknown bucket: not versioned, not a panic.
|
||||
assert.False(t, snap.BucketVersioned("missing"))
|
||||
}
|
||||
|
||||
func TestSnapshot_BucketActionKeysReturnsCompiledList(t *testing.T) {
|
||||
// Every CompileInput rule emits one action key per RuleActionKind;
|
||||
// BucketActionKeys must surface them all (regardless of Mode) so
|
||||
// MatchPath can iterate.
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
engine.CompileOptions{},
|
||||
)
|
||||
keys := snap.BucketActionKeys("bk")
|
||||
require.NotEmpty(t, keys)
|
||||
for _, k := range keys {
|
||||
assert.Equal(t, "bk", k.Bucket)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshot_BucketActionKeysUnknownBucketReturnsNil(t *testing.T) {
|
||||
snap := engine.New().Compile(nil, engine.CompileOptions{})
|
||||
assert.Nil(t, snap.BucketActionKeys("missing"))
|
||||
}
|
||||
|
||||
func TestSnapshot_ActionUnknownKeyReturnsNil(t *testing.T) {
|
||||
snap := engine.New().Compile(nil, engine.CompileOptions{})
|
||||
got := snap.Action(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestSnapshot_AllActionsCoversEveryCompiledKind(t *testing.T) {
|
||||
// AllActions must enumerate every compiled action regardless of
|
||||
// active state, because the dispatcher uses it for full-snapshot
|
||||
// reporting.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
engine.CompileOptions{},
|
||||
)
|
||||
all := snap.AllActions()
|
||||
wantKinds := s3lifecycle.RuleActionKinds(rule)
|
||||
require.Len(t, all, len(wantKinds))
|
||||
seen := map[s3lifecycle.ActionKind]bool{}
|
||||
for _, a := range all {
|
||||
seen[a.Key.ActionKind] = true
|
||||
}
|
||||
for _, k := range wantKinds {
|
||||
assert.True(t, seen[k], "missing kind %v in AllActions", k)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshot_SnapshotIDIsMonotonicAcrossRecompiles(t *testing.T) {
|
||||
// Every Compile call advances snapshotIDSeq; pin that successive
|
||||
// snapshots from the same Engine carry strictly increasing IDs so
|
||||
// the dispatcher's stale-snapshot check works.
|
||||
e := engine.New()
|
||||
first := e.Compile(nil, engine.CompileOptions{})
|
||||
second := e.Compile(nil, engine.CompileOptions{})
|
||||
assert.Greater(t, second.SnapshotID(), first.SnapshotID(),
|
||||
"second compile must produce a strictly greater snapshot id")
|
||||
}
|
||||
@@ -145,13 +145,18 @@ func Route(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, now tim
|
||||
if !info.IsMPUInit && key.ActionKind == s3lifecycle.ActionKindAbortMPU {
|
||||
continue
|
||||
}
|
||||
// Schedule from ModTime, not the meta-log event time: a backdated
|
||||
// or out-of-band entry update has eventTime ≈ now but ModTime far
|
||||
// in the past, so eventTime+Delay would push the dispatch into the
|
||||
// future even though the rule fires immediately. ModTime+Delay is
|
||||
// the correct fire moment; the dispatcher's identity-CAS catches
|
||||
// drift if the object changes meanwhile.
|
||||
dueTime := info.ModTime.Add(action.Delay)
|
||||
// Schedule from the per-kind due moment. ExpirationDate is
|
||||
// rule-relative (the date IS the moment); other kinds are
|
||||
// ModTime-relative. Using ModTime+Delay for ExpirationDate
|
||||
// (Delay=0) puts dueTime at the entry's mtime — a backdated
|
||||
// object's mtime is BEFORE the rule's date, so the eligibility
|
||||
// check below would skip it. ComputeDueAt encapsulates both
|
||||
// shapes; the dispatcher's identity-CAS catches drift if the
|
||||
// object changes meanwhile.
|
||||
dueTime := s3lifecycle.ComputeDueAt(action.Rule, key.ActionKind, info)
|
||||
if dueTime.IsZero() {
|
||||
continue
|
||||
}
|
||||
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
|
||||
if res.Action == s3lifecycle.ActionNone {
|
||||
continue
|
||||
@@ -305,6 +310,14 @@ func routePointerTransitionDisplaced(ctx context.Context, snap *engine.Snapshot,
|
||||
if displaced == nil || displaced.Attributes == nil {
|
||||
return nil
|
||||
}
|
||||
// Prefer the explicit demotion stamp on the displaced entry over the
|
||||
// container-derived successor. Stamp is written by the S3 PUT handler
|
||||
// at the moment the pointer flipped; container value is derived from
|
||||
// the new latest's mtime and may drift across retries.
|
||||
effectiveSuccessor := successor
|
||||
if stamp := s3lifecycle.SuccessorFromEntryStamp(displaced); !stamp.IsZero() {
|
||||
effectiveSuccessor = stamp
|
||||
}
|
||||
idx := 0
|
||||
info := &s3lifecycle.ObjectInfo{
|
||||
Key: logical,
|
||||
@@ -313,12 +326,12 @@ func routePointerTransitionDisplaced(ctx context.Context, snap *engine.Snapshot,
|
||||
IsLatest: false,
|
||||
IsDeleteMarker: string(displaced.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
|
||||
NoncurrentIndex: &idx,
|
||||
SuccessorModTime: successor,
|
||||
SuccessorModTime: effectiveSuccessor,
|
||||
}
|
||||
if tags := extractTags(displaced.Extended); len(tags) > 0 {
|
||||
info.Tags = tags
|
||||
}
|
||||
return emitNoncurrentMatches(snap, ev, keys, info, displaced, displacedID, successor)
|
||||
return emitNoncurrentMatches(snap, ev, keys, info, displaced, displacedID, effectiveSuccessor)
|
||||
}
|
||||
|
||||
// routePointerTransitionExpand routes only the versions that newly
|
||||
@@ -440,6 +453,12 @@ func routePointerTransitionExpand(ctx context.Context, snap *engine.Snapshot, ev
|
||||
} else {
|
||||
thisSuccessor = successor
|
||||
}
|
||||
// Override with the explicit demotion stamp when present —
|
||||
// PUT-time wall clock beats derived sibling mtime for accuracy
|
||||
// and is immune to mtime edits on the sibling itself.
|
||||
if stamp := s3lifecycle.SuccessorFromEntryStamp(s.entry); !stamp.IsZero() {
|
||||
thisSuccessor = stamp
|
||||
}
|
||||
idx := rank
|
||||
info := &s3lifecycle.ObjectInfo{
|
||||
Key: logical,
|
||||
|
||||
@@ -327,8 +327,12 @@ func (b *BucketBootstrapper) expandVersionsDir(ctx context.Context, bucket, root
|
||||
}
|
||||
count := 0
|
||||
for i, it := range items {
|
||||
var successor time.Time
|
||||
if i > 0 {
|
||||
// Prefer the explicit demotion stamp written by the S3 PUT
|
||||
// handler. Falling back to the next-newer sibling's mtime is
|
||||
// the legacy derivation and stays in place for entries written
|
||||
// before the stamp was introduced.
|
||||
successor := s3lifecycle.SuccessorFromEntryStamp(it.entry)
|
||||
if successor.IsZero() && i > 0 {
|
||||
prev := items[i-1].entry.Attributes
|
||||
successor = time.Unix(prev.Mtime, int64(prev.MtimeNs))
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -648,6 +649,111 @@ func TestExpandVersionsDir_LatestAndNoncurrentsByMtime(t *testing.T) {
|
||||
assert.Equal(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix())
|
||||
}
|
||||
|
||||
func TestExpandVersionsDir_NoncurrentSinceStampOverridesSiblingMtime(t *testing.T) {
|
||||
// When a version entry carries an explicit ExtNoncurrentSinceNsKey
|
||||
// stamp written by the S3 PUT handler at demotion time, that stamp
|
||||
// must take precedence over the legacy "use the next-newer sibling's
|
||||
// mtime" derivation. The stamp records exactly when the version
|
||||
// became noncurrent, which the sibling mtime only approximates.
|
||||
now := time.Now()
|
||||
v1mt := now.Add(-10 * time.Hour) // entry mtime, very old
|
||||
v2mt := now.Add(-1 * time.Hour) // sibling that would normally drive successor
|
||||
// Stamp v1's demotion at a fixed wall-clock that doesn't match v2.mt.
|
||||
v1demotion := now.Add(-3 * time.Hour)
|
||||
|
||||
v1 := versionFile("v1", v1mt, false)
|
||||
v1.Extended[s3_constants.ExtNoncurrentSinceNsKey] = []byte(
|
||||
strconv.FormatInt(v1demotion.UnixNano(), 10),
|
||||
)
|
||||
v2 := versionFile("v2", v2mt, false)
|
||||
|
||||
versionsDir := dirEntry("foo"+s3_constants.VersionsFolder, map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v2"),
|
||||
})
|
||||
client := &fakeFilerClient{
|
||||
tree: map[string][]*filer_pb.Entry{
|
||||
testBucketRoot + "/foo" + s3_constants.VersionsFolder: {v1, v2},
|
||||
},
|
||||
}
|
||||
inj := &recordingInjector{}
|
||||
b := &BucketBootstrapper{FilerClient: client, BucketsPath: "/buckets", Injector: inj}
|
||||
|
||||
_, err := b.expandVersionsDir(context.Background(), "b1", testBucketRoot, "foo"+s3_constants.VersionsFolder, versionsDir, nil, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
byID := map[string]*reader.BootstrapVersion{}
|
||||
for _, ev := range inj.snapshot() {
|
||||
require.NotNil(t, ev.BootstrapVersion)
|
||||
byID[ev.BootstrapVersion.VersionID] = ev.BootstrapVersion
|
||||
}
|
||||
require.Contains(t, byID, "v1")
|
||||
// SuccessorModTime must come from the stamp, not from v2's mtime.
|
||||
assert.Equal(t, v1demotion.UnixNano(), byID["v1"].SuccessorModTime.UnixNano(),
|
||||
"stamp must win over sibling mtime; got %v want %v",
|
||||
byID["v1"].SuccessorModTime, v1demotion)
|
||||
assert.NotEqual(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix(),
|
||||
"sibling mtime must not be the SuccessorModTime source when stamp is present")
|
||||
}
|
||||
|
||||
func TestExpandVersionsDir_MissingStampFallsBackToSiblingMtime(t *testing.T) {
|
||||
// Legacy/pre-Phase-1 entries have no stamp. Behavior must be
|
||||
// unchanged: SuccessorModTime falls back to the next-newer sibling's
|
||||
// mtime. This pins the backward-compat path the design promises.
|
||||
now := time.Now()
|
||||
v1mt := now.Add(-3 * time.Hour)
|
||||
v2mt := now.Add(-1 * time.Hour)
|
||||
v1 := versionFile("v1", v1mt, false) // no stamp
|
||||
v2 := versionFile("v2", v2mt, false)
|
||||
versionsDir := dirEntry("foo"+s3_constants.VersionsFolder, map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v2"),
|
||||
})
|
||||
client := &fakeFilerClient{
|
||||
tree: map[string][]*filer_pb.Entry{
|
||||
testBucketRoot + "/foo" + s3_constants.VersionsFolder: {v1, v2},
|
||||
},
|
||||
}
|
||||
inj := &recordingInjector{}
|
||||
b := &BucketBootstrapper{FilerClient: client, BucketsPath: "/buckets", Injector: inj}
|
||||
_, err := b.expandVersionsDir(context.Background(), "b1", testBucketRoot, "foo"+s3_constants.VersionsFolder, versionsDir, nil, nil)
|
||||
require.NoError(t, err)
|
||||
byID := map[string]*reader.BootstrapVersion{}
|
||||
for _, ev := range inj.snapshot() {
|
||||
byID[ev.BootstrapVersion.VersionID] = ev.BootstrapVersion
|
||||
}
|
||||
assert.Equal(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix(),
|
||||
"missing stamp must fall through to sibling mtime")
|
||||
}
|
||||
|
||||
func TestExpandVersionsDir_InvalidStampFallsBackToSiblingMtime(t *testing.T) {
|
||||
// A malformed stamp value is the writer's bug — the reader must
|
||||
// ignore it and fall back to the legacy derivation rather than
|
||||
// blowing up or surfacing a nonsense time.
|
||||
now := time.Now()
|
||||
v1mt := now.Add(-3 * time.Hour)
|
||||
v2mt := now.Add(-1 * time.Hour)
|
||||
v1 := versionFile("v1", v1mt, false)
|
||||
v1.Extended[s3_constants.ExtNoncurrentSinceNsKey] = []byte("not-a-number")
|
||||
v2 := versionFile("v2", v2mt, false)
|
||||
versionsDir := dirEntry("foo"+s3_constants.VersionsFolder, map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v2"),
|
||||
})
|
||||
client := &fakeFilerClient{
|
||||
tree: map[string][]*filer_pb.Entry{
|
||||
testBucketRoot + "/foo" + s3_constants.VersionsFolder: {v1, v2},
|
||||
},
|
||||
}
|
||||
inj := &recordingInjector{}
|
||||
b := &BucketBootstrapper{FilerClient: client, BucketsPath: "/buckets", Injector: inj}
|
||||
_, err := b.expandVersionsDir(context.Background(), "b1", testBucketRoot, "foo"+s3_constants.VersionsFolder, versionsDir, nil, nil)
|
||||
require.NoError(t, err)
|
||||
byID := map[string]*reader.BootstrapVersion{}
|
||||
for _, ev := range inj.snapshot() {
|
||||
byID[ev.BootstrapVersion.VersionID] = ev.BootstrapVersion
|
||||
}
|
||||
assert.Equal(t, v2mt.Unix(), byID["v1"].SuccessorModTime.Unix(),
|
||||
"unparseable stamp must fall through to sibling mtime")
|
||||
}
|
||||
|
||||
func TestExpandVersionsDir_LatestPointerOutOfOrderByMtime(t *testing.T) {
|
||||
// Backdated PUT scenario: latest pointer names v1 but v1's mtime is
|
||||
// OLDER than v2's. After newest-first sort the order is [v2, v1] so
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// pipelineFanout is the thin shard-routing layer the bootstrapper sees
|
||||
// as an EventInjector. It maps Event.ShardID to the pipeline that owns
|
||||
// that shard. Was previously at 0% coverage.
|
||||
|
||||
func TestPipelineFanout_NilEventIsNoOp(t *testing.T) {
|
||||
// A nil event must be silently absorbed; otherwise a follow-up
|
||||
// panic in the receiving pipeline would crash the bootstrapper.
|
||||
f := pipelineFanout{}
|
||||
assert.NoError(t, f.InjectEvent(context.Background(), nil))
|
||||
}
|
||||
|
||||
func TestPipelineFanout_UnknownShardIsNoOp(t *testing.T) {
|
||||
// A shard not covered by any pipeline in the fanout returns nil
|
||||
// rather than erroring; the comment in scheduler.go documents this
|
||||
// as forward-compat for future shard-mapping changes that might
|
||||
// introduce gaps.
|
||||
f := pipelineFanout{0: &dispatcher.Pipeline{EventBuffer: 1}}
|
||||
assert.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 99}))
|
||||
}
|
||||
|
||||
func TestPipelineFanout_KnownShardSucceeds(t *testing.T) {
|
||||
// A matching shard reaches the pipeline's InjectEvent, which writes
|
||||
// to its (buffered) events channel and returns nil.
|
||||
f := pipelineFanout{0: &dispatcher.Pipeline{EventBuffer: 1}}
|
||||
assert.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 0}))
|
||||
}
|
||||
|
||||
func TestPipelineFanout_PropagatesContextCancellation(t *testing.T) {
|
||||
// When the underlying pipeline's InjectEvent blocks on a full
|
||||
// buffer and the ctx is canceled, the fanout must propagate the
|
||||
// ctx error. Pre-fill the pipeline's buffer (size 1) so the second
|
||||
// send blocks long enough for the cancellation to win the select.
|
||||
p := &dispatcher.Pipeline{EventBuffer: 1}
|
||||
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
|
||||
f := pipelineFanout{0: p}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
err := f.InjectEvent(ctx, &reader.Event{ShardID: 0})
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
func TestPipelineFanout_RoutesToCorrectPipeline(t *testing.T) {
|
||||
// Two pipelines, each with buffer=1: an event for shard 7 must
|
||||
// fill pipeline B's buffer (proven by the second send to that
|
||||
// pipeline blocking with canceled ctx) without affecting pipeline
|
||||
// A's buffer (proven by the third send still succeeding to A
|
||||
// because A's buffer is still empty).
|
||||
pA := &dispatcher.Pipeline{EventBuffer: 1}
|
||||
pB := &dispatcher.Pipeline{EventBuffer: 1}
|
||||
f := pipelineFanout{0: pA, 7: pB}
|
||||
|
||||
require.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 7}))
|
||||
|
||||
// Second send to shard 7 would block on the full buffer; use a
|
||||
// pre-canceled ctx to detect the buffer-full state without hanging.
|
||||
canceledCtx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
err := f.InjectEvent(canceledCtx, &reader.Event{ShardID: 7})
|
||||
require.Error(t, err, "B's buffer should be full so a canceled-ctx send returns ctx.Err")
|
||||
|
||||
// Send to shard 0 still succeeds because A's buffer is untouched.
|
||||
require.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 0}))
|
||||
}
|
||||
@@ -398,6 +398,10 @@ func (vs *VolumeServer) VolumeNeedleStatus(ctx context.Context, req *volume_serv
|
||||
|
||||
resp := &volume_server_pb.VolumeNeedleStatusResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
volumeId := needle.VolumeId(req.VolumeId)
|
||||
|
||||
n := &needle.Needle{
|
||||
|
||||
@@ -13,6 +13,10 @@ import (
|
||||
func (vs *VolumeServer) BatchDelete(ctx context.Context, req *volume_server_pb.BatchDeleteRequest) (*volume_server_pb.BatchDeleteResponse, error) {
|
||||
resp := &volume_server_pb.BatchDeleteResponse{}
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(ctx); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if err := vs.CheckMaintenanceMode(); err != nil {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
// TestBatchDelete_DeniesNonWhitelistedPeer verifies that BatchDelete refuses
|
||||
// callers that fall outside the configured admin whitelist, matching the
|
||||
// behaviour of the other destructive volume-server RPCs.
|
||||
func TestBatchDelete_DeniesNonWhitelistedPeer(t *testing.T) {
|
||||
vs := &VolumeServer{
|
||||
guard: security.NewGuard([]string{"10.0.0.1"}, "", 0, "", 0),
|
||||
}
|
||||
|
||||
ctx := peer.NewContext(context.Background(), &peer.Peer{
|
||||
Addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 12345},
|
||||
})
|
||||
|
||||
resp, err := vs.BatchDelete(ctx, &volume_server_pb.BatchDeleteRequest{
|
||||
FileIds: []string{"1,deadbeef"},
|
||||
SkipCookieCheck: true,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("expected PermissionDenied, got nil error (resp=%+v)", resp)
|
||||
}
|
||||
if got := status.Code(err); got != codes.PermissionDenied {
|
||||
t.Fatalf("expected codes.PermissionDenied, got %v (err=%v)", got, err)
|
||||
}
|
||||
if resp == nil {
|
||||
t.Fatalf("expected non-nil response even on auth failure")
|
||||
}
|
||||
if len(resp.Results) != 0 {
|
||||
t.Fatalf("expected no per-file results on auth failure, got %d", len(resp.Results))
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,10 @@ import (
|
||||
|
||||
func (vs *VolumeServer) ReadAllNeedles(req *volume_server_pb.ReadAllNeedlesRequest, stream volume_server_pb.VolumeServer_ReadAllNeedlesServer) (err error) {
|
||||
|
||||
if err := vs.checkGrpcAdminAuth(stream.Context()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, vid := range req.VolumeIds {
|
||||
if err := vs.streamReadOneVolume(needle.VolumeId(vid), stream); err != nil {
|
||||
stats.VolumeServerFileReadFailures.Inc()
|
||||
|
||||
@@ -592,6 +592,22 @@ var (
|
||||
Name: "metadata_only_total",
|
||||
Help: "Counter of LifecycleDelete completions that skipped per-chunk delete (volume TTL reclaim).",
|
||||
}, []string{"bucket", "rule_hash"})
|
||||
|
||||
// S3LifecycleDispatchLimiterWaitSeconds is the cluster-wide rate
|
||||
// limiter's per-dispatch wait time on the daily-replay path. The
|
||||
// limiter blocks just before each LifecycleDelete RPC; near-zero
|
||||
// observations mean the cluster cap isn't binding, a long-tail at
|
||||
// the configured 1/rate ceiling means the cluster cap is the
|
||||
// active throttle. Operators tune cluster_deletes_per_second by
|
||||
// reading p95/p99 on this histogram.
|
||||
S3LifecycleDispatchLimiterWaitSeconds = prometheus.NewHistogram(
|
||||
prometheus.HistogramOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: "s3_lifecycle",
|
||||
Name: "dispatch_limiter_wait_seconds",
|
||||
Help: "Time spent waiting on the cluster rate limiter before issuing a LifecycleDelete RPC. Non-zero values indicate the cluster cap is binding.",
|
||||
Buckets: []float64{0.0001, 0.001, 0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
|
||||
})
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -668,6 +684,7 @@ func init() {
|
||||
Gather.MustRegister(S3LifecycleEventCounter)
|
||||
Gather.MustRegister(S3LifecycleBootstrapDispatchCounter)
|
||||
Gather.MustRegister(S3LifecycleMetadataOnlyCounter)
|
||||
Gather.MustRegister(S3LifecycleDispatchLimiterWaitSeconds)
|
||||
|
||||
Gather.MustRegister(UploadErrorCounter)
|
||||
|
||||
|
||||
@@ -17,6 +17,31 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// maxEagerPreGrow caps how many bytes ParseUpload is willing to pre-allocate
|
||||
// from a request's announced Content-Length. Large enough to skip a few
|
||||
// rounds of bytes.Buffer.ReadFrom geometric grow on typical small uploads;
|
||||
// small enough that a misreported Content-Length or a slow/idle client can
|
||||
// only ever waste this much memory per request. Bigger uploads fall back to
|
||||
// the standard ReadFrom-grow path for the remainder.
|
||||
const maxEagerPreGrow = 4 * 1024 * 1024
|
||||
|
||||
// eagerPreGrow ensures bytesBuffer has at least min(contentLength, sizeLimit,
|
||||
// maxEagerPreGrow) bytes of capacity, so the bytes.Buffer.ReadFrom pumps
|
||||
// inside parseUpload below skip the first round(s) of geometric grow on the
|
||||
// common upload sizes — see #6541. The cap policy is the load-bearing piece
|
||||
// here; it's extracted so unit tests can exercise the policy directly
|
||||
// without spinning a real http upload.
|
||||
func eagerPreGrow(bytesBuffer *bytes.Buffer, contentLength, sizeLimit int64) {
|
||||
if contentLength <= 0 || contentLength > sizeLimit {
|
||||
return
|
||||
}
|
||||
grow := contentLength
|
||||
if grow > maxEagerPreGrow {
|
||||
grow = maxEagerPreGrow
|
||||
}
|
||||
bytesBuffer.Grow(int(grow))
|
||||
}
|
||||
|
||||
type ParsedUpload struct {
|
||||
FileName string
|
||||
Data []byte
|
||||
@@ -35,6 +60,7 @@ type ParsedUpload struct {
|
||||
|
||||
func ParseUpload(r *http.Request, sizeLimit int64, bytesBuffer *bytes.Buffer) (pu *ParsedUpload, e error) {
|
||||
bytesBuffer.Reset()
|
||||
eagerPreGrow(bytesBuffer, r.ContentLength, sizeLimit)
|
||||
pu = &ParsedUpload{bytesBuffer: bytesBuffer}
|
||||
pu.PairMap = make(map[string]string)
|
||||
for k, v := range r.Header {
|
||||
@@ -57,10 +83,16 @@ func ParseUpload(r *http.Request, sizeLimit int64, bytesBuffer *bytes.Buffer) (p
|
||||
pu.UncompressedData = pu.Data
|
||||
// println("received data", len(pu.Data), "isGzipped", pu.IsGzipped, "mime", pu.MimeType, "name", pu.FileName)
|
||||
if pu.IsGzipped {
|
||||
if unzipped, e := util.DecompressData(pu.Data); e == nil {
|
||||
pu.OriginalDataSize = len(unzipped)
|
||||
pu.UncompressedData = unzipped
|
||||
// println("ungzipped data size", len(unzipped))
|
||||
// MD5 check needs the uncompressed bytes; otherwise just count
|
||||
// the gunzip stream — see #6541.
|
||||
needMD5 := r.Header.Get("Content-MD5") != "" || pu.ContentMd5 != ""
|
||||
if needMD5 {
|
||||
if unzipped, err := util.DecompressData(pu.Data); err == nil {
|
||||
pu.OriginalDataSize = len(unzipped)
|
||||
pu.UncompressedData = unzipped
|
||||
}
|
||||
} else if n, err := util.GunzipStream(io.Discard, bytes.NewReader(pu.Data)); err == nil {
|
||||
pu.OriginalDataSize = int(n)
|
||||
}
|
||||
} else {
|
||||
ext := filepath.Base(pu.FileName)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package needle
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestEagerPreGrow is a regression guard for the volume-side amplifier in
|
||||
// https://github.com/seaweedfs/seaweedfs/issues/6541.
|
||||
//
|
||||
// ParseUpload reads the multipart part body via bytes.Buffer.ReadFrom; if the
|
||||
// receive buffer arrives with cap=0 (sync.Pool dropped the prior buffer),
|
||||
// ReadFrom doubles capacity on each grow and pays 2-4x the chunk size in
|
||||
// cumulative allocations. eagerPreGrow shaves the first few rounds off that
|
||||
// grow chain by pre-sizing from r.ContentLength.
|
||||
//
|
||||
// Two policy invariants the cases below pin:
|
||||
//
|
||||
// 1. The cap. We never grow more than maxEagerPreGrow per request, so a
|
||||
// misreported Content-Length or a slow/idle client cannot force
|
||||
// per-request preallocation up to the configured sizeLimit. This is the
|
||||
// review concern that landed during PR review and is what changed the
|
||||
// test from a TotalAlloc bound to this structural form.
|
||||
// 2. The validity gates. Negative / zero / oversized Content-Length and
|
||||
// buffers that already have enough capacity should not trigger a Grow.
|
||||
func TestEagerPreGrow(t *testing.T) {
|
||||
const sizeLimit = int64(256 * 1024 * 1024)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
startCap int
|
||||
cl int64
|
||||
wantMinCap int
|
||||
wantNoop bool // post: cap stays at startCap
|
||||
}{
|
||||
{
|
||||
name: "small content-length grows exactly",
|
||||
cl: 1 * 1024 * 1024,
|
||||
wantMinCap: 1 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "content-length at cap grows to cap",
|
||||
cl: maxEagerPreGrow,
|
||||
wantMinCap: maxEagerPreGrow,
|
||||
},
|
||||
{
|
||||
name: "content-length above cap is clamped to cap",
|
||||
cl: 200 * 1024 * 1024,
|
||||
wantMinCap: maxEagerPreGrow,
|
||||
},
|
||||
{
|
||||
name: "content-length above sizeLimit is rejected",
|
||||
cl: sizeLimit + 1,
|
||||
wantNoop: true,
|
||||
},
|
||||
{
|
||||
name: "zero content-length is a no-op",
|
||||
cl: 0,
|
||||
wantNoop: true,
|
||||
},
|
||||
{
|
||||
name: "negative content-length (chunked encoding) is a no-op",
|
||||
cl: -1,
|
||||
wantNoop: true,
|
||||
},
|
||||
{
|
||||
name: "buffer with sufficient cap is left alone",
|
||||
startCap: maxEagerPreGrow,
|
||||
cl: 1 * 1024 * 1024,
|
||||
wantMinCap: maxEagerPreGrow,
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
bb := &bytes.Buffer{}
|
||||
if c.startCap > 0 {
|
||||
bb.Grow(c.startCap)
|
||||
}
|
||||
startCap := bb.Cap()
|
||||
|
||||
eagerPreGrow(bb, c.cl, sizeLimit)
|
||||
|
||||
if c.wantNoop {
|
||||
if got := bb.Cap(); got != startCap {
|
||||
t.Fatalf("eagerPreGrow(cl=%d, sizeLimit=%d) should not have grown: "+
|
||||
"cap=%d, want %d (regression: validity gate removed?)",
|
||||
c.cl, sizeLimit, got, startCap)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got := bb.Cap(); got < c.wantMinCap {
|
||||
t.Fatalf("after eagerPreGrow(cl=%d): cap=%d, want >=%d", c.cl, got, c.wantMinCap)
|
||||
}
|
||||
// Hard upper bound: never above the cap (regardless of cl/sizeLimit).
|
||||
// Note bytes.Buffer.Grow may round capacity up modestly, so allow
|
||||
// a generous overshoot but still well below sizeLimit.
|
||||
if got := int64(bb.Cap()); got > 2*int64(maxEagerPreGrow) {
|
||||
t.Fatalf("after eagerPreGrow(cl=%d): cap=%d exceeds 2*maxEagerPreGrow=%d "+
|
||||
"(regression: cap removed?)", c.cl, got, 2*maxEagerPreGrow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package needle
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/textproto"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestParseUpload_GzipStreamCount: gzipped uploads without Content-MD5
|
||||
// must take the stream-count path and skip the uncompressed-slice
|
||||
// allocation. See #6541.
|
||||
func TestParseUpload_GzipStreamCount(t *testing.T) {
|
||||
const uncompressedSize = 4 * 1024 * 1024 // 4 MiB
|
||||
uncompressed := make([]byte, uncompressedSize)
|
||||
for i := range uncompressed {
|
||||
uncompressed[i] = byte(i*31 + 7)
|
||||
}
|
||||
gzipped := gzipBytes(t, uncompressed)
|
||||
uncompressedMD5 := base64.StdEncoding.EncodeToString(md5sum(uncompressed))
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
md5OnPart string
|
||||
md5OnReq string
|
||||
wantStream bool
|
||||
}{
|
||||
{name: "no MD5: stream-count", wantStream: true},
|
||||
{name: "MD5 on part: materialize", md5OnPart: uncompressedMD5},
|
||||
{name: "MD5 on request: materialize", md5OnReq: uncompressedMD5},
|
||||
}
|
||||
|
||||
// Warm the gzip.Reader sync.Pool so per-test alloc is steady-state.
|
||||
if _, err := ParseUpload(buildGzipReq(t, gzipped, "", ""), 256<<20, &bytes.Buffer{}); err != nil {
|
||||
t.Fatalf("warmup ParseUpload: %v", err)
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
req := buildGzipReq(t, gzipped, c.md5OnPart, c.md5OnReq)
|
||||
|
||||
runtime.GC()
|
||||
var before, after runtime.MemStats
|
||||
runtime.ReadMemStats(&before)
|
||||
|
||||
pu, err := ParseUpload(req, 256<<20, &bytes.Buffer{})
|
||||
|
||||
runtime.ReadMemStats(&after)
|
||||
allocated := after.TotalAlloc - before.TotalAlloc
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("ParseUpload: %v", err)
|
||||
}
|
||||
if pu.OriginalDataSize != uncompressedSize {
|
||||
t.Errorf("OriginalDataSize=%d, want %d", pu.OriginalDataSize, uncompressedSize)
|
||||
}
|
||||
|
||||
if c.wantStream {
|
||||
if allocated > uint64(uncompressedSize) {
|
||||
t.Errorf("stream path allocated %d, bound %d", allocated, uncompressedSize)
|
||||
}
|
||||
} else {
|
||||
if allocated < uint64(uncompressedSize) {
|
||||
t.Errorf("materialize path allocated %d, want >= %d", allocated, uncompressedSize)
|
||||
}
|
||||
}
|
||||
t.Logf("allocated=%d bytes (gzipped=%d, uncompressed=%d)",
|
||||
allocated, len(gzipped), uncompressedSize)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func gzipBytes(t *testing.T, in []byte) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
gw := gzip.NewWriter(&buf)
|
||||
if _, err := gw.Write(in); err != nil {
|
||||
t.Fatalf("gzip write: %v", err)
|
||||
}
|
||||
if err := gw.Close(); err != nil {
|
||||
t.Fatalf("gzip close: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func md5sum(in []byte) []byte {
|
||||
h := md5.New()
|
||||
h.Write(in)
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
func buildGzipReq(t *testing.T, body []byte, md5OnPart, md5OnReq string) *http.Request {
|
||||
t.Helper()
|
||||
var bodyBuf bytes.Buffer
|
||||
mw := multipart.NewWriter(&bodyBuf)
|
||||
h := make(textproto.MIMEHeader)
|
||||
h.Set("Content-Disposition", `form-data; name="file"; filename="test.bin"`)
|
||||
h.Set("Content-Encoding", "gzip")
|
||||
if md5OnPart != "" {
|
||||
h.Set("Content-MD5", md5OnPart)
|
||||
}
|
||||
fw, err := mw.CreatePart(h)
|
||||
if err != nil {
|
||||
t.Fatalf("CreatePart: %v", err)
|
||||
}
|
||||
if _, err := fw.Write(body); err != nil {
|
||||
t.Fatalf("write part: %v", err)
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatalf("close mw: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(bodyBuf.Bytes()))
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
req.ContentLength = int64(bodyBuf.Len())
|
||||
if md5OnReq != "" {
|
||||
req.Header.Set("Content-MD5", md5OnReq)
|
||||
}
|
||||
return req
|
||||
}
|
||||
@@ -102,8 +102,17 @@ func (t *Topology) ToVolumeLocations() (volumeLocations []*master_pb.VolumeLocat
|
||||
for _, v := range dn.GetVolumes() {
|
||||
volumeLocation.NewVids = append(volumeLocation.NewVids, uint32(v.Id))
|
||||
}
|
||||
// A single EC volume's shards can live on multiple disks of
|
||||
// one DataNode, so GetEcShards returns per-(vid,disk) entries.
|
||||
// Dedupe so the snapshot carries each vid once.
|
||||
seenEcVids := make(map[uint32]struct{})
|
||||
for _, s := range dn.GetEcShards() {
|
||||
volumeLocation.NewVids = append(volumeLocation.NewVids, uint32(s.VolumeId))
|
||||
vid := uint32(s.VolumeId)
|
||||
if _, ok := seenEcVids[vid]; ok {
|
||||
continue
|
||||
}
|
||||
seenEcVids[vid] = struct{}{}
|
||||
volumeLocation.NewEcVids = append(volumeLocation.NewEcVids, vid)
|
||||
}
|
||||
volumeLocations = append(volumeLocations, volumeLocation)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,16 @@ import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// maxRetainedBufferCap caps the capacity of buffers we hand back to the
|
||||
// sync.Pool. Buffers grown past this (e.g. by a 64 MiB chunk upload through
|
||||
// volume.PostHandler -> needle.ParseUpload -> bytes.Buffer.ReadFrom) are
|
||||
// dropped instead of pooled, so the underlying byte array becomes garbage
|
||||
// and is collected. Without this cap the pool effectively hoards every
|
||||
// high-water buffer for the process's lifetime — see #6541, where Harbor's
|
||||
// concurrent UploadPartCopy filled the pool with 64 MiB buffers and RSS
|
||||
// never receded.
|
||||
const maxRetainedBufferCap = 4 * 1024 * 1024
|
||||
|
||||
var syncPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
@@ -16,5 +26,13 @@ func SyncPoolGetBuffer() *bytes.Buffer {
|
||||
}
|
||||
|
||||
func SyncPoolPutBuffer(buffer *bytes.Buffer) {
|
||||
if buffer == nil {
|
||||
return
|
||||
}
|
||||
if buffer.Cap() > maxRetainedBufferCap {
|
||||
// Drop the buffer; let GC reclaim the oversized backing array.
|
||||
return
|
||||
}
|
||||
buffer.Reset()
|
||||
syncPool.Put(buffer)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package buffer_pool
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSyncPoolPutBuffer_DropsOversized is a regression guard for the volume-side
|
||||
// retention amplifier in https://github.com/seaweedfs/seaweedfs/issues/6541.
|
||||
//
|
||||
// volume.PostHandler -> needle.ParseUpload -> bytes.Buffer.ReadFrom grows the
|
||||
// buffer to chunk size. If we Put that buffer back as-is, sync.Pool keeps it
|
||||
// at the grown capacity for the rest of the process's lifetime. With
|
||||
// concurrent UploadPartCopy load that fills the pool with N × chunk-size
|
||||
// backing arrays that never shrink — exactly the "RSS never recedes" pattern
|
||||
// reported in the issue.
|
||||
//
|
||||
// We verify a Put + Get round trip can never round-trip a buffer larger than
|
||||
// maxRetainedBufferCap, regardless of how big it grew while in use.
|
||||
func TestSyncPoolPutBuffer_DropsOversized(t *testing.T) {
|
||||
// Drain the pool so we start from a deterministic point. sync.Pool may
|
||||
// still hold cached entries on other Ps, but for the small/big-cap
|
||||
// distinction below that doesn't matter — we assert an invariant on
|
||||
// every Get, not the identity of a specific buffer.
|
||||
for i := 0; i < 64; i++ {
|
||||
_ = SyncPoolGetBuffer()
|
||||
}
|
||||
|
||||
big := &bytes.Buffer{}
|
||||
big.Grow(maxRetainedBufferCap * 4) // simulate a large upload buffer
|
||||
if got := big.Cap(); got <= maxRetainedBufferCap {
|
||||
t.Fatalf("test setup: big.Cap=%d should exceed threshold %d",
|
||||
got, maxRetainedBufferCap)
|
||||
}
|
||||
SyncPoolPutBuffer(big)
|
||||
|
||||
// Any number of Gets must not return a buffer with cap > threshold.
|
||||
// (If big had been retained, sync.Pool's per-P cache would surface it
|
||||
// on the very next Get on this goroutine.)
|
||||
for i := 0; i < 16; i++ {
|
||||
got := SyncPoolGetBuffer()
|
||||
if cap := got.Cap(); cap > maxRetainedBufferCap {
|
||||
t.Fatalf("Get %d returned buffer with cap=%d, exceeds threshold %d "+
|
||||
"(regression: oversized buffers retained in pool?)",
|
||||
i, cap, maxRetainedBufferCap)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncPoolPutBuffer_KeepsRightSized verifies the cap is one-sided: we
|
||||
// still pool reasonably-sized buffers so the common case (small uploads,
|
||||
// header parsing) doesn't pay an alloc per request.
|
||||
func TestSyncPoolPutBuffer_KeepsRightSized(t *testing.T) {
|
||||
for i := 0; i < 64; i++ {
|
||||
_ = SyncPoolGetBuffer()
|
||||
}
|
||||
|
||||
small := &bytes.Buffer{}
|
||||
small.Grow(maxRetainedBufferCap / 2)
|
||||
smallCap := small.Cap()
|
||||
SyncPoolPutBuffer(small)
|
||||
|
||||
// We don't assert pointer identity (sync.Pool can hand back any cached
|
||||
// buffer), but the previously-Put buffer should appear among Gets on
|
||||
// the same goroutine in the absence of a GC. If our cap-policy ever
|
||||
// regresses to dropping right-sized buffers, this test starts seeing
|
||||
// only fresh (cap=0) buffers and fails.
|
||||
sawPooled := false
|
||||
for i := 0; i < 8; i++ {
|
||||
got := SyncPoolGetBuffer()
|
||||
if got.Cap() == smallCap {
|
||||
sawPooled = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !sawPooled {
|
||||
t.Fatalf("right-sized buffer (cap=%d) never came back from the pool "+
|
||||
"(regression: cap policy too aggressive?)", smallCap)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncPoolPutBuffer_NilSafe documents that Put tolerates a nil buffer.
|
||||
// The volume server defers Put on a buffer obtained via Get, but defensive
|
||||
// callers in other paths may Put(nil); we should not panic.
|
||||
func TestSyncPoolPutBuffer_NilSafe(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("SyncPoolPutBuffer(nil) panicked: %v", r)
|
||||
}
|
||||
}()
|
||||
SyncPoolPutBuffer(nil)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package s3_lifecycle
|
||||
|
||||
// Cluster-wide rate-limit configuration plumbing for the daily-replay
|
||||
// worker. The admin holds a single "cluster delete budget" knob, divides
|
||||
// it by the number of execute-capable s3_lifecycle workers at job-dispatch
|
||||
// time, and ships the per-worker share to the worker via
|
||||
// ExecuteJobRequest.ClusterContext.Metadata. The worker reads the share,
|
||||
// constructs a rate.Limiter, and passes it to dailyrun.Run.
|
||||
//
|
||||
// These constants are the contract between admin (weed/admin/plugin/plugin.go
|
||||
// computes the share and writes the keys) and worker (this package's
|
||||
// handler.go reads them). Changing a name on one side without the other
|
||||
// would silently disable rate limiting — both sides must read these
|
||||
// exact values.
|
||||
|
||||
const (
|
||||
// ClusterDeletesPerSecondAdminKey is the admin-config field that
|
||||
// holds the cluster-wide budget in delete RPCs per second. 0 means
|
||||
// unlimited (legacy behavior). Set via the AdminConfigForm in
|
||||
// handler.go's "Scope" section.
|
||||
ClusterDeletesPerSecondAdminKey = "cluster_deletes_per_second"
|
||||
// ClusterDeletesBurstAdminKey holds the token-bucket burst. 0 means
|
||||
// "2 × rps" (computed by the admin allocator).
|
||||
ClusterDeletesBurstAdminKey = "cluster_deletes_burst"
|
||||
|
||||
// MetadataKeyDeletesPerSecond is the per-worker share value the
|
||||
// admin writes into ClusterContext.Metadata at ExecuteJob time.
|
||||
// Stored as a string of a non-negative float64; empty/missing/zero
|
||||
// means "no rate limit on this run" (cfg.Limiter stays nil).
|
||||
MetadataKeyDeletesPerSecond = "s3_lifecycle.deletes_per_second"
|
||||
// MetadataKeyDeletesBurst is the per-worker burst share. Stored as
|
||||
// a string of a non-negative integer.
|
||||
MetadataKeyDeletesBurst = "s3_lifecycle.deletes_burst"
|
||||
)
|
||||
@@ -0,0 +1,78 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildLimiterFromClusterContext_NilCC(t *testing.T) {
|
||||
l, desc := buildLimiterFromClusterContext(nil)
|
||||
assert.Nil(t, l)
|
||||
assert.Equal(t, "unlimited", desc)
|
||||
}
|
||||
|
||||
func TestBuildLimiterFromClusterContext_NoMetadata(t *testing.T) {
|
||||
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{})
|
||||
assert.Nil(t, l)
|
||||
assert.Equal(t, "unlimited", desc)
|
||||
}
|
||||
|
||||
func TestBuildLimiterFromClusterContext_MissingRateKey(t *testing.T) {
|
||||
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
|
||||
Metadata: map[string]string{"unrelated": "x"},
|
||||
})
|
||||
assert.Nil(t, l)
|
||||
assert.Equal(t, "unlimited", desc)
|
||||
}
|
||||
|
||||
func TestBuildLimiterFromClusterContext_NonPositiveRate(t *testing.T) {
|
||||
// 0 or negative rate means the admin didn't allocate; the worker
|
||||
// must NOT construct a limiter that throttles every request to
|
||||
// zero-throughput.
|
||||
for _, raw := range []string{"0", "-1", "0.0", "not-a-number", ""} {
|
||||
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
|
||||
Metadata: map[string]string{MetadataKeyDeletesPerSecond: raw},
|
||||
})
|
||||
assert.Nil(t, l, "rate=%q must yield nil limiter", raw)
|
||||
assert.Equal(t, "unlimited", desc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildLimiterFromClusterContext_PositiveRateBuildsLimiter(t *testing.T) {
|
||||
l, desc := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
|
||||
Metadata: map[string]string{
|
||||
MetadataKeyDeletesPerSecond: "12.5",
|
||||
MetadataKeyDeletesBurst: "25",
|
||||
},
|
||||
})
|
||||
require.NotNil(t, l)
|
||||
assert.Equal(t, 12.5, float64(l.Limit()))
|
||||
assert.Equal(t, 25, l.Burst())
|
||||
assert.Contains(t, desc, "12.5/s")
|
||||
assert.Contains(t, desc, "burst=25")
|
||||
}
|
||||
|
||||
func TestBuildLimiterFromClusterContext_BurstMissingDefaultsTo2xRate(t *testing.T) {
|
||||
// burst omitted (admin allocator wrote nothing) → worker computes
|
||||
// 2 × rps so a single tick has headroom for two refills.
|
||||
l, _ := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
|
||||
Metadata: map[string]string{MetadataKeyDeletesPerSecond: "10"},
|
||||
})
|
||||
require.NotNil(t, l)
|
||||
assert.Equal(t, 10.0, float64(l.Limit()))
|
||||
assert.Equal(t, 20, l.Burst(), "burst default must be 2× rps")
|
||||
}
|
||||
|
||||
func TestBuildLimiterFromClusterContext_TinyRateClampsBurstToOne(t *testing.T) {
|
||||
// A sub-1-rps allocation (e.g. 0.5/s across few workers) would
|
||||
// compute 2 × 0.5 = 1, but if the int truncation produced 0 the
|
||||
// limiter would never refill. Clamp to at least 1.
|
||||
l, _ := buildLimiterFromClusterContext(&plugin_pb.ClusterContext{
|
||||
Metadata: map[string]string{MetadataKeyDeletesPerSecond: "0.1"},
|
||||
})
|
||||
require.NotNil(t, l)
|
||||
assert.GreaterOrEqual(t, l.Burst(), 1, "burst must never round down to 0")
|
||||
}
|
||||
@@ -9,12 +9,30 @@ import (
|
||||
const (
|
||||
jobType = "s3_lifecycle"
|
||||
|
||||
defaultWorkers = 1
|
||||
// shardPipelineGoroutines is the in-process fan-out across the
|
||||
// 16-shard space. Kept as a hardcoded internal default — formerly
|
||||
// an admin form field, removed because it's a per-worker tuning
|
||||
// knob, not a cluster-coordination concern.
|
||||
shardPipelineGoroutines = 1
|
||||
|
||||
defaultDispatchTickMinutes = int64(1)
|
||||
defaultCheckpointTickSeconds = int64(30)
|
||||
defaultRefreshIntervalMinutes = int64(5)
|
||||
defaultMaxRuntimeMinutes = int64(60)
|
||||
defaultBootstrapIntervalMinutes = int64(0) // 0 = walk once per process
|
||||
|
||||
// AlgorithmDailyReplay routes the worker through dailyrun.Run for
|
||||
// one bounded pass per Execute. Currently Phase 2 / replay-only:
|
||||
// buckets with walker-bound action kinds are refused. Phase 4
|
||||
// extends this to handle every kind. Default — the streaming path
|
||||
// stays in the tree as a runtime escape hatch only.
|
||||
AlgorithmDailyReplay = "daily_replay"
|
||||
// AlgorithmStreaming is the legacy event-driven dispatcher path
|
||||
// (reader + heap + per-shard pipeline). Kept as a fallback knob for
|
||||
// rollout; deleted by Phase 5 once Phase 4 walker integration ships.
|
||||
AlgorithmStreaming = "streaming"
|
||||
|
||||
defaultAlgorithm = AlgorithmDailyReplay
|
||||
)
|
||||
|
||||
// Config is the parsed AdminConfigForm + WorkerConfigForm view.
|
||||
@@ -25,21 +43,20 @@ type Config struct {
|
||||
RefreshInterval time.Duration
|
||||
BootstrapInterval time.Duration
|
||||
MaxRuntime time.Duration
|
||||
Algorithm string
|
||||
}
|
||||
|
||||
// ParseConfig pulls the lifecycle Handler config from the merged
|
||||
// admin+worker config values. Missing fields fall back to defaults.
|
||||
func ParseConfig(adminValues, workerValues map[string]*plugin_pb.ConfigValue) Config {
|
||||
cfg := Config{
|
||||
Workers: int(readInt64(adminValues, "workers", defaultWorkers)),
|
||||
Workers: shardPipelineGoroutines,
|
||||
DispatchTick: time.Duration(readInt64(workerValues, "dispatch_tick_minutes", defaultDispatchTickMinutes)) * time.Minute,
|
||||
CheckpointTick: time.Duration(readInt64(workerValues, "checkpoint_tick_seconds", defaultCheckpointTickSeconds)) * time.Second,
|
||||
RefreshInterval: time.Duration(readInt64(workerValues, "refresh_interval_minutes", defaultRefreshIntervalMinutes)) * time.Minute,
|
||||
BootstrapInterval: time.Duration(readInt64(workerValues, "bootstrap_interval_minutes", defaultBootstrapIntervalMinutes)) * time.Minute,
|
||||
MaxRuntime: time.Duration(readInt64(workerValues, "max_runtime_minutes", defaultMaxRuntimeMinutes)) * time.Minute,
|
||||
}
|
||||
if cfg.Workers <= 0 {
|
||||
cfg.Workers = defaultWorkers
|
||||
Algorithm: readString(adminValues, "algorithm", defaultAlgorithm),
|
||||
}
|
||||
if cfg.DispatchTick <= 0 {
|
||||
cfg.DispatchTick = time.Duration(defaultDispatchTickMinutes) * time.Minute
|
||||
@@ -60,6 +77,12 @@ func ParseConfig(adminValues, workerValues map[string]*plugin_pb.ConfigValue) Co
|
||||
if cfg.MaxRuntime <= 0 {
|
||||
cfg.MaxRuntime = time.Duration(defaultMaxRuntimeMinutes) * time.Minute
|
||||
}
|
||||
switch cfg.Algorithm {
|
||||
case AlgorithmStreaming, AlgorithmDailyReplay:
|
||||
// valid
|
||||
default:
|
||||
cfg.Algorithm = defaultAlgorithm
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
|
||||
func TestParseConfigDefaults(t *testing.T) {
|
||||
cfg := ParseConfig(nil, nil)
|
||||
if cfg.Workers != defaultWorkers {
|
||||
t.Errorf("Workers default=%d, want %d", cfg.Workers, defaultWorkers)
|
||||
if cfg.Workers != shardPipelineGoroutines {
|
||||
t.Errorf("Workers default=%d, want %d", cfg.Workers, shardPipelineGoroutines)
|
||||
}
|
||||
if cfg.DispatchTick != 1*time.Minute {
|
||||
t.Errorf("DispatchTick default=%v, want 1m", cfg.DispatchTick)
|
||||
@@ -27,12 +27,37 @@ func TestParseConfigDefaults(t *testing.T) {
|
||||
if cfg.BootstrapInterval != 0 {
|
||||
t.Errorf("BootstrapInterval default=%v, want 0 (walk-once-per-process)", cfg.BootstrapInterval)
|
||||
}
|
||||
if cfg.Algorithm != AlgorithmDailyReplay {
|
||||
t.Errorf("Algorithm default=%q, want %q", cfg.Algorithm, AlgorithmDailyReplay)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfig_AlgorithmStreamingExplicit(t *testing.T) {
|
||||
// Streaming stays available as a rollout escape hatch until Phase 5
|
||||
// deletes it. Operators must be able to opt back into it explicitly.
|
||||
admin := map[string]*plugin_pb.ConfigValue{
|
||||
"algorithm": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: AlgorithmStreaming}},
|
||||
}
|
||||
cfg := ParseConfig(admin, nil)
|
||||
if cfg.Algorithm != AlgorithmStreaming {
|
||||
t.Errorf("Algorithm=%q, want %q", cfg.Algorithm, AlgorithmStreaming)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfig_AlgorithmUnknownValueFallsBackToDefault(t *testing.T) {
|
||||
// Operators should not be able to silently activate a future
|
||||
// algorithm value by typo. Anything not in the enum falls back to
|
||||
// the default (daily_replay).
|
||||
admin := map[string]*plugin_pb.ConfigValue{
|
||||
"algorithm": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: "future_algo"}},
|
||||
}
|
||||
cfg := ParseConfig(admin, nil)
|
||||
if cfg.Algorithm != AlgorithmDailyReplay {
|
||||
t.Errorf("unknown algorithm=%q must fall back to %q, got %q", "future_algo", AlgorithmDailyReplay, cfg.Algorithm)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfigOverrides(t *testing.T) {
|
||||
admin := map[string]*plugin_pb.ConfigValue{
|
||||
"workers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 4}},
|
||||
}
|
||||
worker := map[string]*plugin_pb.ConfigValue{
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 15}},
|
||||
@@ -40,10 +65,7 @@ func TestParseConfigOverrides(t *testing.T) {
|
||||
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
|
||||
}
|
||||
cfg := ParseConfig(admin, worker)
|
||||
if cfg.Workers != 4 {
|
||||
t.Errorf("Workers=%d, want 4", cfg.Workers)
|
||||
}
|
||||
cfg := ParseConfig(nil, worker)
|
||||
if cfg.DispatchTick != 2*time.Minute {
|
||||
t.Errorf("DispatchTick=%v, want 2m", cfg.DispatchTick)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package s3_lifecycle
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -11,10 +12,13 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dailyrun"
|
||||
"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/util"
|
||||
"golang.org/x/time/rate"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -70,22 +74,42 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
{
|
||||
SectionId: "scope",
|
||||
Title: "Scope",
|
||||
Description: "How many pipeline goroutines split the 16-shard space.",
|
||||
Description: "Cluster-wide algorithm choice and delete-throughput cap.",
|
||||
Fields: []*plugin_pb.ConfigField{
|
||||
{
|
||||
Name: "workers",
|
||||
Label: "Worker Count",
|
||||
Description: "Number of pipeline goroutines per executing worker. Each owns a contiguous slice of [0, 16) shards. Default 1 = one goroutine handles all 16 shards.",
|
||||
Name: "algorithm",
|
||||
Label: "Algorithm",
|
||||
Description: "Daily Replay = bounded daily meta-log scan (Phase 2, replay-only — buckets using ExpirationDate, ExpiredDeleteMarker, NewerNoncurrent, or scan_only rules will fail the run until Phase 4 ships). Streaming = legacy reader+heap path, kept as a runtime escape hatch during the Phase 4 rollout; Phase 5 deletes it.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_ENUM,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_SELECT,
|
||||
Options: []*plugin_pb.ConfigOption{
|
||||
{Value: AlgorithmDailyReplay, Label: "Daily Replay (default)", Description: "Bounded daily meta-log scan. Replay-only in Phase 2; buckets with walker-bound rules fail the run."},
|
||||
{Value: AlgorithmStreaming, Label: "Streaming (legacy fallback)", Description: "Long-running reader + per-shard heap + tick dispatcher. Pre-cutover behavior; removed in Phase 5."},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: ClusterDeletesPerSecondAdminKey,
|
||||
Label: "Cluster Delete Rate (per second)",
|
||||
Description: "Cluster-wide ceiling on lifecycle delete RPCs per second, divided evenly across active s3_lifecycle workers at job-dispatch time. 0 = unlimited (legacy behavior). Only honored by the Daily Replay algorithm; streaming ignores it.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 1}},
|
||||
MaxValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 16}},
|
||||
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
},
|
||||
{
|
||||
Name: ClusterDeletesBurstAdminKey,
|
||||
Label: "Cluster Delete Burst",
|
||||
Description: "Token-bucket burst capacity across the cluster (max simultaneous deletes). 0 = 2 × rate. Same allocation rule as the rate.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
DefaultValues: map[string]*plugin_pb.ConfigValue{
|
||||
"workers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultWorkers}},
|
||||
"algorithm": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultAlgorithm}},
|
||||
ClusterDeletesPerSecondAdminKey: {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
ClusterDeletesBurstAdminKey: {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
},
|
||||
},
|
||||
WorkerConfigForm: &plugin_pb.ConfigForm{
|
||||
@@ -96,11 +120,11 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
{
|
||||
SectionId: "cadence",
|
||||
Title: "Cadence",
|
||||
Description: "Tick intervals for the dispatch loop, durable checkpoint, and engine refresh; plus the wall-clock cap on each daily run.",
|
||||
Description: "How often the worker checks its schedule, saves progress, reloads bucket lifecycle configs, and how long each run may take.",
|
||||
Fields: []*plugin_pb.ConfigField{
|
||||
{
|
||||
Name: "dispatch_tick_minutes",
|
||||
Label: "Dispatch Tick (minutes)",
|
||||
Label: "Schedule Check Interval (minutes)",
|
||||
Description: "How often each pipeline drains its schedule.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
@@ -108,7 +132,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
},
|
||||
{
|
||||
Name: "checkpoint_tick_seconds",
|
||||
Label: "Cursor Checkpoint Tick (seconds)",
|
||||
Label: "Progress Save Interval (seconds)",
|
||||
Description: "How often each pipeline persists its cursor map to the filer.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
@@ -116,7 +140,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
},
|
||||
{
|
||||
Name: "refresh_interval_minutes",
|
||||
Label: "Engine Refresh Interval (minutes)",
|
||||
Label: "Lifecycle Config Reload (minutes)",
|
||||
Description: "How often the scheduler rebuilds the engine snapshot from bucket lifecycle configs.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
@@ -124,7 +148,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
},
|
||||
{
|
||||
Name: "bootstrap_interval_minutes",
|
||||
Label: "Bootstrap Re-walk Interval (minutes)",
|
||||
Label: "Full Bucket Rescan Interval (minutes)",
|
||||
Description: "How often each bucket is re-walked. scan_only rules — those whose retention horizon exceeds meta-log retention — only fire from the bootstrap walk, so a non-zero value is required to enforce them on a long-running worker. 0 keeps the legacy walk-once-per-process behavior.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
@@ -132,7 +156,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
},
|
||||
{
|
||||
Name: "max_runtime_minutes",
|
||||
Label: "Max Runtime (minutes)",
|
||||
Label: "Per-Run Time Limit (minutes)",
|
||||
Description: "Wall-clock cap on each run. Each daily run processes events for one day; the cursor persists across runs.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
@@ -248,6 +272,10 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
|
||||
defer s3Conn.Close()
|
||||
rpc := s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(s3Conn)
|
||||
|
||||
if cfg.Algorithm == AlgorithmDailyReplay {
|
||||
return h.executeDailyReplay(runCtx, request, bucketsPath, filerClient, rpc, cfg, sender)
|
||||
}
|
||||
|
||||
sched := &scheduler.Scheduler{
|
||||
BucketsPath: bucketsPath,
|
||||
Engine: engine.New(),
|
||||
@@ -269,6 +297,112 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDailyReplay runs the bounded daily-replay path. Reuses the
|
||||
// streaming path's filer / s3 / engine setup but routes the per-shard
|
||||
// loop through dailyrun.Run instead of scheduler.Scheduler. Phase 2:
|
||||
// replay-only, refuses walker-bound action kinds with a typed error.
|
||||
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 {
|
||||
eng := engine.New()
|
||||
inputs, parseErrors, err := scheduler.LoadCompileInputs(ctx, filerClient, bucketsPath)
|
||||
if err != nil {
|
||||
return 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)
|
||||
}
|
||||
eng.Compile(inputs, engine.CompileOptions{PriorStates: scheduler.AllActivePriorStates(inputs)})
|
||||
|
||||
shards := make([]int, 0, s3lifecycle.ShardCount)
|
||||
for i := 0; i < s3lifecycle.ShardCount; i++ {
|
||||
shards = append(shards, i)
|
||||
}
|
||||
|
||||
limiter, limiterDesc := buildLimiterFromClusterContext(request.GetClusterContext())
|
||||
|
||||
_ = 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 runtime=%s rate=%s", len(shards), cfg.Workers, cfg.MaxRuntime, limiterDesc),
|
||||
})
|
||||
|
||||
runErr := dailyrun.Run(ctx, dailyrun.Config{
|
||||
Shards: shards,
|
||||
BucketsPath: bucketsPath,
|
||||
Engine: eng,
|
||||
FilerClient: filerClient,
|
||||
Client: lifecycleRPCAdapter{c: rpc},
|
||||
Persister: &dailyrun.FilerCursorPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
|
||||
Lister: dispatcher.NewFilerSiblingLister(filerClient, bucketsPath),
|
||||
Workers: cfg.Workers,
|
||||
Limiter: limiter,
|
||||
ClientName: "worker-s3-lifecycle-daily",
|
||||
})
|
||||
if dailyrun.IsUnsupportedRule(runErr) {
|
||||
// Surface the typed error verbatim so admin marks the run as
|
||||
// failed with the user-facing reason in the activity log.
|
||||
glog.Warningf("daily_replay: %v", runErr)
|
||||
return runErr
|
||||
}
|
||||
if runErr != nil {
|
||||
glog.Warningf("daily_replay: %v", runErr)
|
||||
return runErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildLimiterFromClusterContext parses the per-worker share the admin
|
||||
// wrote into ClusterContext.Metadata (see weed/admin/plugin/plugin.go's
|
||||
// s3_lifecycle injection) and returns a rate.Limiter, or nil when no
|
||||
// rate cap applies. The description string is for the JobProgressUpdate
|
||||
// so operators can see "rate=unlimited" / "rate=12.5/s burst=25" in
|
||||
// the activity log.
|
||||
//
|
||||
// Tolerant of missing keys, empty strings, malformed numbers, and
|
||||
// non-positive values — all treated as "no limit" rather than failing
|
||||
// the run. The admin allocator is the single point that decides whether
|
||||
// to populate these keys; the worker doesn't second-guess.
|
||||
func buildLimiterFromClusterContext(cc *plugin_pb.ClusterContext) (*rate.Limiter, string) {
|
||||
if cc == nil || cc.Metadata == nil {
|
||||
return nil, "unlimited"
|
||||
}
|
||||
rps, ok := parsePositiveFloat(cc.Metadata[MetadataKeyDeletesPerSecond])
|
||||
if !ok {
|
||||
return nil, "unlimited"
|
||||
}
|
||||
burst, _ := parsePositiveInt(cc.Metadata[MetadataKeyDeletesBurst])
|
||||
if burst <= 0 {
|
||||
// Sensible default: enough headroom for one tick's worth of
|
||||
// throughput. Caller may also supply 0 to opt into this default.
|
||||
burst = int(rps * 2)
|
||||
if burst < 1 {
|
||||
burst = 1
|
||||
}
|
||||
}
|
||||
return rate.NewLimiter(rate.Limit(rps), burst), fmt.Sprintf("%.3g/s burst=%d", rps, burst)
|
||||
}
|
||||
|
||||
func parsePositiveFloat(s string) (float64, bool) {
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
if err != nil || v <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
func parsePositiveInt(s string) (int, bool) {
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
v, err := strconv.Atoi(s)
|
||||
if err != nil || v <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -284,31 +284,21 @@ func TestDescriptor_BasicShape(t *testing.T) {
|
||||
assert.Greater(t, d.DescriptorVersion, uint32(0), "descriptor version must be positive (admins use it for compat)")
|
||||
}
|
||||
|
||||
func TestDescriptor_AdminConfigFormHasWorkersField(t *testing.T) {
|
||||
// Workers is the only admin-side knob today; if it disappears, the
|
||||
// admin form would render empty and operators couldn't tune
|
||||
// concurrency.
|
||||
func TestDescriptor_AdminConfigFormHasNoWorkersField(t *testing.T) {
|
||||
// "workers" used to be an admin form field controlling in-process
|
||||
// pipeline goroutines. It's per-worker tuning, not a cluster-wide
|
||||
// scope concern, so it was removed from the form. ParseConfig hard-
|
||||
// codes cfg.Workers from shardPipelineGoroutines instead.
|
||||
h := NewHandler(nil)
|
||||
d := h.Descriptor()
|
||||
require.NotNil(t, d.AdminConfigForm)
|
||||
assert.Equal(t, "s3-lifecycle-admin", d.AdminConfigForm.FormId)
|
||||
|
||||
// Walk every section's fields and find "workers".
|
||||
var found bool
|
||||
for _, sec := range d.AdminConfigForm.Sections {
|
||||
for _, f := range sec.Fields {
|
||||
if f.Name == "workers" {
|
||||
found = true
|
||||
assert.Equal(t, plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64, f.FieldType)
|
||||
}
|
||||
assert.NotEqual(t, "workers", f.Name, "admin form must NOT expose the in-memory pipeline-goroutine knob")
|
||||
}
|
||||
}
|
||||
assert.True(t, found, "admin form must expose 'workers' field")
|
||||
|
||||
// Default value matches the constant used by ParseConfig.
|
||||
dv, ok := d.AdminConfigForm.DefaultValues["workers"]
|
||||
require.True(t, ok, "workers must have a default in AdminConfigForm")
|
||||
assert.Equal(t, int64(defaultWorkers), dv.GetInt64Value())
|
||||
_, hasDefault := d.AdminConfigForm.DefaultValues["workers"]
|
||||
assert.False(t, hasDefault, "DefaultValues must NOT include 'workers' (form field removed)")
|
||||
}
|
||||
|
||||
func TestDescriptor_WorkerConfigFormCadenceDefaultsMatchParseConfig(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user