mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65fcf2d740 | ||
|
|
0955d1aa08 | ||
|
|
edbe7ab140 | ||
|
|
9d20e71883 | ||
|
|
1aa55f5bf9 | ||
|
|
619cb39827 | ||
|
|
435ef7f94f | ||
|
|
1350e681c9 | ||
|
|
cb6e498e0b | ||
|
|
6f9668c20b | ||
|
|
af2a359e45 | ||
|
|
c0cf1417f1 | ||
|
|
284d37c3b6 | ||
|
|
62e04623ce | ||
|
|
551e700e64 | ||
|
|
6021a88606 | ||
|
|
7781eef429 | ||
|
|
8cf42a5abb | ||
|
|
ddfb219ec3 | ||
|
|
bb0c7c779f | ||
|
|
255e9cd0f7 | ||
|
|
aa280443e7 | ||
|
|
1854101125 | ||
|
|
edfa1ce210 | ||
|
|
2f7ac1d664 | ||
|
|
1c917ffacb | ||
|
|
7c60407897 | ||
|
|
c6ad6dcf74 | ||
|
|
196c41d21a |
No files matched your search
@@ -3,6 +3,7 @@ package s3api
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
)
|
||||
|
||||
// LifecycleDelete executes one (rule, action) verdict: re-fetch, identity
|
||||
@@ -54,6 +56,12 @@ 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
|
||||
switch req.ActionKind {
|
||||
case s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE:
|
||||
// Current-version expiration: Enabled -> delete marker; Suspended
|
||||
@@ -74,7 +82,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
return done(), nil
|
||||
case s3_constants.VersioningSuspended:
|
||||
// Best-effort null delete; NotFound is benign.
|
||||
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, "null"); err != nil {
|
||||
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, "null", metadataOnly); err != nil {
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) && !errors.Is(err, ErrVersionNotFound) {
|
||||
return retryLater("TRANSPORT_ERROR: deleteNullVersion: " + err.Error()), nil
|
||||
}
|
||||
@@ -85,7 +93,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
return done(), nil
|
||||
default:
|
||||
err := s3a.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(c, req.Bucket, req.ObjectPath)
|
||||
return s3a.deleteUnversionedObjectWithClient(c, req.Bucket, req.ObjectPath, metadataOnly)
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrObjectNotFound) {
|
||||
@@ -93,6 +101,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
}
|
||||
return retryLater("TRANSPORT_ERROR: deleteUnversioned: " + err.Error()), nil
|
||||
}
|
||||
recordMetadataOnlyIf(metadataOnly, req)
|
||||
return done(), nil
|
||||
}
|
||||
|
||||
@@ -120,12 +129,22 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
|
||||
return noopResolved("VERSION_IS_LATEST"), nil
|
||||
}
|
||||
}
|
||||
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, req.VersionId); err != nil {
|
||||
// Re-check sole-survivor: a fresh PUT can land between schedule
|
||||
// and dispatch. Identity-CAS upstream covers the marker bytes;
|
||||
// this covers the directory shape.
|
||||
if req.ActionKind == s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER {
|
||||
outcome, err := s3a.checkSoleSurvivorMarker(ctx, req.Bucket, req.ObjectPath, req.VersionId)
|
||||
if outcome != nil || err != nil {
|
||||
return outcome, err
|
||||
}
|
||||
}
|
||||
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, req.VersionId, metadataOnly); err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrVersionNotFound) || errors.Is(err, ErrObjectNotFound) {
|
||||
return noopResolved("NOT_FOUND_AT_DELETE"), nil
|
||||
}
|
||||
return retryLater("TRANSPORT_ERROR: deleteSpecificVersion: " + err.Error()), nil
|
||||
}
|
||||
recordMetadataOnlyIf(metadataOnly, req)
|
||||
return done(), nil
|
||||
|
||||
case s3_lifecycle_pb.ActionKind_ABORT_MPU:
|
||||
@@ -175,6 +194,92 @@ func (s3a *S3ApiServer) lifecycleAbortMPU(ctx context.Context, req *s3_lifecycle
|
||||
return done(), nil
|
||||
}
|
||||
|
||||
// checkSoleSurvivorMarker returns nil to proceed with the delete, or a
|
||||
// terminal response when state has drifted: count != 1, the surviving
|
||||
// entry is a different version, the .versions/ directory's latest
|
||||
// pointer doesn't name versionId, or a bare null-version exists outside
|
||||
// .versions/. Pointer missing while a marker is present is treated as
|
||||
// retry-later — the create races with the directory metadata update.
|
||||
func (s3a *S3ApiServer) checkSoleSurvivorMarker(ctx context.Context, bucket, object, versionId string) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
versionsDir := bucketDir + "/" + object + s3_constants.VersionsFolder
|
||||
count := 0
|
||||
var firstName string
|
||||
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return filer_pb.SeaweedList(ctx, client, versionsDir, "", func(entry *filer_pb.Entry, _ bool) error {
|
||||
count++
|
||||
if count == 1 && entry != nil {
|
||||
firstName = entry.Name
|
||||
}
|
||||
return nil
|
||||
}, "", false, 2)
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return noopResolved("NOT_FOUND"), nil
|
||||
}
|
||||
return retryLater("TRANSPORT_ERROR: sole-survivor list: " + err.Error()), nil
|
||||
}
|
||||
if count == 0 {
|
||||
return noopResolved("NOT_FOUND"), nil
|
||||
}
|
||||
if count > 1 {
|
||||
return noopResolved("NOT_SOLE_SURVIVOR"), nil
|
||||
}
|
||||
// SeaweedList delivered a single callback but with a nil entry; we
|
||||
// can't compare names so retry rather than silently bypass the
|
||||
// marker-replaced check.
|
||||
if firstName == "" {
|
||||
return retryLater("PENDING_SURVIVOR_ENTRY"), nil
|
||||
}
|
||||
if versionId != "" && firstName != s3a.getVersionFileName(versionId) {
|
||||
return noopResolved("MARKER_REPLACED"), nil
|
||||
}
|
||||
// Latest-pointer check: createDeleteMarker writes the marker file
|
||||
// and then updates the parent directory's Extended map. Reading
|
||||
// before the second step lands would see count==1 but no pointer;
|
||||
// retry-later rather than mistakenly delete.
|
||||
parent, name := path.Split(versionsDir)
|
||||
parent = strings.TrimRight(parent, "/")
|
||||
if parent == "" {
|
||||
parent = "/"
|
||||
}
|
||||
versionsEntry, err := s3a.getEntry(parent, name)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return noopResolved("NOT_FOUND"), nil
|
||||
}
|
||||
return retryLater("TRANSPORT_ERROR: latest-pointer lookup: " + err.Error()), nil
|
||||
}
|
||||
if versionsEntry == nil {
|
||||
return noopResolved("NOT_FOUND"), nil
|
||||
}
|
||||
latest, hasPointer := versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey]
|
||||
if !hasPointer || len(latest) == 0 {
|
||||
return retryLater("PENDING_LATEST_POINTER"), nil
|
||||
}
|
||||
if string(latest) != versionId {
|
||||
return noopResolved("MARKER_NOT_LATEST"), nil
|
||||
}
|
||||
// Null-version check: pre-versioning objects survive as the bare
|
||||
// <bucket>/<key>. Both regular files and explicit S3 directory-key
|
||||
// markers (object names ending in /) qualify; the listing path
|
||||
// (s3api_object_versioning.go processExplicitDirectory) treats both
|
||||
// as the null version. getEntry uses NewFullPath so a trailing slash
|
||||
// in object splits the same as a regular key.
|
||||
bareEntry, err := s3a.getEntry(bucketDir, object)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return retryLater("TRANSPORT_ERROR: null-version lookup: " + err.Error()), nil
|
||||
}
|
||||
if bareEntry != nil && (!bareEntry.IsDirectory || bareEntry.IsDirectoryKeyObject()) {
|
||||
return noopResolved("NULL_VERSION_PRESENT"), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// isCurrentLatestVersion reports whether versionId is the version the
|
||||
// .versions/ directory currently points to. SeaweedFS records the latest
|
||||
// version on the parent directory's Extended map; without consulting it,
|
||||
@@ -242,6 +347,17 @@ func identityMatches(live, want *s3_lifecycle_pb.EntryIdentity) bool {
|
||||
return bytes.Equal(live.ExtendedHash, want.ExtendedHash)
|
||||
}
|
||||
|
||||
// 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
|
||||
// debugging; nil rule_hash collapses to the empty string.
|
||||
func recordMetadataOnlyIf(on bool, req *s3_lifecycle_pb.LifecycleDeleteRequest) {
|
||||
if !on || req == nil {
|
||||
return
|
||||
}
|
||||
stats_collect.S3LifecycleMetadataOnlyCounter.WithLabelValues(req.Bucket, hex.EncodeToString(req.RuleHash)).Inc()
|
||||
}
|
||||
|
||||
func done() *s3_lifecycle_pb.LifecycleDeleteResponse {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
)
|
||||
|
||||
func TestComputeEntryIdentity_BasicFields(t *testing.T) {
|
||||
@@ -147,3 +149,142 @@ func TestLifecycleAbortMPU_RejectsTraversalUploadIDs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleDispatch_AbortMPUAfterFetchIsBlocked(t *testing.T) {
|
||||
// LifecycleDelete routes ABORT_MPU to lifecycleAbortMPU before
|
||||
// getObjectEntry; reaching lifecycleDispatch with ABORT_MPU means
|
||||
// some caller bypassed that route. Defensive BLOCKED so a
|
||||
// regression there can't accidentally rm a real object via the
|
||||
// expiration paths.
|
||||
s := &S3ApiServer{}
|
||||
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "bk",
|
||||
ObjectPath: "k",
|
||||
ActionKind: s3_lifecycle_pb.ActionKind_ABORT_MPU,
|
||||
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected gRPC error: %v", err)
|
||||
}
|
||||
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
|
||||
t.Fatalf("ABORT_MPU at dispatch should be BLOCKED, got %v reason=%q", resp.Outcome, resp.Reason)
|
||||
}
|
||||
if !contains(resp.Reason, "ABORT_MPU dispatched after fetch") {
|
||||
t.Fatalf("reason should name the route bypass, got %q", resp.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleDispatch_UnknownActionKindIsBlocked(t *testing.T) {
|
||||
// An ActionKind value the proto doesn't define yet must produce a
|
||||
// FATAL outcome rather than fall through to a default delete path.
|
||||
s := &S3ApiServer{}
|
||||
const bogus = s3_lifecycle_pb.ActionKind(999)
|
||||
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "bk",
|
||||
ObjectPath: "k",
|
||||
ActionKind: bogus,
|
||||
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected gRPC error: %v", err)
|
||||
}
|
||||
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
|
||||
t.Fatalf("unknown action kind should be BLOCKED, got %v reason=%q", resp.Outcome, resp.Reason)
|
||||
}
|
||||
if !contains(resp.Reason, "unknown action_kind") {
|
||||
t.Fatalf("reason should name the unknown kind, got %q", resp.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLifecycleDispatch_NoncurrentRequiresVersionID(t *testing.T) {
|
||||
// Noncurrent / EXPIRED_DELETE_MARKER target a specific version; an
|
||||
// empty version_id is a writer-side bug and must be rejected before
|
||||
// any filer call. This pinning keeps the early-return in place so
|
||||
// a refactor doesn't accidentally let the empty-version_id path
|
||||
// reach deleteSpecificObjectVersion.
|
||||
s := &S3ApiServer{}
|
||||
for _, kind := range []s3_lifecycle_pb.ActionKind{
|
||||
s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS,
|
||||
s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT,
|
||||
s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER,
|
||||
} {
|
||||
t.Run(kind.String(), func(t *testing.T) {
|
||||
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "bk",
|
||||
ObjectPath: "k",
|
||||
ActionKind: kind,
|
||||
// VersionId intentionally empty
|
||||
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected gRPC error: %v", err)
|
||||
}
|
||||
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
|
||||
t.Fatalf("kind %v with empty version_id should be BLOCKED, got %v reason=%q",
|
||||
kind, resp.Outcome, resp.Reason)
|
||||
}
|
||||
if !contains(resp.Reason, "version_id required") {
|
||||
t.Fatalf("reason should name the missing version_id, got %q", resp.Reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// contains is a tiny helper so the tests above don't pull in strings
|
||||
// just for a substring check.
|
||||
func contains(haystack, needle string) bool {
|
||||
if len(needle) == 0 {
|
||||
return true
|
||||
}
|
||||
for i := 0; i+len(needle) <= len(haystack); i++ {
|
||||
if haystack[i:i+len(needle)] == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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
|
||||
// in the same suite share the global counter — use distinct bucket
|
||||
// names per test so series don't bleed.
|
||||
c := stats_collect.S3LifecycleMetadataOnlyCounter
|
||||
bucket := "bk-counter-on"
|
||||
hash := []byte{0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04}
|
||||
hexHash := "deadbeef01020304"
|
||||
|
||||
before := testutil.ToFloat64(c.WithLabelValues(bucket, hexHash))
|
||||
recordMetadataOnlyIf(true, &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: bucket,
|
||||
RuleHash: hash,
|
||||
})
|
||||
if got := testutil.ToFloat64(c.WithLabelValues(bucket, hexHash)); got != before+1 {
|
||||
t.Fatalf("on=true should bump by 1; before=%v after=%v", before, got)
|
||||
}
|
||||
|
||||
beforeOff := testutil.ToFloat64(c.WithLabelValues("bk-counter-off", hexHash))
|
||||
recordMetadataOnlyIf(false, &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "bk-counter-off",
|
||||
RuleHash: hash,
|
||||
})
|
||||
if got := testutil.ToFloat64(c.WithLabelValues("bk-counter-off", hexHash)); got != beforeOff {
|
||||
t.Fatalf("on=false should not bump; before=%v after=%v", beforeOff, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordMetadataOnlyIf_NilRequestSafe(t *testing.T) {
|
||||
// A nil req is a defensive no-op; never panic on the prometheus
|
||||
// label call which would otherwise dereference req.Bucket.
|
||||
recordMetadataOnlyIf(true, nil)
|
||||
}
|
||||
|
||||
func TestRecordMetadataOnlyIf_EmptyRuleHashCollapsesToEmptyLabel(t *testing.T) {
|
||||
// Bootstrap or test paths may not stamp a rule hash; the label
|
||||
// must end up as an empty string rather than panicking on
|
||||
// hex.EncodeToString(nil).
|
||||
c := stats_collect.S3LifecycleMetadataOnlyCounter
|
||||
bucket := "bk-counter-emptyhash"
|
||||
before := testutil.ToFloat64(c.WithLabelValues(bucket, ""))
|
||||
recordMetadataOnlyIf(true, &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: bucket})
|
||||
if got := testutil.ToFloat64(c.WithLabelValues(bucket, "")); got != before+1 {
|
||||
t.Fatalf("nil rule_hash should produce empty-label series; before=%v after=%v", before, got)
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s version %s: %v", bucket, object, versionId, err)
|
||||
return result, s3err.ErrAccessDenied
|
||||
}
|
||||
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId); err != nil {
|
||||
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId, false); err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to delete specific version %s for %s/%s: %v", versionId, bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
@@ -148,7 +148,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s null version: %v", bucket, object, err)
|
||||
return result, s3err.ErrAccessDenied
|
||||
}
|
||||
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null"); err != nil {
|
||||
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null", false); err != nil {
|
||||
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
@@ -166,10 +166,15 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
|
||||
return result, s3err.ErrInternalError
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string) error {
|
||||
// deleteUnversionedObjectWithClient removes the bare object entry. When
|
||||
// metadataOnly is true the filer skips per-chunk DeleteFile RPCs and
|
||||
// relies on the volume's natural TTL to reclaim chunks; pass true only
|
||||
// when the entry's Attributes.TtlSec > 0 so the volume is guaranteed to
|
||||
// drop the chunks on its own.
|
||||
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string, metadataOnly bool) error {
|
||||
target := util.NewFullPath(s3a.bucketDir(bucket), object)
|
||||
dir, name := target.DirAndName()
|
||||
return deleteObjectEntry(client, dir, name, true, false)
|
||||
return deleteObjectEntry(client, dir, name, !metadataOnly, false)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -228,7 +233,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
|
||||
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object)
|
||||
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
|
||||
}); err != nil {
|
||||
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
|
||||
return s3err.ErrInternalError
|
||||
@@ -370,7 +375,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key); err != nil {
|
||||
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key, false); err != nil {
|
||||
glog.Errorf("DeleteMultipleObjectsHandler: failed to delete %s/%s: %v", bucket, object.Key, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDeleteUnversionedObjectWithClient_MetadataOnlySkipsChunkDelete(t *testing.T) {
|
||||
// metadataOnly=true must reach the filer as IsDeleteData=false so the
|
||||
// volume server reclaims chunks via TTL instead of the filer enqueueing
|
||||
// per-chunk DeleteFile RPCs.
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
client := &deleteObjectEntryTestClient{}
|
||||
|
||||
err := s3a.deleteUnversionedObjectWithClient(client, "b", "k", true)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, client.deleteReq)
|
||||
assert.Equal(t, "/buckets/b", client.deleteReq.Directory)
|
||||
assert.Equal(t, "k", client.deleteReq.Name)
|
||||
assert.False(t, client.deleteReq.IsDeleteData, "metadataOnly must clear IsDeleteData")
|
||||
}
|
||||
|
||||
func TestDeleteUnversionedObjectWithClient_FullDeletePreservesIsDeleteData(t *testing.T) {
|
||||
// Default behavior (metadataOnly=false): filer should still enqueue
|
||||
// chunk deletions as before.
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
client := &deleteObjectEntryTestClient{}
|
||||
|
||||
err := s3a.deleteUnversionedObjectWithClient(client, "b", "k", false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, client.deleteReq)
|
||||
assert.True(t, client.deleteReq.IsDeleteData, "default delete must keep IsDeleteData true")
|
||||
}
|
||||
|
||||
func TestDeleteUnversionedObjectWithClient_FullPathFromBucketsRoot(t *testing.T) {
|
||||
// Sanity: BucketsPath joins to <bucketsPath>/<bucket>/<object> in the
|
||||
// DeleteEntryRequest so the filer can locate the entry. Object keys
|
||||
// with multiple path segments should split into Directory + Name
|
||||
// correctly.
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
client := &deleteObjectEntryTestClient{}
|
||||
|
||||
err := s3a.deleteUnversionedObjectWithClient(client, "mybucket", "a/b/c.txt", false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, client.deleteReq)
|
||||
assert.Equal(t, "/buckets/mybucket/a/b", client.deleteReq.Directory)
|
||||
assert.Equal(t, "c.txt", client.deleteReq.Name)
|
||||
}
|
||||
|
||||
func TestDeleteUnversionedObjectWithClient_PropagatesEntryAttributesIrrelevant(t *testing.T) {
|
||||
// The metadataOnly decision is the caller's responsibility (the
|
||||
// lifecycle handler). This function is dumb plumbing — it must not
|
||||
// inspect the entry itself, only translate the bool to IsDeleteData.
|
||||
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
|
||||
client := &deleteObjectEntryTestClient{
|
||||
// A response with no error is fine; attributes on a delete are unused.
|
||||
deleteResp: &filer_pb.DeleteEntryResponse{},
|
||||
}
|
||||
|
||||
require.NoError(t, s3a.deleteUnversionedObjectWithClient(client, "b", "k", true))
|
||||
require.NotNil(t, client.deleteReq)
|
||||
assert.False(t, client.deleteReq.IsDeleteData)
|
||||
}
|
||||
@@ -1341,9 +1341,14 @@ func (s3a *S3ApiServer) updateIsLatestFlagsForSuspendedVersioning(bucket, object
|
||||
// Clear the latest version metadata from .versions directory since "null" is now latest
|
||||
versionsEntry, err := s3a.getEntry(bucketDir, versionsObjectPath)
|
||||
if err == nil && versionsEntry.Extended != nil {
|
||||
// Remove latest version metadata so all versions show IsLatest=false
|
||||
// Remove latest version metadata so all versions show IsLatest=false.
|
||||
// Also wipe cached list-metadata (size/mtime/etag/owner/delete-marker):
|
||||
// they were stamped from the prior latest, and stale cached mtime
|
||||
// would let lifecycle compute SuccessorModTime off the displaced
|
||||
// version's age rather than today's null PUT.
|
||||
delete(versionsEntry.Extended, s3_constants.ExtLatestVersionIdKey)
|
||||
delete(versionsEntry.Extended, s3_constants.ExtLatestVersionFileNameKey)
|
||||
clearCachedVersionMetadata(versionsEntry.Extended)
|
||||
|
||||
// Update the .versions directory entry
|
||||
err = s3a.mkFile(bucketDir, versionsObjectPath, versionsEntry.Chunks, func(updatedEntry *filer_pb.Entry) {
|
||||
|
||||
@@ -964,8 +964,11 @@ func (s3a *S3ApiServer) getSpecificObjectVersion(bucket, object, versionId strin
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// deleteSpecificObjectVersion deletes a specific version of an object
|
||||
func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId string) error {
|
||||
// deleteSpecificObjectVersion deletes a specific version of an object.
|
||||
// metadataOnly=true skips per-chunk DeleteFile RPCs at the filer; only
|
||||
// pass true when the live entry's Attributes.TtlSec > 0 so the volume
|
||||
// reclaims chunks on its own.
|
||||
func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId string, metadataOnly bool) error {
|
||||
// Normalize object path to ensure consistency with toFilerPath behavior
|
||||
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
||||
|
||||
@@ -986,7 +989,7 @@ func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId st
|
||||
}
|
||||
|
||||
// Delete the regular file
|
||||
deleteErr := s3a.rmObject(bucketDir, normalizedObject, true, false)
|
||||
deleteErr := s3a.rmObject(bucketDir, normalizedObject, !metadataOnly, false)
|
||||
if deleteErr != nil {
|
||||
// Check if file was already deleted by another process
|
||||
if _, checkErr := s3a.getEntry(bucketDir, normalizedObject); checkErr != nil {
|
||||
@@ -1013,7 +1016,7 @@ func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId st
|
||||
// Attempt to delete the version file
|
||||
// Note: We don't check if the file exists first to avoid race conditions
|
||||
// The deletion operation should be idempotent
|
||||
deleteErr := s3a.rm(versionsDir, versionFile, true, false)
|
||||
deleteErr := s3a.rm(versionsDir, versionFile, !metadataOnly, false)
|
||||
if deleteErr != nil {
|
||||
// Check if file was already deleted by another process (race condition handling)
|
||||
if _, checkErr := s3a.getEntry(versionsDir, versionFile); checkErr != nil {
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
)
|
||||
|
||||
// Layer 2 component tests for the dispatcher pipeline mechanics:
|
||||
// the per-shard composition that Pipeline.Run wires up at runtime
|
||||
// (cursors, schedules, dispatchers, persister), exercised directly so
|
||||
// the tests stay independent of a live filer connection. Pipeline.Run
|
||||
// itself can't run here because it builds a real reader.Reader; these
|
||||
// tests instead drive Tick directly while sharing the same fakeClient
|
||||
// that dispatcher_test.go uses.
|
||||
|
||||
// shardKit bundles the per-shard state Pipeline.Run constructs in
|
||||
// production: a Cursor, a Schedule, and a Dispatcher hooked to both.
|
||||
type shardKit struct {
|
||||
id int
|
||||
cursor *reader.Cursor
|
||||
dispatch *Dispatcher
|
||||
}
|
||||
|
||||
func newShardKit(t *testing.T, id int, client LifecycleClient) *shardKit {
|
||||
t.Helper()
|
||||
c := reader.NewCursor()
|
||||
return &shardKit{
|
||||
id: id,
|
||||
cursor: c,
|
||||
dispatch: &Dispatcher{
|
||||
ShardID: id,
|
||||
Client: client,
|
||||
Cursor: c,
|
||||
Schedule: router.NewSchedule(),
|
||||
RetryBudget: 3,
|
||||
RetryBackoff: time.Millisecond,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// recordingClient lets Layer 2 tests assert exactly which RPCs the
|
||||
// dispatcher made. Goroutine-safe because Tick is called from test
|
||||
// goroutines but inspections happen from the test goroutine.
|
||||
type recordingClient struct {
|
||||
mu sync.Mutex
|
||||
requests []*s3_lifecycle_pb.LifecycleDeleteRequest
|
||||
respond func(req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error)
|
||||
}
|
||||
|
||||
func (r *recordingClient) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
r.mu.Lock()
|
||||
r.requests = append(r.requests, req)
|
||||
r.mu.Unlock()
|
||||
return r.respond(req)
|
||||
}
|
||||
|
||||
func TestPipelineMultiShardFanOutKeepsCursorsIsolated(t *testing.T) {
|
||||
// Two events for two different shards land in different schedules
|
||||
// and dispatch independently. Each shard's cursor advances only
|
||||
// for the event(s) targeting that shard.
|
||||
client := &recordingClient{
|
||||
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
},
|
||||
}
|
||||
shards := map[int]*shardKit{
|
||||
0: newShardKit(t, 0, client),
|
||||
1: newShardKit(t, 1, client),
|
||||
}
|
||||
|
||||
t0 := time.Now()
|
||||
mA := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
EventTs: t0,
|
||||
DueTime: t0,
|
||||
Bucket: "bk",
|
||||
ObjectKey: "alpha",
|
||||
}
|
||||
// Use a different action kind on shard 1 so the cursor key differs
|
||||
// from shard 0 — shared keys would write to the same cursor entry.
|
||||
mB := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
|
||||
EventTs: t0.Add(time.Second),
|
||||
DueTime: t0.Add(time.Second),
|
||||
Bucket: "bk",
|
||||
ObjectKey: "beta",
|
||||
}
|
||||
shards[0].dispatch.Schedule.Add(mA)
|
||||
shards[1].dispatch.Schedule.Add(mB)
|
||||
|
||||
// Tick shard 0 first; shard 1's schedule must still hold its match.
|
||||
if got := shards[0].dispatch.Tick(context.Background(), t0.Add(time.Hour)); got != 1 {
|
||||
t.Fatalf("shard 0 Tick processed=%d, want 1", got)
|
||||
}
|
||||
if got := shards[1].dispatch.Schedule.Len(); got != 1 {
|
||||
t.Fatalf("shard 1 schedule must not be drained by shard 0 Tick: len=%d", got)
|
||||
}
|
||||
|
||||
// Now tick shard 1.
|
||||
if got := shards[1].dispatch.Tick(context.Background(), t0.Add(time.Hour)); got != 1 {
|
||||
t.Fatalf("shard 1 Tick processed=%d, want 1", got)
|
||||
}
|
||||
|
||||
if shards[0].cursor.Get(mA.Key) != mA.EventTs.UnixNano() {
|
||||
t.Fatalf("shard 0 cursor not advanced: got %d", shards[0].cursor.Get(mA.Key))
|
||||
}
|
||||
if shards[1].cursor.Get(mB.Key) != mB.EventTs.UnixNano() {
|
||||
t.Fatalf("shard 1 cursor not advanced: got %d", shards[1].cursor.Get(mB.Key))
|
||||
}
|
||||
// Cursors must NOT cross-contaminate.
|
||||
if shards[0].cursor.Get(mB.Key) != 0 {
|
||||
t.Fatalf("shard 0 cursor saw shard 1's key: got %d", shards[0].cursor.Get(mB.Key))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelineCursorFreezeOnOneShardDoesntBlockOthers(t *testing.T) {
|
||||
// Shard 0 dispatches a poison event that returns BLOCKED — its
|
||||
// cursor freezes at the event TsNs. Shard 1's progress must be
|
||||
// independent: it dispatches successfully and advances.
|
||||
client := &recordingClient{
|
||||
respond: func(req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
if req.Bucket == "bk" && req.ObjectPath == "poison" {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED}, nil
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
},
|
||||
}
|
||||
shards := map[int]*shardKit{
|
||||
0: newShardKit(t, 0, client),
|
||||
1: newShardKit(t, 1, client),
|
||||
}
|
||||
|
||||
t0 := time.Now()
|
||||
poison := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
EventTs: t0,
|
||||
DueTime: t0,
|
||||
Bucket: "bk",
|
||||
ObjectKey: "poison",
|
||||
}
|
||||
good := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
|
||||
EventTs: t0.Add(time.Second),
|
||||
DueTime: t0.Add(time.Second),
|
||||
Bucket: "bk",
|
||||
ObjectKey: "good",
|
||||
}
|
||||
shards[0].dispatch.Schedule.Add(poison)
|
||||
shards[1].dispatch.Schedule.Add(good)
|
||||
|
||||
shards[0].dispatch.Tick(context.Background(), t0.Add(time.Hour))
|
||||
shards[1].dispatch.Tick(context.Background(), t0.Add(time.Hour))
|
||||
|
||||
if !shards[0].cursor.IsFrozen(poison.Key) {
|
||||
t.Fatalf("shard 0 cursor must freeze on BLOCKED outcome")
|
||||
}
|
||||
if shards[1].cursor.IsFrozen(good.Key) {
|
||||
t.Fatalf("shard 1 cursor must not freeze when shard 0 fails")
|
||||
}
|
||||
if shards[1].cursor.Get(good.Key) != good.EventTs.UnixNano() {
|
||||
t.Fatalf("shard 1 cursor must advance independently: got %d", shards[1].cursor.Get(good.Key))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelinePersisterCheckpointRoundTripsEveryShard(t *testing.T) {
|
||||
// A cursor checkpoint persists the per-shard map; a fresh dispatcher
|
||||
// can Restore from that map and resume at the same TsNs. Pipeline.Run
|
||||
// drives this on a ticker; tests exercise the contract directly.
|
||||
client := &recordingClient{
|
||||
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
},
|
||||
}
|
||||
shards := map[int]*shardKit{
|
||||
0: newShardKit(t, 0, client),
|
||||
1: newShardKit(t, 1, client),
|
||||
}
|
||||
|
||||
t0 := time.Now()
|
||||
addAndTick := func(s *shardKit, obj string, kind s3lifecycle.ActionKind, ts time.Time) {
|
||||
s.dispatch.Schedule.Add(router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: kind},
|
||||
EventTs: ts,
|
||||
DueTime: ts,
|
||||
Bucket: "bk",
|
||||
ObjectKey: obj,
|
||||
})
|
||||
s.dispatch.Tick(context.Background(), t0.Add(time.Hour))
|
||||
}
|
||||
addAndTick(shards[0], "alpha", s3lifecycle.ActionKindExpirationDays, t0)
|
||||
addAndTick(shards[1], "beta", s3lifecycle.ActionKindNoncurrentDays, t0.Add(time.Second))
|
||||
|
||||
pers := reader.NewInMemoryPersister()
|
||||
for id, s := range shards {
|
||||
if err := pers.Save(context.Background(), id, s.cursor.Snapshot()); err != nil {
|
||||
t.Fatalf("save shard %d: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Restore into fresh cursors, verify every shard's TsNs round-trips.
|
||||
for id, s := range shards {
|
||||
state, err := pers.Load(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("load shard %d: %v", id, err)
|
||||
}
|
||||
c := reader.NewCursor()
|
||||
c.Restore(state)
|
||||
want := s.cursor.Snapshot()
|
||||
got := c.Snapshot()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("shard %d snapshot len: got %d, want %d", id, len(got), len(want))
|
||||
}
|
||||
for k, v := range want {
|
||||
if got[k] != v {
|
||||
t.Fatalf("shard %d cursor key %v: got %d, want %d", id, k, got[k], v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelineRetryLaterRespectsDispatchTickCadence(t *testing.T) {
|
||||
// RETRY_LATER schedules the match for a later DueTime. A Tick at
|
||||
// the present moment must NOT re-dispatch it; only a Tick past
|
||||
// the new DueTime triggers a second RPC. This pins the cadence
|
||||
// contract against premature retries from later refresh ticks.
|
||||
calls := 0
|
||||
client := &recordingClient{
|
||||
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER}, nil
|
||||
}
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
|
||||
},
|
||||
}
|
||||
s := newShardKit(t, 0, client)
|
||||
s.dispatch.RetryBackoff = time.Hour // long backoff so the second Tick at t0+1m doesn't fire
|
||||
|
||||
t0 := time.Now()
|
||||
m := router.Match{
|
||||
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
EventTs: t0,
|
||||
DueTime: t0,
|
||||
Bucket: "bk",
|
||||
ObjectKey: "obj",
|
||||
}
|
||||
s.dispatch.Schedule.Add(m)
|
||||
|
||||
if got := s.dispatch.Tick(context.Background(), t0); got != 1 {
|
||||
t.Fatalf("first Tick processed=%d, want 1 (RETRY_LATER counts as processed)", got)
|
||||
}
|
||||
|
||||
// Within the backoff window: nothing fires.
|
||||
if got := s.dispatch.Tick(context.Background(), t0.Add(time.Minute)); got != 0 {
|
||||
t.Fatalf("Tick within backoff must skip: processed=%d", got)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("RPC must not retry within backoff: calls=%d", calls)
|
||||
}
|
||||
|
||||
// Past backoff: re-dispatches.
|
||||
if got := s.dispatch.Tick(context.Background(), t0.Add(2*time.Hour)); got != 1 {
|
||||
t.Fatalf("Tick past backoff must re-dispatch: processed=%d", got)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("expected exactly 2 calls (initial + one retry), got %d", calls)
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,8 @@ func (p *Pipeline) Run(ctx context.Context) error {
|
||||
cancel() // wake the dispatcher goroutine to drain & exit
|
||||
}()
|
||||
|
||||
lister := &filerSiblingLister{client: p.FilerClient, bucketsPath: p.BucketsPath}
|
||||
|
||||
// Router/dispatcher goroutine: pulls events, routes them to per-shard
|
||||
// schedules, ticks every shard's dispatcher on the same cadence, and
|
||||
// checkpoints every shard's cursor on the checkpoint cadence. One
|
||||
@@ -257,7 +259,7 @@ func (p *Pipeline) Run(ctx context.Context) error {
|
||||
// against the prior (empty) snapshot would silently drop
|
||||
// every match. Engine.Snapshot is an atomic Load.
|
||||
snap := p.Engine.Snapshot()
|
||||
for _, m := range router.Route(snap, ev, time.Now()) {
|
||||
for _, m := range router.Route(runCtx, snap, ev, time.Now(), lister) {
|
||||
st.dispatch.Schedule.Add(m)
|
||||
}
|
||||
case <-dt.C:
|
||||
|
||||
@@ -2,6 +2,7 @@ package dispatcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -48,7 +49,7 @@ func TestPipelineIntegrationInMemory(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
matches := router.Route(snap, ev, now)
|
||||
matches := router.Route(context.Background(), snap, ev, now, nil)
|
||||
if len(matches) != 1 {
|
||||
t.Fatalf("expected 1 match, got %v", matches)
|
||||
}
|
||||
@@ -82,3 +83,59 @@ func TestPipelineRunRequiresDependencies(t *testing.T) {
|
||||
t.Fatal("expected error for empty Pipeline")
|
||||
}
|
||||
}
|
||||
|
||||
// stubFilerClient satisfies filer_pb.SeaweedFilerClient just enough to
|
||||
// pass the nil-check in Pipeline.Run; methods would panic if called,
|
||||
// but the validation tests below all return before any RPC.
|
||||
type stubFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
}
|
||||
|
||||
// fullPipeline assembles a Pipeline whose dependencies all pass the
|
||||
// nil-check, so individual tests can knock out one piece at a time
|
||||
// to exercise specific validation branches.
|
||||
func fullPipeline() *Pipeline {
|
||||
return &Pipeline{
|
||||
Engine: engine.New(),
|
||||
Persister: reader.NewInMemoryPersister(),
|
||||
Client: &fakeClient{},
|
||||
FilerClient: &stubFilerClient{},
|
||||
BucketsPath: "/buckets",
|
||||
ShardID: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipelineRunValidation(t *testing.T) {
|
||||
// Each case mutates one piece of a fullPipeline() and asserts the
|
||||
// expected error fragment. Per-dependency cases pin that the nil
|
||||
// check exercises every required field individually; the Buckets-
|
||||
// Path case asserts the distinct error message; the shard cases
|
||||
// pin the half-open [0, ShardCount) range and that any one bad
|
||||
// entry refuses the whole multi-shard run.
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Pipeline)
|
||||
wantErr string
|
||||
}{
|
||||
{"missing Engine", func(p *Pipeline) { p.Engine = nil }, "missing required dependency"},
|
||||
{"missing Persister", func(p *Pipeline) { p.Persister = nil }, "missing required dependency"},
|
||||
{"missing Client", func(p *Pipeline) { p.Client = nil }, "missing required dependency"},
|
||||
{"missing FilerClient", func(p *Pipeline) { p.FilerClient = nil }, "missing required dependency"},
|
||||
{"missing BucketsPath", func(p *Pipeline) { p.BucketsPath = "" }, "BucketsPath required"},
|
||||
{"negative ShardID", func(p *Pipeline) { p.ShardID = -1 }, "out of"},
|
||||
{"ShardID at boundary", func(p *Pipeline) { p.ShardID = s3lifecycle.ShardCount }, "out of"},
|
||||
{"multi-shard out of range", func(p *Pipeline) {
|
||||
p.Shards = []int{0, 1, s3lifecycle.ShardCount + 1}
|
||||
}, "out of"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := fullPipeline()
|
||||
tc.mutate(p)
|
||||
err := p.Run(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// filerSiblingLister inspects the .versions/<key>/ folder and the bare
|
||||
// null-version. Listing caps at 2 — callers only distinguish 1 vs >=2.
|
||||
type filerSiblingLister struct {
|
||||
client filer_pb.SeaweedFilerClient
|
||||
bucketsPath string
|
||||
}
|
||||
|
||||
func (l *filerSiblingLister) Survivors(ctx context.Context, bucket, objectKey string) (router.Survivors, error) {
|
||||
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
|
||||
versionsDir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
|
||||
|
||||
var s router.Survivors
|
||||
err := filer_pb.SeaweedList(ctx, l.client, versionsDir, "", func(entry *filer_pb.Entry, _ bool) error {
|
||||
s.Count++
|
||||
if s.Count == 1 && entry != nil {
|
||||
s.LoneEntry = entry
|
||||
} else if s.Count > 1 {
|
||||
s.LoneEntry = nil
|
||||
}
|
||||
return nil
|
||||
}, "", false, 2)
|
||||
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return router.Survivors{}, err
|
||||
}
|
||||
|
||||
// NewFullPath strips a trailing slash from objectKey so directory-key
|
||||
// objects (foo/) split the same as regular keys. LookupEntry
|
||||
// normalizes the gRPC string-mapped not-found into ErrNotFound; a
|
||||
// raw client.LookupDirectoryEntry would return that as a generic
|
||||
// error and suppress every otherwise-valid match.
|
||||
parent, name := util.NewFullPath(bucketPath, objectKey).DirAndName()
|
||||
resp, err := filer_pb.LookupEntry(ctx, l.client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: parent,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return s, nil
|
||||
}
|
||||
return router.Survivors{}, err
|
||||
}
|
||||
// Bare regular file or an explicit S3 directory-marker (an empty
|
||||
// directory entry with Mime set) both count as the null version.
|
||||
if resp.Entry != nil && (!resp.Entry.IsDirectory || resp.Entry.IsDirectoryKeyObject()) {
|
||||
s.HasNullVersion = true
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// ListVersions paginates every file under .versions/<key>/. Used by
|
||||
// the pointer-transition expansion path when a NewerNoncurrentVersions
|
||||
// rule needs accurate per-version ranking. Subdirectories and entries
|
||||
// without ExtVersionIdKey are filtered out. NotFound returns
|
||||
// (nil, nil) so a hard-deleted .versions/ container collapses cleanly.
|
||||
func (l *filerSiblingLister) ListVersions(ctx context.Context, bucket, objectKey string) ([]*filer_pb.Entry, error) {
|
||||
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
|
||||
dir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
|
||||
const pageSize uint32 = 1024
|
||||
startFrom := ""
|
||||
var versions []*filer_pb.Entry
|
||||
for {
|
||||
var pageCount uint32
|
||||
var lastName string
|
||||
err := filer_pb.SeaweedList(ctx, l.client, dir, "", func(e *filer_pb.Entry, _ bool) error {
|
||||
pageCount++
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
lastName = e.Name
|
||||
if e.Attributes == nil || e.IsDirectory {
|
||||
return nil
|
||||
}
|
||||
if id, ok := e.Extended[s3_constants.ExtVersionIdKey]; !ok || len(id) == 0 {
|
||||
return nil
|
||||
}
|
||||
versions = append(versions, e)
|
||||
return nil
|
||||
}, startFrom, false, pageSize)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if pageCount < pageSize {
|
||||
return versions, nil
|
||||
}
|
||||
startFrom = lastName
|
||||
}
|
||||
}
|
||||
|
||||
// LookupNullVersion returns the bare-key entry that represents the
|
||||
// null version of objectKey, if any. Both regular files and explicit
|
||||
// S3 directory-key markers (an empty directory entry with Mime set)
|
||||
// qualify. explicit reports whether the entry's Extended map carries
|
||||
// ExtVersionIdKey="null" — the marker the suspended-versioning write
|
||||
// path applies. NotFound returns (nil, false, nil).
|
||||
func (l *filerSiblingLister) LookupNullVersion(ctx context.Context, bucket, objectKey string) (*filer_pb.Entry, bool, error) {
|
||||
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
|
||||
parent, name := util.NewFullPath(bucketPath, objectKey).DirAndName()
|
||||
resp, err := filer_pb.LookupEntry(ctx, l.client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: parent,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
if resp == nil || resp.Entry == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
e := resp.Entry
|
||||
if e.IsDirectory && !e.IsDirectoryKeyObject() {
|
||||
return nil, false, nil
|
||||
}
|
||||
explicit := false
|
||||
if id, ok := e.Extended[s3_constants.ExtVersionIdKey]; ok && string(id) == "null" {
|
||||
explicit = true
|
||||
}
|
||||
return e, explicit, nil
|
||||
}
|
||||
|
||||
// LookupVersion fetches <bucketsPath>/<bucket>/<objectKey>.versions/v_<id>
|
||||
// for the pointer-transition router branch. NotFound returns (nil, nil)
|
||||
// — the displaced version may have been hard-deleted between the
|
||||
// pointer update and the lookup.
|
||||
func (l *filerSiblingLister) LookupVersion(ctx context.Context, bucket, objectKey, versionID string) (*filer_pb.Entry, error) {
|
||||
if versionID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
|
||||
dir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
|
||||
resp, err := filer_pb.LookupEntry(ctx, l.client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: dir,
|
||||
Name: "v_" + versionID,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return resp.Entry, nil
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// Tests for filerSiblingLister cover the four routing-critical surfaces
|
||||
// the dispatcher pipeline depends on: Survivors (count cap + null
|
||||
// detection), ListVersions (pagination + filter), LookupNullVersion
|
||||
// (regular vs directory-key marker, explicit-null flag), and
|
||||
// LookupVersion (v_ prefix + NotFound collapse).
|
||||
|
||||
type fsListStream struct {
|
||||
responses []*filer_pb.ListEntriesResponse
|
||||
index int
|
||||
// recvErr is returned from the FIRST Recv() call before any
|
||||
// responses are delivered; lets tests inject the gRPC NotFound the
|
||||
// real filer surfaces when the parent directory doesn't exist.
|
||||
recvErr error
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (s *fsListStream) Recv() (*filer_pb.ListEntriesResponse, error) {
|
||||
if s.ctx != nil {
|
||||
if err := s.ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if s.recvErr != nil {
|
||||
err := s.recvErr
|
||||
s.recvErr = nil
|
||||
return nil, err
|
||||
}
|
||||
if s.index >= len(s.responses) {
|
||||
return nil, io.EOF
|
||||
}
|
||||
resp := s.responses[s.index]
|
||||
s.index++
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (s *fsListStream) Header() (metadata.MD, error) { return metadata.MD{}, nil }
|
||||
func (s *fsListStream) Trailer() metadata.MD { return metadata.MD{} }
|
||||
func (s *fsListStream) CloseSend() error { return nil }
|
||||
func (s *fsListStream) Context() context.Context {
|
||||
if s.ctx != nil {
|
||||
return s.ctx
|
||||
}
|
||||
return context.Background()
|
||||
}
|
||||
func (s *fsListStream) SendMsg(any) error { return nil }
|
||||
func (s *fsListStream) RecvMsg(any) error { return nil }
|
||||
|
||||
// fsFakeFiler implements just the SeaweedFilerClient methods that
|
||||
// filerSiblingLister calls (ListEntries + LookupDirectoryEntry). Other
|
||||
// methods on the embedded interface remain nil; calling them panics,
|
||||
// which the tests rely on to catch regressions that try to reach beyond
|
||||
// the documented surface.
|
||||
type fsFakeFiler struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
|
||||
mu sync.Mutex
|
||||
// tree maps a directory path to its immediate children. A directory
|
||||
// is "missing" when its key is absent from tree (we return ErrNotFound
|
||||
// from ListEntries / LookupDirectoryEntry to mimic the real filer).
|
||||
tree map[string][]*filer_pb.Entry
|
||||
// listErr / lookupErr force the next call to fail with this error.
|
||||
// Reset to nil after use so tests can mix success + failure runs.
|
||||
listErr error
|
||||
lookupErr error
|
||||
// missing controls per-directory NotFound for ListEntries: when a path
|
||||
// is in this set, ListEntries returns filer_pb.ErrNotFound regardless
|
||||
// of whether tree has an entry for it. Lets us test the .versions/
|
||||
// not-yet-created vs. empty cases independently.
|
||||
missing map[string]struct{}
|
||||
}
|
||||
|
||||
func newFakeFiler() *fsFakeFiler {
|
||||
return &fsFakeFiler{
|
||||
tree: map[string][]*filer_pb.Entry{},
|
||||
missing: map[string]struct{}{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fsFakeFiler) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.listErr != nil {
|
||||
err := c.listErr
|
||||
c.listErr = nil
|
||||
return nil, err
|
||||
}
|
||||
// Real-filer behavior on a missing parent: stream creation succeeds,
|
||||
// the first Recv() surfaces ErrNotFound. SeaweedList passes that
|
||||
// through unwrapped, which is what filerSiblingLister's
|
||||
// errors.Is(err, filer_pb.ErrNotFound) check depends on.
|
||||
if _, missing := c.missing[in.Directory]; missing {
|
||||
return &fsListStream{recvErr: filer_pb.ErrNotFound, ctx: ctx}, nil
|
||||
}
|
||||
src := c.tree[in.Directory]
|
||||
filtered := make([]*filer_pb.Entry, 0, len(src))
|
||||
for _, e := range src {
|
||||
if e == nil {
|
||||
continue
|
||||
}
|
||||
if in.StartFromFileName != "" {
|
||||
if in.InclusiveStartFrom {
|
||||
if e.Name < in.StartFromFileName {
|
||||
continue
|
||||
}
|
||||
} else if e.Name <= in.StartFromFileName {
|
||||
continue
|
||||
}
|
||||
}
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
sort.SliceStable(filtered, func(i, j int) bool { return filtered[i].Name < filtered[j].Name })
|
||||
if in.Limit > 0 && uint32(len(filtered)) > in.Limit {
|
||||
filtered = filtered[:in.Limit]
|
||||
}
|
||||
resps := make([]*filer_pb.ListEntriesResponse, 0, len(filtered))
|
||||
for _, e := range filtered {
|
||||
resps = append(resps, &filer_pb.ListEntriesResponse{Entry: e})
|
||||
}
|
||||
return &fsListStream{responses: resps, ctx: ctx}, nil
|
||||
}
|
||||
|
||||
func (c *fsFakeFiler) LookupDirectoryEntry(ctx context.Context, in *filer_pb.LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.lookupErr != nil {
|
||||
err := c.lookupErr
|
||||
c.lookupErr = nil
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range c.tree[in.Directory] {
|
||||
if e != nil && e.Name == in.Name {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil
|
||||
}
|
||||
}
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
func (c *fsFakeFiler) put(dir string, entries ...*filer_pb.Entry) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.tree[dir] = append(c.tree[dir], entries...)
|
||||
}
|
||||
|
||||
func (c *fsFakeFiler) markMissing(dir string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.missing[dir] = struct{}{}
|
||||
}
|
||||
|
||||
func newLister(c *fsFakeFiler) *filerSiblingLister {
|
||||
return &filerSiblingLister{client: c, bucketsPath: "/buckets"}
|
||||
}
|
||||
|
||||
func versionEntry(name, versionID string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtVersionIdKey: []byte(versionID),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSurvivors_NoVersionsNoNullReturnsZero(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
// .versions/ doesn't exist (NotFound) and the bare key doesn't exist either.
|
||||
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
|
||||
l := newLister(f)
|
||||
|
||||
s, err := l.Survivors(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, s.Count)
|
||||
assert.False(t, s.HasNullVersion)
|
||||
assert.Nil(t, s.LoneEntry)
|
||||
}
|
||||
|
||||
func TestSurvivors_OneVersionPopulatesLoneEntry(t *testing.T) {
|
||||
// Count == 1 means LoneEntry must be set; the dispatcher's
|
||||
// sole-survivor path uses it to compare against the marker version.
|
||||
f := newFakeFiler()
|
||||
dir := "/buckets/b/k" + s3_constants.VersionsFolder
|
||||
f.put(dir, versionEntry("v_aaa", "aaa"))
|
||||
f.markMissing("/buckets/b") // bare key absent
|
||||
l := newLister(f)
|
||||
|
||||
s, err := l.Survivors(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, s.Count)
|
||||
require.NotNil(t, s.LoneEntry)
|
||||
assert.Equal(t, "v_aaa", s.LoneEntry.Name)
|
||||
assert.False(t, s.HasNullVersion)
|
||||
}
|
||||
|
||||
func TestSurvivors_MoreThanOneClearsLoneEntry(t *testing.T) {
|
||||
// Listing caps at 2; once Count > 1, LoneEntry must be reset to nil
|
||||
// so the caller doesn't mistakenly treat the second-arrival entry as
|
||||
// the sole survivor.
|
||||
f := newFakeFiler()
|
||||
dir := "/buckets/b/k" + s3_constants.VersionsFolder
|
||||
f.put(dir, versionEntry("v_aaa", "aaa"), versionEntry("v_bbb", "bbb"))
|
||||
f.markMissing("/buckets/b")
|
||||
l := newLister(f)
|
||||
|
||||
s, err := l.Survivors(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, s.Count)
|
||||
assert.Nil(t, s.LoneEntry, "Count > 1 must clear LoneEntry")
|
||||
}
|
||||
|
||||
func TestSurvivors_NullVersionDetectedFromBareRegularFile(t *testing.T) {
|
||||
// The bare <bucket>/<key> path resolves to a regular file when the
|
||||
// object pre-dates versioning; that file is the null version.
|
||||
f := newFakeFiler()
|
||||
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
|
||||
f.put("/buckets/b", &filer_pb.Entry{Name: "k", IsDirectory: false, Attributes: &filer_pb.FuseAttributes{}})
|
||||
l := newLister(f)
|
||||
|
||||
s, err := l.Survivors(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, s.HasNullVersion)
|
||||
}
|
||||
|
||||
func TestSurvivors_DirectoryKeyMarkerCountsAsNull(t *testing.T) {
|
||||
// An explicit S3 directory-key marker (IsDirectory=true with
|
||||
// Attributes.Mime set) is also the null version. The listing path
|
||||
// downstream treats both the regular-file and the directory-marker
|
||||
// shape as null; Survivors must agree. The lister's NewFullPath
|
||||
// trims the trailing slash from objectKey before splitting, so the
|
||||
// stored entry Name has no trailing slash.
|
||||
f := newFakeFiler()
|
||||
f.markMissing("/buckets/b/dir" + s3_constants.VersionsFolder)
|
||||
f.put("/buckets/b", &filer_pb.Entry{
|
||||
Name: "dir",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"},
|
||||
})
|
||||
l := newLister(f)
|
||||
|
||||
s, err := l.Survivors(context.Background(), "b", "dir/")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, s.HasNullVersion, "directory-key marker must count as null version")
|
||||
}
|
||||
|
||||
func TestSurvivors_PlainDirectoryDoesNotCount(t *testing.T) {
|
||||
// A plain directory (no Mime, just IsDirectory=true) is implicit-only
|
||||
// and must NOT register as a null version — otherwise normal prefix
|
||||
// directories would shadow real null-version detection.
|
||||
f := newFakeFiler()
|
||||
f.markMissing("/buckets/b/dir" + s3_constants.VersionsFolder)
|
||||
f.put("/buckets/b", &filer_pb.Entry{
|
||||
Name: "dir",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{}, // no Mime
|
||||
})
|
||||
l := newLister(f)
|
||||
|
||||
s, err := l.Survivors(context.Background(), "b", "dir/")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, s.HasNullVersion, "plain directory must not count as null version")
|
||||
}
|
||||
|
||||
func TestSurvivors_VersionsListingErrorPropagates(t *testing.T) {
|
||||
// A non-NotFound error from the .versions/ listing must surface; the
|
||||
// dispatcher promotes this to a retry instead of a NOOP.
|
||||
f := newFakeFiler()
|
||||
f.listErr = errors.New("transport boom")
|
||||
l := newLister(f)
|
||||
|
||||
_, err := l.Survivors(context.Background(), "b", "k")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "transport boom")
|
||||
}
|
||||
|
||||
func TestSurvivors_NullLookupErrorPropagates(t *testing.T) {
|
||||
// A non-NotFound error from the bare-key lookup must surface; we
|
||||
// can't conclude "no null" from a transport failure.
|
||||
f := newFakeFiler()
|
||||
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
|
||||
f.lookupErr = errors.New("lookup boom")
|
||||
l := newLister(f)
|
||||
|
||||
_, err := l.Survivors(context.Background(), "b", "k")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "lookup boom")
|
||||
}
|
||||
|
||||
func TestListVersions_NotFoundReturnsNil(t *testing.T) {
|
||||
// A hard-deleted .versions/ container collapses to (nil, nil) so
|
||||
// callers can treat it as "no versions" without special-casing.
|
||||
f := newFakeFiler()
|
||||
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
|
||||
l := newLister(f)
|
||||
|
||||
versions, err := l.ListVersions(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, versions)
|
||||
}
|
||||
|
||||
func TestListVersions_FiltersOutDirectoriesAndMissingVersionId(t *testing.T) {
|
||||
// Subdirectories and entries without ExtVersionIdKey aren't real
|
||||
// versions; the bootstrap walker writes them sometimes so the
|
||||
// listing must filter rather than treat them as data.
|
||||
f := newFakeFiler()
|
||||
dir := "/buckets/b/k" + s3_constants.VersionsFolder
|
||||
f.put(dir,
|
||||
versionEntry("v_aaa", "aaa"),
|
||||
&filer_pb.Entry{Name: "subdir", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
|
||||
&filer_pb.Entry{Name: "v_no_attrs"}, // nil Attributes
|
||||
&filer_pb.Entry{Name: "v_no_ext", Attributes: &filer_pb.FuseAttributes{}}, // missing Extended
|
||||
&filer_pb.Entry{Name: "v_empty_ext", Attributes: &filer_pb.FuseAttributes{}, Extended: map[string][]byte{s3_constants.ExtVersionIdKey: nil}}, // empty value
|
||||
versionEntry("v_zzz", "zzz"),
|
||||
)
|
||||
l := newLister(f)
|
||||
|
||||
versions, err := l.ListVersions(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions, 2)
|
||||
assert.Equal(t, "v_aaa", versions[0].Name)
|
||||
assert.Equal(t, "v_zzz", versions[1].Name)
|
||||
}
|
||||
|
||||
func TestListVersions_PaginatesAcrossPages(t *testing.T) {
|
||||
// pageSize is 1024 inside the lister; populate just over the boundary
|
||||
// to force a second listing call. The fake's StartFromFileName
|
||||
// handling mirrors the real filer.
|
||||
f := newFakeFiler()
|
||||
dir := "/buckets/b/k" + s3_constants.VersionsFolder
|
||||
const total = 1030
|
||||
entries := make([]*filer_pb.Entry, 0, total)
|
||||
for i := 0; i < total; i++ {
|
||||
entries = append(entries, versionEntry(fmt.Sprintf("v_%05d", i), fmt.Sprintf("id_%05d", i)))
|
||||
}
|
||||
f.put(dir, entries...)
|
||||
l := newLister(f)
|
||||
|
||||
versions, err := l.ListVersions(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions, total)
|
||||
// Order is preserved across pages.
|
||||
assert.Equal(t, "v_00000", versions[0].Name)
|
||||
assert.Equal(t, fmt.Sprintf("v_%05d", total-1), versions[total-1].Name)
|
||||
}
|
||||
|
||||
func TestListVersions_ErrorPropagates(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
f.listErr = errors.New("list boom")
|
||||
l := newLister(f)
|
||||
|
||||
versions, err := l.ListVersions(context.Background(), "b", "k")
|
||||
assert.Nil(t, versions)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "list boom")
|
||||
}
|
||||
|
||||
func TestLookupNullVersion_RegularFileExplicitFalse(t *testing.T) {
|
||||
// A bare regular file with no ExtVersionIdKey is the null version
|
||||
// but not "explicit" — the suspended-versioning write path flags
|
||||
// explicit nulls with ExtVersionIdKey="null".
|
||||
f := newFakeFiler()
|
||||
f.put("/buckets/b", &filer_pb.Entry{Name: "k", IsDirectory: false, Attributes: &filer_pb.FuseAttributes{}})
|
||||
l := newLister(f)
|
||||
|
||||
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.Equal(t, "k", entry.Name)
|
||||
assert.False(t, explicit)
|
||||
}
|
||||
|
||||
func TestLookupNullVersion_ExplicitNullFlag(t *testing.T) {
|
||||
// ExtVersionIdKey="null" is the marker the suspended-versioning
|
||||
// write path sets; the lister surfaces it via the explicit return.
|
||||
f := newFakeFiler()
|
||||
f.put("/buckets/b", &filer_pb.Entry{
|
||||
Name: "k",
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("null")},
|
||||
})
|
||||
l := newLister(f)
|
||||
|
||||
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.True(t, explicit)
|
||||
}
|
||||
|
||||
func TestLookupNullVersion_DirectoryKeyMarkerQualifies(t *testing.T) {
|
||||
// NewFullPath strips a trailing slash before splitting; the entry
|
||||
// Name as stored has no slash.
|
||||
f := newFakeFiler()
|
||||
f.put("/buckets/b", &filer_pb.Entry{
|
||||
Name: "dir",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"},
|
||||
})
|
||||
l := newLister(f)
|
||||
|
||||
entry, _, err := l.LookupNullVersion(context.Background(), "b", "dir/")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
}
|
||||
|
||||
func TestLookupNullVersion_PlainDirectoryRejected(t *testing.T) {
|
||||
// A plain directory must not be returned — otherwise the dispatcher
|
||||
// would treat any prefix directory as a null version.
|
||||
f := newFakeFiler()
|
||||
f.put("/buckets/b", &filer_pb.Entry{
|
||||
Name: "dir",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
})
|
||||
l := newLister(f)
|
||||
|
||||
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "dir/")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.False(t, explicit)
|
||||
}
|
||||
|
||||
func TestLookupNullVersion_NotFoundCollapses(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
l := newLister(f) // empty tree -> NotFound on lookup
|
||||
|
||||
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
assert.False(t, explicit)
|
||||
}
|
||||
|
||||
func TestLookupNullVersion_TransportErrorPropagates(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
f.lookupErr = errors.New("lookup boom")
|
||||
l := newLister(f)
|
||||
|
||||
_, _, err := l.LookupNullVersion(context.Background(), "b", "k")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "lookup boom")
|
||||
}
|
||||
|
||||
func TestLookupVersion_EmptyVersionIdReturnsNil(t *testing.T) {
|
||||
// An empty versionID is a no-op — neither error nor result.
|
||||
f := newFakeFiler()
|
||||
l := newLister(f)
|
||||
|
||||
entry, err := l.LookupVersion(context.Background(), "b", "k", "")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
}
|
||||
|
||||
func TestLookupVersion_AppliesVPrefix(t *testing.T) {
|
||||
// File name on disk is "v_<id>"; the caller passes only the id.
|
||||
f := newFakeFiler()
|
||||
dir := "/buckets/b/k" + s3_constants.VersionsFolder
|
||||
f.put(dir, versionEntry("v_abc123", "abc123"))
|
||||
l := newLister(f)
|
||||
|
||||
entry, err := l.LookupVersion(context.Background(), "b", "k", "abc123")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.Equal(t, "v_abc123", entry.Name)
|
||||
}
|
||||
|
||||
func TestLookupVersion_NotFoundCollapses(t *testing.T) {
|
||||
// Hard-delete between pointer update and lookup is the documented
|
||||
// race; collapse to (nil, nil) so the dispatcher continues without
|
||||
// retry-storming.
|
||||
f := newFakeFiler()
|
||||
l := newLister(f)
|
||||
|
||||
entry, err := l.LookupVersion(context.Background(), "b", "k", "abc")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, entry)
|
||||
}
|
||||
|
||||
func TestLookupVersion_TransportErrorPropagates(t *testing.T) {
|
||||
f := newFakeFiler()
|
||||
f.lookupErr = errors.New("lookup boom")
|
||||
l := newLister(f)
|
||||
|
||||
_, err := l.LookupVersion(context.Background(), "b", "k", "abc")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "lookup boom")
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package dispatcher
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// toProtoActionKind / toProtoIdentity are the worker-side CAS-witness
|
||||
// converters; getting them wrong silently breaks the LifecycleDelete
|
||||
// flow because the server's identity check always fails. These tests
|
||||
// pin the full mapping so a new ActionKind added in s3lifecycle but
|
||||
// forgotten here can't slip through as ACTION_KIND_UNSPECIFIED.
|
||||
|
||||
func TestToProtoActionKind_AllKnownKindsMap(t *testing.T) {
|
||||
cases := []struct {
|
||||
in s3lifecycle.ActionKind
|
||||
want s3_lifecycle_pb.ActionKind
|
||||
}{
|
||||
{s3lifecycle.ActionKindExpirationDays, s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS},
|
||||
{s3lifecycle.ActionKindExpirationDate, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE},
|
||||
{s3lifecycle.ActionKindNoncurrentDays, s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS},
|
||||
{s3lifecycle.ActionKindNewerNoncurrent, s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT},
|
||||
{s3lifecycle.ActionKindAbortMPU, s3_lifecycle_pb.ActionKind_ABORT_MPU},
|
||||
{s3lifecycle.ActionKindExpiredDeleteMarker, s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.in.String(), func(t *testing.T) {
|
||||
assert.Equal(t, c.want, toProtoActionKind(c.in))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToProtoActionKind_UnspecifiedAndUnknownFallToUnspecified(t *testing.T) {
|
||||
// Both the in-package zero value and a future kind not listed in
|
||||
// the switch must collapse to ACTION_KIND_UNSPECIFIED so the server
|
||||
// can reject with FATAL rather than silently dispatch a wrong kind.
|
||||
assert.Equal(t, s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED,
|
||||
toProtoActionKind(s3lifecycle.ActionKindUnspecified))
|
||||
assert.Equal(t, s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED,
|
||||
toProtoActionKind(s3lifecycle.ActionKind(999)))
|
||||
}
|
||||
|
||||
func TestToProtoIdentity_NilReturnsNil(t *testing.T) {
|
||||
// LifecycleDelete treats a nil ExpectedIdentity as "no CAS"; the
|
||||
// converter must preserve that signal rather than emit an empty
|
||||
// non-nil identity that would force a re-fetch + comparison.
|
||||
assert.Nil(t, toProtoIdentity(nil))
|
||||
}
|
||||
|
||||
func TestToProtoIdentity_AllFieldsCopied(t *testing.T) {
|
||||
in := &router.EntryIdentity{
|
||||
MtimeNs: 1700000000_000_000_123,
|
||||
Size: 4096,
|
||||
HeadFid: "1,abc",
|
||||
ExtendedHash: []byte{0xde, 0xad, 0xbe, 0xef},
|
||||
}
|
||||
out := toProtoIdentity(in)
|
||||
if out == nil {
|
||||
t.Fatal("non-nil input must produce non-nil output")
|
||||
}
|
||||
assert.Equal(t, in.MtimeNs, out.MtimeNs)
|
||||
assert.Equal(t, in.Size, out.Size)
|
||||
assert.Equal(t, in.HeadFid, out.HeadFid)
|
||||
assert.Equal(t, in.ExtendedHash, out.ExtendedHash)
|
||||
}
|
||||
|
||||
func TestToProtoIdentity_EmptyFieldsSurvive(t *testing.T) {
|
||||
// A bootstrap-fresh entry can land at the dispatcher with zero
|
||||
// MtimeNs / Size / no HeadFid — the converter must still produce a
|
||||
// non-nil identity so the server treats it as a real CAS witness
|
||||
// rather than the no-CAS sentinel.
|
||||
in := &router.EntryIdentity{}
|
||||
out := toProtoIdentity(in)
|
||||
if out == nil {
|
||||
t.Fatal("zero-valued identity must still produce non-nil")
|
||||
}
|
||||
assert.Zero(t, out.MtimeNs)
|
||||
assert.Zero(t, out.Size)
|
||||
assert.Empty(t, out.HeadFid)
|
||||
assert.Empty(t, out.ExtendedHash)
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// prefixMatches and filterAllows are pure helpers exercised indirectly
|
||||
// through MatchOriginalWrite / MatchPath; pinning them directly catches
|
||||
// a regression at the helper level so a Match-test failure isn't the
|
||||
// first signal of a broken filter.
|
||||
|
||||
func TestPrefixMatches_EmptyPrefixAllowsEverything(t *testing.T) {
|
||||
// An empty prefix on a rule means "match every key in the bucket"
|
||||
// — the no-op fast path that skips the HasPrefix call.
|
||||
assert.True(t, prefixMatches("", "logs/2026/01/01"))
|
||||
assert.True(t, prefixMatches("", ""))
|
||||
assert.True(t, prefixMatches("", "/"))
|
||||
}
|
||||
|
||||
func TestPrefixMatches_HonorsExactPrefix(t *testing.T) {
|
||||
assert.True(t, prefixMatches("logs/", "logs/2026/01/01"))
|
||||
assert.True(t, prefixMatches("logs/", "logs/"))
|
||||
}
|
||||
|
||||
func TestPrefixMatches_RejectsNonMatchingPath(t *testing.T) {
|
||||
assert.False(t, prefixMatches("logs/", "metrics/2026/01/01"))
|
||||
assert.False(t, prefixMatches("logs/", "log/2026/01/01")) // no trailing slash
|
||||
}
|
||||
|
||||
func TestPrefixMatches_PathShorterThanPrefixIsReject(t *testing.T) {
|
||||
// Path shorter than the rule prefix can't satisfy HasPrefix; the
|
||||
// helper must say no rather than treat it as a partial match.
|
||||
assert.False(t, prefixMatches("logs/2026/", "logs/"))
|
||||
}
|
||||
|
||||
func TestFilterAllows_NoFiltersAcceptsAnything(t *testing.T) {
|
||||
// A rule without any filter knobs allows every event regardless of
|
||||
// size or tag map. Pins the documented "no filter" fast path.
|
||||
rule := &s3lifecycle.Rule{}
|
||||
assert.True(t, filterAllows(rule, &Event{Size: 0}))
|
||||
assert.True(t, filterAllows(rule, &Event{Size: 1024}))
|
||||
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"a": "b"}}))
|
||||
}
|
||||
|
||||
func TestFilterAllows_SizeGreaterThanGate(t *testing.T) {
|
||||
// FilterSizeGreaterThan is "strictly greater"; events at or below
|
||||
// the threshold are rejected.
|
||||
rule := &s3lifecycle.Rule{FilterSizeGreaterThan: 1024}
|
||||
assert.False(t, filterAllows(rule, &Event{Size: 1024}), "boundary value rejected (gate is >, not >=)")
|
||||
assert.False(t, filterAllows(rule, &Event{Size: 100}))
|
||||
assert.True(t, filterAllows(rule, &Event{Size: 1025}))
|
||||
}
|
||||
|
||||
func TestFilterAllows_SizeLessThanGate(t *testing.T) {
|
||||
// FilterSizeLessThan is "strictly less"; events at or above the
|
||||
// threshold are rejected.
|
||||
rule := &s3lifecycle.Rule{FilterSizeLessThan: 1024}
|
||||
assert.False(t, filterAllows(rule, &Event{Size: 1024}), "boundary value rejected (gate is <, not <=)")
|
||||
assert.False(t, filterAllows(rule, &Event{Size: 4096}))
|
||||
assert.True(t, filterAllows(rule, &Event{Size: 1023}))
|
||||
}
|
||||
|
||||
func TestFilterAllows_ZeroSizeFilterIsDisabled(t *testing.T) {
|
||||
// FilterSizeGreaterThan/LessThan = 0 means "not set"; the filter
|
||||
// must let any size through. A regression treating 0 as a real
|
||||
// threshold would reject every event at or above 0 (i.e., all of
|
||||
// them).
|
||||
greater := &s3lifecycle.Rule{FilterSizeGreaterThan: 0}
|
||||
less := &s3lifecycle.Rule{FilterSizeLessThan: 0}
|
||||
for _, size := range []int64{0, 1, 1024, 1 << 30} {
|
||||
assert.True(t, filterAllows(greater, &Event{Size: size}), "Gt 0 must allow size %d", size)
|
||||
assert.True(t, filterAllows(less, &Event{Size: size}), "Lt 0 must allow size %d", size)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterAllows_RequiredTagPresent(t *testing.T) {
|
||||
// A FilterTags entry is "must equal"; the event's Tags map must
|
||||
// have the same key with the same value.
|
||||
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod"}}
|
||||
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod"}}))
|
||||
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "a"}}))
|
||||
}
|
||||
|
||||
func TestFilterAllows_RequiredTagMissingOrWrong(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod"}}
|
||||
assert.False(t, filterAllows(rule, &Event{}), "nil tags map rejected")
|
||||
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{}}), "empty tags rejected")
|
||||
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"team": "a"}}), "different key rejected")
|
||||
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "stage"}}), "wrong value rejected")
|
||||
}
|
||||
|
||||
func TestFilterAllows_AllRequiredTagsMustMatch(t *testing.T) {
|
||||
// Multiple FilterTags are AND'd; missing any one rejects.
|
||||
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod", "team": "data"}}
|
||||
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "data"}}))
|
||||
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod"}}), "missing one tag rejected")
|
||||
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"team": "data"}}), "missing other tag rejected")
|
||||
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "ops"}}), "wrong value on second tag rejected")
|
||||
}
|
||||
|
||||
func TestFilterAllows_SizeAndTagAreANDed(t *testing.T) {
|
||||
// A rule with both size and tag filters requires BOTH to pass;
|
||||
// either one failing rejects the event.
|
||||
rule := &s3lifecycle.Rule{
|
||||
FilterSizeGreaterThan: 100,
|
||||
FilterTags: map[string]string{"env": "prod"},
|
||||
}
|
||||
// Both pass.
|
||||
assert.True(t, filterAllows(rule, &Event{Size: 200, Tags: map[string]string{"env": "prod"}}))
|
||||
// Size fails.
|
||||
assert.False(t, filterAllows(rule, &Event{Size: 50, Tags: map[string]string{"env": "prod"}}))
|
||||
// Tag fails.
|
||||
assert.False(t, filterAllows(rule, &Event{Size: 200, Tags: map[string]string{"env": "stage"}}))
|
||||
}
|
||||
|
||||
// ---------- MatchOriginalWrite / MatchPredicateChange / MatchPath edge cases ----------
|
||||
|
||||
// helperSnapshot constructs a Snapshot via the engine's Compile path so
|
||||
// the action map and bucket index are populated correctly. Tests below
|
||||
// poke at the public Match functions rather than the internal maps.
|
||||
func helperSnapshot(t *testing.T) (*Snapshot, *s3lifecycle.Rule, s3lifecycle.ActionKey) {
|
||||
t.Helper()
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
Prefix: "logs/",
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
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},
|
||||
)
|
||||
key := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
return snap, rule, key
|
||||
}
|
||||
|
||||
func TestMatchOriginalWrite_NilEventReturnsNil(t *testing.T) {
|
||||
// A nil event is treated as "no match"; the routing path should
|
||||
// not panic on a defensive caller.
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
assert.Nil(t, snap.MatchOriginalWrite(nil, 7*24*time.Hour))
|
||||
}
|
||||
|
||||
func TestMatchOriginalWrite_WrongShapeReturnsNil(t *testing.T) {
|
||||
// Only EventShapeOriginalWrite goes through this path; a
|
||||
// PredicateChange event must not produce delay-group matches.
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
got := snap.MatchOriginalWrite(&Event{Shape: EventShapePredicateChange, Bucket: "bk"}, 7*24*time.Hour)
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestMatchOriginalWrite_DelayMismatchReturnsNil(t *testing.T) {
|
||||
// The action is in the 7-day delay group; asking for a different
|
||||
// delay must produce no matches.
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
got := snap.MatchOriginalWrite(&Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "logs/x"}, 30*24*time.Hour)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestMatchPredicateChange_NilEventReturnsNil(t *testing.T) {
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
assert.Nil(t, snap.MatchPredicateChange(nil))
|
||||
}
|
||||
|
||||
func TestMatchPredicateChange_WrongShapeReturnsNil(t *testing.T) {
|
||||
// EventShapeOriginalWrite events go through MatchOriginalWrite; a
|
||||
// caller passing one to MatchPredicateChange gets nothing back.
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
got := snap.MatchPredicateChange(&Event{Shape: EventShapeOriginalWrite, Bucket: "bk"})
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestMatchPredicateChange_NoTagSensitiveActionsReturnsNil(t *testing.T) {
|
||||
// The default helperSnapshot rule has no FilterTags, so it's not
|
||||
// tag-sensitive — predicate changes must yield no matches.
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
got := snap.MatchPredicateChange(&Event{Shape: EventShapePredicateChange, Bucket: "bk", Path: "logs/x"})
|
||||
assert.Nil(t, got, "non-tag-sensitive snapshot returns nil from predicate change")
|
||||
}
|
||||
|
||||
func TestMatchPath_UnknownBucketReturnsNil(t *testing.T) {
|
||||
snap, _, _ := helperSnapshot(t)
|
||||
got := snap.MatchPath("other-bucket", "logs/x", nil)
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestMatchPath_NilEventStillAppliesPrefix(t *testing.T) {
|
||||
// MatchPath with ev=nil applies prefix matching only; tags/size
|
||||
// don't gate. Pinned because the bootstrap walker calls it that
|
||||
// way.
|
||||
snap, _, key := helperSnapshot(t)
|
||||
matches := snap.MatchPath("bk", "logs/2026/01/01", nil)
|
||||
assert.Contains(t, matches, key)
|
||||
assert.Empty(t, snap.MatchPath("bk", "metrics/x", nil), "prefix mismatch must reject even with nil event")
|
||||
}
|
||||
|
||||
func TestMatchPath_FilterRespectedWhenEventProvided(t *testing.T) {
|
||||
// When the caller supplies an Event, both prefix and filter gates
|
||||
// fire. A size-filter rule rejects an event below the threshold.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
FilterSizeGreaterThan: 1000,
|
||||
}
|
||||
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},
|
||||
)
|
||||
belowThreshold := &Event{Size: 500}
|
||||
aboveThreshold := &Event{Size: 2000}
|
||||
assert.Empty(t, snap.MatchPath("bk", "x", belowThreshold), "size below threshold must reject")
|
||||
assert.NotEmpty(t, snap.MatchPath("bk", "x", aboveThreshold), "size above threshold must allow")
|
||||
}
|
||||
|
||||
// ---------- filterMatching direct coverage ----------
|
||||
|
||||
func TestFilterMatching_BucketScoping(t *testing.T) {
|
||||
// Two buckets sharing identical rules: filterMatching must reject
|
||||
// keys whose action.Bucket doesn't match ev.Bucket so a match in
|
||||
// "alpha" doesn't bleed into "beta".
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{}
|
||||
for _, b := range []string{"alpha", "beta"} {
|
||||
for _, k := range s3lifecycle.RuleActionKinds(rule) {
|
||||
prior[s3lifecycle.ActionKey{Bucket: b, RuleHash: hash, ActionKind: k}] = PriorState{
|
||||
BootstrapComplete: true,
|
||||
Mode: ModeEventDriven,
|
||||
}
|
||||
}
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{
|
||||
{Bucket: "alpha", Rules: []*s3lifecycle.Rule{rule}},
|
||||
{Bucket: "beta", Rules: []*s3lifecycle.Rule{rule}},
|
||||
},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
got := snap.MatchOriginalWrite(&Event{
|
||||
Shape: EventShapeOriginalWrite, Bucket: "alpha", Path: "x", Size: 1,
|
||||
}, 7*24*time.Hour)
|
||||
require.NotEmpty(t, got)
|
||||
for _, k := range got {
|
||||
assert.Equal(t, "alpha", k.Bucket, "match leaked across bucket")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterMatching_AbortMPURequiresMPUInit(t *testing.T) {
|
||||
// AbortMPU actions only fire on MPU-init events; a normal write to
|
||||
// the same prefix must not trigger them.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
AbortMPUDaysAfterInitiation: 7,
|
||||
}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{
|
||||
abortKey: {BootstrapComplete: true, Mode: ModeEventDriven},
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
regular := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsMPUInit: false}
|
||||
mpu := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsMPUInit: true}
|
||||
assert.Empty(t, snap.MatchOriginalWrite(regular, 7*24*time.Hour), "regular write must not trigger AbortMPU")
|
||||
assert.Contains(t, snap.MatchOriginalWrite(mpu, 7*24*time.Hour), abortKey, "MPU init must trigger AbortMPU")
|
||||
}
|
||||
|
||||
func TestFilterMatching_ExpiredDeleteMarkerRequiresMarkerLatest(t *testing.T) {
|
||||
// EXPIRED_DELETE_MARKER actions only fire when the event is both a
|
||||
// delete marker AND the current latest version. A non-delete event
|
||||
// or a noncurrent delete marker must not trigger.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpiredObjectDeleteMarker: true,
|
||||
}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
markerKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpiredDeleteMarker}
|
||||
prior := map[s3lifecycle.ActionKey]PriorState{
|
||||
markerKey: {BootstrapComplete: true, Mode: ModeEventDriven},
|
||||
}
|
||||
snap := New().Compile(
|
||||
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
CompileOptions{PriorStates: prior},
|
||||
)
|
||||
// ExpiredDeleteMarker has MinTriggerAge=0; the action lives in the
|
||||
// zero-duration delay group, so the dispatcher polls it on every
|
||||
// tick.
|
||||
delay := time.Duration(0)
|
||||
notMarker := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: false, IsLatest: true}
|
||||
notLatest := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: true, IsLatest: false}
|
||||
bothTrue := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: true, IsLatest: true}
|
||||
assert.Empty(t, snap.MatchOriginalWrite(notMarker, delay), "non-marker must not trigger")
|
||||
assert.Empty(t, snap.MatchOriginalWrite(notLatest, delay), "noncurrent marker must not trigger")
|
||||
assert.Contains(t, snap.MatchOriginalWrite(bothTrue, delay), markerKey, "marker that is also latest must trigger")
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// decideMode is the per-action mode classifier the scheduler uses when
|
||||
// no durable Mode exists yet. Compile tests cover most paths
|
||||
// indirectly; these direct tests pin every branch so a regression in
|
||||
// decideMode itself can't slip through behind a more elaborate Compile
|
||||
// test failure.
|
||||
|
||||
func TestDecideMode_NilRuleIsDisabled(t *testing.T) {
|
||||
got := decideMode(nil, s3lifecycle.ActionKindExpirationDays, 0, 0)
|
||||
assert.Equal(t, ModeDisabled, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_DisabledStatusIsDisabled(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{Status: s3lifecycle.StatusDisabled, ExpirationDays: 30}
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 0, 0)
|
||||
assert.Equal(t, ModeDisabled, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_ExpirationDateIsScanAtDate(t *testing.T) {
|
||||
// ExpirationDate is a one-shot wall-clock trigger; no event log
|
||||
// involvement, so retention gates don't apply.
|
||||
rule := &s3lifecycle.Rule{
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDate: time.Now().Add(24 * time.Hour),
|
||||
}
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDate, 0, 0)
|
||||
assert.Equal(t, ModeScanAtDate, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_UnboundedRetentionIsEventDriven(t *testing.T) {
|
||||
// metaLogRetention=0 means unbounded; the retention gate doesn't
|
||||
// trip, so any horizon falls back to event-driven.
|
||||
rule := &s3lifecycle.Rule{
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 365,
|
||||
}
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 0, time.Hour)
|
||||
assert.Equal(t, ModeEventDriven, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_HorizonWithinRetentionIsEventDriven(t *testing.T) {
|
||||
// retention=30d, horizon=7d, lookback=1m → 7d+1m < 30d → no gate.
|
||||
rule := &s3lifecycle.Rule{
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 30*24*time.Hour, time.Minute)
|
||||
assert.Equal(t, ModeEventDriven, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_HorizonExceedsRetentionIsScanOnly(t *testing.T) {
|
||||
// retention=7d, horizon=30d → can't drive from event log alone, so
|
||||
// the action is promoted to scan_only and only fires from the
|
||||
// bootstrap walk.
|
||||
rule := &s3lifecycle.Rule{
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 7*24*time.Hour, time.Minute)
|
||||
assert.Equal(t, ModeScanOnly, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_LookbackPushesAcrossThreshold(t *testing.T) {
|
||||
// retention=7d, horizon=7d - the bare horizon fits, but adding the
|
||||
// bootstrapLookbackMin must push it past retention so the gate
|
||||
// trips. Pins that lookback is added to horizon (not retention).
|
||||
rule := &s3lifecycle.Rule{
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
}
|
||||
retention := 7 * 24 * time.Hour
|
||||
// horizon already ~= retention; even a tiny lookback should trip.
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, retention, 5*time.Minute)
|
||||
assert.Equal(t, ModeScanOnly, got)
|
||||
}
|
||||
|
||||
func TestDecideMode_ZeroHorizonNeverGates(t *testing.T) {
|
||||
// EventLogHorizon returns 0 for kinds whose rule fields aren't set
|
||||
// (e.g. an EXPIRATION_DAYS kind on a rule with ExpirationDays=0).
|
||||
// A zero horizon must skip the gate so the action falls through to
|
||||
// event-driven rather than incorrectly promote to scan_only.
|
||||
rule := &s3lifecycle.Rule{
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
// ExpirationDays unset -> EventLogHorizon returns 0
|
||||
}
|
||||
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, time.Hour, time.Minute)
|
||||
assert.Equal(t, ModeEventDriven, got)
|
||||
}
|
||||
|
||||
func TestRuleMode_StringRendersDocumentedNames(t *testing.T) {
|
||||
// Operators read these via metrics labels and admin UI; pin the
|
||||
// exact strings so a rename can't break dashboards.
|
||||
cases := []struct {
|
||||
mode RuleMode
|
||||
want string
|
||||
}{
|
||||
{ModeUnspecified, "unspecified"},
|
||||
{ModeEventDriven, "event_driven"},
|
||||
{ModeScanAtDate, "scan_at_date"},
|
||||
{ModeScanOnly, "scan_only"},
|
||||
{ModeDisabled, "disabled"},
|
||||
{ModePendingBootstrap, "pending_bootstrap"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.want, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, c.mode.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleMode_StringFallsToUnspecifiedForUnknown(t *testing.T) {
|
||||
// A bogus enum value (e.g., a future RuleMode added without a
|
||||
// String() update) must render as "unspecified" rather than empty
|
||||
// or panic.
|
||||
bogus := RuleMode(999)
|
||||
assert.Equal(t, "unspecified", bogus.String())
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package lifecycletest
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
)
|
||||
|
||||
// EventOption mutates a reader.Event during construction. Options compose
|
||||
// in order — later options override earlier ones if they touch the same
|
||||
// field, which lets a default+override pattern work without surprises.
|
||||
type EventOption func(*reader.Event)
|
||||
|
||||
// WithSize sets the Size on whichever entry the event populates (NewEntry
|
||||
// for Create / Update, OldEntry for Delete). Constructors that build
|
||||
// both entries apply the size to NewEntry.
|
||||
func WithSize(bytes int64) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
|
||||
e.NewEntry.Attributes.FileSize = uint64(bytes)
|
||||
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
|
||||
e.OldEntry.Attributes.FileSize = uint64(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithModTime sets Mtime/MtimeNs on the populated entry.
|
||||
func WithModTime(t time.Time) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
secs, nanos := t.Unix(), int32(t.Nanosecond())
|
||||
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
|
||||
e.NewEntry.Attributes.Mtime = secs
|
||||
e.NewEntry.Attributes.MtimeNs = nanos
|
||||
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
|
||||
e.OldEntry.Attributes.Mtime = secs
|
||||
e.OldEntry.Attributes.MtimeNs = nanos
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithTtlSec sets the TTL on the populated entry. Used by tests that
|
||||
// exercise the lifecycle metadata-only delete path (TtlSec > 0 means
|
||||
// the volume reclaims chunks naturally).
|
||||
func WithTtlSec(ttl int32) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
|
||||
e.NewEntry.Attributes.TtlSec = ttl
|
||||
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
|
||||
e.OldEntry.Attributes.TtlSec = ttl
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithVersionID stamps Seaweed-X-Amz-Version-Id on the populated entry's
|
||||
// Extended map. Used by versioning-aware router and dispatcher tests.
|
||||
func WithVersionID(versionID string) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
var entry *filer_pb.Entry
|
||||
if e.NewEntry != nil {
|
||||
entry = e.NewEntry
|
||||
} else if e.OldEntry != nil {
|
||||
entry = e.OldEntry
|
||||
}
|
||||
if entry == nil {
|
||||
return
|
||||
}
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = map[string][]byte{}
|
||||
}
|
||||
entry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionID)
|
||||
}
|
||||
}
|
||||
|
||||
// WithExtended sets an arbitrary Extended key/value on the populated entry.
|
||||
func WithExtended(key string, value []byte) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
var entry *filer_pb.Entry
|
||||
if e.NewEntry != nil {
|
||||
entry = e.NewEntry
|
||||
} else if e.OldEntry != nil {
|
||||
entry = e.OldEntry
|
||||
}
|
||||
if entry == nil {
|
||||
return
|
||||
}
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = map[string][]byte{}
|
||||
}
|
||||
entry.Extended[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
// WithChunks attaches FileChunks to the populated entry. Identity-CAS in
|
||||
// LifecycleDelete uses the head chunk's FID, so tests that exercise CAS
|
||||
// drift need at least one chunk. For Update events the chunks land on
|
||||
// NewEntry; use WithOldChunks to target the pre-update state.
|
||||
func WithChunks(chunks ...*filer_pb.FileChunk) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
if e.NewEntry != nil {
|
||||
e.NewEntry.Chunks = append(e.NewEntry.Chunks, chunks...)
|
||||
} else if e.OldEntry != nil {
|
||||
e.OldEntry.Chunks = append(e.OldEntry.Chunks, chunks...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithOldSize sets FileSize on OldEntry specifically. Use on Update
|
||||
// events to configure the pre-update size (the WithSize default lands
|
||||
// on NewEntry when both are populated).
|
||||
func WithOldSize(bytes int64) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
if e.OldEntry != nil && e.OldEntry.Attributes != nil {
|
||||
e.OldEntry.Attributes.FileSize = uint64(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithOldChunks attaches FileChunks to OldEntry specifically. Use on
|
||||
// Update events to configure the pre-update chunk list (WithChunks
|
||||
// targets NewEntry when both are populated).
|
||||
func WithOldChunks(chunks ...*filer_pb.FileChunk) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
if e.OldEntry != nil {
|
||||
e.OldEntry.Chunks = append(e.OldEntry.Chunks, chunks...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithOldModTime sets Mtime/MtimeNs on OldEntry specifically. Update
|
||||
// events whose pre-update mtime should differ from the event timestamp
|
||||
// use this to override the default.
|
||||
func WithOldModTime(t time.Time) EventOption {
|
||||
return func(e *reader.Event) {
|
||||
if e.OldEntry != nil && e.OldEntry.Attributes != nil {
|
||||
e.OldEntry.Attributes.Mtime = t.Unix()
|
||||
e.OldEntry.Attributes.MtimeNs = int32(t.Nanosecond())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WithBootstrapVersion attaches a BootstrapVersion to the event.
|
||||
// Bootstrap-walk events use this to carry per-version state the live
|
||||
// meta-log doesn't see.
|
||||
func WithBootstrapVersion(bv *reader.BootstrapVersion) EventOption {
|
||||
return func(e *reader.Event) { e.BootstrapVersion = bv }
|
||||
}
|
||||
|
||||
// WithShardID overrides the computed ShardID. Most tests should leave
|
||||
// it as the s3lifecycle.ShardID default to mirror production routing.
|
||||
func WithShardID(shard int) EventOption {
|
||||
return func(e *reader.Event) { e.ShardID = shard }
|
||||
}
|
||||
|
||||
// NewCreate builds a Create event (NewEntry populated, OldEntry nil) at
|
||||
// the given timestamp. Bucket and key are required; everything else is
|
||||
// derived (Mtime defaults to ts, FileSize defaults to 0). Apply options
|
||||
// to override.
|
||||
func NewCreate(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
|
||||
e := &reader.Event{
|
||||
TsNs: ts.UnixNano(),
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
ShardID: s3lifecycle.ShardID(bucket, key),
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: leafOf(key),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: ts.Unix(),
|
||||
MtimeNs: int32(ts.Nanosecond()),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(e)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// NewDelete builds a Delete event (OldEntry populated, NewEntry nil).
|
||||
// Tests usually pass the entry the prior Create produced as a snapshot
|
||||
// of pre-delete state; this helper builds a minimal stand-in.
|
||||
func NewDelete(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
|
||||
e := &reader.Event{
|
||||
TsNs: ts.UnixNano(),
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
ShardID: s3lifecycle.ShardID(bucket, key),
|
||||
OldEntry: &filer_pb.Entry{
|
||||
Name: leafOf(key),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: ts.Unix(),
|
||||
MtimeNs: int32(ts.Nanosecond()),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(e)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// NewUpdate builds an Update event (both OldEntry and NewEntry populated).
|
||||
// Same defaults as NewCreate; options apply to NewEntry per the rules in
|
||||
// each option's doc.
|
||||
func NewUpdate(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
|
||||
e := &reader.Event{
|
||||
TsNs: ts.UnixNano(),
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
ShardID: s3lifecycle.ShardID(bucket, key),
|
||||
OldEntry: &filer_pb.Entry{
|
||||
Name: leafOf(key),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: ts.Unix(),
|
||||
MtimeNs: int32(ts.Nanosecond()),
|
||||
},
|
||||
},
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: leafOf(key),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: ts.Unix(),
|
||||
MtimeNs: int32(ts.Nanosecond()),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(e)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// MetaLogClock produces monotonically increasing timestamps for fixture
|
||||
// generation. Each call to Next advances by Step (default 1s) so tests
|
||||
// don't have to thread a counter through every helper invocation. Safe
|
||||
// for concurrent use.
|
||||
type MetaLogClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
step time.Duration
|
||||
}
|
||||
|
||||
// NewMetaLogClock returns a clock that ticks forward Step on every Next
|
||||
// call. Step defaults to 1s when zero.
|
||||
func NewMetaLogClock(start time.Time, step time.Duration) *MetaLogClock {
|
||||
if step <= 0 {
|
||||
step = time.Second
|
||||
}
|
||||
return &MetaLogClock{now: start, step: step}
|
||||
}
|
||||
|
||||
// Next returns the current timestamp and advances by Step.
|
||||
func (c *MetaLogClock) Next() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
t := c.now
|
||||
c.now = c.now.Add(c.step)
|
||||
return t
|
||||
}
|
||||
|
||||
// Peek returns what Next() would return without advancing.
|
||||
func (c *MetaLogClock) Peek() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
|
||||
// leafOf returns the basename of a slash-separated key. Filer entries
|
||||
// store only the leaf name; tests that mirror production layout need
|
||||
// the same shape. Trailing slashes are stripped first so directory-key
|
||||
// fixtures (e.g. "folder/") get the slashless leaf "folder" — the
|
||||
// production directory-marker write path stores the name without the
|
||||
// trailing slash.
|
||||
func leafOf(key string) string {
|
||||
for len(key) > 0 && key[len(key)-1] == '/' {
|
||||
key = key[:len(key)-1]
|
||||
}
|
||||
for i := len(key) - 1; i >= 0; i-- {
|
||||
if key[i] == '/' {
|
||||
return key[i+1:]
|
||||
}
|
||||
}
|
||||
return key
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package lifecycletest
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewCreate_PopulatesNewEntryOnly(t *testing.T) {
|
||||
t0 := time.Unix(1700000000, 123)
|
||||
e := NewCreate("bk", "obj.txt", t0)
|
||||
require.NotNil(t, e.NewEntry)
|
||||
assert.Nil(t, e.OldEntry)
|
||||
assert.True(t, e.IsCreate())
|
||||
assert.Equal(t, t0.UnixNano(), e.TsNs)
|
||||
assert.Equal(t, "bk", e.Bucket)
|
||||
assert.Equal(t, "obj.txt", e.Key)
|
||||
assert.Equal(t, "obj.txt", e.NewEntry.Name)
|
||||
// Mtime defaults to the event timestamp; tests that don't care can
|
||||
// rely on this rather than threading time through every call.
|
||||
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
|
||||
assert.Equal(t, int32(t0.Nanosecond()), e.NewEntry.Attributes.MtimeNs)
|
||||
}
|
||||
|
||||
func TestNewDelete_PopulatesOldEntryOnly(t *testing.T) {
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
e := NewDelete("bk", "obj.txt", t0)
|
||||
require.NotNil(t, e.OldEntry)
|
||||
assert.Nil(t, e.NewEntry)
|
||||
assert.True(t, e.IsDelete())
|
||||
assert.Equal(t, "obj.txt", e.OldEntry.Name)
|
||||
}
|
||||
|
||||
func TestNewUpdate_PopulatesBothEntries(t *testing.T) {
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
e := NewUpdate("bk", "obj.txt", t0)
|
||||
require.NotNil(t, e.OldEntry)
|
||||
require.NotNil(t, e.NewEntry)
|
||||
assert.False(t, e.IsCreate())
|
||||
assert.False(t, e.IsDelete())
|
||||
// OldEntry's Mtime defaults to the event ts so its mirror of pre-
|
||||
// update state reflects the same wall-clock origin as NewEntry —
|
||||
// a downstream router that compares mtimes won't see a synthetic
|
||||
// 1970 epoch.
|
||||
assert.Equal(t, t0.Unix(), e.OldEntry.Attributes.Mtime)
|
||||
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
|
||||
}
|
||||
|
||||
func TestNewCreate_NestedKeyUsesLeafName(t *testing.T) {
|
||||
// Filer entries store only the leaf name; mirroring that in the
|
||||
// fixture keeps router/dispatcher tests realistic.
|
||||
e := NewCreate("bk", "a/b/c.txt", time.Unix(0, 0))
|
||||
assert.Equal(t, "c.txt", e.NewEntry.Name)
|
||||
}
|
||||
|
||||
func TestNewCreate_DirectoryKeyUsesSlashlessLeaf(t *testing.T) {
|
||||
// Directory-marker objects (S3 keys ending in "/") store the leaf
|
||||
// name without the trailing slash on the filer side. A pre-fix
|
||||
// regression returned "" here.
|
||||
e := NewCreate("bk", "folder/", time.Unix(0, 0))
|
||||
assert.Equal(t, "folder", e.NewEntry.Name)
|
||||
|
||||
// Nested directory key strips both the trailing slash AND the
|
||||
// parent prefix.
|
||||
e2 := NewCreate("bk", "a/b/folder/", time.Unix(0, 0))
|
||||
assert.Equal(t, "folder", e2.NewEntry.Name)
|
||||
|
||||
// Multiple trailing slashes collapse.
|
||||
e3 := NewCreate("bk", "folder///", time.Unix(0, 0))
|
||||
assert.Equal(t, "folder", e3.NewEntry.Name)
|
||||
}
|
||||
|
||||
func TestNewCreate_ShardIDDerivedFromKey(t *testing.T) {
|
||||
// ShardID matches s3lifecycle.ShardID(bucket, key) so the event
|
||||
// routes through the same shard the production reader would
|
||||
// classify it under.
|
||||
e := NewCreate("bk", "obj.txt", time.Unix(0, 0))
|
||||
assert.Equal(t, s3lifecycle.ShardID("bk", "obj.txt"), e.ShardID)
|
||||
}
|
||||
|
||||
func TestEventOption_WithSize(t *testing.T) {
|
||||
e := NewCreate("bk", "k", time.Unix(0, 0), WithSize(4096))
|
||||
assert.Equal(t, uint64(4096), e.NewEntry.Attributes.FileSize)
|
||||
}
|
||||
|
||||
func TestEventOption_WithSizeAppliesToOldEntryOnDelete(t *testing.T) {
|
||||
// Delete events have OldEntry only; WithSize must apply there.
|
||||
e := NewDelete("bk", "k", time.Unix(0, 0), WithSize(8192))
|
||||
assert.Equal(t, uint64(8192), e.OldEntry.Attributes.FileSize)
|
||||
}
|
||||
|
||||
func TestEventOption_WithModTimeOverridesDefault(t *testing.T) {
|
||||
// Default Mtime is event ts; explicit WithModTime overrides.
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
override := time.Unix(1700000123, 456)
|
||||
e := NewCreate("bk", "k", t0, WithModTime(override))
|
||||
assert.Equal(t, override.Unix(), e.NewEntry.Attributes.Mtime)
|
||||
assert.Equal(t, int32(override.Nanosecond()), e.NewEntry.Attributes.MtimeNs)
|
||||
}
|
||||
|
||||
func TestEventOption_WithTtlSec(t *testing.T) {
|
||||
// WithTtlSec drives the lifecycle metadata-only delete path; the
|
||||
// gate fires when the live entry's TtlSec > 0.
|
||||
e := NewCreate("bk", "k", time.Unix(0, 0), WithTtlSec(300))
|
||||
assert.Equal(t, int32(300), e.NewEntry.Attributes.TtlSec)
|
||||
}
|
||||
|
||||
func TestEventOption_WithVersionID(t *testing.T) {
|
||||
e := NewCreate("bk", "k", time.Unix(0, 0), WithVersionID("v_abc"))
|
||||
assert.Equal(t, []byte("v_abc"), e.NewEntry.Extended[s3_constants.ExtVersionIdKey])
|
||||
}
|
||||
|
||||
func TestEventOption_WithExtendedKeyValue(t *testing.T) {
|
||||
e := NewCreate("bk", "k", time.Unix(0, 0), WithExtended("Custom-Tag", []byte("v1")))
|
||||
assert.Equal(t, []byte("v1"), e.NewEntry.Extended["Custom-Tag"])
|
||||
}
|
||||
|
||||
func TestEventOption_WithChunks(t *testing.T) {
|
||||
c1 := &filer_pb.FileChunk{FileId: "1,abc"}
|
||||
c2 := &filer_pb.FileChunk{FileId: "1,def"}
|
||||
e := NewCreate("bk", "k", time.Unix(0, 0), WithChunks(c1, c2))
|
||||
require.Len(t, e.NewEntry.Chunks, 2)
|
||||
assert.Equal(t, "1,abc", e.NewEntry.Chunks[0].FileId)
|
||||
assert.Equal(t, "1,def", e.NewEntry.Chunks[1].FileId)
|
||||
}
|
||||
|
||||
func TestEventOption_WithShardIDOverrides(t *testing.T) {
|
||||
e := NewCreate("bk", "obj.txt", time.Unix(0, 0), WithShardID(7))
|
||||
assert.Equal(t, 7, e.ShardID)
|
||||
}
|
||||
|
||||
func TestEventOption_WithOldSizeTargetsOldEntryOnUpdate(t *testing.T) {
|
||||
// On Update events, WithSize lands on NewEntry; WithOldSize lets
|
||||
// the caller configure pre-update state independently. Both options
|
||||
// in a single call should produce distinct sizes on the two entries.
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
e := NewUpdate("bk", "k", t0, WithSize(200), WithOldSize(100))
|
||||
assert.Equal(t, uint64(200), e.NewEntry.Attributes.FileSize, "WithSize lands on NewEntry")
|
||||
assert.Equal(t, uint64(100), e.OldEntry.Attributes.FileSize, "WithOldSize lands on OldEntry")
|
||||
}
|
||||
|
||||
func TestEventOption_WithOldChunksTargetsOldEntryOnUpdate(t *testing.T) {
|
||||
newChunk := &filer_pb.FileChunk{FileId: "1,new"}
|
||||
oldChunk := &filer_pb.FileChunk{FileId: "1,old"}
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
e := NewUpdate("bk", "k", t0, WithChunks(newChunk), WithOldChunks(oldChunk))
|
||||
require.Len(t, e.NewEntry.Chunks, 1)
|
||||
require.Len(t, e.OldEntry.Chunks, 1)
|
||||
assert.Equal(t, "1,new", e.NewEntry.Chunks[0].FileId)
|
||||
assert.Equal(t, "1,old", e.OldEntry.Chunks[0].FileId)
|
||||
}
|
||||
|
||||
func TestEventOption_WithOldModTimeTargetsOldEntryOnUpdate(t *testing.T) {
|
||||
// Pre-update mtime can lag the event timestamp; WithOldModTime lets
|
||||
// a router test pin the noncurrent-clock origin.
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
older := time.Unix(1699000000, 500)
|
||||
e := NewUpdate("bk", "k", t0, WithOldModTime(older))
|
||||
assert.Equal(t, older.Unix(), e.OldEntry.Attributes.Mtime)
|
||||
assert.Equal(t, int32(500), e.OldEntry.Attributes.MtimeNs)
|
||||
// NewEntry's mtime stays at the default ts.
|
||||
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
|
||||
}
|
||||
|
||||
func TestEventOption_WithOldOptionsAreNoOpsOnCreate(t *testing.T) {
|
||||
// Create events have no OldEntry; the WithOld* options must not
|
||||
// panic and must not leak fields into NewEntry.
|
||||
t0 := time.Unix(1700000000, 0)
|
||||
e := NewCreate("bk", "k", t0,
|
||||
WithOldSize(999),
|
||||
WithOldChunks(&filer_pb.FileChunk{FileId: "phantom"}),
|
||||
WithOldModTime(time.Unix(1, 0)),
|
||||
)
|
||||
assert.Nil(t, e.OldEntry)
|
||||
assert.Equal(t, uint64(0), e.NewEntry.Attributes.FileSize, "WithOldSize must not bleed to NewEntry")
|
||||
assert.Empty(t, e.NewEntry.Chunks, "WithOldChunks must not bleed to NewEntry")
|
||||
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime, "WithOldModTime must not bleed to NewEntry")
|
||||
}
|
||||
|
||||
func TestEventOption_LaterOverridesEarlier(t *testing.T) {
|
||||
// Apply order matters: later options win on the same field. Pins
|
||||
// the documented ordering so tests can compose default+override
|
||||
// patterns without surprises.
|
||||
e := NewCreate("bk", "k", time.Unix(0, 0),
|
||||
WithSize(100),
|
||||
WithSize(200),
|
||||
)
|
||||
assert.Equal(t, uint64(200), e.NewEntry.Attributes.FileSize)
|
||||
}
|
||||
|
||||
func TestMetaLogClock_DefaultStepIsOneSecond(t *testing.T) {
|
||||
c := NewMetaLogClock(time.Unix(1000, 0), 0)
|
||||
t1 := c.Next()
|
||||
t2 := c.Next()
|
||||
assert.Equal(t, time.Second, t2.Sub(t1))
|
||||
}
|
||||
|
||||
func TestMetaLogClock_CustomStep(t *testing.T) {
|
||||
c := NewMetaLogClock(time.Unix(1000, 0), 250*time.Millisecond)
|
||||
t1 := c.Next()
|
||||
t2 := c.Next()
|
||||
assert.Equal(t, 250*time.Millisecond, t2.Sub(t1))
|
||||
}
|
||||
|
||||
func TestMetaLogClock_PeekDoesNotAdvance(t *testing.T) {
|
||||
c := NewMetaLogClock(time.Unix(1000, 0), time.Second)
|
||||
first := c.Peek()
|
||||
again := c.Peek()
|
||||
assert.True(t, first.Equal(again), "Peek must not advance the clock")
|
||||
advanced := c.Next()
|
||||
assert.True(t, first.Equal(advanced), "Next returns what Peek returned")
|
||||
}
|
||||
|
||||
func TestMetaLogClock_ConcurrentNextNoRace(t *testing.T) {
|
||||
// Tests that produce events from many goroutines (e.g. fan-out
|
||||
// fixtures) need the clock to serialize without deadlock or
|
||||
// duplicate timestamps. -race catches a regression that drops
|
||||
// the lock.
|
||||
c := NewMetaLogClock(time.Unix(0, 0), time.Microsecond)
|
||||
const N = 64
|
||||
seen := sync.Map{}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(N)
|
||||
for i := 0; i < N; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
seen.Store(c.Next(), struct{}{})
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
count := 0
|
||||
seen.Range(func(_, _ any) bool { count++; return true })
|
||||
assert.Equal(t, N, count, "every Next must produce a unique timestamp")
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Package lifecycletest provides reusable test doubles for the lifecycle
|
||||
// worker pipeline. The pieces here let component-level tests stand up the
|
||||
// gRPC boundary the worker dials at runtime without pulling in a real
|
||||
// S3ApiServer or filer.
|
||||
package lifecycletest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Outcome is what the fake returns for a single LifecycleDelete call.
|
||||
// Code is required; Reason is echoed verbatim into LifecycleDeleteResponse.
|
||||
type Outcome struct {
|
||||
Code s3_lifecycle_pb.LifecycleDeleteOutcome
|
||||
Reason string
|
||||
}
|
||||
|
||||
// Done, NoopResolved, RetryLater, Blocked, SkippedObjectLock are
|
||||
// constructors for the common outcomes; tests can also build Outcome
|
||||
// values directly when they need a specific Reason.
|
||||
func Done() Outcome {
|
||||
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}
|
||||
}
|
||||
func NoopResolved(reason string) Outcome {
|
||||
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED, Reason: reason}
|
||||
}
|
||||
func RetryLater(reason string) Outcome {
|
||||
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, Reason: reason}
|
||||
}
|
||||
func Blocked(reason string) Outcome {
|
||||
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, Reason: reason}
|
||||
}
|
||||
func SkippedObjectLock(reason string) Outcome {
|
||||
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK, Reason: reason}
|
||||
}
|
||||
|
||||
// FakeLifecycleServer implements s3_lifecycle_pb.SeaweedS3LifecycleInternalServer.
|
||||
// It returns per-key queued outcomes (FIFO) and falls back to Default when a
|
||||
// key has no queued entry. Every received request is recorded; tests assert
|
||||
// against Recorded() in arrival order.
|
||||
//
|
||||
// A non-nil Err short-circuits everything — LifecycleDelete returns (nil, Err)
|
||||
// immediately, before the per-key lookup or the request recording. Use it to
|
||||
// simulate transport failures.
|
||||
//
|
||||
// All methods are safe for concurrent use. Outcomes/Default may be set at
|
||||
// construction or via Queue/SetDefault between calls; mid-call mutation is
|
||||
// supported but ordering across that boundary is undefined.
|
||||
type FakeLifecycleServer struct {
|
||||
s3_lifecycle_pb.UnimplementedSeaweedS3LifecycleInternalServer
|
||||
|
||||
mu sync.Mutex
|
||||
queues map[requestKey][]Outcome
|
||||
def Outcome
|
||||
err error
|
||||
received []*s3_lifecycle_pb.LifecycleDeleteRequest
|
||||
}
|
||||
|
||||
// requestKey is the map key for queues. A struct rather than a delimited
|
||||
// string so bucket/object/versionId values containing "/" or "@" can't
|
||||
// collide.
|
||||
type requestKey struct {
|
||||
bucket, objectPath, versionId string
|
||||
}
|
||||
|
||||
// NewFakeLifecycleServer returns a server whose Default outcome is DONE.
|
||||
// Most tests want a different default; call SetDefault to change it.
|
||||
func NewFakeLifecycleServer() *FakeLifecycleServer {
|
||||
return &FakeLifecycleServer{
|
||||
queues: map[requestKey][]Outcome{},
|
||||
def: Done(),
|
||||
}
|
||||
}
|
||||
|
||||
// Queue appends an outcome to the FIFO for (bucket, objectPath, versionId).
|
||||
// Subsequent calls matching the same key return outcomes in the order they
|
||||
// were queued; once the queue is drained, Default applies.
|
||||
func (f *FakeLifecycleServer) Queue(bucket, objectPath, versionId string, outcome Outcome) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
k := key(bucket, objectPath, versionId)
|
||||
f.queues[k] = append(f.queues[k], outcome)
|
||||
}
|
||||
|
||||
// SetDefault sets the outcome returned when no per-key queue entry remains.
|
||||
func (f *FakeLifecycleServer) SetDefault(o Outcome) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.def = o
|
||||
}
|
||||
|
||||
// SetError makes LifecycleDelete return (nil, err) on every call until
|
||||
// SetError(nil) clears it. The request is not recorded while Err is set —
|
||||
// transport-error tests should rely on the worker's own bookkeeping.
|
||||
func (f *FakeLifecycleServer) SetError(err error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.err = err
|
||||
}
|
||||
|
||||
// Recorded returns a deep-copied snapshot of every request the server has
|
||||
// received (excluding calls that returned a transport error). Both the
|
||||
// slice and each element are independent of the fake's internal state, so
|
||||
// callers can mutate freely without affecting later Recorded() snapshots.
|
||||
func (f *FakeLifecycleServer) Recorded() []*s3_lifecycle_pb.LifecycleDeleteRequest {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
out := make([]*s3_lifecycle_pb.LifecycleDeleteRequest, len(f.received))
|
||||
for i, r := range f.received {
|
||||
out[i] = cloneRequest(r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LifecycleDelete is the gRPC handler. It honors Err first, then dequeues
|
||||
// the per-key outcome, falling back to Default.
|
||||
func (f *FakeLifecycleServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
|
||||
f.mu.Lock()
|
||||
if f.err != nil {
|
||||
err := f.err
|
||||
f.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
// Record a deep copy so a caller mutating a Recorded() entry can't
|
||||
// reach back into the fake's bookkeeping (and so subsequent calls'
|
||||
// view of "what arrived" stays stable across assertions).
|
||||
f.received = append(f.received, cloneRequest(req))
|
||||
if req == nil {
|
||||
out := f.def
|
||||
f.mu.Unlock()
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out.Code, Reason: out.Reason}, nil
|
||||
}
|
||||
k := key(req.Bucket, req.ObjectPath, req.VersionId)
|
||||
q := f.queues[k]
|
||||
var out Outcome
|
||||
if len(q) > 0 {
|
||||
out = q[0]
|
||||
f.queues[k] = q[1:]
|
||||
} else {
|
||||
out = f.def
|
||||
}
|
||||
f.mu.Unlock()
|
||||
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out.Code, Reason: out.Reason}, nil
|
||||
}
|
||||
|
||||
func key(bucket, objectPath, versionId string) requestKey {
|
||||
return requestKey{bucket: bucket, objectPath: objectPath, versionId: versionId}
|
||||
}
|
||||
|
||||
func cloneRequest(req *s3_lifecycle_pb.LifecycleDeleteRequest) *s3_lifecycle_pb.LifecycleDeleteRequest {
|
||||
if req == nil {
|
||||
return nil
|
||||
}
|
||||
return proto.Clone(req).(*s3_lifecycle_pb.LifecycleDeleteRequest)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package lifecycletest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFake_DefaultIsDoneOutOfTheBox(t *testing.T) {
|
||||
// A test that doesn't queue anything should still get a non-error
|
||||
// response so it can exercise the worker's happy path.
|
||||
f := NewFakeLifecycleServer()
|
||||
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "b",
|
||||
ObjectPath: "k",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, resp.Outcome)
|
||||
assert.Equal(t, "", resp.Reason)
|
||||
}
|
||||
|
||||
func TestFake_QueuedOutcomesPopFIFO(t *testing.T) {
|
||||
// Per-key queue is FIFO and one-shot per entry; after the queue
|
||||
// drains, Default kicks in.
|
||||
f := NewFakeLifecycleServer()
|
||||
f.SetDefault(NoopResolved("nothing more queued"))
|
||||
f.Queue("b", "k", "", RetryLater("first"))
|
||||
f.Queue("b", "k", "", Blocked("second"))
|
||||
|
||||
got := []s3_lifecycle_pb.LifecycleDeleteOutcome{}
|
||||
reasons := []string{}
|
||||
for i := 0; i < 3; i++ {
|
||||
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "b", ObjectPath: "k",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
got = append(got, resp.Outcome)
|
||||
reasons = append(reasons, resp.Reason)
|
||||
}
|
||||
assert.Equal(t, []s3_lifecycle_pb.LifecycleDeleteOutcome{
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED,
|
||||
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
|
||||
}, got)
|
||||
assert.Equal(t, []string{"first", "second", "nothing more queued"}, reasons)
|
||||
}
|
||||
|
||||
func TestFake_QueuesIsolatedByKey(t *testing.T) {
|
||||
// Queues are partitioned by (bucket, objectPath, versionId); a queued
|
||||
// outcome for one key must not bleed into another's lookup.
|
||||
f := NewFakeLifecycleServer()
|
||||
f.Queue("b", "a", "", Blocked("a-only"))
|
||||
f.Queue("b", "b", "", RetryLater("b-only"))
|
||||
|
||||
respA, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "a"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, respA.Outcome)
|
||||
|
||||
respB, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "b"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, respB.Outcome)
|
||||
}
|
||||
|
||||
func TestFake_VersionIDPartOfKey(t *testing.T) {
|
||||
// Two requests for the same bucket/objectPath but different
|
||||
// versionIds must address different queues.
|
||||
f := NewFakeLifecycleServer()
|
||||
f.Queue("b", "k", "v1", SkippedObjectLock("v1-locked"))
|
||||
f.Queue("b", "k", "v2", Done())
|
||||
|
||||
respV1, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v1"})
|
||||
require.NoError(t, err)
|
||||
respV2, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v2"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK, respV1.Outcome)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, respV2.Outcome)
|
||||
}
|
||||
|
||||
func TestFake_KeyComponentsWithDelimitersDoNotCollide(t *testing.T) {
|
||||
// String-concatenation keys would have made these two requests
|
||||
// indistinguishable. The struct key keeps them separate.
|
||||
f := NewFakeLifecycleServer()
|
||||
f.Queue("b/k", "", "", Blocked("variant-a"))
|
||||
f.Queue("b", "k", "", Done())
|
||||
|
||||
respA, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b/k", ObjectPath: ""})
|
||||
require.NoError(t, err)
|
||||
respB, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, respA.Outcome)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, respB.Outcome)
|
||||
}
|
||||
|
||||
func TestFake_ErrShortCircuitsBeforeRecording(t *testing.T) {
|
||||
// Err makes LifecycleDelete return (nil, err) without recording the
|
||||
// request — transport-error tests rely on the worker's own
|
||||
// bookkeeping, not the fake's.
|
||||
f := NewFakeLifecycleServer()
|
||||
transportErr := errors.New("connection refused")
|
||||
f.SetError(transportErr)
|
||||
|
||||
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
|
||||
assert.Nil(t, resp)
|
||||
assert.ErrorIs(t, err, transportErr)
|
||||
assert.Empty(t, f.Recorded(), "transport-error calls must not be recorded")
|
||||
|
||||
// Clearing the error returns the server to normal behavior.
|
||||
f.SetError(nil)
|
||||
resp2, err2 := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
|
||||
require.NoError(t, err2)
|
||||
require.NotNil(t, resp2)
|
||||
assert.Len(t, f.Recorded(), 1)
|
||||
}
|
||||
|
||||
func TestFake_RecordsRequestsInOrder(t *testing.T) {
|
||||
// Recorded() preserves arrival order so tests can assert that
|
||||
// dispatch happened in the expected sequence.
|
||||
f := NewFakeLifecycleServer()
|
||||
for _, key := range []string{"k1", "k2", "k3"} {
|
||||
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
|
||||
Bucket: "b", ObjectPath: key,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
rec := f.Recorded()
|
||||
require.Len(t, rec, 3)
|
||||
assert.Equal(t, "k1", rec[0].ObjectPath)
|
||||
assert.Equal(t, "k2", rec[1].ObjectPath)
|
||||
assert.Equal(t, "k3", rec[2].ObjectPath)
|
||||
}
|
||||
|
||||
func TestFake_RecordedIsSnapshot(t *testing.T) {
|
||||
// Mutating the slice the caller got back must not bleed into the
|
||||
// fake's internal state — otherwise a flaky test could corrupt
|
||||
// bookkeeping for later assertions.
|
||||
f := NewFakeLifecycleServer()
|
||||
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
|
||||
require.NoError(t, err)
|
||||
|
||||
snap := f.Recorded()
|
||||
require.Len(t, snap, 1)
|
||||
snap[0] = nil
|
||||
again := f.Recorded()
|
||||
require.Len(t, again, 1)
|
||||
assert.NotNil(t, again[0], "internal record must survive caller-side mutation of the snapshot")
|
||||
}
|
||||
|
||||
func TestFake_RecordedRequestsAreDeepCopies(t *testing.T) {
|
||||
// A caller mutating fields on a Recorded() entry must not bleed
|
||||
// into a later Recorded() snapshot. We also confirm the original
|
||||
// request the caller passed in stays decoupled from internal state
|
||||
// — proto.Clone runs at record time, so the caller's pointer is
|
||||
// no longer the one the fake holds.
|
||||
f := NewFakeLifecycleServer()
|
||||
orig := &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v"}
|
||||
_, err := f.LifecycleDelete(context.Background(), orig)
|
||||
require.NoError(t, err)
|
||||
|
||||
snap := f.Recorded()
|
||||
require.Len(t, snap, 1)
|
||||
snap[0].Bucket = "mutated-by-caller"
|
||||
snap[0].ObjectPath = "also-mutated"
|
||||
|
||||
again := f.Recorded()
|
||||
require.Len(t, again, 1)
|
||||
assert.Equal(t, "b", again[0].Bucket, "field mutations on a snapshot must not bleed back")
|
||||
assert.Equal(t, "k", again[0].ObjectPath)
|
||||
assert.Equal(t, "v", again[0].VersionId)
|
||||
|
||||
// The caller's own pointer is independent of the fake's record.
|
||||
orig.Bucket = "caller-mutates-original"
|
||||
yetAgain := f.Recorded()
|
||||
assert.Equal(t, "b", yetAgain[0].Bucket, "caller mutating the input pointer must not bleed in either")
|
||||
}
|
||||
|
||||
func TestFake_NilRequestUsesDefault(t *testing.T) {
|
||||
// gRPC won't deliver a nil request in practice, but defensive code
|
||||
// in the fake should still produce a deterministic response so a
|
||||
// regressing client doesn't panic the test process.
|
||||
f := NewFakeLifecycleServer()
|
||||
f.SetDefault(Blocked("no request"))
|
||||
resp, err := f.LifecycleDelete(context.Background(), nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp)
|
||||
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, resp.Outcome)
|
||||
}
|
||||
|
||||
func TestFake_ConcurrentCallsSerializeWithoutDeadlock(t *testing.T) {
|
||||
// The dispatcher fans dispatch across many goroutines; the fake
|
||||
// must not livelock or drop records under concurrent load. Capture
|
||||
// each goroutine's err so a regression in concurrent paths surfaces
|
||||
// instead of being masked by length-only assertions.
|
||||
f := NewFakeLifecycleServer()
|
||||
const N = 64
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, N)
|
||||
wg.Add(N)
|
||||
for i := 0; i < N; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
|
||||
errCh <- err
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
for err := range errCh {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
assert.Len(t, f.Recorded(), N)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package reader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Layer 2 contracts the dispatcher pipeline relies on. These augment
|
||||
// reader_test.go (extract + dispatch) and cursor_test.go (Advance +
|
||||
// Freeze) by pinning the cursor composition surface that
|
||||
// dispatcher.Pipeline depends on for resume-point selection,
|
||||
// checkpoint persistence, and Run-time input validation.
|
||||
|
||||
func TestCursorMinTsNsWithFrozenKeysIncluded(t *testing.T) {
|
||||
// MinTsNs is the resume point Reader.Run feeds to SubscribeMetadata
|
||||
// when StartTsNs is zero. A freeze pins a key at its current TsNs;
|
||||
// the min must still see that pinned position so the subscription
|
||||
// doesn't rewind past it. Mixing frozen + non-frozen keys exercises
|
||||
// the path where the smallest position belongs to a frozen key.
|
||||
c := NewCursor()
|
||||
frozenKey := key("a", s3lifecycle.ActionKindExpirationDays)
|
||||
movingKey := key("b", s3lifecycle.ActionKindNoncurrentDays)
|
||||
otherKey := key("c", s3lifecycle.ActionKindAbortMPU)
|
||||
|
||||
c.Advance(frozenKey, 100)
|
||||
c.Advance(movingKey, 500)
|
||||
c.Advance(otherKey, 300)
|
||||
c.Freeze(frozenKey, 100)
|
||||
|
||||
// Frozen key holds at 100; Advance must not move it.
|
||||
c.Advance(frozenKey, 9_999)
|
||||
require.Equal(t, int64(100), c.Get(frozenKey))
|
||||
|
||||
// MinTsNs reflects the frozen key because it is still the smallest.
|
||||
assert.Equal(t, int64(100), c.MinTsNs())
|
||||
|
||||
// Non-frozen keys keep advancing; min stays anchored to the freeze.
|
||||
c.Advance(movingKey, 700)
|
||||
c.Advance(otherKey, 600)
|
||||
assert.Equal(t, int64(100), c.MinTsNs())
|
||||
}
|
||||
|
||||
func TestCursorSnapshotIsDeepCopy(t *testing.T) {
|
||||
// Snapshot is persisted via the persister; callers must be able to
|
||||
// hold the returned map without observing live cursor mutations,
|
||||
// and the cursor must not observe caller-side edits to the map.
|
||||
c := NewCursor()
|
||||
a := key("a", s3lifecycle.ActionKindExpirationDays)
|
||||
b := key("b", s3lifecycle.ActionKindNoncurrentDays)
|
||||
c.Advance(a, 100)
|
||||
c.Advance(b, 200)
|
||||
|
||||
snap := c.Snapshot()
|
||||
require.Equal(t, int64(100), snap[a])
|
||||
require.Equal(t, int64(200), snap[b])
|
||||
|
||||
// Mutating the returned map must not bleed into the cursor.
|
||||
snap[a] = 9_999
|
||||
delete(snap, b)
|
||||
snap[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
|
||||
assert.Equal(t, int64(100), c.Get(a), "cursor must be insulated from snapshot writes")
|
||||
assert.Equal(t, int64(200), c.Get(b), "cursor must retain key the caller deleted from snapshot")
|
||||
assert.Equal(t, int64(0), c.Get(key("z", s3lifecycle.ActionKindAbortMPU)), "cursor must not see keys added to snapshot")
|
||||
|
||||
// Mutating the cursor after Snapshot must not bleed into the map
|
||||
// the caller is still holding (e.g., between Snapshot and Save).
|
||||
snap2 := c.Snapshot()
|
||||
c.Advance(a, 1_000)
|
||||
c.Advance(key("d", s3lifecycle.ActionKindAbortMPU), 50)
|
||||
assert.Equal(t, int64(100), snap2[a], "snapshot must not see post-snapshot Advance")
|
||||
_, hasNew := snap2[key("d", s3lifecycle.ActionKindAbortMPU)]
|
||||
assert.False(t, hasNew, "snapshot must not see post-snapshot key insertions")
|
||||
}
|
||||
|
||||
func TestCursorRestoreReplacesNotMerges(t *testing.T) {
|
||||
// On startup the persister loads the last checkpoint and Restores
|
||||
// the cursor. A subsequent Restore (e.g., after a re-bootstrap)
|
||||
// must fully replace the in-memory map: keys present before but
|
||||
// absent in the new map must vanish, otherwise stale resume
|
||||
// points would survive across restores.
|
||||
c := NewCursor()
|
||||
a := key("a", s3lifecycle.ActionKindExpirationDays)
|
||||
b := key("b", s3lifecycle.ActionKindNoncurrentDays)
|
||||
cc := key("c", s3lifecycle.ActionKindAbortMPU)
|
||||
|
||||
c.Restore(map[s3lifecycle.ActionKey]int64{a: 100, b: 200, cc: 300})
|
||||
require.Equal(t, int64(100), c.Get(a))
|
||||
require.Equal(t, int64(200), c.Get(b))
|
||||
require.Equal(t, int64(300), c.Get(cc))
|
||||
|
||||
// Freeze a key before second Restore; Restore must clear frozen state
|
||||
// alongside the value map so a stale freeze doesn't survive a reload.
|
||||
c.Freeze(a, 100)
|
||||
require.True(t, c.IsFrozen(a))
|
||||
|
||||
// Second Restore drops keys b and c entirely; a is replaced.
|
||||
c.Restore(map[s3lifecycle.ActionKey]int64{a: 50})
|
||||
assert.Equal(t, int64(50), c.Get(a))
|
||||
assert.False(t, c.IsFrozen(a), "Restore must clear frozen state")
|
||||
assert.Equal(t, int64(0), c.Get(b), "key absent from second Restore must be removed")
|
||||
assert.Equal(t, int64(0), c.Get(cc), "key absent from second Restore must be removed")
|
||||
|
||||
// MinTsNs reflects only the surviving key.
|
||||
assert.Equal(t, int64(50), c.MinTsNs())
|
||||
|
||||
// Restoring an empty map clears all state.
|
||||
c.Restore(map[s3lifecycle.ActionKey]int64{})
|
||||
assert.Equal(t, int64(0), c.Get(a))
|
||||
assert.Equal(t, int64(0), c.MinTsNs())
|
||||
}
|
||||
|
||||
func TestReaderRunValidatesInputsBeforeSubscribing(t *testing.T) {
|
||||
// Run guards: out-of-range ShardID (no predicate), nil Events
|
||||
// channel, empty BucketsPath. Each error path must fire before any
|
||||
// client call, so a nil client suffices to drive the assertions.
|
||||
out := make(chan *Event, 1)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
reader *Reader
|
||||
wantSub string
|
||||
}{
|
||||
{
|
||||
name: "shard id below zero",
|
||||
reader: &Reader{ShardID: -1, BucketsPath: "/buckets", Events: out},
|
||||
wantSub: "shard_id",
|
||||
},
|
||||
{
|
||||
name: "shard id at or above ShardCount",
|
||||
reader: &Reader{ShardID: s3lifecycle.ShardCount, BucketsPath: "/buckets", Events: out},
|
||||
wantSub: "shard_id",
|
||||
},
|
||||
{
|
||||
name: "nil events channel",
|
||||
reader: &Reader{ShardID: 0, BucketsPath: "/buckets", Events: nil},
|
||||
wantSub: "nil Events",
|
||||
},
|
||||
{
|
||||
name: "empty buckets path",
|
||||
reader: &Reader{ShardID: 0, BucketsPath: "", Events: out},
|
||||
wantSub: "empty BucketsPath",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Bound the call so a regression that lets Run reach the
|
||||
// nil client's blocking subscribe surfaces as a test failure
|
||||
// instead of hanging the suite.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
err := tc.reader.Run(ctx, nil, "test", 0)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tc.wantSub)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package reader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// InMemoryPersister is the in-memory test double other lifecycle tests
|
||||
// rely on for cursor checkpointing. The deep-copy contract documented
|
||||
// on the Persister interface is what insulates each test's state from
|
||||
// the others — these tests pin every direction of that contract so a
|
||||
// regression here can't silently corrupt downstream tests.
|
||||
|
||||
func TestInMemoryPersister_LoadOnUnknownShardReturnsEmptyMap(t *testing.T) {
|
||||
// Contract: Load returns an empty map (not an error) when no prior
|
||||
// state exists. The dispatcher startup path relies on this so a
|
||||
// fresh worker doesn't have to special-case the "no checkpoint yet"
|
||||
// branch.
|
||||
p := NewInMemoryPersister()
|
||||
got, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, got)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_SaveLoadRoundTrip(t *testing.T) {
|
||||
p := NewInMemoryPersister()
|
||||
want := map[s3lifecycle.ActionKey]int64{
|
||||
key("a", s3lifecycle.ActionKindExpirationDays): 100,
|
||||
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
|
||||
}
|
||||
require.NoError(t, p.Save(context.Background(), 7, want))
|
||||
|
||||
got, err := p.Load(context.Background(), 7)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_SaveCopiesInput(t *testing.T) {
|
||||
// Caller mutating the map after Save must not bleed into stored
|
||||
// state — the next Load must return what was saved.
|
||||
p := NewInMemoryPersister()
|
||||
in := map[s3lifecycle.ActionKey]int64{
|
||||
key("a", s3lifecycle.ActionKindExpirationDays): 100,
|
||||
}
|
||||
require.NoError(t, p.Save(context.Background(), 0, in))
|
||||
|
||||
in[key("a", s3lifecycle.ActionKindExpirationDays)] = 9_999
|
||||
in[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
|
||||
delete(in, key("a", s3lifecycle.ActionKindExpirationDays))
|
||||
|
||||
got, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(100), got[key("a", s3lifecycle.ActionKindExpirationDays)],
|
||||
"caller-side mutation must not bleed into stored state")
|
||||
assert.NotContains(t, got, key("z", s3lifecycle.ActionKindAbortMPU),
|
||||
"caller-side insertion must not bleed into stored state")
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_LoadReturnsACopy(t *testing.T) {
|
||||
// Caller mutating the returned map must not bleed back; otherwise
|
||||
// a test reusing the persister across cases could see drift.
|
||||
p := NewInMemoryPersister()
|
||||
want := map[s3lifecycle.ActionKey]int64{
|
||||
key("a", s3lifecycle.ActionKindExpirationDays): 100,
|
||||
}
|
||||
require.NoError(t, p.Save(context.Background(), 0, want))
|
||||
|
||||
first, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
first[key("a", s3lifecycle.ActionKindExpirationDays)] = 9_999
|
||||
first[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
|
||||
|
||||
second, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(100), second[key("a", s3lifecycle.ActionKindExpirationDays)],
|
||||
"caller-side mutation of the first snapshot must not bleed back")
|
||||
assert.NotContains(t, second, key("z", s3lifecycle.ActionKindAbortMPU),
|
||||
"caller-side insertion into the first snapshot must not bleed back")
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_SaveReplacesNotMerges(t *testing.T) {
|
||||
// Documented contract: Save replaces prior state atomically. A
|
||||
// merge would silently keep stale resume points across restarts.
|
||||
p := NewInMemoryPersister()
|
||||
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
|
||||
key("a", s3lifecycle.ActionKindExpirationDays): 100,
|
||||
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
|
||||
}))
|
||||
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
|
||||
key("c", s3lifecycle.ActionKindAbortMPU): 300,
|
||||
}))
|
||||
|
||||
got, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[s3lifecycle.ActionKey]int64{
|
||||
key("c", s3lifecycle.ActionKindAbortMPU): 300,
|
||||
}, got, "second Save must replace prior state, not merge")
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_DifferentShardsIsolated(t *testing.T) {
|
||||
// State for shardID=1 must not leak into Load(shardID=2).
|
||||
p := NewInMemoryPersister()
|
||||
require.NoError(t, p.Save(context.Background(), 1, map[s3lifecycle.ActionKey]int64{
|
||||
key("a", s3lifecycle.ActionKindExpirationDays): 100,
|
||||
}))
|
||||
require.NoError(t, p.Save(context.Background(), 2, map[s3lifecycle.ActionKey]int64{
|
||||
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
|
||||
}))
|
||||
|
||||
got1, err := p.Load(context.Background(), 1)
|
||||
require.NoError(t, err)
|
||||
got2, err := p.Load(context.Background(), 2)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(100), got1[key("a", s3lifecycle.ActionKindExpirationDays)])
|
||||
assert.NotContains(t, got1, key("b", s3lifecycle.ActionKindNoncurrentDays))
|
||||
assert.Equal(t, int64(200), got2[key("b", s3lifecycle.ActionKindNoncurrentDays)])
|
||||
assert.NotContains(t, got2, key("a", s3lifecycle.ActionKindExpirationDays))
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_SaveEmptyMapClearsState(t *testing.T) {
|
||||
// An empty map is valid input; Save must accept it and a subsequent
|
||||
// Load must return an empty map (not the prior contents).
|
||||
p := NewInMemoryPersister()
|
||||
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
|
||||
key("a", s3lifecycle.ActionKindExpirationDays): 100,
|
||||
}))
|
||||
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{}))
|
||||
got, err := p.Load(context.Background(), 0)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestInMemoryPersister_ConcurrentSaveLoadDoesNotRace(t *testing.T) {
|
||||
// The dispatcher fans cursor reads/writes across many goroutines;
|
||||
// the persister must hold under load without livelocking or
|
||||
// data-racing (-race detector enforces that).
|
||||
p := NewInMemoryPersister()
|
||||
var wg sync.WaitGroup
|
||||
const N = 64
|
||||
wg.Add(N * 2)
|
||||
for i := 0; i < N; i++ {
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = p.Save(context.Background(), i%4, map[s3lifecycle.ActionKey]int64{
|
||||
key("k", s3lifecycle.ActionKindExpirationDays): int64(i),
|
||||
})
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = p.Load(context.Background(), i%4)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -13,14 +14,36 @@ import (
|
||||
)
|
||||
|
||||
// Event is one in-shard meta-log event delivered to the router.
|
||||
//
|
||||
// BootstrapVersion is set only by the bucket bootstrapper when it
|
||||
// expands a .versions/ directory; the meta-log path leaves it nil.
|
||||
// Carries pre-computed sibling state so the router can fire
|
||||
// NoncurrentDays / NewerNoncurrent without listing again.
|
||||
type Event struct {
|
||||
TsNs int64
|
||||
Bucket string
|
||||
Key string
|
||||
ShardID int
|
||||
OldEntry *filer_pb.Entry
|
||||
NewEntry *filer_pb.Entry
|
||||
NewParent string
|
||||
TsNs int64
|
||||
Bucket string
|
||||
Key string
|
||||
ShardID int
|
||||
OldEntry *filer_pb.Entry
|
||||
NewEntry *filer_pb.Entry
|
||||
NewParent string
|
||||
BootstrapVersion *BootstrapVersion
|
||||
}
|
||||
|
||||
// BootstrapVersion is the per-version state computed once per
|
||||
// .versions/<key>/ directory at bootstrap time. Key fields shape
|
||||
// EvaluateAction: IsLatest gates current vs. noncurrent rules,
|
||||
// NoncurrentIndex gates NewerNoncurrentVersions retention,
|
||||
// SuccessorModTime sets the noncurrent clock (when this version was
|
||||
// replaced).
|
||||
type BootstrapVersion struct {
|
||||
LogicalKey string
|
||||
VersionID string
|
||||
IsLatest bool
|
||||
IsDeleteMarker bool
|
||||
NumVersions int
|
||||
NoncurrentIndex int // 0 = newest noncurrent
|
||||
SuccessorModTime time.Time
|
||||
}
|
||||
|
||||
// IsDelete reports whether this event removes an entry.
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Direct coverage for the pure helpers in router.go that the larger
|
||||
// Route* tests exercise indirectly. Pinning each one separately catches
|
||||
// regressions before they manifest as a broader Route failure that's
|
||||
// harder to diagnose.
|
||||
|
||||
// ---------- successorModTimeFromContainer ----------
|
||||
|
||||
func TestSuccessorModTimeFromContainer_MissingExtReturnsZero(t *testing.T) {
|
||||
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{}).IsZero())
|
||||
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{},
|
||||
}).IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_EmptyValueReturnsZero(t *testing.T) {
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: nil},
|
||||
})
|
||||
assert.True(t, got.IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_NonNumericReturnsZero(t *testing.T) {
|
||||
// A malformed value is the writer's bug; the helper must not
|
||||
// propagate a parse error or surface a nonsense time.
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("not-a-number")},
|
||||
})
|
||||
assert.True(t, got.IsZero())
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_NonPositiveReturnsZero(t *testing.T) {
|
||||
// The container ext stores Unix seconds; <=0 means "not set" so
|
||||
// the helper falls back to zero rather than emitting 1970-01-01.
|
||||
for _, raw := range []string{"0", "-1", "-1000"} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte(raw)},
|
||||
})
|
||||
assert.True(t, got.IsZero(), "value %q must produce zero time", raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessorModTimeFromContainer_PositiveSecondsRoundTrip(t *testing.T) {
|
||||
got := successorModTimeFromContainer(&filer_pb.Entry{
|
||||
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("1700000000")},
|
||||
})
|
||||
assert.Equal(t, time.Unix(1700000000, 0).UTC(), got.UTC())
|
||||
}
|
||||
|
||||
// ---------- logicalKeyFromVersionPath ----------
|
||||
|
||||
func TestLogicalKeyFromVersionPath_ExtractsLogicalKey(t *testing.T) {
|
||||
logical, ok := logicalKeyFromVersionPath("a/b/c.versions/v_abc")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "a/b/c", logical)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsPathWithoutVersionsParent(t *testing.T) {
|
||||
// The parent of the version file must end with .versions; otherwise
|
||||
// it's not a version path.
|
||||
_, ok := logicalKeyFromVersionPath("a/b/c/v_abc")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsRootLevelPath(t *testing.T) {
|
||||
// LastIndex returning 0 means the only "/" is at index 0, which
|
||||
// would yield an empty parent — not a real version path.
|
||||
_, ok := logicalKeyFromVersionPath("/v_abc")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsNoSlashes(t *testing.T) {
|
||||
_, ok := logicalKeyFromVersionPath("v_abc")
|
||||
assert.False(t, ok)
|
||||
_, ok = logicalKeyFromVersionPath("")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestLogicalKeyFromVersionPath_RejectsBareVersionsContainer(t *testing.T) {
|
||||
// A path that's only the .versions container has no version-file
|
||||
// child to extract a logical key from.
|
||||
_, ok := logicalKeyFromVersionPath(s3_constants.VersionsFolder + "/v_x")
|
||||
assert.False(t, ok, "logical key cannot be empty after trim")
|
||||
}
|
||||
|
||||
// ---------- isVersionsContainerKey ----------
|
||||
|
||||
func TestIsVersionsContainerKey(t *testing.T) {
|
||||
cases := []struct {
|
||||
key string
|
||||
want bool
|
||||
}{
|
||||
{"obj" + s3_constants.VersionsFolder, true},
|
||||
{"a/b/obj" + s3_constants.VersionsFolder, true},
|
||||
// Bucket-root .versions is rejected explicitly: it has no
|
||||
// logical object key, so the router can't process it.
|
||||
{s3_constants.VersionsFolder, false},
|
||||
{"obj.versions/v_x", false}, // the version file inside, not the container
|
||||
{"obj", false},
|
||||
{"", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.key, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, isVersionsContainerKey(c.key))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- isVersionFolderPath ----------
|
||||
|
||||
func TestIsVersionFolderPath(t *testing.T) {
|
||||
// Reports whether a key sits inside a .versions/ folder, looking at
|
||||
// the parent segment specifically. The router uses this to skip
|
||||
// version-file events that need sibling state to classify.
|
||||
cases := []struct {
|
||||
key string
|
||||
want bool
|
||||
}{
|
||||
{"obj.versions/v_aaa", true},
|
||||
{"a/b/obj.versions/v_aaa", true},
|
||||
{"obj/v_aaa", false}, // parent isn't .versions
|
||||
{"obj.versions", false}, // the container itself, not a child
|
||||
// "obj.versions/" reads as the trailing-slash form of the path
|
||||
// "obj.versions" → leaf is "obj.versions" which ends with the
|
||||
// suffix → true. The router never sees this shape from the
|
||||
// reader (events carry concrete leaf names), but pin it here so
|
||||
// the contract is documented.
|
||||
{"obj.versions/", true},
|
||||
{"v_aaa", false}, // no slash at all
|
||||
{"", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.key, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, isVersionFolderPath(c.key))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- isDeleteMarkerEntry ----------
|
||||
|
||||
func TestIsDeleteMarkerEntry_NilOrEmptyExtendedReturnsFalse(t *testing.T) {
|
||||
assert.False(t, isDeleteMarkerEntry(nil))
|
||||
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{}))
|
||||
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{Extended: map[string][]byte{}}))
|
||||
}
|
||||
|
||||
func TestIsDeleteMarkerEntry_TrueOnlyForLiteralTrue(t *testing.T) {
|
||||
// The marker key must be exactly "true"; any other value is not a
|
||||
// marker. Pinning catches a regression that does case-insensitive
|
||||
// matching or treats "1" as truthy.
|
||||
mk := func(val string) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte(val)}}
|
||||
}
|
||||
assert.True(t, isDeleteMarkerEntry(mk("true")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("True")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("TRUE")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("1")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("")))
|
||||
assert.False(t, isDeleteMarkerEntry(mk("false")))
|
||||
}
|
||||
|
||||
// ---------- extractTags ----------
|
||||
|
||||
func TestExtractTags_NilOrEmptyReturnsNil(t *testing.T) {
|
||||
assert.Nil(t, extractTags(nil))
|
||||
assert.Nil(t, extractTags(map[string][]byte{}))
|
||||
}
|
||||
|
||||
func TestExtractTags_OnlyKeysWithObjectTaggingPrefix(t *testing.T) {
|
||||
// extractTags returns ExtVersionIdKey, Mime, etc. → no.
|
||||
// It only picks up keys with the AmzObjectTagging prefix and strips
|
||||
// that prefix to produce the tag map.
|
||||
prefix := s3_constants.AmzObjectTagging + "-"
|
||||
ext := map[string][]byte{
|
||||
prefix + "env": []byte("prod"),
|
||||
prefix + "team": []byte("data"),
|
||||
"X-Amz-Other": []byte("ignored"),
|
||||
"Seaweed-X-Internal": []byte("ignored"),
|
||||
}
|
||||
got := extractTags(ext)
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "prod", got["env"])
|
||||
assert.Equal(t, "data", got["team"])
|
||||
}
|
||||
|
||||
func TestExtractTags_ReturnsNilWhenNoTaggingPrefixedKeys(t *testing.T) {
|
||||
// Keys with no tagging prefix produce a nil map (not an empty map);
|
||||
// the router treats nil as "no tags" without an extra branch.
|
||||
ext := map[string][]byte{
|
||||
"X-Amz-Other": []byte("ignored"),
|
||||
"Seaweed-X-Internal": []byte("ignored"),
|
||||
}
|
||||
got := extractTags(ext)
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
// ---------- hasActiveEventDrivenAction ----------
|
||||
|
||||
func TestHasActiveEventDrivenAction(t *testing.T) {
|
||||
// Build a snapshot with two action kinds and one of them set to
|
||||
// scan-only (inactive in event-driven view). hasActiveEventDrivenAction
|
||||
// must answer true only for the active event-driven kind.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
}
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
|
||||
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
|
||||
prior := map[s3lifecycle.ActionKey]engine.PriorState{
|
||||
expirationKey: {BootstrapComplete: true, Mode: engine.ModeEventDriven},
|
||||
abortKey: {BootstrapComplete: true, Mode: engine.ModeScanOnly},
|
||||
}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
engine.CompileOptions{PriorStates: prior},
|
||||
)
|
||||
keys := []s3lifecycle.ActionKey{expirationKey, abortKey}
|
||||
|
||||
// Active event-driven kind matches.
|
||||
assert.True(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
|
||||
// Scan-only kind does NOT match — operator promoted it to scan-only
|
||||
// and the router must respect that by skipping the event-driven path.
|
||||
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindAbortMPU))
|
||||
// A kind not in the keys list is false.
|
||||
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNoncurrentDays))
|
||||
}
|
||||
|
||||
func TestHasActiveEventDrivenAction_NilActionSkipped(t *testing.T) {
|
||||
// A key the snapshot doesn't know about returns nil from Action;
|
||||
// the helper must skip rather than panic.
|
||||
snap := engine.New().Compile(nil, engine.CompileOptions{})
|
||||
keys := []s3lifecycle.ActionKey{
|
||||
{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays},
|
||||
}
|
||||
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
|
||||
}
|
||||
|
||||
// ---------- engine.Snapshot accessors ----------
|
||||
|
||||
func TestSnapshot_BucketVersionedReportsCompiledFlag(t *testing.T) {
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{
|
||||
{Bucket: "vbk", Rules: []*s3lifecycle.Rule{rule}, Versioned: true},
|
||||
{Bucket: "ubk", Rules: []*s3lifecycle.Rule{rule}, Versioned: false},
|
||||
},
|
||||
engine.CompileOptions{},
|
||||
)
|
||||
assert.True(t, snap.BucketVersioned("vbk"))
|
||||
assert.False(t, snap.BucketVersioned("ubk"))
|
||||
// Unknown bucket: not versioned, not a panic.
|
||||
assert.False(t, snap.BucketVersioned("missing"))
|
||||
}
|
||||
|
||||
func TestSnapshot_BucketActionKeysReturnsCompiledList(t *testing.T) {
|
||||
// Every CompileInput rule emits one action key per RuleActionKind;
|
||||
// BucketActionKeys must surface them all (regardless of Mode) so
|
||||
// MatchPath can iterate.
|
||||
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
engine.CompileOptions{},
|
||||
)
|
||||
keys := snap.BucketActionKeys("bk")
|
||||
require.NotEmpty(t, keys)
|
||||
for _, k := range keys {
|
||||
assert.Equal(t, "bk", k.Bucket)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshot_BucketActionKeysUnknownBucketReturnsNil(t *testing.T) {
|
||||
snap := engine.New().Compile(nil, engine.CompileOptions{})
|
||||
assert.Nil(t, snap.BucketActionKeys("missing"))
|
||||
}
|
||||
|
||||
func TestSnapshot_ActionUnknownKeyReturnsNil(t *testing.T) {
|
||||
snap := engine.New().Compile(nil, engine.CompileOptions{})
|
||||
got := snap.Action(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestSnapshot_AllActionsCoversEveryCompiledKind(t *testing.T) {
|
||||
// AllActions must enumerate every compiled action regardless of
|
||||
// active state, because the dispatcher uses it for full-snapshot
|
||||
// reporting.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 7,
|
||||
AbortMPUDaysAfterInitiation: 3,
|
||||
}
|
||||
snap := engine.New().Compile(
|
||||
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
|
||||
engine.CompileOptions{},
|
||||
)
|
||||
all := snap.AllActions()
|
||||
wantKinds := s3lifecycle.RuleActionKinds(rule)
|
||||
require.Len(t, all, len(wantKinds))
|
||||
seen := map[s3lifecycle.ActionKind]bool{}
|
||||
for _, a := range all {
|
||||
seen[a.Key.ActionKind] = true
|
||||
}
|
||||
for _, k := range wantKinds {
|
||||
assert.True(t, seen[k], "missing kind %v in AllActions", k)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshot_SnapshotIDIsMonotonicAcrossRecompiles(t *testing.T) {
|
||||
// Every Compile call advances snapshotIDSeq; pin that successive
|
||||
// snapshots from the same Engine carry strictly increasing IDs so
|
||||
// the dispatcher's stale-snapshot check works.
|
||||
e := engine.New()
|
||||
first := e.Compile(nil, engine.CompileOptions{})
|
||||
second := e.Compile(nil, engine.CompileOptions{})
|
||||
assert.Greater(t, second.SnapshotID(), first.SnapshotID(),
|
||||
"second compile must produce a strictly greater snapshot id")
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
@@ -11,6 +15,34 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
)
|
||||
|
||||
// SiblingLister inspects the surviving versions of a versioned key.
|
||||
// nil receiver or an error means "unknown" — callers suppress. Four
|
||||
// queries: Survivors paginates the .versions/ container plus the bare
|
||||
// null version (used by sole-survivor and bootstrap); LookupVersion
|
||||
// fetches a single version file by id (used by pointer-transition
|
||||
// routing to read the displaced version's identity and mtime);
|
||||
// ListVersions paginates every version file in the .versions/
|
||||
// container (used to compute NoncurrentIndex when a NewerNoncurrent
|
||||
// rule is active); LookupNullVersion returns the bare-key entry that
|
||||
// represents the null version (used by pointer-transition routing
|
||||
// when oldID is empty and to include the null in expansion ranks).
|
||||
type SiblingLister interface {
|
||||
Survivors(ctx context.Context, bucket, objectKey string) (Survivors, error)
|
||||
LookupVersion(ctx context.Context, bucket, objectKey, versionID string) (*filer_pb.Entry, error)
|
||||
ListVersions(ctx context.Context, bucket, objectKey string) ([]*filer_pb.Entry, error)
|
||||
LookupNullVersion(ctx context.Context, bucket, objectKey string) (entry *filer_pb.Entry, explicit bool, err error)
|
||||
}
|
||||
|
||||
// Survivors describes the state under .versions/<key>/ plus the bare
|
||||
// null-version that exists when versioning was turned on after the
|
||||
// object was first PUT (s3api_object_versioning.go treats <bucket>/<key>
|
||||
// as a regular file, the null version, in that case).
|
||||
type Survivors struct {
|
||||
Count int // entries under .versions/<key>/, capped at 2
|
||||
LoneEntry *filer_pb.Entry // populated when Count == 1
|
||||
HasNullVersion bool // bare <bucket>/<key> exists as a regular file
|
||||
}
|
||||
|
||||
// Match is one (event, action) pair where EvaluateAction fired. The
|
||||
// dispatcher runs `LifecycleDelete` at DueTime; identity-CAS in the RPC
|
||||
// guards against drift between schedule time and dispatch time.
|
||||
@@ -42,26 +74,52 @@ type EntryIdentity struct {
|
||||
ExtendedHash []byte
|
||||
}
|
||||
|
||||
// Route returns the matches that fire for ev against snap. Only EVENT_DRIVEN
|
||||
// actions on this bucket are considered; actions in SCAN_AT_DATE or DISABLED
|
||||
// modes are out-of-band of the event stream. Inactive actions
|
||||
// (BootstrapComplete=false) are also skipped.
|
||||
func Route(snap *engine.Snapshot, ev *reader.Event, now time.Time) []Match {
|
||||
// Route returns the matches that fire for ev against snap. Only active
|
||||
// event-driven actions are considered; SCAN_AT_DATE and DISABLED bypass
|
||||
// this path.
|
||||
func Route(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, now time.Time, lister SiblingLister) []Match {
|
||||
if snap == nil || ev == nil {
|
||||
return nil
|
||||
}
|
||||
// Hard deletes carry no schedule-relevant state: an Expiration would
|
||||
// hit NOOP_RESOLVED at dispatch time anyway, ExpiredObjectDeleteMarker
|
||||
// only fires on the latest-version delete-marker which is a Create
|
||||
// from the server's perspective. Skip rather than burn a schedule slot.
|
||||
if ev.NewEntry == nil {
|
||||
return nil
|
||||
}
|
||||
keys := snap.BucketActionKeys(ev.Bucket)
|
||||
if len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
info := buildObjectInfo(ev, snap.BucketVersioned(ev.Bucket))
|
||||
// Bootstrap-expanded version event: sibling state is pre-computed,
|
||||
// info.Key is the LOGICAL key so rule prefixes match. Skip the
|
||||
// meta-log path's version-folder skip.
|
||||
if ev.BootstrapVersion != nil {
|
||||
return routeBootstrapVersion(snap, ev, keys)
|
||||
}
|
||||
|
||||
versioned := snap.BucketVersioned(ev.Bucket)
|
||||
|
||||
// .versions/ directory metadata update: when ExtLatestVersionIdKey
|
||||
// changes, the OLD pointer value names a version that's now
|
||||
// noncurrent. Route NoncurrentDays / NewerNoncurrent for it without
|
||||
// waiting for the next bootstrap.
|
||||
if versioned && ev.NewEntry != nil && ev.OldEntry != nil && ev.NewEntry.IsDirectory && isVersionsContainerKey(ev.Key) {
|
||||
if !hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNoncurrentDays) &&
|
||||
!hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNewerNoncurrent) {
|
||||
return nil
|
||||
}
|
||||
return routePointerTransition(ctx, snap, ev, keys, lister)
|
||||
}
|
||||
|
||||
// EXP_DM can fire on two version-folder events: the marker create
|
||||
// (sole survivor immediately) and a noncurrent hard-delete that
|
||||
// leaves only the marker behind. Both reach routeSoleSurvivorMarker.
|
||||
if versioned && isVersionFolderPath(ev.Key) {
|
||||
if !hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpiredDeleteMarker) {
|
||||
return nil
|
||||
}
|
||||
return routeSoleSurvivorMarker(ctx, snap, ev, keys, lister)
|
||||
}
|
||||
|
||||
if ev.NewEntry == nil {
|
||||
return nil
|
||||
}
|
||||
info := buildObjectInfo(ev, versioned)
|
||||
if info == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -112,42 +170,540 @@ func Route(snap *engine.Snapshot, ev *reader.Event, now time.Time) []Match {
|
||||
return matches
|
||||
}
|
||||
|
||||
// buildObjectInfo derives an ObjectInfo from a meta-log event and the
|
||||
// bucket's versioning state. Returns nil when the event has no usable
|
||||
// shape (missing attributes, hard delete already handled upstream).
|
||||
// routePointerTransition handles a .versions/ container update where
|
||||
// ExtLatestVersionIdKey changed: the OLD pointer value names a version
|
||||
// that just became noncurrent. Two lookup shapes:
|
||||
//
|
||||
// On a versioned bucket the storage layout (<key>.versions/v_<id>) is
|
||||
// shared between the current latest and the noncurrent versions; the
|
||||
// latest pointer lives in the .versions/ directory's Extended map and
|
||||
// is updated separately. Without that pointer-transition signal here,
|
||||
// the router conservatively classifies every event as if it were the
|
||||
// current version (IsLatest=true) so it never deletes the live
|
||||
// latest; bootstrap walking + the server-side dispatch guard handle
|
||||
// noncurrent retention. NumVersions=0 keeps ExpiredObjectDeleteMarker
|
||||
// (which requires sole-survivor) suppressed.
|
||||
// - Pure NoncurrentVersionExpirationDays without NewerNoncurrentVersions:
|
||||
// a single LookupVersion of oldID is enough — the displaced version
|
||||
// is the only one that newly entered eligibility for this rule.
|
||||
//
|
||||
// MPU init directories at .uploads/<upload_id> populate IsMPUInit and
|
||||
// use the destination object key from the entry's Extended map for
|
||||
// filter matching, so a rule with Filter.Prefix=foo/ matches an MPU
|
||||
// uploading to foo/bar.txt.
|
||||
// - Any active NewerNoncurrentVersions rule: a pointer flip shifts
|
||||
// every prior noncurrent's rank by one, so the version that *just
|
||||
// crossed* the keep-count threshold needs evaluation too. List the
|
||||
// full .versions/ container, rank newest-first, and route every
|
||||
// eligible noncurrent. Identity-CAS handles dedup with earlier
|
||||
// schedules.
|
||||
//
|
||||
// Without this branch the worker has to wait for the next bootstrap to
|
||||
// schedule retention on a freshly-noncurrent version.
|
||||
func routePointerTransition(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister) []Match {
|
||||
if lister == nil {
|
||||
return nil
|
||||
}
|
||||
logical := strings.TrimSuffix(ev.Key, s3_constants.VersionsFolder)
|
||||
if logical == "" {
|
||||
return nil
|
||||
}
|
||||
oldID := string(ev.OldEntry.Extended[s3_constants.ExtLatestVersionIdKey])
|
||||
newID := string(ev.NewEntry.Extended[s3_constants.ExtLatestVersionIdKey])
|
||||
if oldID == newID {
|
||||
// Same id means the update didn't transition the pointer.
|
||||
return nil
|
||||
}
|
||||
// oldID == "" doesn't mean "nothing displaced": a bare null may
|
||||
// have been the implicit/explicit latest before the pointer
|
||||
// flipped to a real id.
|
||||
// newID == "" means a suspended-versioning write cleared the
|
||||
// pointer and made the bare null current. The cached
|
||||
// ExtLatestVersionMtimeKey may still hold the prior latest's
|
||||
// mtime (stale), so we must NOT use successorModTimeFromContainer
|
||||
// in that case — derive the successor clock from the null entry's
|
||||
// mtime instead. latestIDForExpand carries the same substitution
|
||||
// so the expansion path's latestPos lookup matches the null sibling.
|
||||
var successor time.Time
|
||||
latestIDForExpand := newID
|
||||
if newID == "" {
|
||||
nullEntry, _, err := lister.LookupNullVersion(ctx, ev.Bucket, logical)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("lifecycle router: lookup null %s/%s: %v", ev.Bucket, logical, err)
|
||||
return nil
|
||||
}
|
||||
if nullEntry == nil || nullEntry.Attributes == nil {
|
||||
return nil
|
||||
}
|
||||
successor = time.Unix(nullEntry.Attributes.Mtime, int64(nullEntry.Attributes.MtimeNs))
|
||||
latestIDForExpand = "null"
|
||||
} else {
|
||||
successor = successorModTimeFromContainer(ev.NewEntry)
|
||||
}
|
||||
if successor.IsZero() {
|
||||
return nil
|
||||
}
|
||||
if needsFullExpansion(snap, keys) {
|
||||
return routePointerTransitionExpand(ctx, snap, ev, keys, lister, logical, latestIDForExpand, successor)
|
||||
}
|
||||
return routePointerTransitionDisplaced(ctx, snap, ev, keys, lister, logical, oldID, successor)
|
||||
}
|
||||
|
||||
// needsFullExpansion reports whether any active event-driven rule on
|
||||
// this bucket cares about NoncurrentIndex (NewerNoncurrentVersions > 0
|
||||
// in either NoncurrentDays or pure-count NewerNoncurrent).
|
||||
func needsFullExpansion(snap *engine.Snapshot, keys []s3lifecycle.ActionKey) bool {
|
||||
for _, k := range keys {
|
||||
if k.ActionKind != s3lifecycle.ActionKindNoncurrentDays && k.ActionKind != s3lifecycle.ActionKindNewerNoncurrent {
|
||||
continue
|
||||
}
|
||||
a := snap.Action(k)
|
||||
if a == nil || !a.IsActive() || a.Mode != engine.ModeEventDriven {
|
||||
continue
|
||||
}
|
||||
if a.Rule != nil && a.Rule.NewerNoncurrentVersions > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// successorModTimeFromContainer reads the cached latest-version mtime
|
||||
// from the .versions/ container's Extended map.
|
||||
// updateLatestVersionInDirectory writes it via setCachedListMetadata
|
||||
// alongside ExtLatestVersionIdKey, but the directory's own
|
||||
// Attributes.Mtime is preserved across pointer updates — using it
|
||||
// directly would let a stale dir mtime trigger expiration immediately.
|
||||
// Returns zero time if the cached mtime is missing or unparseable; the
|
||||
// caller suppresses in that case.
|
||||
func successorModTimeFromContainer(entry *filer_pb.Entry) time.Time {
|
||||
raw, ok := entry.Extended[s3_constants.ExtLatestVersionMtimeKey]
|
||||
if !ok || len(raw) == 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
secs, err := strconv.ParseInt(string(raw), 10, 64)
|
||||
if err != nil || secs <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Unix(secs, 0)
|
||||
}
|
||||
|
||||
// routePointerTransitionDisplaced is the single-lookup path: only the
|
||||
// displaced version's noncurrent eligibility could have changed, so
|
||||
// fetching just its file is enough. oldID == "" routes the bare null
|
||||
// version instead — it was the implicit latest before the pointer
|
||||
// flipped to a real id.
|
||||
func routePointerTransitionDisplaced(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister, logical, oldID string, successor time.Time) []Match {
|
||||
var displaced *filer_pb.Entry
|
||||
displacedID := oldID
|
||||
if oldID == "" {
|
||||
nullEntry, _, err := lister.LookupNullVersion(ctx, ev.Bucket, logical)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("lifecycle router: lookup null version %s/%s: %v", ev.Bucket, logical, err)
|
||||
return nil
|
||||
}
|
||||
if nullEntry == nil {
|
||||
return nil
|
||||
}
|
||||
displaced = nullEntry
|
||||
displacedID = "null"
|
||||
} else {
|
||||
entry, err := lister.LookupVersion(ctx, ev.Bucket, logical, oldID)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("lifecycle router: lookup displaced version %s/%s/%s: %v", ev.Bucket, logical, oldID, err)
|
||||
return nil
|
||||
}
|
||||
displaced = entry
|
||||
}
|
||||
if displaced == nil || displaced.Attributes == nil {
|
||||
return nil
|
||||
}
|
||||
idx := 0
|
||||
info := &s3lifecycle.ObjectInfo{
|
||||
Key: logical,
|
||||
ModTime: time.Unix(displaced.Attributes.Mtime, int64(displaced.Attributes.MtimeNs)),
|
||||
Size: int64(displaced.Attributes.FileSize),
|
||||
IsLatest: false,
|
||||
IsDeleteMarker: string(displaced.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
|
||||
NoncurrentIndex: &idx,
|
||||
SuccessorModTime: successor,
|
||||
}
|
||||
if tags := extractTags(displaced.Extended); len(tags) > 0 {
|
||||
info.Tags = tags
|
||||
}
|
||||
return emitNoncurrentMatches(snap, ev, keys, info, displaced, displacedID, successor)
|
||||
}
|
||||
|
||||
// routePointerTransitionExpand routes only the versions that newly
|
||||
// became eligible by the pointer flip:
|
||||
//
|
||||
// - rank 0: the displaced version (newly noncurrent), needed for the
|
||||
// pure-NoncurrentDays clock,
|
||||
// - rank == rule.NewerNoncurrentVersions for each active rule that
|
||||
// gates on count: the version at exactly that rank just crossed
|
||||
// from kept to expired.
|
||||
//
|
||||
// Emitting every eligible noncurrent on every PUT would push
|
||||
// O(versions) heap entries per flip — Schedule.Add doesn't dedup, so
|
||||
// identity-CAS at dispatch only stops the wasted RPC, not the heap
|
||||
// growth. Bootstrap still owns full backfill.
|
||||
func routePointerTransitionExpand(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister, logical, newID string, successor time.Time) []Match {
|
||||
rawVersions, err := lister.ListVersions(ctx, ev.Bucket, logical)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("lifecycle router: list versions %s/%s: %v", ev.Bucket, logical, err)
|
||||
return nil
|
||||
}
|
||||
// Include the bare null version in the sibling set: count-based
|
||||
// ranks are wrong if a pre-versioning or suspended-null entry
|
||||
// exists outside .versions/. ID is "null" for sort + emit.
|
||||
nullEntry, _, nullErr := lister.LookupNullVersion(ctx, ev.Bucket, logical)
|
||||
if nullErr != nil {
|
||||
glog.V(2).Infof("lifecycle router: lookup null %s/%s: %v", ev.Bucket, logical, nullErr)
|
||||
return nil
|
||||
}
|
||||
type sibling struct {
|
||||
entry *filer_pb.Entry
|
||||
id string
|
||||
}
|
||||
siblings := make([]sibling, 0, len(rawVersions)+1)
|
||||
for _, v := range rawVersions {
|
||||
if v == nil || v.Attributes == nil {
|
||||
continue
|
||||
}
|
||||
id := string(v.Extended[s3_constants.ExtVersionIdKey])
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
siblings = append(siblings, sibling{entry: v, id: id})
|
||||
}
|
||||
if nullEntry != nil && nullEntry.Attributes != nil {
|
||||
siblings = append(siblings, sibling{entry: nullEntry, id: "null"})
|
||||
}
|
||||
if len(siblings) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.SliceStable(siblings, func(i, j int) bool {
|
||||
mi := siblings[i].entry.Attributes.Mtime*int64(1e9) + int64(siblings[i].entry.Attributes.MtimeNs)
|
||||
mj := siblings[j].entry.Attributes.Mtime*int64(1e9) + int64(siblings[j].entry.Attributes.MtimeNs)
|
||||
if mi != mj {
|
||||
return mi > mj
|
||||
}
|
||||
return s3lifecycle.CompareVersionIds(siblings[i].id, siblings[j].id) < 0
|
||||
})
|
||||
// Resolve latestPos by finding newID. Default to -1 so a missing
|
||||
// newID (race with the listing, or torn write) suppresses the
|
||||
// expansion: we'd otherwise call the actual newest sibling "latest"
|
||||
// against the pointer's intent and misrank every noncurrent.
|
||||
// Bootstrap repairs state on the next walk.
|
||||
latestPos := -1
|
||||
if newID != "" {
|
||||
for i, s := range siblings {
|
||||
if s.id == newID {
|
||||
latestPos = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if latestPos < 0 {
|
||||
glog.V(2).Infof("lifecycle router: pointer transition %s/%s: new id %s not found in listing", ev.Bucket, logical, newID)
|
||||
return nil
|
||||
}
|
||||
noncurrentCount := len(siblings) - 1
|
||||
|
||||
// Collect the target noncurrent ranks: 0 (the freshly displaced)
|
||||
// plus N for each active count-gated rule.
|
||||
rankSet := map[int]struct{}{0: {}}
|
||||
for _, k := range keys {
|
||||
if k.ActionKind != s3lifecycle.ActionKindNoncurrentDays && k.ActionKind != s3lifecycle.ActionKindNewerNoncurrent {
|
||||
continue
|
||||
}
|
||||
a := snap.Action(k)
|
||||
if a == nil || !a.IsActive() || a.Mode != engine.ModeEventDriven {
|
||||
continue
|
||||
}
|
||||
if a.Rule != nil && a.Rule.NewerNoncurrentVersions > 0 {
|
||||
rankSet[a.Rule.NewerNoncurrentVersions] = struct{}{}
|
||||
}
|
||||
}
|
||||
ranks := make([]int, 0, len(rankSet))
|
||||
for r := range rankSet {
|
||||
ranks = append(ranks, r)
|
||||
}
|
||||
sort.Ints(ranks)
|
||||
|
||||
var matches []Match
|
||||
for _, rank := range ranks {
|
||||
if rank >= noncurrentCount {
|
||||
continue
|
||||
}
|
||||
// Convert noncurrent rank to position in the sorted slice,
|
||||
// skipping the latest's slot.
|
||||
i := rank
|
||||
if rank >= latestPos {
|
||||
i = rank + 1
|
||||
}
|
||||
s := siblings[i]
|
||||
// Successor mtime: the entry directly newer than this one in
|
||||
// the sorted list. When the next-newer slot is the latest,
|
||||
// use the cached successor (the new latest's mtime); otherwise
|
||||
// the immediate predecessor's mtime.
|
||||
var thisSuccessor time.Time
|
||||
if i > 0 && i-1 != latestPos {
|
||||
thisSuccessor = time.Unix(siblings[i-1].entry.Attributes.Mtime, int64(siblings[i-1].entry.Attributes.MtimeNs))
|
||||
} else {
|
||||
thisSuccessor = successor
|
||||
}
|
||||
idx := rank
|
||||
info := &s3lifecycle.ObjectInfo{
|
||||
Key: logical,
|
||||
ModTime: time.Unix(s.entry.Attributes.Mtime, int64(s.entry.Attributes.MtimeNs)),
|
||||
Size: int64(s.entry.Attributes.FileSize),
|
||||
IsLatest: false,
|
||||
IsDeleteMarker: string(s.entry.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
|
||||
NoncurrentIndex: &idx,
|
||||
SuccessorModTime: thisSuccessor,
|
||||
NumVersions: len(siblings),
|
||||
}
|
||||
if tags := extractTags(s.entry.Extended); len(tags) > 0 {
|
||||
info.Tags = tags
|
||||
}
|
||||
matches = append(matches, emitNoncurrentMatches(snap, ev, keys, info, s.entry, s.id, thisSuccessor)...)
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// emitNoncurrentMatches walks NoncurrentDays / NewerNoncurrent action
|
||||
// keys and emits Matches for each one that fires. Shared between the
|
||||
// single-lookup and full-expansion paths.
|
||||
func emitNoncurrentMatches(snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, info *s3lifecycle.ObjectInfo, entry *filer_pb.Entry, versionID string, successor time.Time) []Match {
|
||||
eventTime := time.Unix(0, ev.TsNs)
|
||||
identity := buildIdentityFromEntry(entry)
|
||||
var matches []Match
|
||||
for _, key := range keys {
|
||||
if key.ActionKind != s3lifecycle.ActionKindNoncurrentDays && key.ActionKind != s3lifecycle.ActionKindNewerNoncurrent {
|
||||
continue
|
||||
}
|
||||
action := snap.Action(key)
|
||||
if action == nil || !action.IsActive() || action.Mode != engine.ModeEventDriven {
|
||||
continue
|
||||
}
|
||||
clock := successor
|
||||
if clock.IsZero() {
|
||||
clock = info.ModTime
|
||||
}
|
||||
dueTime := clock.Add(action.Delay)
|
||||
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
|
||||
if res.Action == s3lifecycle.ActionNone {
|
||||
continue
|
||||
}
|
||||
matches = append(matches, Match{
|
||||
Key: key,
|
||||
Action: action,
|
||||
Result: res,
|
||||
EventTs: eventTime,
|
||||
DueTime: dueTime,
|
||||
Bucket: ev.Bucket,
|
||||
ObjectKey: info.Key,
|
||||
VersionID: versionID,
|
||||
Identity: identity,
|
||||
})
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// routeSoleSurvivorMarker emits an EXP_DM Match against the LOGICAL key
|
||||
// (so the dispatcher can call deleteSpecificObjectVersion) with the
|
||||
// marker's version_id. Handles two events: a marker create (the new
|
||||
// entry IS the marker) and a noncurrent hard-delete that leaves the
|
||||
// marker behind (the listing's lone entry IS the marker). The server
|
||||
// re-checks before deleting.
|
||||
func routeSoleSurvivorMarker(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister) []Match {
|
||||
if lister == nil {
|
||||
return nil
|
||||
}
|
||||
// Skip the listing RPC for events that can't possibly produce a
|
||||
// sole-survivor marker: a regular non-marker version create/update
|
||||
// always lands at Count >= 2.
|
||||
if ev.NewEntry != nil && !isDeleteMarkerEntry(ev.NewEntry) {
|
||||
return nil
|
||||
}
|
||||
logicalKey, ok := logicalKeyFromVersionPath(ev.Key)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
s, err := lister.Survivors(ctx, ev.Bucket, logicalKey)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("lifecycle router: survivors %s/%s: %v", ev.Bucket, logicalKey, err)
|
||||
return nil
|
||||
}
|
||||
// Pre-versioning bare-key objects (the "null" version) live outside
|
||||
// .versions/. Treating count==1 as sole-survivor while a null
|
||||
// version exists would let lifecycle delete the marker and re-expose
|
||||
// the old object.
|
||||
if s.Count != 1 || s.HasNullVersion || s.LoneEntry == nil {
|
||||
return nil
|
||||
}
|
||||
if !isDeleteMarkerEntry(s.LoneEntry) {
|
||||
return nil
|
||||
}
|
||||
versionID := string(s.LoneEntry.Extended[s3_constants.ExtVersionIdKey])
|
||||
if versionID == "" {
|
||||
// Empty version_id would BLOCK at dispatch and freeze the cursor.
|
||||
return nil
|
||||
}
|
||||
entry := s.LoneEntry
|
||||
info := &s3lifecycle.ObjectInfo{
|
||||
Key: logicalKey,
|
||||
ModTime: time.Unix(entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)),
|
||||
Size: int64(entry.Attributes.FileSize),
|
||||
IsLatest: true,
|
||||
IsDeleteMarker: true,
|
||||
NumVersions: 1,
|
||||
}
|
||||
if tags := extractTags(entry.Extended); len(tags) > 0 {
|
||||
info.Tags = tags
|
||||
}
|
||||
eventTime := time.Unix(0, ev.TsNs)
|
||||
identity := buildIdentityFromEntry(entry)
|
||||
var matches []Match
|
||||
for _, key := range keys {
|
||||
if key.ActionKind != s3lifecycle.ActionKindExpiredDeleteMarker {
|
||||
continue
|
||||
}
|
||||
action := snap.Action(key)
|
||||
if action == nil || !action.IsActive() || action.Mode != engine.ModeEventDriven {
|
||||
continue
|
||||
}
|
||||
dueTime := info.ModTime.Add(action.Delay)
|
||||
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
|
||||
if res.Action == s3lifecycle.ActionNone {
|
||||
continue
|
||||
}
|
||||
matches = append(matches, Match{
|
||||
Key: key,
|
||||
Action: action,
|
||||
Result: res,
|
||||
EventTs: eventTime,
|
||||
DueTime: dueTime,
|
||||
Bucket: ev.Bucket,
|
||||
ObjectKey: logicalKey,
|
||||
VersionID: versionID,
|
||||
Identity: identity,
|
||||
})
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// routeBootstrapVersion handles a synthesized event from BucketBootstrapper.
|
||||
// The bootstrap walker has already listed .versions/<key>/, sorted siblings
|
||||
// newest-first, and stamped each one's IsLatest / NoncurrentIndex /
|
||||
// SuccessorModTime. The router only needs to assemble ObjectInfo and run
|
||||
// the match loop with the standard kind gates. ev.NewEntry is the version
|
||||
// file itself; ev.Key is the version-folder path; the LOGICAL key from
|
||||
// BootstrapVersion drives prefix matching and the dispatcher.
|
||||
func routeBootstrapVersion(snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey) []Match {
|
||||
bv := ev.BootstrapVersion
|
||||
entry := ev.NewEntry
|
||||
if entry == nil || entry.Attributes == nil || bv.LogicalKey == "" {
|
||||
return nil
|
||||
}
|
||||
idx := bv.NoncurrentIndex
|
||||
info := &s3lifecycle.ObjectInfo{
|
||||
Key: bv.LogicalKey,
|
||||
ModTime: time.Unix(entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)),
|
||||
Size: int64(entry.Attributes.FileSize),
|
||||
IsLatest: bv.IsLatest,
|
||||
IsDeleteMarker: bv.IsDeleteMarker,
|
||||
NumVersions: bv.NumVersions,
|
||||
SuccessorModTime: bv.SuccessorModTime,
|
||||
}
|
||||
if !bv.IsLatest {
|
||||
info.NoncurrentIndex = &idx
|
||||
}
|
||||
if tags := extractTags(entry.Extended); len(tags) > 0 {
|
||||
info.Tags = tags
|
||||
}
|
||||
eventTime := time.Unix(0, ev.TsNs)
|
||||
identity := buildIdentityFromEntry(entry)
|
||||
var matches []Match
|
||||
for _, key := range keys {
|
||||
action := snap.Action(key)
|
||||
if action == nil || !action.IsActive() || action.Mode != engine.ModeEventDriven {
|
||||
continue
|
||||
}
|
||||
// ABORT_MPU never applies to a versioned object.
|
||||
if key.ActionKind == s3lifecycle.ActionKindAbortMPU {
|
||||
continue
|
||||
}
|
||||
// Noncurrent rules clock from when this version was replaced
|
||||
// (SuccessorModTime), not from when it was originally written.
|
||||
// Bootstrap populates SuccessorModTime; fall back to ModTime
|
||||
// for the latest version (no successor exists).
|
||||
clock := info.ModTime
|
||||
if !info.IsLatest && !info.SuccessorModTime.IsZero() {
|
||||
clock = info.SuccessorModTime
|
||||
}
|
||||
dueTime := clock.Add(action.Delay)
|
||||
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
|
||||
if res.Action == s3lifecycle.ActionNone {
|
||||
continue
|
||||
}
|
||||
// Pin the version_id only for kinds the dispatcher needs to
|
||||
// target by version: noncurrent retention and the marker
|
||||
// itself. EXPIRATION_DAYS / EXPIRATION_DATE on the latest
|
||||
// must NOT carry it — between schedule and dispatch a fresh
|
||||
// PUT can land, and identity-CAS against the original
|
||||
// version's bytes would still pass even though the latest has
|
||||
// moved on. Empty VersionID makes the dispatcher fetch the
|
||||
// current latest, where identity-CAS resolves to STALE_IDENTITY
|
||||
// and bootstrap re-schedules with the new latest's identity.
|
||||
var matchVersionID string
|
||||
switch key.ActionKind {
|
||||
case s3lifecycle.ActionKindNoncurrentDays,
|
||||
s3lifecycle.ActionKindNewerNoncurrent,
|
||||
s3lifecycle.ActionKindExpiredDeleteMarker:
|
||||
matchVersionID = bv.VersionID
|
||||
}
|
||||
matches = append(matches, Match{
|
||||
Key: key,
|
||||
Action: action,
|
||||
Result: res,
|
||||
EventTs: eventTime,
|
||||
DueTime: dueTime,
|
||||
Bucket: ev.Bucket,
|
||||
ObjectKey: bv.LogicalKey,
|
||||
VersionID: matchVersionID,
|
||||
Identity: identity,
|
||||
})
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// logicalKeyFromVersionPath extracts <logical> from <logical>.versions/<file>.
|
||||
// Returns false for a bucket-root marker (path = ".versions/<file>"), since
|
||||
// AWS S3 has no concept of an object at the bucket key itself.
|
||||
func logicalKeyFromVersionPath(versionPath string) (string, bool) {
|
||||
lastSlash := strings.LastIndex(versionPath, "/")
|
||||
if lastSlash <= 0 {
|
||||
return "", false
|
||||
}
|
||||
parent := versionPath[:lastSlash]
|
||||
if !strings.HasSuffix(parent, s3_constants.VersionsFolder) {
|
||||
return "", false
|
||||
}
|
||||
logical := strings.TrimSuffix(parent, s3_constants.VersionsFolder)
|
||||
if logical == "" {
|
||||
return "", false
|
||||
}
|
||||
return logical, true
|
||||
}
|
||||
|
||||
// buildObjectInfo derives an ObjectInfo from a meta-log event. Returns
|
||||
// nil for shapes the router can't classify safely: missing attributes,
|
||||
// non-MPU directories, version-folder files (those route through
|
||||
// routeSoleSurvivorMarker upstream when EXP_DM applies). On a versioned
|
||||
// bucket the latest pointer lives in the .versions/ directory's
|
||||
// Extended map; without it we leave NumVersions=0 so the bootstrap walk
|
||||
// drives noncurrent retention.
|
||||
func buildObjectInfo(ev *reader.Event, versioned bool) *s3lifecycle.ObjectInfo {
|
||||
entry := ev.NewEntry
|
||||
if entry == nil || entry.Attributes == nil {
|
||||
return nil
|
||||
}
|
||||
if destKey, ok := mpuInitInfo(ev, entry); ok {
|
||||
// MPU intermediate state has no tags, no versions, no delete-marker
|
||||
// semantics. info.Key is the user's destination key so a rule's
|
||||
// Filter.Prefix matches the eventual object; the dispatcher already
|
||||
// carries .uploads/<upload_id> in m.ObjectKey for ABORT_MPU.
|
||||
return &s3lifecycle.ObjectInfo{
|
||||
Key: destKey,
|
||||
ModTime: time.Unix(entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)),
|
||||
IsMPUInit: true,
|
||||
}
|
||||
}
|
||||
// Directory entries that aren't MPU inits aren't lifecycle subjects:
|
||||
// the .versions/ folder itself, prefix dirs, etc. — emit nothing.
|
||||
if entry.IsDirectory {
|
||||
return nil
|
||||
}
|
||||
@@ -159,22 +715,9 @@ func buildObjectInfo(ev *reader.Event, versioned bool) *s3lifecycle.ObjectInfo {
|
||||
NumVersions: 1,
|
||||
}
|
||||
if versioned {
|
||||
// On a versioned bucket the actual file path doesn't tell us
|
||||
// whether the entry is the current latest or a noncurrent
|
||||
// version — the latest pointer lives in the .versions/
|
||||
// directory's Extended map and isn't part of this event. We
|
||||
// also can't compute NumVersions / NoncurrentIndex here. Skip
|
||||
// any version-folder file event for now; bootstrap walking
|
||||
// drives noncurrent retention and current-version expiration
|
||||
// for versioned buckets until pointer-transition routing
|
||||
// lands. The bare-key path (null-version, pre-versioning
|
||||
// objects) keeps the regular routing.
|
||||
if isVersionFolderPath(ev.Key) {
|
||||
return nil
|
||||
}
|
||||
// NumVersions=0 keeps ExpiredObjectDeleteMarker (sole-survivor
|
||||
// gate) suppressed for the bare-key delete-marker case until
|
||||
// sibling listing lands.
|
||||
info.NumVersions = 0
|
||||
}
|
||||
if tags := extractTags(entry.Extended); len(tags) > 0 {
|
||||
@@ -186,6 +729,18 @@ func buildObjectInfo(ev *reader.Event, versioned bool) *s3lifecycle.ObjectInfo {
|
||||
return info
|
||||
}
|
||||
|
||||
// isVersionsContainerKey reports whether the bucket-relative key IS a
|
||||
// .versions/ container itself (e.g. "logs/foo.versions"), as opposed to
|
||||
// a file inside one. Used to recognize directory-level events whose
|
||||
// Extended map carries the latest pointer for an object.
|
||||
func isVersionsContainerKey(key string) bool {
|
||||
if key == s3_constants.VersionsFolder {
|
||||
// Bucket-root .versions: no logical object key.
|
||||
return false
|
||||
}
|
||||
return strings.HasSuffix(key, s3_constants.VersionsFolder)
|
||||
}
|
||||
|
||||
// isVersionFolderPath reports whether the bucket-relative key sits inside a
|
||||
// .versions/ folder — i.e. the path's parent segment ends with the
|
||||
// VersionsFolder suffix. Used by the versioned-bucket gate so the router
|
||||
@@ -226,7 +781,10 @@ func mpuInitInfo(ev *reader.Event, entry *filer_pb.Entry) (destKey string, ok bo
|
||||
// buildIdentity captures the entry's schedule-time fingerprint for the CAS
|
||||
// witness. Returns nil if the event has no entry to fingerprint (deletes).
|
||||
func buildIdentity(ev *reader.Event) *EntryIdentity {
|
||||
entry := ev.NewEntry
|
||||
return buildIdentityFromEntry(ev.NewEntry)
|
||||
}
|
||||
|
||||
func buildIdentityFromEntry(entry *filer_pb.Entry) *EntryIdentity {
|
||||
if entry == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -266,10 +824,31 @@ func extractTags(ext map[string][]byte) map[string]string {
|
||||
return out
|
||||
}
|
||||
|
||||
// hasActiveEventDrivenAction gates I/O (e.g. sibling listing) on whether
|
||||
// a match could actually fire. Mirrors the per-key filter in Route so
|
||||
// disabled or scan-only actions don't pay the RPC.
|
||||
func hasActiveEventDrivenAction(snap *engine.Snapshot, keys []s3lifecycle.ActionKey, kind s3lifecycle.ActionKind) bool {
|
||||
for _, k := range keys {
|
||||
if k.ActionKind != kind {
|
||||
continue
|
||||
}
|
||||
a := snap.Action(k)
|
||||
if a == nil {
|
||||
continue
|
||||
}
|
||||
if a.IsActive() && a.Mode == engine.ModeEventDriven {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isDeleteMarkerEntry mirrors every read site for ExtDeleteMarkerKey:
|
||||
// production writes []byte("true").
|
||||
func isDeleteMarkerEntry(entry *filer_pb.Entry) bool {
|
||||
if entry == nil || len(entry.Extended) == 0 {
|
||||
return false
|
||||
}
|
||||
v, ok := entry.Extended[s3_constants.ExtDeleteMarkerKey]
|
||||
return ok && len(v) == 1 && v[0] == 1
|
||||
return ok && string(v) == "true"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -84,3 +85,119 @@ func TestScheduleAllowsDuplicates(t *testing.T) {
|
||||
t.Fatalf("Drain dup count=%d, want 2", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleDrainBeforeAnyDueReturnsNothing(t *testing.T) {
|
||||
// Drain at a time before the earliest DueTime must return an empty
|
||||
// slice and leave the heap intact. Otherwise the dispatcher would
|
||||
// consume future-due matches early.
|
||||
s := NewSchedule()
|
||||
t0 := time.Now()
|
||||
s.Add(mkMatch(t0.Add(5*time.Second), "a"))
|
||||
s.Add(mkMatch(t0.Add(10*time.Second), "b"))
|
||||
|
||||
got := s.Drain(t0)
|
||||
if got != nil {
|
||||
t.Fatalf("Drain before any due should be nil, got %+v", got)
|
||||
}
|
||||
if s.Len() != 2 {
|
||||
t.Fatalf("Len after no-op Drain=%d, want 2", s.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleNextDueAfterPartialDrain(t *testing.T) {
|
||||
// After draining a prefix, NextDue must point at the earliest
|
||||
// remaining Match — regression catch for a Drain implementation
|
||||
// that forgets to maintain the heap invariant.
|
||||
s := NewSchedule()
|
||||
t0 := time.Now()
|
||||
s.Add(mkMatch(t0.Add(1*time.Second), "a"))
|
||||
s.Add(mkMatch(t0.Add(2*time.Second), "b"))
|
||||
s.Add(mkMatch(t0.Add(3*time.Second), "c"))
|
||||
|
||||
got := s.Drain(t0.Add(1500 * time.Millisecond))
|
||||
if len(got) != 1 || got[0].ObjectKey != "a" {
|
||||
t.Fatalf("Drain prefix=%+v, want [a]", got)
|
||||
}
|
||||
due, ok := s.NextDue()
|
||||
if !ok || !due.Equal(t0.Add(2*time.Second)) {
|
||||
t.Fatalf("NextDue after partial Drain=%v ok=%v, want t+2s", due, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleAddAfterDrainKeepsOrder(t *testing.T) {
|
||||
// Adding to a non-empty schedule mid-stream — after a real Drain
|
||||
// has popped at least one entry, a fresh Match with an earlier
|
||||
// DueTime than the existing minimum must become the next drainable.
|
||||
// Pins that heap.Pop + Push together preserve the heap invariant
|
||||
// across the Drain → Add boundary.
|
||||
s := NewSchedule()
|
||||
t0 := time.Now()
|
||||
s.Add(mkMatch(t0.Add(10*time.Second), "old"))
|
||||
s.Add(mkMatch(t0.Add(6*time.Second), "drain_me"))
|
||||
|
||||
drained := s.Drain(t0.Add(7 * time.Second))
|
||||
if len(drained) != 1 || drained[0].ObjectKey != "drain_me" {
|
||||
t.Fatalf("pre-drain=%+v, want [drain_me]", drained)
|
||||
}
|
||||
|
||||
s.Add(mkMatch(t0.Add(5*time.Second), "new")) // added after Drain, earlier than old
|
||||
|
||||
due, ok := s.NextDue()
|
||||
if !ok || !due.Equal(t0.Add(5*time.Second)) {
|
||||
t.Fatalf("NextDue=%v ok=%v, want t+5s", due, ok)
|
||||
}
|
||||
|
||||
got := s.Drain(t0.Add(6 * time.Second))
|
||||
if len(got) != 1 || got[0].ObjectKey != "new" {
|
||||
t.Fatalf("Drain=%+v, want [new]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleDrainOrderIsAscendingDueTime(t *testing.T) {
|
||||
// Drain must return Matches in DueTime order regardless of insert
|
||||
// order — explicit pinning of the contract documented on Drain.
|
||||
s := NewSchedule()
|
||||
t0 := time.Now()
|
||||
for _, off := range []time.Duration{
|
||||
5 * time.Second,
|
||||
1 * time.Second,
|
||||
3 * time.Second,
|
||||
2 * time.Second,
|
||||
4 * time.Second,
|
||||
} {
|
||||
s.Add(mkMatch(t0.Add(off), "k"))
|
||||
}
|
||||
|
||||
got := s.Drain(t0.Add(10 * time.Second))
|
||||
if len(got) != 5 {
|
||||
t.Fatalf("Drain count=%d, want 5", len(got))
|
||||
}
|
||||
for i := 1; i < len(got); i++ {
|
||||
if got[i].DueTime.Before(got[i-1].DueTime) {
|
||||
t.Fatalf("Drain[%d]=%v is before Drain[%d]=%v", i, got[i].DueTime, i-1, got[i-1].DueTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleConcurrentAddDrainNoRace(t *testing.T) {
|
||||
// The dispatcher's Add and Drain run on separate goroutines; the
|
||||
// schedule's mutex must serialize them without deadlock. -race
|
||||
// catches a regression that drops the lock on either path.
|
||||
s := NewSchedule()
|
||||
t0 := time.Now()
|
||||
const N = 64
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(N * 2)
|
||||
for i := 0; i < N; i++ {
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.Add(mkMatch(t0.Add(time.Duration(i)*time.Millisecond), "k"))
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_ = s.Drain(t0.Add(10 * time.Second))
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -3,14 +3,18 @@ package scheduler
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// EventInjector is the bootstrap-side hook into the dispatcher pipeline.
|
||||
@@ -20,6 +24,46 @@ type EventInjector interface {
|
||||
InjectEvent(ctx context.Context, ev *reader.Event) error
|
||||
}
|
||||
|
||||
// listPageSize is the page size for paginated directory listings during
|
||||
// the bucket walk. The filer caps SeaweedList(..., limit=0) at
|
||||
// DirListingLimit (1000 by default) per call, so a single-page list
|
||||
// would silently truncate large directories — a correctness bug for
|
||||
// noncurrent retention since older versions past the page boundary
|
||||
// would never reach the rank/sort math. Atomic so tests can shrink it
|
||||
// without racing the async bootstrap goroutines other tests leave
|
||||
// behind (KickOffNew dispatches walks via `go b.walkBucket(...)`,
|
||||
// and a fresh test's Cleanup might land before those goroutines exit).
|
||||
var listPageSize atomic.Uint32
|
||||
|
||||
func init() {
|
||||
listPageSize.Store(1024)
|
||||
}
|
||||
|
||||
// listAll issues paginated SeaweedList calls until the listing is
|
||||
// exhausted, invoking fn for every entry. Pagination uses
|
||||
// startFrom = lastEntryName (exclusive) to advance.
|
||||
func listAll(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string, fn func(*filer_pb.Entry) error) error {
|
||||
pageSize := listPageSize.Load()
|
||||
startFrom := ""
|
||||
for {
|
||||
var pageCount uint32
|
||||
var lastName string
|
||||
if err := filer_pb.SeaweedList(ctx, client, dir, "", func(e *filer_pb.Entry, _ bool) error {
|
||||
pageCount++
|
||||
if e != nil {
|
||||
lastName = e.Name
|
||||
}
|
||||
return fn(e)
|
||||
}, startFrom, false, pageSize); err != nil {
|
||||
return err
|
||||
}
|
||||
if pageCount < pageSize {
|
||||
return nil
|
||||
}
|
||||
startFrom = lastName
|
||||
}
|
||||
}
|
||||
|
||||
// BucketBootstrapper backfills already-existing entries when a freshly-PUT
|
||||
// rule's bucket appears in the engine. The reader-driven path only sees
|
||||
// meta-log events created after the rule lands; without this walk,
|
||||
@@ -34,33 +78,70 @@ type EventInjector interface {
|
||||
// Synthesized events carry TsNs=0 so dispatcher.advance is a no-op for
|
||||
// them — the reader still resumes from its persisted cursor on restart.
|
||||
//
|
||||
// Bucket completion is in-memory per process; a fresh worker run walks
|
||||
// each bucket once on first refresh.
|
||||
// Walk state is tracked in-memory per process via two maps:
|
||||
// - lastCompleted: time of the last successful walk, drives the
|
||||
// BootstrapInterval cadence; zero interval means "walk once per
|
||||
// process".
|
||||
// - inFlight: buckets whose walk goroutines are still running.
|
||||
// Skipped regardless of cadence so a walk that takes longer than
|
||||
// BootstrapInterval can't trigger a duplicate goroutine on the
|
||||
// next refresh.
|
||||
type BucketBootstrapper struct {
|
||||
FilerClient filer_pb.SeaweedFilerClient
|
||||
BucketsPath string
|
||||
Injector EventInjector
|
||||
|
||||
mu sync.Mutex
|
||||
known map[string]bool
|
||||
// BootstrapInterval gates re-walks. Zero means "walk once per
|
||||
// process". Non-zero means "walk again once it's been at least
|
||||
// this long since the last completed walk" — the cadence scan_only
|
||||
// actions rely on, since they can only fire from bootstrap.
|
||||
BootstrapInterval time.Duration
|
||||
|
||||
// Now overrides time.Now for tests.
|
||||
Now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
lastCompleted map[string]time.Time
|
||||
inFlight map[string]bool
|
||||
}
|
||||
|
||||
func (b *BucketBootstrapper) now() time.Time {
|
||||
if b.Now != nil {
|
||||
return b.Now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// KickOffNew launches a one-shot walker goroutine for every bucket
|
||||
// in `buckets` that hasn't been seen before.
|
||||
// that's not currently in flight and either has never completed a walk
|
||||
// or whose last successful walk finished more than BootstrapInterval ago.
|
||||
func (b *BucketBootstrapper) KickOffNew(ctx context.Context, buckets []string) {
|
||||
if b.Injector == nil {
|
||||
return
|
||||
}
|
||||
now := b.now()
|
||||
b.mu.Lock()
|
||||
if b.known == nil {
|
||||
b.known = map[string]bool{}
|
||||
if b.lastCompleted == nil {
|
||||
b.lastCompleted = map[string]time.Time{}
|
||||
}
|
||||
if b.inFlight == nil {
|
||||
b.inFlight = map[string]bool{}
|
||||
}
|
||||
fresh := make([]string, 0, len(buckets))
|
||||
for _, bucket := range buckets {
|
||||
if b.known[bucket] {
|
||||
if b.inFlight[bucket] {
|
||||
// Walk still running from an earlier KickOffNew — never
|
||||
// double up regardless of cadence. A large bucket that
|
||||
// takes longer than BootstrapInterval would otherwise
|
||||
// have a fresh goroutine fire on every refresh tick.
|
||||
continue
|
||||
}
|
||||
b.known[bucket] = true
|
||||
if last, ok := b.lastCompleted[bucket]; ok {
|
||||
if b.BootstrapInterval <= 0 || now.Sub(last) < b.BootstrapInterval {
|
||||
continue
|
||||
}
|
||||
}
|
||||
b.inFlight[bucket] = true
|
||||
fresh = append(fresh, bucket)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
@@ -75,7 +156,26 @@ func (b *BucketBootstrapper) walkBucket(ctx context.Context, bucket string) {
|
||||
root := strings.TrimSuffix(b.BucketsPath, "/") + "/" + bucket
|
||||
glog.V(0).Infof("lifecycle bootstrap: starting walk for bucket %s (root=%s)", bucket, root)
|
||||
count := 0
|
||||
if err := walkBucketDir(ctx, b.FilerClient, root, root, func(entry *filer_pb.Entry, key string) error {
|
||||
// skipBare records bucket-relative bare-key paths that
|
||||
// expandVersionsDir already routed as the null version. Without it
|
||||
// the walker's regular emission would also fire for the bare entry
|
||||
// — in a versioned bucket buildObjectInfo classifies it as
|
||||
// IsLatest=true, NumVersions=0, and ExpirationDays would create a
|
||||
// stray delete marker that hides the real latest.
|
||||
skipBare := map[string]bool{}
|
||||
var cb func(entry *filer_pb.Entry, key string) error
|
||||
cb = func(entry *filer_pb.Entry, key string) error {
|
||||
if isVersionsDir(entry) {
|
||||
n, err := b.expandVersionsDir(ctx, bucket, root, key, entry, cb, skipBare)
|
||||
count += n
|
||||
return err
|
||||
}
|
||||
if !entry.IsDirectory && skipBare[key] {
|
||||
return nil
|
||||
}
|
||||
if entry.IsDirectoryKeyObject() && skipBare[key] {
|
||||
return nil
|
||||
}
|
||||
ev := &reader.Event{
|
||||
// TsNs=0 sentinel: dispatcher.advance treats <=0 as no-op,
|
||||
// so the reader's persisted cursor isn't ratcheted forward
|
||||
@@ -88,51 +188,267 @@ func (b *BucketBootstrapper) walkBucket(ctx context.Context, bucket string) {
|
||||
}
|
||||
count++
|
||||
return b.Injector.InjectEvent(ctx, ev)
|
||||
}); err != nil {
|
||||
}
|
||||
walkErr := walkBucketDir(ctx, b.FilerClient, root, root, cb)
|
||||
b.mu.Lock()
|
||||
delete(b.inFlight, bucket)
|
||||
if walkErr == nil {
|
||||
// Stamp completion so BootstrapInterval cadence measures from
|
||||
// end-of-walk. Failures leave lastCompleted alone, so the next
|
||||
// KickOffNew sees no record and walks the bucket again.
|
||||
if b.lastCompleted == nil {
|
||||
b.lastCompleted = map[string]time.Time{}
|
||||
}
|
||||
b.lastCompleted[bucket] = b.now()
|
||||
}
|
||||
b.mu.Unlock()
|
||||
if walkErr != nil {
|
||||
if ctx.Err() == nil {
|
||||
glog.V(0).Infof("lifecycle bootstrap %s: %v", bucket, err)
|
||||
glog.V(0).Infof("lifecycle bootstrap %s: %v", bucket, walkErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
glog.V(0).Infof("lifecycle bootstrap: bucket %s injected %d entries", bucket, count)
|
||||
}
|
||||
|
||||
// walkBucketDir lists every file under dir recursively and invokes cb
|
||||
// with the filer entry plus its bucket-relative key. MPU init dirs at
|
||||
// .uploads/<id> are emitted as a single (directory-shaped) entry so the
|
||||
// router's MPU detection fires; deeper directories recurse.
|
||||
func walkBucketDir(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, bucketRoot string, cb func(entry *filer_pb.Entry, key string) error) error {
|
||||
// versionItem is the per-sibling state expandVersionsDir builds: the
|
||||
// filer entry plus its version_id (or "null" for the bare null version
|
||||
// living outside .versions/). isExplicitNull marks bare entries the
|
||||
// suspended-versioning write path tagged with ExtVersionIdKey="null"
|
||||
// (s3api_object_handlers_put.go); we trust those as latest when the
|
||||
// .versions/ pointer is missing. A pre-versioning bare object has no
|
||||
// such marker, so a missing pointer there is a race window with a new
|
||||
// version write and we keep the newest-sibling fallback.
|
||||
type versionItem struct {
|
||||
entry *filer_pb.Entry
|
||||
versionID string
|
||||
bareKey string // bucket-relative path; non-empty only for the null version
|
||||
isExplicitNull bool
|
||||
}
|
||||
|
||||
// expandVersionsDir lists <root>/<key>/ and, when the children look like
|
||||
// SeaweedFS version files, injects one reader.Event per version with
|
||||
// BootstrapVersion populated. The bare logical key (the "null" version,
|
||||
// living outside .versions/) is included as a sibling so:
|
||||
// - pre-versioning objects with a newer .versions/ history fire
|
||||
// NoncurrentDays as id="null"
|
||||
// - suspended-bucket writes (which clear the .versions/ latest pointer)
|
||||
// correctly classify null as the current version while every
|
||||
// .versions/ child becomes noncurrent
|
||||
//
|
||||
// versionsKey is the bucket-relative path of the .versions/ directory
|
||||
// (e.g. "logs/foo.versions"). When the bare null version is included,
|
||||
// its bucket-relative path is added to skipBare so the walker's regular
|
||||
// emission for the same entry is suppressed.
|
||||
//
|
||||
// When no child has ExtVersionIdKey the directory is a coincidentally-
|
||||
// named user folder; recurse via fallback (the bucket walk's own cb).
|
||||
func (b *BucketBootstrapper) expandVersionsDir(ctx context.Context, bucket, root, versionsKey string, versionsEntry *filer_pb.Entry, fallback func(*filer_pb.Entry, string) error, skipBare map[string]bool) (int, error) {
|
||||
logical := strings.TrimSuffix(versionsKey, s3_constants.VersionsFolder)
|
||||
if logical == "" {
|
||||
return 0, nil
|
||||
}
|
||||
versionsDir := strings.TrimSuffix(b.BucketsPath, "/") + "/" + bucket + "/" + versionsKey
|
||||
// Collect file children only. Subdirectories under .versions/ would
|
||||
// corrupt sort/rank math; the disambiguation pass below also wants
|
||||
// to see only file-shaped children. Paginate so a hot key with
|
||||
// thousands of versions doesn't truncate at DirListingLimit.
|
||||
var children []*filer_pb.Entry
|
||||
if err := filer_pb.SeaweedList(ctx, client, dir, "", func(e *filer_pb.Entry, _ bool) error {
|
||||
children = append(children, e)
|
||||
if err := listAll(ctx, b.FilerClient, versionsDir, func(e *filer_pb.Entry) error {
|
||||
if e != nil && e.Attributes != nil && !e.IsDirectory {
|
||||
children = append(children, e)
|
||||
}
|
||||
return nil
|
||||
}, "", false, 0); err != nil {
|
||||
}); err != nil {
|
||||
return 0, fmt.Errorf("list %s: %w", versionsDir, err)
|
||||
}
|
||||
items := make([]versionItem, 0, len(children)+1)
|
||||
for _, e := range children {
|
||||
if id, ok := e.Extended[s3_constants.ExtVersionIdKey]; ok && len(id) > 0 {
|
||||
items = append(items, versionItem{entry: e, versionID: string(id)})
|
||||
}
|
||||
}
|
||||
if len(items) == 0 {
|
||||
// Coincidentally-named user folder (or an empty .versions
|
||||
// container). fallback is the bucket walk's own cb so nested
|
||||
// .versions/ entries inside still expand.
|
||||
if fallback == nil {
|
||||
return 0, nil
|
||||
}
|
||||
if err := walkBucketDir(ctx, b.FilerClient, versionsDir, root, fallback); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
// Look up the bare null version. SeaweedFS keeps it at the logical
|
||||
// path for pre-versioning objects and for suspended-bucket writes.
|
||||
// Both shapes count: regular file (PUT'd object) and explicit S3
|
||||
// directory-key marker (object name ends in /).
|
||||
if nullEntry, nullKey, explicit, ok := b.lookupNullVersion(ctx, bucket, logical); ok {
|
||||
items = append(items, versionItem{
|
||||
entry: nullEntry,
|
||||
versionID: "null",
|
||||
bareKey: nullKey,
|
||||
isExplicitNull: explicit,
|
||||
})
|
||||
}
|
||||
// Sort newest-first: primary by mtime ns, fallback by version_id
|
||||
// (CompareVersionIds returns <0 when first arg is newer). PUTs only
|
||||
// set second-level Mtime, so collisions in the same second are
|
||||
// resolved by the canonical version-id ordering used elsewhere.
|
||||
sort.SliceStable(items, func(i, j int) bool {
|
||||
mi := items[i].entry.Attributes.Mtime*int64(1e9) + int64(items[i].entry.Attributes.MtimeNs)
|
||||
mj := items[j].entry.Attributes.Mtime*int64(1e9) + int64(items[j].entry.Attributes.MtimeNs)
|
||||
if mi != mj {
|
||||
return mi > mj
|
||||
}
|
||||
return s3lifecycle.CompareVersionIds(items[i].versionID, items[j].versionID) < 0
|
||||
})
|
||||
// Resolve latest position.
|
||||
// 1. Pointer names a real id -> that wins (in-order or backdated).
|
||||
// 2. Pointer absent + items[0] is an EXPLICIT null (suspended write
|
||||
// cleared the pointer and tagged the bare object as null, AND
|
||||
// the bare object is newest by mtime) -> null is latest.
|
||||
// 3. Pointer absent in any other shape: fall back to newest
|
||||
// sibling. Catches the post-suspended re-enable race window —
|
||||
// a fresh .versions/<v1> write whose pointer update hasn't
|
||||
// landed yet outranks the older suspended-null bare object.
|
||||
latestID := string(versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey])
|
||||
latestPos := 0
|
||||
if latestID != "" {
|
||||
for i, it := range items {
|
||||
if it.versionID == latestID {
|
||||
latestPos = i
|
||||
break
|
||||
}
|
||||
}
|
||||
} else if len(items) > 0 && items[0].versionID == "null" && items[0].isExplicitNull {
|
||||
latestPos = 0
|
||||
}
|
||||
count := 0
|
||||
for i, it := range items {
|
||||
var successor time.Time
|
||||
if i > 0 {
|
||||
prev := items[i-1].entry.Attributes
|
||||
successor = time.Unix(prev.Mtime, int64(prev.MtimeNs))
|
||||
}
|
||||
bv := &reader.BootstrapVersion{
|
||||
LogicalKey: logical,
|
||||
VersionID: it.versionID,
|
||||
IsLatest: i == latestPos,
|
||||
IsDeleteMarker: string(it.entry.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
|
||||
NumVersions: len(items),
|
||||
SuccessorModTime: successor,
|
||||
}
|
||||
if !bv.IsLatest {
|
||||
rank := i
|
||||
if i > latestPos {
|
||||
rank = i - 1
|
||||
}
|
||||
bv.NoncurrentIndex = rank
|
||||
}
|
||||
// Event Key for bookkeeping: real version files keep the
|
||||
// .versions/<file> path; the null version uses its bare path
|
||||
// so the dispatcher's identity check resolves to the same
|
||||
// entry the walker would have emitted.
|
||||
evKey := versionsKey + "/" + it.entry.Name
|
||||
if it.versionID == "null" {
|
||||
evKey = it.bareKey
|
||||
}
|
||||
ev := &reader.Event{
|
||||
TsNs: 0,
|
||||
Bucket: bucket,
|
||||
Key: evKey,
|
||||
ShardID: s3lifecycle.ShardID(bucket, logical),
|
||||
NewEntry: it.entry,
|
||||
BootstrapVersion: bv,
|
||||
}
|
||||
if err := b.Injector.InjectEvent(ctx, ev); err != nil {
|
||||
return count, err
|
||||
}
|
||||
if it.versionID == "null" && skipBare != nil {
|
||||
skipBare[it.bareKey] = true
|
||||
}
|
||||
count++
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// lookupNullVersion returns the bare-key entry that represents the null
|
||||
// version of logical, if any. Both regular files and S3 directory-key
|
||||
// markers (an empty directory entry with Mime set) qualify. The
|
||||
// explicit return reports whether the entry's Extended map carries
|
||||
// ExtVersionIdKey == "null" — the marker the suspended-versioning
|
||||
// write path applies (s3api_object_handlers_put.go). bucketRelKey is
|
||||
// the bucket-relative path the walker would otherwise emit, so the
|
||||
// caller can suppress the duplicate.
|
||||
func (b *BucketBootstrapper) lookupNullVersion(ctx context.Context, bucket, logical string) (entry *filer_pb.Entry, bucketRelKey string, explicit bool, ok bool) {
|
||||
bucketPath := strings.TrimSuffix(b.BucketsPath, "/") + "/" + bucket
|
||||
parent, name := util.NewFullPath(bucketPath, logical).DirAndName()
|
||||
resp, err := filer_pb.LookupEntry(ctx, b.FilerClient, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: parent,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil || resp == nil || resp.Entry == nil {
|
||||
return nil, "", false, false
|
||||
}
|
||||
e := resp.Entry
|
||||
if e.IsDirectory && !e.IsDirectoryKeyObject() {
|
||||
return nil, "", false, false
|
||||
}
|
||||
if id, hasID := e.Extended[s3_constants.ExtVersionIdKey]; hasID && string(id) == "null" {
|
||||
explicit = true
|
||||
}
|
||||
return e, strings.TrimPrefix(parent+"/"+name, bucketPath+"/"), explicit, true
|
||||
}
|
||||
|
||||
// walkBucketDir streams entries under dir and invokes cb. Two kinds of
|
||||
// directories are emitted whole rather than recursed into:
|
||||
// - .uploads/<id> MPU init dirs (router fires ABORT_MPU off the dir entry)
|
||||
// - <key>.versions/ directories (caller expands them into per-version
|
||||
// events; recursing here would emit individual version files without
|
||||
// the sibling state needed for NoncurrentDays / NewerNoncurrent)
|
||||
//
|
||||
// .versions/ dirs are processed before everything else at each level so
|
||||
// the cb's expandVersionsDir call can record the bare null-version key
|
||||
// in the walk-shared skip set before the same level emits the bare entry.
|
||||
// Two streaming passes (rather than buffering the whole directory) trade
|
||||
// a second listing for bounded memory on flat buckets with millions of
|
||||
// entries.
|
||||
func walkBucketDir(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, bucketRoot string, cb func(entry *filer_pb.Entry, key string) error) error {
|
||||
// Pass 1: .versions/ dirs only.
|
||||
if err := listAll(ctx, client, dir, func(e *filer_pb.Entry) error {
|
||||
if e == nil || e.Attributes == nil {
|
||||
return nil
|
||||
}
|
||||
if !e.IsDirectory || !isVersionsDir(e) {
|
||||
return nil
|
||||
}
|
||||
full := dir + "/" + e.Name
|
||||
key := strings.TrimPrefix(full, bucketRoot+"/")
|
||||
return cb(e, key)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("list %s: %w", dir, err)
|
||||
}
|
||||
for _, entry := range children {
|
||||
if entry == nil || entry.Attributes == nil {
|
||||
continue
|
||||
// Pass 2: everything else. Bare entries whose name was claimed by
|
||||
// a sibling .versions/ expansion are dropped by the cb's skip-set.
|
||||
return listAll(ctx, client, dir, func(e *filer_pb.Entry) error {
|
||||
if e == nil || e.Attributes == nil {
|
||||
return nil
|
||||
}
|
||||
full := dir + "/" + entry.Name
|
||||
if e.IsDirectory && isVersionsDir(e) {
|
||||
return nil
|
||||
}
|
||||
full := dir + "/" + e.Name
|
||||
key := strings.TrimPrefix(full, bucketRoot+"/")
|
||||
|
||||
if entry.IsDirectory {
|
||||
if isMPUInitDir(key, entry) {
|
||||
if err := cb(entry, key); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
if e.IsDirectory {
|
||||
if isMPUInitDir(key, e) {
|
||||
return cb(e, key)
|
||||
}
|
||||
if err := walkBucketDir(ctx, client, full, bucketRoot, cb); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
return walkBucketDir(ctx, client, full, bucketRoot, cb)
|
||||
}
|
||||
if err := cb(entry, key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return cb(e, key)
|
||||
})
|
||||
}
|
||||
|
||||
// isMPUInitDir mirrors router.mpuInitInfo: a directory at .uploads/<id>
|
||||
@@ -152,3 +468,16 @@ func isMPUInitDir(key string, entry *filer_pb.Entry) bool {
|
||||
return ok && len(v) > 0
|
||||
}
|
||||
|
||||
// isVersionsDir matches `<x>.versions/` by name suffix. We can't gate on
|
||||
// ExtLatestVersionIdKey here: createDeleteMarker writes the version file
|
||||
// before updating the parent's Extended pointer, so a walk that races
|
||||
// with that update would see the directory without the pointer and
|
||||
// recurse into raw version files, losing the sibling state needed for
|
||||
// noncurrent rules. expandVersionsDir handles disambiguation by
|
||||
// inspecting children for ExtVersionIdKey; coincidentally-named
|
||||
// directories that aren't real .versions storage fall through to a
|
||||
// regular recursion.
|
||||
func isVersionsDir(entry *filer_pb.Entry) bool {
|
||||
return entry.IsDirectory && strings.HasSuffix(entry.Name, s3_constants.VersionsFolder)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,236 @@
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Tests for LoadCompileInputs / IsBucketVersioned / AllActivePriorStates.
|
||||
// LoadCompileInputs is the bridge between the filer's bucket directory
|
||||
// and the engine snapshot the scheduler compiles every refresh —
|
||||
// pagination, parse-error surfacing, and the empty/missing-XML skip
|
||||
// semantics matter because a missed bucket silently disables lifecycle
|
||||
// for that prefix until the next refresh.
|
||||
|
||||
const testBucketsRoot = "/buckets"
|
||||
|
||||
// minimalLifecycleXML is the smallest XML that ParseCanonical accepts as
|
||||
// a non-empty rule set; the actual rule details are exercised by the
|
||||
// lifecycle_xml package's own tests.
|
||||
const minimalLifecycleXML = `<LifecycleConfiguration>
|
||||
<Rule>
|
||||
<ID>r1</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Filter><Prefix>logs/</Prefix></Filter>
|
||||
<Expiration><Days>30</Days></Expiration>
|
||||
</Rule>
|
||||
</LifecycleConfiguration>`
|
||||
|
||||
func bucketEntry(name string, extended map[string][]byte) *filer_pb.Entry {
|
||||
return dirEntry(name, extended)
|
||||
}
|
||||
|
||||
func TestIsBucketVersioned_MissingExtendedReturnsFalse(t *testing.T) {
|
||||
assert.False(t, IsBucketVersioned(&filer_pb.Entry{}))
|
||||
assert.False(t, IsBucketVersioned(&filer_pb.Entry{Extended: map[string][]byte{}}))
|
||||
}
|
||||
|
||||
func TestIsBucketVersioned_AcceptsEnabledAndSuspended(t *testing.T) {
|
||||
// Casing and surrounding whitespace are normalized so the worker
|
||||
// tolerates whatever casing the writer chose.
|
||||
for _, raw := range []string{"Enabled", "ENABLED", "enabled", " enabled ", "Suspended", "suspended"} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
e := &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersioningKey: []byte(raw)}}
|
||||
assert.True(t, IsBucketVersioned(e), "value %q must classify as versioned", raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsBucketVersioned_RejectsOtherValues(t *testing.T) {
|
||||
for _, raw := range []string{"", "Disabled", "Off", "true", "1", "garbage"} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
e := &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersioningKey: []byte(raw)}}
|
||||
assert.False(t, IsBucketVersioned(e), "value %q must NOT classify as versioned", raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllActivePriorStates_EmptyInputs(t *testing.T) {
|
||||
assert.Empty(t, AllActivePriorStates(nil))
|
||||
assert.Empty(t, AllActivePriorStates([]engine.CompileInput{}))
|
||||
}
|
||||
|
||||
func TestAllActivePriorStates_SeedsAllActionsAsActive(t *testing.T) {
|
||||
// Every (bucket, ruleHash, actionKind) tuple from the inputs must
|
||||
// receive a PriorState with BootstrapComplete=true and
|
||||
// Mode=ModeEventDriven so the scheduler dispatches matched events
|
||||
// immediately rather than waiting for a per-action bootstrap walk.
|
||||
rule := &s3lifecycle.Rule{
|
||||
ID: "r1",
|
||||
Status: s3lifecycle.StatusEnabled,
|
||||
ExpirationDays: 30,
|
||||
}
|
||||
inputs := []engine.CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}}
|
||||
prior := AllActivePriorStates(inputs)
|
||||
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
kinds := s3lifecycle.RuleActionKinds(rule)
|
||||
require.NotEmpty(t, kinds, "expiration-days rule must yield at least one action kind")
|
||||
for _, kind := range kinds {
|
||||
key := s3lifecycle.ActionKey{Bucket: "b1", RuleHash: hash, ActionKind: kind}
|
||||
state, ok := prior[key]
|
||||
require.True(t, ok, "prior state missing for action kind %v", kind)
|
||||
assert.True(t, state.BootstrapComplete, "bootstrap complete for kind %v", kind)
|
||||
assert.Equal(t, engine.ModeEventDriven, state.Mode, "mode for kind %v", kind)
|
||||
}
|
||||
assert.Len(t, prior, len(kinds), "exactly one prior-state entry per action kind")
|
||||
}
|
||||
|
||||
func TestAllActivePriorStates_KeysSeparatedByBucket(t *testing.T) {
|
||||
// Two buckets sharing identical rules must still get distinct
|
||||
// PriorState entries, otherwise refresh would conflate their state.
|
||||
rule := &s3lifecycle.Rule{ID: "r1", Status: s3lifecycle.StatusEnabled, ExpirationDays: 30}
|
||||
inputs := []engine.CompileInput{
|
||||
{Bucket: "alpha", Rules: []*s3lifecycle.Rule{rule}},
|
||||
{Bucket: "beta", Rules: []*s3lifecycle.Rule{rule}},
|
||||
}
|
||||
prior := AllActivePriorStates(inputs)
|
||||
hash := s3lifecycle.RuleHash(rule)
|
||||
for _, kind := range s3lifecycle.RuleActionKinds(rule) {
|
||||
assert.Contains(t, prior, s3lifecycle.ActionKey{Bucket: "alpha", RuleHash: hash, ActionKind: kind})
|
||||
assert.Contains(t, prior, s3lifecycle.ActionKey{Bucket: "beta", RuleHash: hash, ActionKind: kind})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_EmptyBucketDir(t *testing.T) {
|
||||
// No buckets at all -> no inputs, no parse errors, no transport error.
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{testBucketsRoot: {}}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, inputs)
|
||||
assert.Empty(t, perr)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_FilesAtBucketLevelSkipped(t *testing.T) {
|
||||
// A bare file at the buckets root isn't a bucket; the loader must
|
||||
// skip it without touching the parser.
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: {fileEntry("stray.txt")},
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, inputs)
|
||||
assert.Empty(t, perr)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_BucketWithoutLifecycleConfigSkipped(t *testing.T) {
|
||||
// Buckets that don't carry the lifecycle XML extended attribute are
|
||||
// silently skipped — operators may have many buckets without rules.
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: {bucketEntry("b1", nil)},
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, inputs)
|
||||
assert.Empty(t, perr)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_BucketWithEmptyLifecycleXMLSkipped(t *testing.T) {
|
||||
// Empty bytes under the lifecycle key shouldn't reach the parser.
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
|
||||
BucketLifecycleConfigurationXMLKey: nil,
|
||||
})},
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, inputs)
|
||||
assert.Empty(t, perr)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_ValidConfigBecomesInput(t *testing.T) {
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
|
||||
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
|
||||
})},
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, perr)
|
||||
require.Len(t, inputs, 1)
|
||||
assert.Equal(t, "b1", inputs[0].Bucket)
|
||||
assert.False(t, inputs[0].Versioned, "no versioning attr -> not versioned")
|
||||
assert.NotEmpty(t, inputs[0].Rules)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_VersioningAttrPropagates(t *testing.T) {
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
|
||||
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
|
||||
s3_constants.ExtVersioningKey: []byte("Enabled"),
|
||||
})},
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, perr)
|
||||
require.Len(t, inputs, 1)
|
||||
assert.True(t, inputs[0].Versioned)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_MalformedXMLBecomesParseError(t *testing.T) {
|
||||
// Malformed XML must not abort the whole walk — surfacing it as a
|
||||
// ParseError lets operators see the bucket-level failure while
|
||||
// other buckets keep loading.
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: {
|
||||
bucketEntry("bad", map[string][]byte{
|
||||
BucketLifecycleConfigurationXMLKey: []byte("<not-valid-xml"),
|
||||
}),
|
||||
bucketEntry("good", map[string][]byte{
|
||||
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
|
||||
}),
|
||||
},
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, perr, 1)
|
||||
assert.Equal(t, "bad", perr[0].Bucket)
|
||||
assert.Error(t, perr[0].Err)
|
||||
|
||||
require.Len(t, inputs, 1)
|
||||
assert.Equal(t, "good", inputs[0].Bucket)
|
||||
}
|
||||
|
||||
func TestLoadCompileInputs_PaginatesAcrossPages(t *testing.T) {
|
||||
// pageSize is 1024 inside LoadCompileInputs; populate just over the
|
||||
// boundary to force a second listing call. Every bucket has the same
|
||||
// minimal config so the input count must equal the bucket count.
|
||||
const total = 1030
|
||||
entries := make([]*filer_pb.Entry, 0, total)
|
||||
for i := 0; i < total; i++ {
|
||||
entries = append(entries, bucketEntry(fmt.Sprintf("b%05d", i), map[string][]byte{
|
||||
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
|
||||
}))
|
||||
}
|
||||
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
|
||||
testBucketsRoot: entries,
|
||||
}}
|
||||
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, perr)
|
||||
require.Len(t, inputs, total, "pagination must surface every bucket")
|
||||
// Order is preserved across pages, and the page boundary at 1023/1024
|
||||
// (pageSize is 1024) must not skip or duplicate entries.
|
||||
assert.Equal(t, "b00000", inputs[0].Bucket)
|
||||
assert.Equal(t, "b01023", inputs[1023].Bucket, "last entry of first page")
|
||||
assert.Equal(t, "b01024", inputs[1024].Bucket, "first entry of second page")
|
||||
assert.Equal(t, fmt.Sprintf("b%05d", total-1), inputs[total-1].Bucket)
|
||||
}
|
||||
@@ -33,11 +33,12 @@ type Scheduler struct {
|
||||
ClientID int32
|
||||
ClientName string
|
||||
|
||||
Workers int
|
||||
DispatchTick time.Duration
|
||||
CheckpointTick time.Duration
|
||||
RefreshInterval time.Duration
|
||||
RetryBackoff time.Duration
|
||||
Workers int
|
||||
DispatchTick time.Duration
|
||||
CheckpointTick time.Duration
|
||||
RefreshInterval time.Duration
|
||||
BootstrapInterval time.Duration
|
||||
RetryBackoff time.Duration
|
||||
}
|
||||
|
||||
// Run blocks until ctx is canceled. Spawns Workers + 1 goroutines: one
|
||||
@@ -100,9 +101,10 @@ func (s *Scheduler) Run(ctx context.Context) error {
|
||||
}
|
||||
|
||||
bs := &BucketBootstrapper{
|
||||
FilerClient: s.FilerClient,
|
||||
BucketsPath: s.BucketsPath,
|
||||
Injector: pipelineFanout(pipelinesByShard),
|
||||
FilerClient: s.FilerClient,
|
||||
BucketsPath: s.BucketsPath,
|
||||
Injector: pipelineFanout(pipelinesByShard),
|
||||
BootstrapInterval: s.BootstrapInterval,
|
||||
}
|
||||
|
||||
s.refreshEngine(ctx, bs)
|
||||
|
||||
@@ -1,6 +1,76 @@
|
||||
package s3lifecycle
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// versionIdFormatThreshold distinguishes old vs new format version IDs.
|
||||
// New format (inverted timestamps) produces values above this threshold;
|
||||
// old format (raw timestamps) produces values below it.
|
||||
const versionIdFormatThreshold = 0x4000000000000000
|
||||
|
||||
// CompareVersionIds returns negative if a is newer than b, positive if b
|
||||
// is newer, 0 if equal. Mirrors compareVersionIds in s3api_version_id.go
|
||||
// (kept duplicated to avoid the s3api -> s3lifecycle import cycle). Used
|
||||
// as a tiebreak when version mtimes collide at second resolution.
|
||||
func CompareVersionIds(a, b string) int {
|
||||
if a == b {
|
||||
return 0
|
||||
}
|
||||
if a == "null" {
|
||||
return 1 // null sorts last
|
||||
}
|
||||
if b == "null" {
|
||||
return -1
|
||||
}
|
||||
aIsNew := isNewFormatVersionId(a)
|
||||
bIsNew := isNewFormatVersionId(b)
|
||||
if aIsNew == bIsNew {
|
||||
// Same format. New format (inverted timestamps) sorts smaller=newer
|
||||
// lexicographically; old format sorts smaller=older.
|
||||
if aIsNew {
|
||||
if a < b {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
if a < b {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
at := getVersionTimestamp(a)
|
||||
bt := getVersionTimestamp(b)
|
||||
if at > bt {
|
||||
return -1
|
||||
}
|
||||
if at < bt {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func isNewFormatVersionId(versionId string) bool {
|
||||
if len(versionId) < 16 || versionId == "null" {
|
||||
return false
|
||||
}
|
||||
t, err := strconv.ParseUint(versionId[:16], 16, 64)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return t > versionIdFormatThreshold
|
||||
}
|
||||
|
||||
func getVersionTimestamp(versionId string) int64 {
|
||||
if len(versionId) < 16 || versionId == "null" {
|
||||
return 0
|
||||
}
|
||||
t, err := strconv.ParseUint(versionId[:16], 16, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
if t > versionIdFormatThreshold {
|
||||
return int64(^uint64(0)>>1) - int64(t)
|
||||
}
|
||||
return int64(t)
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package s3lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// CompareVersionIds is the version-id tiebreak the router falls back to
|
||||
// when two versions land at the same mtime second; getting the format /
|
||||
// null / mixed-format axes wrong silently inverts retention rankings,
|
||||
// which would resurrect deleted versions or evict live ones. The tests
|
||||
// below pin every documented branch.
|
||||
|
||||
const (
|
||||
// 16-char hex prefix above 0x4000000000000000 → new-format inverted
|
||||
// timestamp.
|
||||
newFormatPrefix1 = "4123456789abcdef"
|
||||
newFormatPrefix2 = "5123456789abcdef" // strictly larger than prefix1
|
||||
// 16-char hex prefix at or below the threshold → old-format raw
|
||||
// timestamp.
|
||||
oldFormatPrefix1 = "0123456789abcdef"
|
||||
oldFormatPrefix2 = "0223456789abcdef" // strictly larger than prefix1
|
||||
)
|
||||
|
||||
func TestCompareVersionIds_EqualReturnsZero(t *testing.T) {
|
||||
assert.Equal(t, 0, CompareVersionIds("abc", "abc"))
|
||||
assert.Equal(t, 0, CompareVersionIds("null", "null"))
|
||||
assert.Equal(t, 0, CompareVersionIds("", ""))
|
||||
}
|
||||
|
||||
func TestCompareVersionIds_NullSortsLast(t *testing.T) {
|
||||
// "null" represents the bare pre-versioning entry; the router treats
|
||||
// it as older than any real version-id so genuine versions take
|
||||
// precedence in tiebreaks.
|
||||
assert.Equal(t, 1, CompareVersionIds("null", newFormatPrefix1))
|
||||
assert.Equal(t, 1, CompareVersionIds("null", oldFormatPrefix1))
|
||||
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, "null"))
|
||||
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix1, "null"))
|
||||
}
|
||||
|
||||
func TestCompareVersionIds_BothNewFormatSmallerIsNewer(t *testing.T) {
|
||||
// New-format encodes the timestamp inverted, so the lexicographically
|
||||
// smaller string represents a newer wall-clock time.
|
||||
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, newFormatPrefix2),
|
||||
"new-format: smaller lex → newer → -1")
|
||||
assert.Equal(t, 1, CompareVersionIds(newFormatPrefix2, newFormatPrefix1),
|
||||
"new-format: larger lex → older → 1")
|
||||
}
|
||||
|
||||
func TestCompareVersionIds_BothOldFormatLargerIsNewer(t *testing.T) {
|
||||
// Old-format encodes the timestamp raw, so the lexicographically
|
||||
// larger string is the newer wall-clock time.
|
||||
assert.Equal(t, 1, CompareVersionIds(oldFormatPrefix1, oldFormatPrefix2),
|
||||
"old-format: smaller lex → older → 1")
|
||||
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix2, oldFormatPrefix1),
|
||||
"old-format: larger lex → newer → -1")
|
||||
}
|
||||
|
||||
func TestCompareVersionIds_MixedFormatComparesByTimestamp(t *testing.T) {
|
||||
// New-format inverted timestamp = MaxInt64 - prefix; old-format raw =
|
||||
// prefix. With prefix1 = 0x4123… and old prefix1 = 0x0123… the
|
||||
// inverted new value is small but still positive, while the raw old
|
||||
// value is also small. Whichever is numerically larger wins.
|
||||
at := getVersionTimestamp(newFormatPrefix1)
|
||||
bt := getVersionTimestamp(oldFormatPrefix1)
|
||||
if at == bt {
|
||||
assert.Equal(t, 0, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
|
||||
return
|
||||
}
|
||||
if at > bt {
|
||||
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
|
||||
assert.Equal(t, 1, CompareVersionIds(oldFormatPrefix1, newFormatPrefix1))
|
||||
} else {
|
||||
assert.Equal(t, 1, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
|
||||
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix1, newFormatPrefix1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareVersionIds_MixedFormatEqualTimestampReturnsZero(t *testing.T) {
|
||||
// If a new-format inverted timestamp equals an old-format raw
|
||||
// timestamp, neither is newer — should be 0. We can synthesize this:
|
||||
// pick an old prefix P, the matching new prefix is MaxInt64 - P.
|
||||
old := uint64(0x0000000000010000)
|
||||
new_ := uint64(int64(^uint64(0)>>1) - int64(old))
|
||||
oldHex := uintToHex16(old)
|
||||
newHex := uintToHex16(new_)
|
||||
// Sanity: new_ must be above the threshold, otherwise it'd be parsed
|
||||
// as old-format and the test wouldn't exercise the mixed branch.
|
||||
if !isNewFormatVersionId(newHex) {
|
||||
t.Fatalf("constructed new-format prefix %q didn't classify as new", newHex)
|
||||
}
|
||||
if isNewFormatVersionId(oldHex) {
|
||||
t.Fatalf("constructed old-format prefix %q classified as new", oldHex)
|
||||
}
|
||||
assert.Equal(t, 0, CompareVersionIds(newHex, oldHex), "mixed-format equal timestamps must be 0")
|
||||
}
|
||||
|
||||
func TestIsNewFormatVersionId_TooShortRejected(t *testing.T) {
|
||||
// Strings shorter than 16 chars can't carry a hex timestamp prefix;
|
||||
// they must classify as old-format so getVersionTimestamp returns 0
|
||||
// rather than panic on slice bounds.
|
||||
assert.False(t, isNewFormatVersionId(""))
|
||||
assert.False(t, isNewFormatVersionId("4123"))
|
||||
assert.False(t, isNewFormatVersionId("4123456789abcde")) // 15 chars
|
||||
}
|
||||
|
||||
func TestIsNewFormatVersionId_NullRejected(t *testing.T) {
|
||||
assert.False(t, isNewFormatVersionId("null"))
|
||||
}
|
||||
|
||||
func TestIsNewFormatVersionId_NonHexRejected(t *testing.T) {
|
||||
// Parse failure on the 16-char prefix means the comparator falls
|
||||
// back to old-format treatment. Non-hex characters or surrounding
|
||||
// whitespace must reject without erroring out.
|
||||
assert.False(t, isNewFormatVersionId("zzzzzzzzzzzzzzzz"))
|
||||
assert.False(t, isNewFormatVersionId("0xff000000000000")) // "0x" prefix breaks ParseUint base-16
|
||||
assert.False(t, isNewFormatVersionId("ABC GHIJKLMNOPQR")) // space mid-string
|
||||
}
|
||||
|
||||
func TestIsNewFormatVersionId_ThresholdBoundary(t *testing.T) {
|
||||
// versionIdFormatThreshold = 0x4000000000000000. The check is
|
||||
// strictly greater than, so the threshold value itself must
|
||||
// classify as old-format.
|
||||
assert.False(t, isNewFormatVersionId("4000000000000000"), "exactly at threshold is old")
|
||||
assert.True(t, isNewFormatVersionId("4000000000000001"), "one above threshold is new")
|
||||
assert.False(t, isNewFormatVersionId("3fffffffffffffff"), "one below threshold is old")
|
||||
}
|
||||
|
||||
func TestGetVersionTimestamp_ReturnsZeroOnMalformed(t *testing.T) {
|
||||
assert.Equal(t, int64(0), getVersionTimestamp(""))
|
||||
assert.Equal(t, int64(0), getVersionTimestamp("null"))
|
||||
assert.Equal(t, int64(0), getVersionTimestamp("4123456789abcde")) // too short
|
||||
assert.Equal(t, int64(0), getVersionTimestamp("zzzzzzzzzzzzzzzz")) // not hex
|
||||
assert.Equal(t, int64(0), getVersionTimestamp("zzzzzzzzzzzzzzzzMORE")) // not hex prefix
|
||||
}
|
||||
|
||||
func TestGetVersionTimestamp_OldFormatReturnsRawValue(t *testing.T) {
|
||||
// Old-format: prefix below threshold, returned raw.
|
||||
assert.Equal(t, int64(0x0123456789abcdef), getVersionTimestamp(oldFormatPrefix1))
|
||||
assert.Equal(t, int64(0x0223456789abcdef), getVersionTimestamp(oldFormatPrefix2))
|
||||
// Trailing characters past the 16-char prefix are ignored.
|
||||
assert.Equal(t, int64(0x0123456789abcdef), getVersionTimestamp(oldFormatPrefix1+"-suffix"))
|
||||
}
|
||||
|
||||
func TestGetVersionTimestamp_NewFormatReturnsInvertedValue(t *testing.T) {
|
||||
// New-format inversion: int64 max - parsed value. So a smaller
|
||||
// stored prefix yields a larger inverted timestamp (= newer time).
|
||||
maxI64 := int64(^uint64(0) >> 1)
|
||||
assert.Equal(t, maxI64-int64(0x4123456789abcdef), getVersionTimestamp(newFormatPrefix1))
|
||||
assert.Equal(t, maxI64-int64(0x5123456789abcdef), getVersionTimestamp(newFormatPrefix2))
|
||||
// The smaller-prefix-=-newer-timestamp invariant the comparator
|
||||
// relies on:
|
||||
assert.Greater(t, getVersionTimestamp(newFormatPrefix1), getVersionTimestamp(newFormatPrefix2))
|
||||
}
|
||||
|
||||
// uintToHex16 turns a uint64 into a 16-char lowercase hex string,
|
||||
// padding with leading zeros. Used for synthesizing mixed-format
|
||||
// equal-timestamp pairs in TestCompareVersionIds_MixedFormatEqualTimestampReturnsZero.
|
||||
func uintToHex16(v uint64) string {
|
||||
const hex = "0123456789abcdef"
|
||||
out := make([]byte, 16)
|
||||
for i := 15; i >= 0; i-- {
|
||||
out[i] = hex[v&0xf]
|
||||
v >>= 4
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
@@ -68,6 +68,7 @@ func (c *commandS3LifecycleRunShard) Do(args []string, env *CommandEnv, writer i
|
||||
dispatchTick := fs.Duration("dispatch", 5*time.Second, "dispatcher tick cadence")
|
||||
checkpointTick := fs.Duration("checkpoint", 30*time.Second, "cursor checkpoint cadence")
|
||||
refreshInterval := fs.Duration("refresh", 5*time.Minute, "interval for rebuilding the engine snapshot from filer-backed bucket configs; 0 = compile once at startup")
|
||||
bootstrapInterval := fs.Duration("bootstrap-interval", 0, "cadence for revisiting each bucket's bootstrap walk; 0 = walk once per process. scan_only actions only fire from bootstrap, so a long-running worker needs a non-zero value to handle their retention horizon")
|
||||
runtime := fs.Duration("runtime", 0, "wall-clock cap on the run; 0 = no timeout. -events alone can hang on quiet shards")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
@@ -119,9 +120,10 @@ func (c *commandS3LifecycleRunShard) Do(args []string, env *CommandEnv, writer i
|
||||
}
|
||||
|
||||
bsr := &scheduler.BucketBootstrapper{
|
||||
FilerClient: filerClient,
|
||||
BucketsPath: bucketsPath,
|
||||
Injector: pipeline,
|
||||
FilerClient: filerClient,
|
||||
BucketsPath: bucketsPath,
|
||||
Injector: pipeline,
|
||||
BootstrapInterval: *bootstrapInterval,
|
||||
}
|
||||
bootstrapCtx, bootstrapCancel := context.WithCancel(context.Background())
|
||||
defer bootstrapCancel()
|
||||
|
||||
@@ -577,6 +577,21 @@ var (
|
||||
Name: "bootstrap_dispatch_total",
|
||||
Help: "Counter of bootstrap-walk Delete dispatches by bucket and action kind.",
|
||||
}, []string{"bucket", "kind"})
|
||||
|
||||
// S3LifecycleMetadataOnlyCounter counts successful LifecycleDelete
|
||||
// dispatches that took the metadata-only path — entry was removed
|
||||
// without per-chunk DeleteFile RPCs because the entry's Attributes
|
||||
// .TtlSec > 0 and the volume's natural TTL will reclaim chunks. Per-
|
||||
// rule cardinality (rule_hash hex-encoded) lets operators identify
|
||||
// which specific rule is exercising the optimization; in clusters
|
||||
// with many rules this can be reduced via Prometheus relabeling.
|
||||
S3LifecycleMetadataOnlyCounter = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: Namespace,
|
||||
Subsystem: "s3_lifecycle",
|
||||
Name: "metadata_only_total",
|
||||
Help: "Counter of LifecycleDelete completions that skipped per-chunk delete (volume TTL reclaim).",
|
||||
}, []string{"bucket", "rule_hash"})
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -652,6 +667,7 @@ func init() {
|
||||
Gather.MustRegister(S3LifecycleCursorMinTsNs)
|
||||
Gather.MustRegister(S3LifecycleEventCounter)
|
||||
Gather.MustRegister(S3LifecycleBootstrapDispatchCounter)
|
||||
Gather.MustRegister(S3LifecycleMetadataOnlyCounter)
|
||||
|
||||
Gather.MustRegister(UploadErrorCounter)
|
||||
|
||||
@@ -727,6 +743,7 @@ func DeleteBucketMetrics(bucket string) {
|
||||
c += S3BucketObjectCountGauge.DeletePartialMatch(labels)
|
||||
c += S3LifecycleDispatchCounter.DeletePartialMatch(labels)
|
||||
c += S3LifecycleBootstrapDispatchCounter.DeletePartialMatch(labels)
|
||||
c += S3LifecycleMetadataOnlyCounter.DeletePartialMatch(labels)
|
||||
|
||||
glog.V(0).Infof("delete bucket metrics, %s: %d", bucket, c)
|
||||
}
|
||||
|
||||
+39
-24
@@ -394,12 +394,7 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
collectionVolumeDeletedBytes := make(map[string]int64)
|
||||
collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
|
||||
for _, location := range s.Locations {
|
||||
// keepRemoteData is parallel to deleteVids: true entries preserve the
|
||||
// cloud-tier object on Volume.Destroy. IO-error deletions on a
|
||||
// remote-tiered volume must not nuke the remote object — the error
|
||||
// is local/transient and the cloud copy is the source of truth.
|
||||
var deleteVids []needle.VolumeId
|
||||
var keepRemoteData []bool
|
||||
effectiveMaxCount := location.MaxVolumeCount
|
||||
if location.isDiskSpaceLow {
|
||||
usedSlots := int32(location.LocalVolumesLen())
|
||||
@@ -420,26 +415,42 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
if maxFileKey < curMaxFileKey {
|
||||
maxFileKey = curMaxFileKey
|
||||
}
|
||||
shouldDeleteVolume := false
|
||||
|
||||
if v.lastIoError != nil {
|
||||
deleteVids = append(deleteVids, v.Id)
|
||||
keepRemoteData = append(keepRemoteData, v.HasRemoteFile())
|
||||
shouldDeleteVolume = true
|
||||
glog.Warningf("volume %d has IO error: %v", v.Id, v.lastIoError)
|
||||
ioErr, ioCount, quarantined := v.getIoErrorState()
|
||||
if quarantined || (ioErr != nil && ioCount >= IoErrorTolerance) {
|
||||
// Sustained EIO: stop announcing this replica so the master
|
||||
// re-replicates from healthy peers, and mark it read-only
|
||||
// so further writes fail fast instead of producing more
|
||||
// EIOs. Never physically delete the data — the disk may
|
||||
// be transiently bad and this could be the last good
|
||||
// copy. The quarantine is sticky: a stray successful read
|
||||
// clears the streak counter but must not silently put a
|
||||
// known-bad replica back into rotation; recovery is via
|
||||
// MarkVolumeWritable.
|
||||
if !quarantined {
|
||||
glog.Warningf("volume %d quarantined after %d consecutive IO errors: %v",
|
||||
v.Id, ioCount, ioErr)
|
||||
v.markIoQuarantined()
|
||||
}
|
||||
v.noWriteLock.Lock()
|
||||
v.noWriteOrDelete = true
|
||||
v.noWriteLock.Unlock()
|
||||
// Skip per-volume size and read-only bookkeeping: a
|
||||
// quarantined replica should not be summed into the
|
||||
// collection's reported total nor counted in the
|
||||
// read-only stats.
|
||||
continue
|
||||
}
|
||||
|
||||
shouldDeleteVolume := false
|
||||
if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
|
||||
volumeMessages = append(volumeMessages, volumeMessage)
|
||||
} else {
|
||||
if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
|
||||
volumeMessages = append(volumeMessages, volumeMessage)
|
||||
if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
|
||||
deleteVids = append(deleteVids, v.Id)
|
||||
shouldDeleteVolume = true
|
||||
} else {
|
||||
if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
|
||||
if !shouldDeleteVolume {
|
||||
deleteVids = append(deleteVids, v.Id)
|
||||
keepRemoteData = append(keepRemoteData, false)
|
||||
shouldDeleteVolume = true
|
||||
}
|
||||
} else {
|
||||
glog.V(0).Infof("volume %d is expired", v.Id)
|
||||
}
|
||||
glog.V(0).Infof("volume %d is expired", v.Id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,8 +494,8 @@ func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
|
||||
if len(deleteVids) > 0 {
|
||||
// delete expired volumes.
|
||||
location.volumesLock.Lock()
|
||||
for i, vid := range deleteVids {
|
||||
found, err := location.deleteVolumeById(vid, false, keepRemoteData[i])
|
||||
for _, vid := range deleteVids {
|
||||
found, err := location.deleteVolumeById(vid, false, false)
|
||||
if err == nil {
|
||||
if found {
|
||||
glog.V(0).Infof("volume %d is deleted", vid)
|
||||
@@ -678,6 +689,10 @@ func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
|
||||
v.noWriteOrDelete = false
|
||||
v.PersistReadOnly(false)
|
||||
v.noWriteLock.Unlock()
|
||||
// Clear the EIO streak and the sticky quarantine flag so the next
|
||||
// CollectHeartbeat can announce the volume again. If the disk is
|
||||
// still bad, the next failed op will re-arm the streak.
|
||||
v.resetIoErrorState()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+71
-1
@@ -53,7 +53,77 @@ type Volume struct {
|
||||
location *DiskLocation
|
||||
diskId uint32 // ID of this volume's disk in Store.Locations array
|
||||
|
||||
lastIoError error
|
||||
// lastIoError is the most recent EIO from a read/write/delete; cleared
|
||||
// on the next successful or non-EIO op. lastIoErrorCount tracks
|
||||
// consecutive EIOs so CollectHeartbeat can require a sustained failure
|
||||
// before unmounting the replica — protects against a transient
|
||||
// hardware/network blip hitting multiple replicas at once and
|
||||
// stranding the only good copy.
|
||||
//
|
||||
// ioErrorQuarantined is sticky: once CollectHeartbeat sees the streak
|
||||
// cross IoErrorTolerance it sets this and never clears it on its own.
|
||||
// A subsequent successful read clears the streak counter but must NOT
|
||||
// un-quarantine the volume — only MarkVolumeWritable does that, after
|
||||
// an operator has decided the disk is healthy. Without the sticky
|
||||
// bit, one good read between heartbeats would silently put a known-
|
||||
// bad replica back into rotation.
|
||||
//
|
||||
// All four fields are guarded together so the heartbeat reader sees
|
||||
// a consistent snapshot.
|
||||
lastIoError error
|
||||
lastIoErrorCount int32
|
||||
ioErrorQuarantined bool
|
||||
lastIoErrorLock sync.RWMutex
|
||||
}
|
||||
|
||||
// noteIoError records an EIO and increments the consecutive-error
|
||||
// counter. Caller has already verified errors.Is(err, syscall.EIO).
|
||||
func (v *Volume) noteIoError(err error) {
|
||||
v.lastIoErrorLock.Lock()
|
||||
defer v.lastIoErrorLock.Unlock()
|
||||
v.lastIoError = err
|
||||
v.lastIoErrorCount++
|
||||
}
|
||||
|
||||
// clearIoError resets the EIO streak counter only. The sticky quarantine
|
||||
// bit set by CollectHeartbeat is intentionally left alone — recovery is
|
||||
// an operator decision via MarkVolumeWritable. Called on any successful
|
||||
// op or on a non-EIO error (which still breaks the EIO streak; only
|
||||
// sustained EIOs are diagnostic of a failing volume).
|
||||
func (v *Volume) clearIoError() {
|
||||
v.lastIoErrorLock.Lock()
|
||||
defer v.lastIoErrorLock.Unlock()
|
||||
v.lastIoError = nil
|
||||
v.lastIoErrorCount = 0
|
||||
}
|
||||
|
||||
// resetIoErrorState clears both the EIO streak and the sticky quarantine
|
||||
// flag. Used by MarkVolumeWritable to rejoin a previously-quarantined
|
||||
// replica; if the disk is still bad, the next failed op re-arms the
|
||||
// streak.
|
||||
func (v *Volume) resetIoErrorState() {
|
||||
v.lastIoErrorLock.Lock()
|
||||
defer v.lastIoErrorLock.Unlock()
|
||||
v.lastIoError = nil
|
||||
v.lastIoErrorCount = 0
|
||||
v.ioErrorQuarantined = false
|
||||
}
|
||||
|
||||
// markIoQuarantined sets the sticky quarantine flag. Idempotent; safe
|
||||
// to call from CollectHeartbeat each pass while the volume remains
|
||||
// quarantined.
|
||||
func (v *Volume) markIoQuarantined() {
|
||||
v.lastIoErrorLock.Lock()
|
||||
defer v.lastIoErrorLock.Unlock()
|
||||
v.ioErrorQuarantined = true
|
||||
}
|
||||
|
||||
// getIoErrorState returns the latest EIO, the consecutive-EIO count,
|
||||
// and the sticky quarantine flag as one consistent snapshot.
|
||||
func (v *Volume) getIoErrorState() (error, int32, bool) {
|
||||
v.lastIoErrorLock.RLock()
|
||||
defer v.lastIoErrorLock.RUnlock()
|
||||
return v.lastIoError, v.lastIoErrorCount, v.ioErrorQuarantined
|
||||
}
|
||||
|
||||
func NewVolume(dirname string, dirIdx string, collection string, id needle.VolumeId, needleMapKind NeedleMapKind, replicaPlacement *super_block.ReplicaPlacement, ttl *needle.TTL, preallocate int64, ver needle.Version, memoryMapMaxSizeMb uint32, ldbTimeout int64) (v *Volume, e error) {
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
// eioBackend is a backend.BackendStorageFile that returns EIO from
|
||||
// every ReadAt — used to verify the streaming read path threads
|
||||
// errors through checkReadWriteError.
|
||||
type eioBackend struct{}
|
||||
|
||||
func (eioBackend) ReadAt(p []byte, off int64) (int, error) { return 0, syscall.EIO }
|
||||
func (eioBackend) WriteAt(p []byte, off int64) (int, error) {
|
||||
return len(p), nil
|
||||
}
|
||||
func (eioBackend) Truncate(int64) error { return nil }
|
||||
func (eioBackend) Close() error { return nil }
|
||||
func (eioBackend) GetStat() (int64, time.Time, error) { return 0, time.Time{}, nil }
|
||||
func (eioBackend) Name() string { return "eio" }
|
||||
func (eioBackend) Sync() error { return nil }
|
||||
|
||||
func TestCheckReadWriteErrorTracksConsecutiveEIO(t *testing.T) {
|
||||
v := &Volume{}
|
||||
|
||||
// each EIO bumps the counter.
|
||||
for i := int32(1); i <= 5; i++ {
|
||||
v.checkReadWriteError(fmt.Errorf("disk failed: %w", syscall.EIO))
|
||||
_, count, _ := v.getIoErrorState()
|
||||
if count != i {
|
||||
t.Fatalf("after %d EIO(s): counter = %d, want %d", i, count, i)
|
||||
}
|
||||
}
|
||||
|
||||
// a single success resets the streak (but not the quarantine flag,
|
||||
// which is not set here).
|
||||
v.checkReadWriteError(nil)
|
||||
if err, count, q := v.getIoErrorState(); err != nil || count != 0 || q {
|
||||
t.Fatalf("success did not reset state: err=%v count=%d quarantined=%v", err, count, q)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckReadWriteErrorNonEIOResetsStreak(t *testing.T) {
|
||||
v := &Volume{}
|
||||
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
if _, count, _ := v.getIoErrorState(); count != 2 {
|
||||
t.Fatalf("expected count=2 after two EIOs, got %d", count)
|
||||
}
|
||||
|
||||
// a non-EIO error breaks the streak — only sustained EIOs are
|
||||
// diagnostic of a failing disk.
|
||||
v.checkReadWriteError(fmt.Errorf("other: %w", syscall.ENOSPC))
|
||||
if err, count, _ := v.getIoErrorState(); err != nil || count != 0 {
|
||||
t.Fatalf("non-EIO did not reset streak: err=%v count=%d", err, count)
|
||||
}
|
||||
|
||||
// a fresh EIO starts the streak from 1, not 3.
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
if _, count, _ := v.getIoErrorState(); count != 1 {
|
||||
t.Fatalf("EIO after non-EIO did not restart streak: count=%d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckReadWriteErrorIgnoresPlainError(t *testing.T) {
|
||||
v := &Volume{}
|
||||
|
||||
v.checkReadWriteError(errors.New("some other error"))
|
||||
if err, count, _ := v.getIoErrorState(); err != nil || count != 0 {
|
||||
t.Fatalf("non-EIO with no prior streak set state: err=%v count=%d", err, count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIoErrorToleranceGate(t *testing.T) {
|
||||
v := &Volume{}
|
||||
|
||||
for i := 0; i < IoErrorTolerance-1; i++ {
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
}
|
||||
if _, count, _ := v.getIoErrorState(); count >= IoErrorTolerance {
|
||||
t.Fatalf("counter %d already crossed tolerance %d after %d errors",
|
||||
count, IoErrorTolerance, IoErrorTolerance-1)
|
||||
}
|
||||
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
if _, count, _ := v.getIoErrorState(); count < IoErrorTolerance {
|
||||
t.Fatalf("counter %d below tolerance %d after %d errors",
|
||||
count, IoErrorTolerance, IoErrorTolerance)
|
||||
}
|
||||
}
|
||||
|
||||
// Once CollectHeartbeat marks a replica quarantined, a stray successful
|
||||
// read must NOT silently put a known-bad disk back into rotation. Only
|
||||
// MarkVolumeWritable (resetIoErrorState) clears the sticky bit.
|
||||
func TestQuarantineIsSticky(t *testing.T) {
|
||||
v := &Volume{}
|
||||
|
||||
for i := 0; i < IoErrorTolerance; i++ {
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
}
|
||||
v.markIoQuarantined()
|
||||
|
||||
if _, _, q := v.getIoErrorState(); !q {
|
||||
t.Fatalf("markIoQuarantined did not set the flag")
|
||||
}
|
||||
|
||||
// A successful read clears the streak counter…
|
||||
v.checkReadWriteError(nil)
|
||||
if _, count, q := v.getIoErrorState(); count != 0 {
|
||||
t.Fatalf("success did not clear streak: count=%d", count)
|
||||
} else if !q {
|
||||
t.Fatalf("success cleared the sticky quarantine flag — operator-only recovery violated")
|
||||
}
|
||||
|
||||
// …and a non-EIO error also clears the streak but not the flag.
|
||||
v.checkReadWriteError(fmt.Errorf("other: %w", syscall.ENOSPC))
|
||||
if _, _, q := v.getIoErrorState(); !q {
|
||||
t.Fatalf("non-EIO cleared the sticky quarantine flag")
|
||||
}
|
||||
|
||||
// Only resetIoErrorState (used by MarkVolumeWritable) un-quarantines.
|
||||
v.resetIoErrorState()
|
||||
if err, count, q := v.getIoErrorState(); err != nil || count != 0 || q {
|
||||
t.Fatalf("resetIoErrorState left state: err=%v count=%d quarantined=%v", err, count, q)
|
||||
}
|
||||
}
|
||||
|
||||
// Streaming/range reads (ReadNeedleBlob) used to bypass the EIO
|
||||
// counter, so a failing disk taking range GETs all day would never
|
||||
// trip IoErrorTolerance. ReadNeedleBlob now threads the backend error
|
||||
// through checkReadWriteError; one EIO must bump the streak by one.
|
||||
func TestReadNeedleBlobTracksEIO(t *testing.T) {
|
||||
v := &Volume{
|
||||
DataBackend: eioBackend{},
|
||||
SuperBlock: super_block.SuperBlock{Version: needle.GetCurrentVersion()},
|
||||
volumeInfo: &volume_server_pb.VolumeInfo{Version: uint32(needle.GetCurrentVersion())},
|
||||
}
|
||||
|
||||
if _, err := v.ReadNeedleBlob(0, 1); !errors.Is(err, syscall.EIO) {
|
||||
t.Fatalf("expected EIO from fake backend, got %v", err)
|
||||
}
|
||||
if _, count, _ := v.getIoErrorState(); count != 1 {
|
||||
t.Fatalf("ReadNeedleBlob did not bump EIO streak: count=%d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIoErrorStateIsRaceFree(t *testing.T) {
|
||||
// Relies on `go test -race` to detect any unprotected access on
|
||||
// lastIoError / lastIoErrorCount / ioErrorQuarantined.
|
||||
v := &Volume{}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
v.checkReadWriteError(fmt.Errorf("eio: %w", syscall.EIO))
|
||||
}
|
||||
}
|
||||
}()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
v.checkReadWriteError(nil)
|
||||
}
|
||||
}
|
||||
}()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
v.markIoQuarantined()
|
||||
v.resetIoErrorState()
|
||||
}
|
||||
}
|
||||
}()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 1000; i++ {
|
||||
v.getIoErrorState()
|
||||
}
|
||||
close(stop)
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -180,6 +180,14 @@ func (v *Volume) readNeedleDataInto(n *needle.Needle, readOption *ReadOption, wr
|
||||
if readOption.HasSlowRead {
|
||||
v.dataFileAccessLock.RUnlock()
|
||||
}
|
||||
// Thread the underlying read error through the EIO tracker.
|
||||
// Without this, large/range GETs through readNeedleDataInto
|
||||
// would never trip IoErrorTolerance even on a failing disk.
|
||||
// io.EOF is treated as a clean end-of-stream below, not an
|
||||
// error.
|
||||
if err != nil && err != io.EOF {
|
||||
v.checkReadWriteError(err)
|
||||
}
|
||||
|
||||
toWrite := min(count, int(offset+size-x))
|
||||
if toWrite > 0 {
|
||||
@@ -201,6 +209,11 @@ func (v *Volume) readNeedleDataInto(n *needle.Needle, readOption *ReadOption, wr
|
||||
break
|
||||
}
|
||||
}
|
||||
// Whole-needle read completed without a backend error — clear any
|
||||
// pending EIO streak. If a non-EIO failure happens later (CRC etc.)
|
||||
// we still return that error to the caller, but the disk itself
|
||||
// produced clean bytes.
|
||||
v.checkReadWriteError(nil)
|
||||
if offset == 0 && size == int64(n.DataSize) && (n.Checksum != crc && uint32(n.Checksum) != crc.Value()) {
|
||||
// the crc.Value() function is to be deprecated. this double checking is for backward compatibility
|
||||
// with seaweed version using crc.Value() instead of uint32(crc), which appears in commit 056c480eb
|
||||
@@ -224,7 +237,9 @@ func (v *Volume) ReadNeedleBlob(offset int64, size Size) ([]byte, error) {
|
||||
v.dataFileAccessLock.RLock()
|
||||
defer v.dataFileAccessLock.RUnlock()
|
||||
|
||||
return needle.ReadNeedleBlob(v.DataBackend, offset, size, v.Version())
|
||||
blob, err := needle.ReadNeedleBlob(v.DataBackend, offset, size, v.Version())
|
||||
v.checkReadWriteError(err)
|
||||
return blob, err
|
||||
}
|
||||
|
||||
type VolumeFileScanner interface {
|
||||
|
||||
@@ -17,16 +17,25 @@ var ErrorNotFound = errors.New("not found")
|
||||
var ErrorDeleted = errors.New("already deleted")
|
||||
var ErrorSizeMismatch = errors.New("size mismatch")
|
||||
|
||||
// IoErrorTolerance is the number of consecutive EIOs a volume must
|
||||
// see before CollectHeartbeat treats the replica as broken. A single
|
||||
// transient error is forgiven so a brief NFS / fabric / power blip
|
||||
// affecting several replicas at once does not cascade into removal of
|
||||
// the last healthy copy.
|
||||
const IoErrorTolerance = 3
|
||||
|
||||
func (v *Volume) checkReadWriteError(err error) {
|
||||
if err == nil {
|
||||
if v.lastIoError != nil {
|
||||
v.lastIoError = nil
|
||||
}
|
||||
v.clearIoError()
|
||||
return
|
||||
}
|
||||
if errors.Is(err, syscall.EIO) {
|
||||
v.lastIoError = err
|
||||
v.noteIoError(err)
|
||||
return
|
||||
}
|
||||
// non-EIO error breaks the EIO streak — only sustained EIOs should
|
||||
// be treated as a failing volume.
|
||||
v.clearIoError()
|
||||
}
|
||||
|
||||
// isFileUnchanged checks whether this needle to write is same as last one.
|
||||
|
||||
@@ -9,31 +9,34 @@ import (
|
||||
const (
|
||||
jobType = "s3_lifecycle"
|
||||
|
||||
defaultWorkers = 1
|
||||
defaultDispatchTickMinutes = int64(1)
|
||||
defaultCheckpointTickSeconds = int64(30)
|
||||
defaultRefreshIntervalMinutes = int64(5)
|
||||
defaultMaxRuntimeMinutes = int64(60)
|
||||
defaultWorkers = 1
|
||||
defaultDispatchTickMinutes = int64(1)
|
||||
defaultCheckpointTickSeconds = int64(30)
|
||||
defaultRefreshIntervalMinutes = int64(5)
|
||||
defaultMaxRuntimeMinutes = int64(60)
|
||||
defaultBootstrapIntervalMinutes = int64(0) // 0 = walk once per process
|
||||
)
|
||||
|
||||
// Config is the parsed AdminConfigForm + WorkerConfigForm view.
|
||||
type Config struct {
|
||||
Workers int
|
||||
DispatchTick time.Duration
|
||||
CheckpointTick time.Duration
|
||||
RefreshInterval time.Duration
|
||||
MaxRuntime time.Duration
|
||||
Workers int
|
||||
DispatchTick time.Duration
|
||||
CheckpointTick time.Duration
|
||||
RefreshInterval time.Duration
|
||||
BootstrapInterval time.Duration
|
||||
MaxRuntime time.Duration
|
||||
}
|
||||
|
||||
// ParseConfig pulls the lifecycle Handler config from the merged
|
||||
// admin+worker config values. Missing fields fall back to defaults.
|
||||
func ParseConfig(adminValues, workerValues map[string]*plugin_pb.ConfigValue) Config {
|
||||
cfg := Config{
|
||||
Workers: int(readInt64(adminValues, "workers", defaultWorkers)),
|
||||
DispatchTick: time.Duration(readInt64(workerValues, "dispatch_tick_minutes", defaultDispatchTickMinutes)) * time.Minute,
|
||||
CheckpointTick: time.Duration(readInt64(workerValues, "checkpoint_tick_seconds", defaultCheckpointTickSeconds)) * time.Second,
|
||||
RefreshInterval: time.Duration(readInt64(workerValues, "refresh_interval_minutes", defaultRefreshIntervalMinutes)) * time.Minute,
|
||||
MaxRuntime: time.Duration(readInt64(workerValues, "max_runtime_minutes", defaultMaxRuntimeMinutes)) * time.Minute,
|
||||
Workers: int(readInt64(adminValues, "workers", defaultWorkers)),
|
||||
DispatchTick: time.Duration(readInt64(workerValues, "dispatch_tick_minutes", defaultDispatchTickMinutes)) * time.Minute,
|
||||
CheckpointTick: time.Duration(readInt64(workerValues, "checkpoint_tick_seconds", defaultCheckpointTickSeconds)) * time.Second,
|
||||
RefreshInterval: time.Duration(readInt64(workerValues, "refresh_interval_minutes", defaultRefreshIntervalMinutes)) * time.Minute,
|
||||
BootstrapInterval: time.Duration(readInt64(workerValues, "bootstrap_interval_minutes", defaultBootstrapIntervalMinutes)) * time.Minute,
|
||||
MaxRuntime: time.Duration(readInt64(workerValues, "max_runtime_minutes", defaultMaxRuntimeMinutes)) * time.Minute,
|
||||
}
|
||||
if cfg.Workers <= 0 {
|
||||
cfg.Workers = defaultWorkers
|
||||
@@ -47,6 +50,13 @@ func ParseConfig(adminValues, workerValues map[string]*plugin_pb.ConfigValue) Co
|
||||
if cfg.RefreshInterval <= 0 {
|
||||
cfg.RefreshInterval = time.Duration(defaultRefreshIntervalMinutes) * time.Minute
|
||||
}
|
||||
// BootstrapInterval is intentionally NOT clamped — zero means
|
||||
// "walk once per process", which is the legacy default for any
|
||||
// deployment that hasn't opted into a cadence yet. Negative values
|
||||
// fall back to zero.
|
||||
if cfg.BootstrapInterval < 0 {
|
||||
cfg.BootstrapInterval = 0
|
||||
}
|
||||
if cfg.MaxRuntime <= 0 {
|
||||
cfg.MaxRuntime = time.Duration(defaultMaxRuntimeMinutes) * time.Minute
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ func TestParseConfigDefaults(t *testing.T) {
|
||||
if cfg.MaxRuntime != 60*time.Minute {
|
||||
t.Errorf("MaxRuntime default=%v, want 60m", cfg.MaxRuntime)
|
||||
}
|
||||
if cfg.BootstrapInterval != 0 {
|
||||
t.Errorf("BootstrapInterval default=%v, want 0 (walk-once-per-process)", cfg.BootstrapInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfigOverrides(t *testing.T) {
|
||||
@@ -31,10 +34,11 @@ func TestParseConfigOverrides(t *testing.T) {
|
||||
"workers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 4}},
|
||||
}
|
||||
worker := map[string]*plugin_pb.ConfigValue{
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 15}},
|
||||
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 10}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 15}},
|
||||
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 10}},
|
||||
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
|
||||
}
|
||||
cfg := ParseConfig(admin, worker)
|
||||
if cfg.Workers != 4 {
|
||||
@@ -49,6 +53,9 @@ func TestParseConfigOverrides(t *testing.T) {
|
||||
if cfg.RefreshInterval != 10*time.Minute {
|
||||
t.Errorf("RefreshInterval=%v, want 10m", cfg.RefreshInterval)
|
||||
}
|
||||
if cfg.BootstrapInterval != 120*time.Minute {
|
||||
t.Errorf("BootstrapInterval=%v, want 120m", cfg.BootstrapInterval)
|
||||
}
|
||||
if cfg.MaxRuntime != 120*time.Minute {
|
||||
t.Errorf("MaxRuntime=%v, want 120m", cfg.MaxRuntime)
|
||||
}
|
||||
@@ -56,10 +63,11 @@ func TestParseConfigOverrides(t *testing.T) {
|
||||
|
||||
func TestParseConfigClampsZeroAndNegative(t *testing.T) {
|
||||
worker := map[string]*plugin_pb.ConfigValue{
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -5}},
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -5}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -5}},
|
||||
}
|
||||
cfg := ParseConfig(nil, worker)
|
||||
if cfg.DispatchTick != 1*time.Minute {
|
||||
@@ -71,7 +79,23 @@ func TestParseConfigClampsZeroAndNegative(t *testing.T) {
|
||||
if cfg.RefreshInterval != 5*time.Minute {
|
||||
t.Errorf("zero RefreshInterval should clamp to default, got %v", cfg.RefreshInterval)
|
||||
}
|
||||
if cfg.BootstrapInterval != 0 {
|
||||
t.Errorf("negative BootstrapInterval should clamp to 0, got %v", cfg.BootstrapInterval)
|
||||
}
|
||||
if cfg.MaxRuntime != 60*time.Minute {
|
||||
t.Errorf("negative MaxRuntime should clamp to default, got %v", cfg.MaxRuntime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfigBootstrapIntervalZeroIsLegacy(t *testing.T) {
|
||||
// Explicit zero stays zero (walk-once-per-process). Existing
|
||||
// deployments that don't set bootstrap_interval_minutes get the
|
||||
// legacy behavior unchanged.
|
||||
worker := map[string]*plugin_pb.ConfigValue{
|
||||
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
}
|
||||
cfg := ParseConfig(nil, worker)
|
||||
if cfg.BootstrapInterval != 0 {
|
||||
t.Errorf("zero BootstrapInterval must stay zero, got %v", cfg.BootstrapInterval)
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,14 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 1}},
|
||||
},
|
||||
{
|
||||
Name: "bootstrap_interval_minutes",
|
||||
Label: "Bootstrap Re-walk Interval (minutes)",
|
||||
Description: "How often each bucket is re-walked. scan_only rules — those whose retention horizon exceeds meta-log retention — only fire from the bootstrap walk, so a non-zero value is required to enforce them on a long-running worker. 0 keeps the legacy walk-once-per-process behavior.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
},
|
||||
{
|
||||
Name: "max_runtime_minutes",
|
||||
Label: "Max Runtime (minutes)",
|
||||
@@ -134,10 +142,11 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
},
|
||||
},
|
||||
DefaultValues: map[string]*plugin_pb.ConfigValue{
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDispatchTickMinutes}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultCheckpointTickSeconds}},
|
||||
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultRefreshIntervalMinutes}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxRuntimeMinutes}},
|
||||
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDispatchTickMinutes}},
|
||||
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultCheckpointTickSeconds}},
|
||||
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultRefreshIntervalMinutes}},
|
||||
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultBootstrapIntervalMinutes}},
|
||||
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxRuntimeMinutes}},
|
||||
},
|
||||
},
|
||||
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
|
||||
@@ -240,17 +249,18 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
|
||||
rpc := s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(s3Conn)
|
||||
|
||||
sched := &scheduler.Scheduler{
|
||||
BucketsPath: bucketsPath,
|
||||
Engine: engine.New(),
|
||||
Persister: &dispatcher.FilerPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
|
||||
Client: lifecycleRPCAdapter{c: rpc},
|
||||
FilerClient: filerClient,
|
||||
ClientID: util.RandomInt32(),
|
||||
ClientName: "worker-s3-lifecycle",
|
||||
Workers: cfg.Workers,
|
||||
DispatchTick: cfg.DispatchTick,
|
||||
CheckpointTick: cfg.CheckpointTick,
|
||||
RefreshInterval: cfg.RefreshInterval,
|
||||
BucketsPath: bucketsPath,
|
||||
Engine: engine.New(),
|
||||
Persister: &dispatcher.FilerPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
|
||||
Client: lifecycleRPCAdapter{c: rpc},
|
||||
FilerClient: filerClient,
|
||||
ClientID: util.RandomInt32(),
|
||||
ClientName: "worker-s3-lifecycle",
|
||||
Workers: cfg.Workers,
|
||||
DispatchTick: cfg.DispatchTick,
|
||||
CheckpointTick: cfg.CheckpointTick,
|
||||
RefreshInterval: cfg.RefreshInterval,
|
||||
BootstrapInterval: cfg.BootstrapInterval,
|
||||
}
|
||||
if err := sched.Run(runCtx); err != nil {
|
||||
glog.Warningf("s3 lifecycle execute: %v", err)
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
package s3_lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Tests cover the worker-handler surface that runs without a live filer
|
||||
// or S3 server: pure helpers (clusterS3Endpoints, readString),
|
||||
// Capability/Descriptor sanity, and the Detect input-validation /
|
||||
// skip-activity / proposal paths driven by a recorder sender.
|
||||
|
||||
// recordingSender captures everything the handler sends so each Detect
|
||||
// case can assert on activities, proposals, and completion.
|
||||
type recordingSender struct {
|
||||
proposals []*plugin_pb.DetectionProposals
|
||||
completes []*plugin_pb.DetectionComplete
|
||||
activities []*plugin_pb.ActivityEvent
|
||||
// errOn forces the named send to fail; lets tests cover the
|
||||
// SendComplete error-propagation path without a full transport stub.
|
||||
errOn map[string]error
|
||||
}
|
||||
|
||||
func (r *recordingSender) SendProposals(p *plugin_pb.DetectionProposals) error {
|
||||
if err := r.errOn["proposals"]; err != nil {
|
||||
return err
|
||||
}
|
||||
r.proposals = append(r.proposals, p)
|
||||
return nil
|
||||
}
|
||||
func (r *recordingSender) SendComplete(c *plugin_pb.DetectionComplete) error {
|
||||
if err := r.errOn["complete"]; err != nil {
|
||||
return err
|
||||
}
|
||||
r.completes = append(r.completes, c)
|
||||
return nil
|
||||
}
|
||||
func (r *recordingSender) SendActivity(a *plugin_pb.ActivityEvent) error {
|
||||
if err := r.errOn["activity"]; err != nil {
|
||||
return err
|
||||
}
|
||||
r.activities = append(r.activities, a)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------- clusterS3Endpoints ----------
|
||||
|
||||
func TestClusterS3Endpoints_NilContext(t *testing.T) {
|
||||
// A nil ClusterContext occurs in early-bootstrap detect calls; the
|
||||
// handler must return an empty slice rather than panic.
|
||||
assert.Nil(t, clusterS3Endpoints(nil))
|
||||
}
|
||||
|
||||
func TestClusterS3Endpoints_EmptyList(t *testing.T) {
|
||||
assert.Empty(t, clusterS3Endpoints(&plugin_pb.ClusterContext{}))
|
||||
}
|
||||
|
||||
func TestClusterS3Endpoints_FiltersEmptyEntries(t *testing.T) {
|
||||
// An empty-string address represents a stale registry entry the
|
||||
// master is about to evict; never dial that. Order of the surviving
|
||||
// entries must be preserved so the handler dials a deterministic
|
||||
// host across detect runs.
|
||||
cc := &plugin_pb.ClusterContext{S3GrpcAddresses: []string{"s3a:8333", "", "s3b:8333", ""}}
|
||||
assert.Equal(t, []string{"s3a:8333", "s3b:8333"}, clusterS3Endpoints(cc))
|
||||
}
|
||||
|
||||
func TestClusterS3Endpoints_AllValid(t *testing.T) {
|
||||
cc := &plugin_pb.ClusterContext{S3GrpcAddresses: []string{"s3a:8333", "s3b:8333"}}
|
||||
assert.Equal(t, []string{"s3a:8333", "s3b:8333"}, clusterS3Endpoints(cc))
|
||||
}
|
||||
|
||||
// ---------- readString ----------
|
||||
|
||||
func TestReadString_MissingKeyReturnsFallback(t *testing.T) {
|
||||
got := readString(map[string]*plugin_pb.ConfigValue{}, "missing", "fallback")
|
||||
assert.Equal(t, "fallback", got)
|
||||
}
|
||||
|
||||
func TestReadString_NilValueReturnsFallback(t *testing.T) {
|
||||
got := readString(map[string]*plugin_pb.ConfigValue{"k": nil}, "k", "fallback")
|
||||
assert.Equal(t, "fallback", got)
|
||||
}
|
||||
|
||||
func TestReadString_WrongKindReturnsFallback(t *testing.T) {
|
||||
// Configs are typed; an Int64 in a string slot is a writer-side bug
|
||||
// the handler must tolerate rather than panic on a type assertion.
|
||||
values := map[string]*plugin_pb.ConfigValue{
|
||||
"k": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 42}},
|
||||
}
|
||||
assert.Equal(t, "fallback", readString(values, "k", "fallback"))
|
||||
}
|
||||
|
||||
func TestReadString_StringValueReturned(t *testing.T) {
|
||||
values := map[string]*plugin_pb.ConfigValue{
|
||||
"k": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: "expected"}},
|
||||
}
|
||||
assert.Equal(t, "expected", readString(values, "k", "fallback"))
|
||||
}
|
||||
|
||||
// ---------- Capability ----------
|
||||
|
||||
func TestCapability_AdvertisesJobType(t *testing.T) {
|
||||
h := NewHandler(nil)
|
||||
cap := h.Capability()
|
||||
require.NotNil(t, cap)
|
||||
assert.Equal(t, jobType, cap.JobType)
|
||||
assert.True(t, cap.CanDetect)
|
||||
assert.True(t, cap.CanExecute)
|
||||
// Admin caps concurrency at one job per worker; a rebuild of the
|
||||
// scheduler must wait for the prior one to exit.
|
||||
assert.Equal(t, int32(1), cap.MaxDetectionConcurrency)
|
||||
assert.Equal(t, int32(1), cap.MaxExecutionConcurrency)
|
||||
}
|
||||
|
||||
// ---------- Detect ----------
|
||||
|
||||
func TestDetect_NilRequestErrors(t *testing.T) {
|
||||
h := NewHandler(nil)
|
||||
r := &recordingSender{}
|
||||
err := h.Detect(context.Background(), nil, r)
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, r.proposals)
|
||||
assert.Empty(t, r.completes)
|
||||
}
|
||||
|
||||
func TestDetect_NilSenderErrors(t *testing.T) {
|
||||
h := NewHandler(nil)
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{}, nil)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestDetect_WrongJobTypeErrors(t *testing.T) {
|
||||
// A request routed to this handler with a foreign JobType is the
|
||||
// admin's bug; surface as an error so it's visible rather than
|
||||
// silently emitting a bogus proposal.
|
||||
h := NewHandler(nil)
|
||||
r := &recordingSender{}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{JobType: "different_job"}, r)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "different_job")
|
||||
}
|
||||
|
||||
func TestDetect_NoS3EndpointsCompletesWithSkipActivity(t *testing.T) {
|
||||
// A cluster with no S3 servers registered yet must not spawn the
|
||||
// scheduler; emit a "skipped" activity for operator visibility and
|
||||
// complete with success so the admin doesn't classify as a failure.
|
||||
h := NewHandler(nil)
|
||||
r := &recordingSender{}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
|
||||
JobType: jobType,
|
||||
ClusterContext: &plugin_pb.ClusterContext{},
|
||||
}, r)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, r.proposals, "no S3 endpoints must not yield a proposal")
|
||||
require.Len(t, r.activities, 1)
|
||||
assert.Equal(t, "skipped", r.activities[0].Stage)
|
||||
assert.Contains(t, r.activities[0].Message, "no s3 servers")
|
||||
require.Len(t, r.completes, 1)
|
||||
assert.True(t, r.completes[0].Success, "skip is success, not failure")
|
||||
assert.Equal(t, jobType, r.completes[0].JobType)
|
||||
}
|
||||
|
||||
func TestDetect_NoFilerAddressesCompletesWithSkipActivity(t *testing.T) {
|
||||
h := NewHandler(nil)
|
||||
r := &recordingSender{}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
|
||||
JobType: jobType,
|
||||
ClusterContext: &plugin_pb.ClusterContext{
|
||||
S3GrpcAddresses: []string{"s3a:8333"},
|
||||
// no FilerGrpcAddresses
|
||||
},
|
||||
}, r)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, r.proposals)
|
||||
require.Len(t, r.activities, 1)
|
||||
assert.Equal(t, "skipped", r.activities[0].Stage)
|
||||
assert.Contains(t, r.activities[0].Message, "no filer addresses")
|
||||
require.Len(t, r.completes, 1)
|
||||
assert.True(t, r.completes[0].Success)
|
||||
}
|
||||
|
||||
func TestDetect_HappyPathProposesOneJobWithFirstFilerAddress(t *testing.T) {
|
||||
// Detect must propose exactly one job that targets the first filer
|
||||
// address in the cluster context; the master refreshes the list so
|
||||
// a stale entry self-heals on the next run.
|
||||
h := NewHandler(nil)
|
||||
r := &recordingSender{}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
|
||||
JobType: jobType,
|
||||
ClusterContext: &plugin_pb.ClusterContext{
|
||||
S3GrpcAddresses: []string{"s3a:8333"},
|
||||
FilerGrpcAddresses: []string{"filer-a:18888", "filer-b:18888"},
|
||||
},
|
||||
}, r)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, r.activities, "happy path emits no skip activity")
|
||||
|
||||
require.Len(t, r.proposals, 1)
|
||||
require.Len(t, r.proposals[0].Proposals, 1)
|
||||
prop := r.proposals[0].Proposals[0]
|
||||
assert.Equal(t, jobType, prop.JobType)
|
||||
assert.NotEmpty(t, prop.ProposalId, "proposal id must be unique-per-run")
|
||||
require.Contains(t, prop.Parameters, "filer_grpc_address")
|
||||
val := prop.Parameters["filer_grpc_address"].GetStringValue()
|
||||
assert.Equal(t, "filer-a:18888", val, "first reachable filer is dialed")
|
||||
|
||||
require.Len(t, r.completes, 1)
|
||||
assert.True(t, r.completes[0].Success)
|
||||
assert.Equal(t, int32(1), r.completes[0].TotalProposals)
|
||||
}
|
||||
|
||||
func TestDetect_EmptyJobTypeAccepted(t *testing.T) {
|
||||
// Detect is sometimes invoked with an unset JobType (broadcast
|
||||
// detect); the handler must accept and behave as if it matched.
|
||||
h := NewHandler(nil)
|
||||
r := &recordingSender{}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
|
||||
ClusterContext: &plugin_pb.ClusterContext{
|
||||
S3GrpcAddresses: []string{"s3a:8333"},
|
||||
FilerGrpcAddresses: []string{"f:18888"},
|
||||
},
|
||||
}, r)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, r.proposals, 1)
|
||||
}
|
||||
|
||||
func TestDetect_PropagatesProposalsSendError(t *testing.T) {
|
||||
// SendProposals failing must propagate; otherwise the worker would
|
||||
// silently report success despite never delivering the proposal.
|
||||
h := NewHandler(nil)
|
||||
want := errors.New("transport down")
|
||||
r := &recordingSender{errOn: map[string]error{"proposals": want}}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
|
||||
JobType: jobType,
|
||||
ClusterContext: &plugin_pb.ClusterContext{
|
||||
S3GrpcAddresses: []string{"s3a:8333"},
|
||||
FilerGrpcAddresses: []string{"f:18888"},
|
||||
},
|
||||
}, r)
|
||||
assert.ErrorIs(t, err, want)
|
||||
assert.Empty(t, r.proposals)
|
||||
assert.Empty(t, r.completes, "complete must not fire when proposals fail")
|
||||
}
|
||||
|
||||
func TestDetect_PropagatesCompleteSendError(t *testing.T) {
|
||||
// SendComplete failing must propagate; otherwise the worker would
|
||||
// report success to the admin despite the completion signal never
|
||||
// landing. Proposals went out before the failure, so they remain in
|
||||
// the recorder.
|
||||
h := NewHandler(nil)
|
||||
want := errors.New("transport down")
|
||||
r := &recordingSender{errOn: map[string]error{"complete": want}}
|
||||
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
|
||||
JobType: jobType,
|
||||
ClusterContext: &plugin_pb.ClusterContext{
|
||||
S3GrpcAddresses: []string{"s3a:8333"},
|
||||
FilerGrpcAddresses: []string{"f:18888"},
|
||||
},
|
||||
}, r)
|
||||
assert.ErrorIs(t, err, want)
|
||||
assert.Len(t, r.proposals, 1, "proposals send before complete and remain recorded")
|
||||
assert.Empty(t, r.completes)
|
||||
}
|
||||
|
||||
// ---------- Descriptor ----------
|
||||
|
||||
func TestDescriptor_BasicShape(t *testing.T) {
|
||||
// Sanity-check the Descriptor's public-facing identifiers so a
|
||||
// rename in handler.go doesn't silently break the admin UI without
|
||||
// an admin-side change too.
|
||||
h := NewHandler(nil)
|
||||
d := h.Descriptor()
|
||||
require.NotNil(t, d)
|
||||
assert.Equal(t, jobType, d.JobType)
|
||||
assert.NotEmpty(t, d.DisplayName)
|
||||
assert.NotEmpty(t, d.Description)
|
||||
assert.Greater(t, d.DescriptorVersion, uint32(0), "descriptor version must be positive (admins use it for compat)")
|
||||
}
|
||||
|
||||
func TestDescriptor_AdminConfigFormHasWorkersField(t *testing.T) {
|
||||
// Workers is the only admin-side knob today; if it disappears, the
|
||||
// admin form would render empty and operators couldn't tune
|
||||
// concurrency.
|
||||
h := NewHandler(nil)
|
||||
d := h.Descriptor()
|
||||
require.NotNil(t, d.AdminConfigForm)
|
||||
assert.Equal(t, "s3-lifecycle-admin", d.AdminConfigForm.FormId)
|
||||
|
||||
// Walk every section's fields and find "workers".
|
||||
var found bool
|
||||
for _, sec := range d.AdminConfigForm.Sections {
|
||||
for _, f := range sec.Fields {
|
||||
if f.Name == "workers" {
|
||||
found = true
|
||||
assert.Equal(t, plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64, f.FieldType)
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.True(t, found, "admin form must expose 'workers' field")
|
||||
|
||||
// Default value matches the constant used by ParseConfig.
|
||||
dv, ok := d.AdminConfigForm.DefaultValues["workers"]
|
||||
require.True(t, ok, "workers must have a default in AdminConfigForm")
|
||||
assert.Equal(t, int64(defaultWorkers), dv.GetInt64Value())
|
||||
}
|
||||
|
||||
func TestDescriptor_WorkerConfigFormCadenceDefaultsMatchParseConfig(t *testing.T) {
|
||||
// Every default the parser reads must be exposed in the descriptor's
|
||||
// DefaultValues; otherwise the admin UI would seed the form with a
|
||||
// blank or zero value and the worker would silently clamp to the
|
||||
// hardcoded fallback. Drift between the two is the bug this test
|
||||
// catches.
|
||||
h := NewHandler(nil)
|
||||
d := h.Descriptor()
|
||||
require.NotNil(t, d.WorkerConfigForm)
|
||||
assert.Equal(t, "s3-lifecycle-worker", d.WorkerConfigForm.FormId)
|
||||
|
||||
wantDefaults := map[string]int64{
|
||||
"dispatch_tick_minutes": defaultDispatchTickMinutes,
|
||||
"checkpoint_tick_seconds": defaultCheckpointTickSeconds,
|
||||
"refresh_interval_minutes": defaultRefreshIntervalMinutes,
|
||||
"bootstrap_interval_minutes": defaultBootstrapIntervalMinutes,
|
||||
"max_runtime_minutes": defaultMaxRuntimeMinutes,
|
||||
}
|
||||
for name, want := range wantDefaults {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
dv, ok := d.WorkerConfigForm.DefaultValues[name]
|
||||
require.True(t, ok, "WorkerConfigForm.DefaultValues missing %q", name)
|
||||
assert.Equal(t, want, dv.GetInt64Value(), "default mismatch for %q", name)
|
||||
})
|
||||
}
|
||||
// And the form fields themselves: every default must be paired with
|
||||
// a field of matching name AND INT64 type so the admin can render +
|
||||
// edit it and ParseConfig's readInt64 reads it correctly. Drift to
|
||||
// e.g. STRING here would silently make the worker fall back to the
|
||||
// hardcoded default and ignore admin edits.
|
||||
declared := map[string]plugin_pb.ConfigFieldType{}
|
||||
for _, sec := range d.WorkerConfigForm.Sections {
|
||||
for _, f := range sec.Fields {
|
||||
declared[f.Name] = f.FieldType
|
||||
}
|
||||
}
|
||||
for name := range wantDefaults {
|
||||
ft, ok := declared[name]
|
||||
assert.True(t, ok, "WorkerConfigForm has no field named %q", name)
|
||||
assert.Equal(t, plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64, ft, "field %q must be INT64 to match readInt64", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDescriptor_AdminRuntimeDefaultsDailyCadence(t *testing.T) {
|
||||
// Lifecycle is a daily batch; the admin must default to a 24-hour
|
||||
// detection interval so cron pressure doesn't escalate. Bound the
|
||||
// detection timeout so a stuck detect can't pin a worker slot
|
||||
// indefinitely. Max 1 job per detection = scheduler runs alone.
|
||||
h := NewHandler(nil)
|
||||
d := h.Descriptor()
|
||||
require.NotNil(t, d.AdminRuntimeDefaults)
|
||||
assert.Equal(t, int32(24*60), d.AdminRuntimeDefaults.DetectionIntervalMinutes)
|
||||
assert.Equal(t, int32(60), d.AdminRuntimeDefaults.DetectionTimeoutSeconds, "60s timeout caps a stuck detect at one minute")
|
||||
assert.Equal(t, int32(1), d.AdminRuntimeDefaults.MaxJobsPerDetection)
|
||||
}
|
||||
|
||||
// ---------- Execute ----------
|
||||
|
||||
// recordingExecSender captures Execute-side messages. The Execute path
|
||||
// dials gRPC after passing validation, so these tests only exercise
|
||||
// the validation surface that errors out before any dial — proving
|
||||
// the handler refuses malformed jobs early instead of waiting on a
|
||||
// 30s dial timeout.
|
||||
type recordingExecSender struct {
|
||||
progress []*plugin_pb.JobProgressUpdate
|
||||
completed []*plugin_pb.JobCompleted
|
||||
}
|
||||
|
||||
func (r *recordingExecSender) SendProgress(p *plugin_pb.JobProgressUpdate) error {
|
||||
r.progress = append(r.progress, p)
|
||||
return nil
|
||||
}
|
||||
func (r *recordingExecSender) SendCompleted(c *plugin_pb.JobCompleted) error {
|
||||
r.completed = append(r.completed, c)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestExecute_NilRequestErrors(t *testing.T) {
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), nil, &recordingExecSender{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "nil")
|
||||
}
|
||||
|
||||
func TestExecute_NilJobErrors(t *testing.T) {
|
||||
// A non-nil request with nil Job is a writer-side bug; refuse it
|
||||
// rather than panic dereferencing request.Job.JobType.
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{}, &recordingExecSender{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "nil")
|
||||
}
|
||||
|
||||
func TestExecute_NilSenderErrors(t *testing.T) {
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{JobType: jobType},
|
||||
}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "nil")
|
||||
}
|
||||
|
||||
func TestExecute_WrongJobTypeErrors(t *testing.T) {
|
||||
// A foreign job type routed to this handler is the admin's bug;
|
||||
// surface as an error rather than running a bogus scheduler.
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{JobType: "different_job"},
|
||||
}, &recordingExecSender{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "different_job")
|
||||
}
|
||||
|
||||
func TestExecute_NoS3EndpointsErrors(t *testing.T) {
|
||||
// Detect emits a "skipped" activity for this case; Execute is
|
||||
// stricter — the admin shouldn't have routed an Execute request
|
||||
// without S3 endpoints, so error out instead of silently no-oping.
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{JobType: jobType},
|
||||
ClusterContext: &plugin_pb.ClusterContext{}, // no S3GrpcAddresses
|
||||
}, &recordingExecSender{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "no s3 servers")
|
||||
}
|
||||
|
||||
func TestExecute_MissingFilerAddressErrors(t *testing.T) {
|
||||
// filer_grpc_address is set by Detect when it builds the proposal;
|
||||
// missing it means the proposal was tampered with or the admin
|
||||
// dropped the parameter. Refuse rather than dial nothing.
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{
|
||||
JobType: jobType,
|
||||
Parameters: map[string]*plugin_pb.ConfigValue{}, // no filer_grpc_address
|
||||
},
|
||||
ClusterContext: &plugin_pb.ClusterContext{
|
||||
S3GrpcAddresses: []string{"s3a:8333"},
|
||||
},
|
||||
}, &recordingExecSender{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "filer_grpc_address")
|
||||
}
|
||||
|
||||
func TestExecute_EmptyJobTypeAccepted(t *testing.T) {
|
||||
// Same convention as Detect: an empty JobType is broadcast routing
|
||||
// and must be accepted. The handler then errors at the next
|
||||
// validation step (no S3 endpoints) rather than at the type check.
|
||||
h := NewHandler(nil)
|
||||
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
|
||||
Job: &plugin_pb.JobSpec{}, // empty JobType
|
||||
ClusterContext: &plugin_pb.ClusterContext{},
|
||||
}, &recordingExecSender{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "no s3 servers", "validation flowed past the type check")
|
||||
}
|
||||
|
||||
// ---------- lookupBucketsPath ----------
|
||||
|
||||
// stubFilerConfigClient implements filer_pb.SeaweedFilerClient for the
|
||||
// GetFilerConfiguration call lookupBucketsPath relies on; methods that
|
||||
// aren't named here would panic if called, which the tests rely on to
|
||||
// keep the surface narrow.
|
||||
type stubFilerConfigClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
resp *filer_pb.GetFilerConfigurationResponse
|
||||
err error
|
||||
}
|
||||
|
||||
func (c *stubFilerConfigClient) GetFilerConfiguration(_ context.Context, _ *filer_pb.GetFilerConfigurationRequest, _ ...grpc.CallOption) (*filer_pb.GetFilerConfigurationResponse, error) {
|
||||
if c.err != nil {
|
||||
return nil, c.err
|
||||
}
|
||||
return c.resp, nil
|
||||
}
|
||||
|
||||
func TestLookupBucketsPath_PropagatesGRPCError(t *testing.T) {
|
||||
// A failed config lookup must surface; without it, Execute would
|
||||
// proceed to dial S3 with an empty buckets path and quietly never
|
||||
// dispatch anything.
|
||||
want := errors.New("filer down")
|
||||
got, err := lookupBucketsPath(context.Background(), &stubFilerConfigClient{err: want})
|
||||
assert.ErrorIs(t, err, want)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestLookupBucketsPath_UsesConfiguredDirBuckets(t *testing.T) {
|
||||
// When the filer reports a non-empty DirBuckets, the worker honors
|
||||
// it. Operators with a non-default layout (e.g. "/data/buckets")
|
||||
// can't be routed to "/buckets".
|
||||
got, err := lookupBucketsPath(context.Background(), &stubFilerConfigClient{
|
||||
resp: &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/data/buckets"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/data/buckets", got)
|
||||
}
|
||||
|
||||
func TestLookupBucketsPath_EmptyDirBucketsFallsBackToDefault(t *testing.T) {
|
||||
// Filer doesn't always populate DirBuckets (older configs); the
|
||||
// helper falls back to the documented default "/buckets" rather
|
||||
// than returning an empty path that would force-route to root.
|
||||
got, err := lookupBucketsPath(context.Background(), &stubFilerConfigClient{
|
||||
resp: &filer_pb.GetFilerConfigurationResponse{DirBuckets: ""},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "/buckets", got)
|
||||
}
|
||||
Reference in new issue
Block a user