mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25cfeb3a2a | ||
|
|
843e4b7cdb | ||
|
|
f70f338e7f | ||
|
|
6f2bf40d5a | ||
|
|
26c257bf40 | ||
|
|
ca12934834 | ||
|
|
82648cca53 | ||
|
|
1b1d4aa814 | ||
|
|
c7b01c72b2 | ||
|
|
2840980c7d | ||
|
|
b740e22e63 | ||
|
|
ad77362be3 | ||
|
|
7996dc1d67 | ||
|
|
ca95d33092 |
No files matched your search
+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,441 @@
|
||||
// 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/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>.
|
||||
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
|
||||
_, 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")
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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,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,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,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()
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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}))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user