From 7fbee96bd057ab044ad6d7e408b4488aeb90a54f Mon Sep 17 00:00:00 2001 From: Max Schettler Date: Thu, 19 Nov 2026 13:48:47 +0100 Subject: [PATCH 1/6] fix(objectstore): grant objectstores/finalizers RBAC permission The ObjectStore controller sets an owner reference with blockOwnerDeletion when creating the gateway's ServiceAccount, which requires update on the ObjectStore's finalizers subresource. That permission was never granted, so the API server rejects the create and the ObjectStore never becomes Ready. The S3Bucket controller already has the equivalent permission; this brings ObjectStore in line. SFAM-2858 --- .../simplyblock-operator/templates/roles/manager_role.yaml | 1 + operator/config/rbac/role.yaml | 1 + .../internal/controllers/objectstore/objectstore_controller.go | 1 + 3 files changed, 3 insertions(+) diff --git a/helm-charts/charts/simplyblock-operator/templates/roles/manager_role.yaml b/helm-charts/charts/simplyblock-operator/templates/roles/manager_role.yaml index 2f393cf4ca..03a3331bc5 100644 --- a/helm-charts/charts/simplyblock-operator/templates/roles/manager_role.yaml +++ b/helm-charts/charts/simplyblock-operator/templates/roles/manager_role.yaml @@ -446,6 +446,7 @@ rules: - controlplaneops/finalizers - controlplanes/finalizers - nfsexports/finalizers + - objectstores/finalizers - operatorops/finalizers - persistentvolumeops/finalizers - replicationops/finalizers diff --git a/operator/config/rbac/role.yaml b/operator/config/rbac/role.yaml index 6c67bf7817..53ad6676fa 100644 --- a/operator/config/rbac/role.yaml +++ b/operator/config/rbac/role.yaml @@ -446,6 +446,7 @@ rules: - controlplaneops/finalizers - controlplanes/finalizers - nfsexports/finalizers + - objectstores/finalizers - operatorops/finalizers - persistentvolumeops/finalizers - replicationops/finalizers diff --git a/operator/internal/controllers/objectstore/objectstore_controller.go b/operator/internal/controllers/objectstore/objectstore_controller.go index a632def584..9468e95f77 100644 --- a/operator/internal/controllers/objectstore/objectstore_controller.go +++ b/operator/internal/controllers/objectstore/objectstore_controller.go @@ -89,6 +89,7 @@ type ObjectStoreReconciler struct { // +kubebuilder:rbac:groups=storage.simplyblock.io,resources=objectstores,verbs=get;list;watch;update;patch // +kubebuilder:rbac:groups=storage.simplyblock.io,resources=objectstores/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=storage.simplyblock.io,resources=objectstores/finalizers,verbs=update // +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=cert-manager.io,resources=certificates,verbs=get;list;watch;create;update;delete From 5aac36a386851e5c3759c97e3b4afc8891d5841a Mon Sep 17 00:00:00 2001 From: Max Schettler Date: Mon, 23 Nov 2026 12:11:35 +0100 Subject: [PATCH 2/6] fix(objectstore): expand a bucket's PVC when capacityBytes grows (TC-S3-004) The CRD documents that an increase of S3Bucket.spec.capacityBytes reconciles to a PVC expansion and that a decrease is rejected. Neither was implemented. ensurePVC returned an existing PVC unchanged and the Ready path only ran mount delivery, so in CI run 45100042373 the PVC still requested 1Gi ten minutes after capacityBytes went to 3Gi. The Ready path now raises the PVC's requested storage to capacityBytes when the spec asks for more, and emits CapacityExpanding. A StorageClass that does not allow expansion is reported as a CapacityExpansionRefused warning instead of an error retried on every pass. A CEL transition rule rejects a decrease at admission. Tests I-14 and I-15 were red against the unchanged tree (PVC stayed at 50Mi, decrease admitted) and are green with the fix. --- .../storage.simplyblock.io_s3buckets.yaml | 3 + operator/api/v1alpha2/s3bucket_types.go | 1 + .../storage.simplyblock.io_s3buckets.yaml | 3 + .../tests/test-plan-bucket-provisioning.md | 9 +- .../objectstore/s3bucket_controller.go | 40 +++++++ .../objectstore/s3bucket_controller_test.go | 100 ++++++++++++++++++ 6 files changed, 155 insertions(+), 1 deletion(-) diff --git a/helm-charts/charts/simplyblock-operator/crds/storage.simplyblock.io_s3buckets.yaml b/helm-charts/charts/simplyblock-operator/crds/storage.simplyblock.io_s3buckets.yaml index 9be73f2950..6b2a070291 100644 --- a/helm-charts/charts/simplyblock-operator/crds/storage.simplyblock.io_s3buckets.yaml +++ b/helm-charts/charts/simplyblock-operator/crds/storage.simplyblock.io_s3buckets.yaml @@ -76,6 +76,9 @@ spec: restriction the PVC it wraps already carries. format: int64 type: integer + x-kubernetes-validations: + - message: capacityBytes cannot decrease + rule: self >= oldSelf objectStoreRef: description: |- ObjectStoreRef names the ObjectStore whose gateway Deployment serves diff --git a/operator/api/v1alpha2/s3bucket_types.go b/operator/api/v1alpha2/s3bucket_types.go index 572c9cf3da..2ddcfb9ab2 100644 --- a/operator/api/v1alpha2/s3bucket_types.go +++ b/operator/api/v1alpha2/s3bucket_types.go @@ -53,6 +53,7 @@ type S3BucketSpec struct { // reconciles to a PVC expansion. A decrease is rejected, the same // restriction the PVC it wraps already carries. // +kubebuilder:validation:Required + // +kubebuilder:validation:XValidation:rule="self >= oldSelf",message="capacityBytes cannot decrease" CapacityBytes int64 `json:"capacityBytes"` // StorageClassName names the StorageClass the backing PVC is created diff --git a/operator/config/crd/bases/storage.simplyblock.io_s3buckets.yaml b/operator/config/crd/bases/storage.simplyblock.io_s3buckets.yaml index 9be73f2950..6b2a070291 100644 --- a/operator/config/crd/bases/storage.simplyblock.io_s3buckets.yaml +++ b/operator/config/crd/bases/storage.simplyblock.io_s3buckets.yaml @@ -76,6 +76,9 @@ spec: restriction the PVC it wraps already carries. format: int64 type: integer + x-kubernetes-validations: + - message: capacityBytes cannot decrease + rule: self >= oldSelf objectStoreRef: description: |- ObjectStoreRef names the ObjectStore whose gateway Deployment serves diff --git a/operator/docs/tests/test-plan-bucket-provisioning.md b/operator/docs/tests/test-plan-bucket-provisioning.md index 95f0c2c0f9..790874287a 100644 --- a/operator/docs/tests/test-plan-bucket-provisioning.md +++ b/operator/docs/tests/test-plan-bucket-provisioning.md @@ -82,6 +82,13 @@ Run the full controller reconciliation loop against a real Kubernetes API via `e | I-05 | `spec.objectStoreRef` names an `ObjectStore` that does not exist → `Degraded`, event `ObjectStoreNotFound` | Negative | — | | I-06 | Operator process restarted mid-`Provisioning` (envtest manager stopped and restarted) → resumes from `status` without re-issuing `DeliverBucket` on already-confirmed nodes | Positive | — | +### Capacity (CRD `capacityBytes`) + +| # | Scenario | Type | Test | +|------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|---------------------------------------------| +| I-14 | `capacityBytes` raised on a `Ready` bucket → PVC requested storage raised to match, bucket stays `Ready`. Regression: 2026-11-23-s3bucket-capacity-never-expands (CI run 45100042373, TC-S3-004: the PVC stayed at its creation size) | Regression | `TestS3BucketCapacityIncreaseExpandsThePVC` | +| I-15 | `capacityBytes` lowered → rejected at admission by the CRD's transition rule | Negative | `TestS3BucketCapacityDecreaseIsRejected` | + ### Bucket Delivery Reconciliation (§5.3, §7.3) | # | Scenario | Type | Test | @@ -189,7 +196,7 @@ Run against a live simplyblock cluster with the pNFS path actually deployed (`de | Class | Scenarios | Covered | Not covered | |-------------|---------------------------------------------|---------|-------------| | Unit | 20 (U-19 moved to `csi-driver`'s own suite) | 20 | — | -| Integration | 13 | 11 | I-08, I-11 | +| Integration | 15 | 13 | I-08, I-11 | | E2E | 8 (E-09 obsolete) | 0 | E-01 … E-08 | | Manual | 2 (both resolved) | 2 | — | diff --git a/operator/internal/controllers/objectstore/s3bucket_controller.go b/operator/internal/controllers/objectstore/s3bucket_controller.go index a3954bb6b6..902e6256e6 100644 --- a/operator/internal/controllers/objectstore/s3bucket_controller.go +++ b/operator/internal/controllers/objectstore/s3bucket_controller.go @@ -158,6 +158,9 @@ func (r *S3BucketReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c // declining to act, and NFSExport's own Degraded carries the same // rule. if sm.CurrentState() == phaseReady { + if err := r.reconcileCapacity(ctx, &bucket); err != nil { + return ctrl.Result{}, err + } export, err := r.matchingNFSExport(ctx, &bucket) if err != nil { return ctrl.Result{}, err @@ -373,6 +376,43 @@ func (r *S3BucketReconciler) toDegraded( }) } +// reconcileCapacity raises the backing PVC's requested storage to +// spec.capacityBytes when the spec asks for more. It never lowers it: the CRD +// rejects a decrease at admission, and a PVC cannot shrink in any case. The +// expansion itself is the CSI resizer's work, so the bucket stays Ready while +// it runs. +func (r *S3BucketReconciler) reconcileCapacity(ctx context.Context, bucket *simplyblockv1alpha2.S3Bucket) error { + var pvc corev1.PersistentVolumeClaim + key := client.ObjectKey{Namespace: bucket.Namespace, Name: pvcNameFor(bucket.Spec.BucketName)} + if err := r.Get(ctx, key, &pvc); err != nil { + // A missing PVC has nothing to expand. Mount delivery, which runs + // next, is what reports a Ready bucket whose volume is gone. + return client.IgnoreNotFound(err) + } + current := pvc.Spec.Resources.Requests[corev1.ResourceStorage] + if bucket.Spec.CapacityBytes <= current.Value() { + return nil + } + patch := client.MergeFrom(pvc.DeepCopy()) + if pvc.Spec.Resources.Requests == nil { + pvc.Spec.Resources.Requests = corev1.ResourceList{} + } + pvc.Spec.Resources.Requests[corev1.ResourceStorage] = *resource.NewQuantity(bucket.Spec.CapacityBytes, resource.BinarySI) + if err := r.Patch(ctx, &pvc, patch); err != nil { + if apierrors.IsForbidden(err) { + // The StorageClass does not allow expansion. Retrying cannot + // change that, so the refusal is reported instead of returned. + r.event(bucket, corev1.EventTypeWarning, "CapacityExpansionRefused", + fmt.Sprintf("PVC %s cannot be expanded to %d bytes: %v", key.Name, bucket.Spec.CapacityBytes, err)) + return nil + } + return fmt.Errorf("expanding PVC %s to %d bytes: %w", key.Name, bucket.Spec.CapacityBytes, err) + } + r.event(bucket, corev1.EventTypeNormal, "CapacityExpanding", + fmt.Sprintf("PVC %s requested storage raised from %s to %d bytes", key.Name, current.String(), bucket.Spec.CapacityBytes)) + return nil +} + // ensurePVC creates the backing PersistentVolumeClaim if it does not already // exist, and returns the current copy either way. Idempotent: a reconcile // that died between the create and the status write finds the claim already diff --git a/operator/internal/controllers/objectstore/s3bucket_controller_test.go b/operator/internal/controllers/objectstore/s3bucket_controller_test.go index 61a09680c0..ddd97e83da 100644 --- a/operator/internal/controllers/objectstore/s3bucket_controller_test.go +++ b/operator/internal/controllers/objectstore/s3bucket_controller_test.go @@ -15,8 +15,11 @@ import ( "time" corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/events" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" simplyblockv1alpha2 "github.com/simplyblock/simplyblock-operator/api/v1alpha2" @@ -423,3 +426,100 @@ func forcePastDeadline(t *testing.T, cli client.Client, key client.ObjectKey) { t.Fatalf("forcing the deadline into the past: %v", err) } } + +// I-14: raising capacityBytes on a Ready bucket raises the PVC's requested +// storage to match, and the bucket stays Ready. +// +// Regression: 2026-11-23-s3bucket-capacity-never-expands. ensurePVC returned +// an existing PVC unchanged and the Ready path never looked at capacity +// again, so a grown capacityBytes left the PVC at its creation size and the +// bucket filled up at the old limit (CI run 45100042373, TC-S3-004). +func TestS3BucketCapacityIncreaseExpandsThePVC(t *testing.T) { + cli := apiServer(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + startFakeCSIBinder(ctx, t, cli) + startFakeNFSExportCreator(ctx, cli) + + // The apiserver only admits a PVC expansion when the PVC's StorageClass + // allows one, which is what the e2e StorageClass sets as well. + sc := &storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{Name: fakeStorageClassName}, + Provisioner: "csi.simplyblock.io", + AllowVolumeExpansion: ptr.To(true), + } + if err := cli.Create(ctx, sc); err != nil && !apierrors.IsAlreadyExists(err) { + t.Fatalf("creating the StorageClass: %v", err) + } + + store := testObjectStoreNamed("i14-store") + if err := cli.Create(ctx, store); err != nil { + t.Fatalf("creating the ObjectStore: %v", err) + } + bucket := &simplyblockv1alpha2.S3Bucket{ + ObjectMeta: metav1.ObjectMeta{Name: "i14-bucket", Namespace: "default"}, + Spec: simplyblockv1alpha2.S3BucketSpec{ + ObjectStoreRef: store.Name, BucketName: "i14-bucket", + CapacityBytes: 50 * 1 << 20, StorageClassName: fakeStorageClassName, + }, + } + if err := cli.Create(ctx, bucket); err != nil { + t.Fatalf("creating the bucket: %v", err) + } + + r := &S3BucketReconciler{ + Client: cli, Scheme: cli.Scheme(), Recorder: events.NewFakeRecorder(16), + Registry: newFakePeerRegistry(ctx, t), + } + key := client.ObjectKeyFromObject(bucket) + got := reconcileBucketUntil(t, r, key, func(b *simplyblockv1alpha2.S3Bucket) bool { + return b.Status.Phase == phaseReady + }) + + const grown = 150 * 1 << 20 + got.Spec.CapacityBytes = grown + if err := cli.Update(ctx, got); err != nil { + t.Fatalf("raising capacityBytes: %v", err) + } + if _, err := r.Reconcile(ctx, ctrlRequestKey(key)); err != nil { + t.Fatalf("Reconcile: %v", err) + } + + var pvc corev1.PersistentVolumeClaim + if err := cli.Get(ctx, client.ObjectKey{Namespace: "default", Name: pvcNameFor(bucket.Spec.BucketName)}, &pvc); err != nil { + t.Fatalf("reading the PVC: %v", err) + } + if req := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; req.Value() != grown { + t.Errorf("PVC requests %s after capacityBytes went to %d, want %d bytes", req.String(), int64(grown), int64(grown)) + } + var after simplyblockv1alpha2.S3Bucket + if err := cli.Get(ctx, key, &after); err != nil { + t.Fatalf("reading the bucket back: %v", err) + } + if after.Status.Phase != phaseReady { + t.Errorf("bucket phase = %q after its own expansion, want %q", after.Status.Phase, phaseReady) + } +} + +// I-15: lowering capacityBytes is refused at admission. A PVC cannot shrink, +// so a lower value accepted into the spec would leave spec and volume +// disagreeing with nothing reporting it. +func TestS3BucketCapacityDecreaseIsRejected(t *testing.T) { + cli := apiServer(t) + ctx := context.Background() + + bucket := &simplyblockv1alpha2.S3Bucket{ + ObjectMeta: metav1.ObjectMeta{Name: "i15-bucket", Namespace: "default"}, + Spec: simplyblockv1alpha2.S3BucketSpec{ + ObjectStoreRef: "i15-store", BucketName: "i15-bucket", + CapacityBytes: 100 * 1 << 20, StorageClassName: fakeStorageClassName, + }, + } + if err := cli.Create(ctx, bucket); err != nil { + t.Fatalf("creating the bucket: %v", err) + } + bucket.Spec.CapacityBytes = 50 * 1 << 20 + if err := cli.Update(ctx, bucket); err == nil { + t.Error("lowering capacityBytes was admitted, want it rejected") + } +} From bb8753be2b52228a3f346ad0ae574446f3f65c8e Mon Sep 17 00:00:00 2001 From: Max Schettler Date: Mon, 23 Nov 2026 12:13:37 +0100 Subject: [PATCH 3/6] fix(gateway): answer a write to a full bucket with 507, not 409 (TC-S3-003) versitygw v1.9.0's posix backend maps every error from linking a finished object into place to ExistingObjectIsDirectory. On a pNFS mount that is where a full volume surfaces: write() only fills the client's page cache, and the server's ENOSPC comes back from the fsync and close inside the link. In CI run 45100042373 the 14th 64 MiB object into a 1 GiB bucket was refused with 409 ExistingObjectIsDirectory, which no S3 client treats as out of space. The gateway's Backend wrapper now overrides PutObject, CopyObject, and CompleteMultipartUpload. When versitygw answers ExistingObjectIsDirectory and the key is not actually blocked by a directory or by an object in its path, the bucket volume's free space decides: below the request size, or below 1% of capacity when the size is unknown, the answer is 507 InsufficientStorage, and otherwise 500 InternalError. versitygw discards the errno, so the cause is inferred from statfs, not observed. The full-volume and space-left cases were red against the unchanged wrapper (409 ExistingObjectIsDirectory) and are green with the fix. --- gateway/go.mod | 2 +- gateway/internal/buckets/buckets.go | 15 ++- gateway/internal/buckets/nospace.go | 117 +++++++++++++++++++ gateway/internal/buckets/nospace_test.go | 137 +++++++++++++++++++++++ 4 files changed, 266 insertions(+), 5 deletions(-) create mode 100644 gateway/internal/buckets/nospace.go create mode 100644 gateway/internal/buckets/nospace_test.go diff --git a/gateway/go.mod b/gateway/go.mod index a2fa17a8ea..1feb4c6a47 100644 --- a/gateway/go.mod +++ b/gateway/go.mod @@ -109,7 +109,7 @@ require ( golang.org/x/crypto v0.58.0 // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect + golang.org/x/sys v0.49.0 golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.16.0 // indirect ) diff --git a/gateway/internal/buckets/buckets.go b/gateway/internal/buckets/buckets.go index 21a24956ff..03bee1e6f3 100644 --- a/gateway/internal/buckets/buckets.go +++ b/gateway/internal/buckets/buckets.go @@ -3,8 +3,10 @@ // (README.md "Why bucket-per-volume"), which only the // operator can provision, so CreateBucket creates the S3Bucket and waits for // its volume to be mounted under the gateway's root, and DeleteBucket deletes -// the S3Bucket and waits for it to be gone. Every other call goes to the -// posix backend unchanged. +// the S3Bucket and waits for it to be gone. PutObject, CopyObject, and +// CompleteMultipartUpload go to the posix backend with their errors +// reclassified (nospace.go). Every other call goes to the posix backend +// unchanged. package buckets @@ -76,18 +78,23 @@ type Settings struct { PollInterval time.Duration } -// Backend is the posix backend with CreateBucket and DeleteBucket replaced. +// Backend is the posix backend with CreateBucket and DeleteBucket replaced +// and the write errors of a full volume corrected. type Backend struct { backend.Backend client client.Client settings Settings + + // statfs reports a path's available and total bytes. A field so a test + // can stand in for a full volume. + statfs func(path string) (avail, total uint64, err error) } // New wraps be. The client needs get, create, and delete on S3Buckets in // settings.Namespace, which the operator grants the gateway's // ServiceAccount. func New(be backend.Backend, cli client.Client, settings Settings) *Backend { - return &Backend{Backend: be, client: cli, settings: settings} + return &Backend{Backend: be, client: cli, settings: settings, statfs: statfs} } // CreateBucket creates the bucket's S3Bucket, waits until the operator diff --git a/gateway/internal/buckets/nospace.go b/gateway/internal/buckets/nospace.go new file mode 100644 index 0000000000..3b5c5b6758 --- /dev/null +++ b/gateway/internal/buckets/nospace.go @@ -0,0 +1,117 @@ +// Reclassifies the ExistingObjectIsDirectory error versitygw's posix backend +// returns for any failed write, so a full bucket volume answers 507 +// InsufficientStorage. It lives beside Backend because the gateway's own +// wrapper of the posix backend is the only place the error can be corrected +// without patching versitygw. +// +// versitygw v1.9.0 maps every error from linking a finished object into place +// to ExistingObjectIsDirectory (backend/posix/posix.go, PutObjectWithPostFunc +// and CompleteMultipartUploadWithCopy). On a pNFS mount a full volume surfaces +// exactly there: write() only fills the client's page cache, and the server's +// ENOSPC comes back from the fsync and close inside the link. The errno is +// discarded, so the cause is re-derived from the filesystem instead. + +package buckets + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/versity/versitygw/s3err" + "github.com/versity/versitygw/s3response" + "golang.org/x/sys/unix" +) + +// lowSpaceDivisor sets the free-space floor for a write whose size is not +// known up front: a volume with less than 1/lowSpaceDivisor of its capacity +// left counts as full. +const lowSpaceDivisor = 100 + +// PutObject is the posix backend's PutObject with a full volume reported as +// InsufficientStorage. +func (b *Backend) PutObject(ctx context.Context, input s3response.PutObjectInput) (s3response.PutObjectOutput, error) { + out, err := b.Backend.PutObject(ctx, input) + return out, b.classifyWriteErr(err, aws.ToString(input.Bucket), aws.ToString(input.Key), aws.ToInt64(input.ContentLength)) +} + +// CopyObject is the posix backend's CopyObject with a full volume reported as +// InsufficientStorage. The posix backend's CopyObject calls its own PutObject, +// not this Backend's, so it needs the same correction. +func (b *Backend) CopyObject(ctx context.Context, input s3response.CopyObjectInput) (s3response.CopyObjectOutput, error) { + out, err := b.Backend.CopyObject(ctx, input) + return out, b.classifyWriteErr(err, aws.ToString(input.Bucket), aws.ToString(input.Key), 0) +} + +// CompleteMultipartUpload is the posix backend's CompleteMultipartUpload with +// a full volume reported as InsufficientStorage. +func (b *Backend) CompleteMultipartUpload( + ctx context.Context, input *s3.CompleteMultipartUploadInput, +) (s3response.CompleteMultipartUploadResult, string, error) { + out, version, err := b.Backend.CompleteMultipartUpload(ctx, input) + return out, version, b.classifyWriteErr(err, aws.ToString(input.Bucket), aws.ToString(input.Key), 0) +} + +// classifyWriteErr returns err unchanged unless it is ExistingObjectIsDirectory +// and the key is not blocked by the filesystem layout. Then it is +// InsufficientStorage when the bucket's volume has less than size bytes, or +// less than 1/lowSpaceDivisor of its capacity, available, and InternalError +// otherwise. The free space is read after the failed write's temporary file +// is removed, so a write that did not fit still finds less than its own size +// free. +func (b *Backend) classifyWriteErr(err error, bucket, key string, size int64) error { + var apiErr s3err.APIError + if !errors.As(err, &apiErr) || apiErr.Code != s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory).Code { + return err + } + bucketDir := filepath.Join(b.settings.RootDir, bucket) + if keyBlocked(bucketDir, key) { + return err + } + avail, total, serr := b.statfs(bucketDir) + if serr != nil { + return internalError("storing the object failed, and the bucket's free space could not be read: " + serr.Error()) + } + floor := total / lowSpaceDivisor + if size > 0 && uint64(size) > floor { + floor = uint64(size) + } + if avail < floor { + return s3err.GetAPIError(s3err.ErrNoSpaceLeftOnDevice) + } + return internalError("storing the object failed for a reason the storage backend did not report") +} + +// keyBlocked reports whether the layout under bucketDir really prevents key +// from being stored as a file: key itself is a directory, or one of its +// parents exists as something other than a directory. +func keyBlocked(bucketDir, key string) bool { + path := bucketDir + parts := strings.Split(strings.Trim(key, "/"), "/") + for i, part := range parts { + path = filepath.Join(path, part) + fi, err := os.Lstat(path) + if err != nil { + return false + } + last := i == len(parts)-1 + if last && fi.IsDir() || !last && !fi.IsDir() { + return true + } + } + return false +} + +// statfs is the Backend.statfs default: the filesystem holding path, as the +// unprivileged caller sees it. +func statfs(path string) (avail, total uint64, err error) { + var st unix.Statfs_t + if err := unix.Statfs(path, &st); err != nil { + return 0, 0, err + } + return st.Bavail * uint64(st.Bsize), st.Blocks * uint64(st.Bsize), nil +} diff --git a/gateway/internal/buckets/nospace_test.go b/gateway/internal/buckets/nospace_test.go new file mode 100644 index 0000000000..f9fec14e27 --- /dev/null +++ b/gateway/internal/buckets/nospace_test.go @@ -0,0 +1,137 @@ +// The writes whose ExistingObjectIsDirectory error Backend reclassifies, over +// a fake inner backend that fails every write the way versitygw's posix +// backend does when the bucket's volume is full, and a stubbed statfs. + +package buckets + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/versity/versitygw/backend" + "github.com/versity/versitygw/s3err" + "github.com/versity/versitygw/s3response" +) + +// fullVolume fails every write with ExistingObjectIsDirectory, which is what +// versitygw v1.9.0's posix backend returns for any error from linking the +// finished object into place, ENOSPC included. +type fullVolume struct { + backend.BackendUnsupported +} + +func (fullVolume) PutObject(context.Context, s3response.PutObjectInput) (s3response.PutObjectOutput, error) { + return s3response.PutObjectOutput{}, s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) +} + +func (fullVolume) CopyObject(context.Context, s3response.CopyObjectInput) (s3response.CopyObjectOutput, error) { + return s3response.CopyObjectOutput{}, s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) +} + +func (fullVolume) CompleteMultipartUpload(context.Context, *s3.CompleteMultipartUploadInput) (s3response.CompleteMultipartUploadResult, string, error) { + return s3response.CompleteMultipartUploadResult{}, "", s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) +} + +// newFullVolumeBackend is a Backend over fullVolume whose bucket volume +// reports avail of total bytes free. +func newFullVolumeBackend(t *testing.T, avail, total uint64) (*Backend, string) { + t.Helper() + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "reports"), 0o755); err != nil { + t.Fatalf("creating the bucket directory: %v", err) + } + b := New(fullVolume{}, nil, Settings{RootDir: root}) + b.statfs = func(string) (uint64, uint64, error) { return avail, total, nil } + return b, root +} + +// The three writes, each called against bucket "reports" and key. +var writes = map[string]func(*Backend, string) error{ + "PutObject": func(b *Backend, key string) error { + _, err := b.PutObject(context.Background(), s3response.PutObjectInput{ + Bucket: aws.String("reports"), Key: aws.String(key), ContentLength: aws.Int64(64 << 20), + }) + return err + }, + "CopyObject": func(b *Backend, key string) error { + _, err := b.CopyObject(context.Background(), s3response.CopyObjectInput{ + Bucket: aws.String("reports"), Key: aws.String(key), CopySource: aws.String("reports/source"), + }) + return err + }, + "CompleteMultipartUpload": func(b *Backend, key string) error { + _, _, err := b.CompleteMultipartUpload(context.Background(), &s3.CompleteMultipartUploadInput{ + Bucket: aws.String("reports"), Key: aws.String(key), UploadId: aws.String("upload"), + }) + return err + }, +} + +// Regression: 2026-11-23-s3-full-bucket-reports-directory. A write into a +// full bucket volume answered 409 ExistingObjectIsDirectory, which no S3 +// client treats as out of space, so clients neither stopped nor alerted (CI +// run 45100042373, TC-S3-003). A full volume must answer 507 +// InsufficientStorage. +func TestWriteToAFullVolumeIsInsufficientStorage(t *testing.T) { + for name, write := range writes { + t.Run(name, func(t *testing.T) { + b, _ := newFullVolumeBackend(t, 1<<20, 1<<30) + code, status := s3Code(t, write(b, "fill/00014")) + if code != "InsufficientStorage" || status != 507 { + t.Errorf("full volume answered %d %s, want 507 InsufficientStorage", status, code) + } + }) + } +} + +// A key that really is a directory keeps versitygw's own 409, whatever the +// free space. +func TestWriteOverADirectoryStaysExistingObjectIsDirectory(t *testing.T) { + for name, write := range writes { + t.Run(name, func(t *testing.T) { + b, root := newFullVolumeBackend(t, 1<<20, 1<<30) + if err := os.MkdirAll(filepath.Join(root, "reports", "fill", "00014"), 0o755); err != nil { + t.Fatalf("creating the directory: %v", err) + } + code, status := s3Code(t, write(b, "fill/00014")) + if code != "ExistingObjectIsDirectory" || status != 409 { + t.Errorf("write over a directory answered %d %s, want 409 ExistingObjectIsDirectory", status, code) + } + }) + } +} + +// A key whose parent is an object keeps versitygw's own 409 too: the key +// cannot be created as a file below another file. +func TestWriteBelowAnObjectStaysExistingObjectIsDirectory(t *testing.T) { + for name, write := range writes { + t.Run(name, func(t *testing.T) { + b, root := newFullVolumeBackend(t, 1<<20, 1<<30) + if err := os.WriteFile(filepath.Join(root, "reports", "fill"), nil, 0o644); err != nil { + t.Fatalf("creating the object: %v", err) + } + code, status := s3Code(t, write(b, "fill/00014")) + if code != "ExistingObjectIsDirectory" || status != 409 { + t.Errorf("write below an object answered %d %s, want 409 ExistingObjectIsDirectory", status, code) + } + }) + } +} + +// With neither a directory in the way nor the volume full, the cause is +// unknown, which is an InternalError rather than a claim about the key. +func TestWriteFailureWithSpaceLeftIsInternalError(t *testing.T) { + for name, write := range writes { + t.Run(name, func(t *testing.T) { + b, _ := newFullVolumeBackend(t, 900<<20, 1<<30) + code, status := s3Code(t, write(b, "fill/00014")) + if code != "InternalError" || status != 500 { + t.Errorf("unexplained write failure answered %d %s, want 500 InternalError", status, code) + } + }) + } +} From 563b42cabe6094f05285f67987b61009562230e2 Mon Sep 17 00:00:00 2001 From: Max Schettler Date: Mon, 23 Nov 2026 12:14:31 +0100 Subject: [PATCH 4/6] fix(chart): serve the operator's metrics endpoint (TC-S3-014) The operator records simplyblock_objectstore_bucket_provisioning_seconds and the other ObjectStore/S3Bucket families on controller-runtime's registry, but --metrics-bind-address defaults to "0" and only the kustomize deployment set it. The Helm chart never did, so a chart-installed operator served no metrics at all, and in CI run 45100042373 the histogram had no samples after six buckets reached Ready. The chart now passes --metrics-bind-address=:8443 and declares it as the container port named metrics, both behind operatorMetrics.enabled (default false). There is no Service: the metrics belong to one pod, so a scraper addresses pods, and a PodMonitor can select the named port. The endpoint keeps controller-runtime's secure serving: a scraper needs a token bound to the existing simplyblock-operator-metrics-reader ClusterRole, and the manager role already carries the tokenreviews and subjectaccessreviews it authorizes with. The chart has no test suite to make red first. Verified by rendering with helm template: the arg and port are absent with the default and appear with operatorMetrics.enabled=true. The e2e scrape is fixed separately in sbcli, and its workflow enables the endpoint. --- .../templates/simplyblock-operator.yaml | 8 ++++++++ helm-charts/charts/simplyblock-operator/values.yaml | 11 +++++++++++ support-tool/internal/helmvalues/chart/values.yaml | 11 +++++++++++ 3 files changed, 30 insertions(+) diff --git a/helm-charts/charts/simplyblock-operator/templates/simplyblock-operator.yaml b/helm-charts/charts/simplyblock-operator/templates/simplyblock-operator.yaml index 797636b22f..5a8ebf189d 100644 --- a/helm-charts/charts/simplyblock-operator/templates/simplyblock-operator.yaml +++ b/helm-charts/charts/simplyblock-operator/templates/simplyblock-operator.yaml @@ -81,6 +81,9 @@ spec: # migration cannot be carried across and is drained instead. - --legacy-volume-migration {{- end }} + {{- if .Values.operatorMetrics.enabled }} + - --metrics-bind-address=:{{ .Values.operatorMetrics.port }} + {{- end }} {{- if .Values.metricsAPI.enabled }} - --metrics-api-bind-port={{ .Values.metricsAPI.port }} - --prometheus-url={{ .Values.metricsAPI.prometheusURL }} @@ -197,6 +200,11 @@ spec: containerPort: {{ .Values.metricsAPI.port }} protocol: TCP {{- end }} + {{- if .Values.operatorMetrics.enabled }} + - name: metrics + containerPort: {{ .Values.operatorMetrics.port }} + protocol: TCP + {{- end }} livenessProbe: httpGet: path: /healthz diff --git a/helm-charts/charts/simplyblock-operator/values.yaml b/helm-charts/charts/simplyblock-operator/values.yaml index 50fbeef98c..64520901cf 100644 --- a/helm-charts/charts/simplyblock-operator/values.yaml +++ b/helm-charts/charts/simplyblock-operator/values.yaml @@ -1042,6 +1042,17 @@ metricsAPI: # -- Prometheus the capacity samples are read from. Empty serves provisioned sizes only. prometheusURL: http://simplyblock-prometheus:9090 +operatorMetrics: + # The operator's controller-runtime metrics, including the ObjectStore and + # S3Bucket families. Served per pod, on the container port named "metrics", + # over HTTPS behind Kubernetes authentication and authorization: a scraper + # presents a ServiceAccount token bound to the + # simplyblock-operator-metrics-reader ClusterRole. + # -- Serves the operator's own metrics. `false` closes the port. + enabled: false + # -- Container port of the operator's metrics endpoint. + port: 8443 + mongodb-kubernetes: # -- Name of the MongoDB operator. name: "simplyblock-mongodb" diff --git a/support-tool/internal/helmvalues/chart/values.yaml b/support-tool/internal/helmvalues/chart/values.yaml index 50fbeef98c..64520901cf 100644 --- a/support-tool/internal/helmvalues/chart/values.yaml +++ b/support-tool/internal/helmvalues/chart/values.yaml @@ -1042,6 +1042,17 @@ metricsAPI: # -- Prometheus the capacity samples are read from. Empty serves provisioned sizes only. prometheusURL: http://simplyblock-prometheus:9090 +operatorMetrics: + # The operator's controller-runtime metrics, including the ObjectStore and + # S3Bucket families. Served per pod, on the container port named "metrics", + # over HTTPS behind Kubernetes authentication and authorization: a scraper + # presents a ServiceAccount token bound to the + # simplyblock-operator-metrics-reader ClusterRole. + # -- Serves the operator's own metrics. `false` closes the port. + enabled: false + # -- Container port of the operator's metrics endpoint. + port: 8443 + mongodb-kubernetes: # -- Name of the MongoDB operator. name: "simplyblock-mongodb" From 7271405689f74df9baa8f1b88bdef695d0895bf7 Mon Sep 17 00:00:00 2001 From: Max Schettler Date: Mon, 23 Nov 2026 12:19:37 +0100 Subject: [PATCH 5/6] fix(objectstore): leave Degraded when the missing reference appears (S3MissingEnvFromSecretK8s) Degraded had no outgoing edge and Reconcile returned early on it, so an ObjectStore that degraded because spec.envFrom named a Secret that did not exist yet stayed Degraded after the Secret was created. In CI run 45100042373 s3-fn went Degraded at 05:53:41, the Secret was created the same second, and the ObjectStore was still Degraded ten minutes later. Degraded now returns to Provisioning with a fresh deadline when the cause may be gone: a Secret or ConfigMap named in spec.envFrom was created or written after the ObjectStore degraded, or, for an ObjectStore degraded on its certificate, the Certificate reports Ready. The controller watches Secrets and ConfigMaps and enqueues the ObjectStores whose envFrom names them. The Certificate is unstructured and not watched, so a certificate-degraded ObjectStore re-reads it once a minute. Nothing else leaves Degraded, so a refusal is still not retried on every event. The design's state machine and failure tables record the new edge. U-20, U-22, and U-23 were red against the unchanged tree and are green with the fix. U-21 guards against flapping and passed before and after. --- operator/docs/designs/design-objectstore.md | 21 ++- operator/docs/tests/test-plan-objectstore.md | 21 ++- .../objectstore/objectstore_controller.go | 154 ++++++++++++++++-- .../objectstore_recovery_unit_test.go | 109 +++++++++++++ 4 files changed, 282 insertions(+), 23 deletions(-) create mode 100644 operator/internal/controllers/objectstore/objectstore_recovery_unit_test.go diff --git a/operator/docs/designs/design-objectstore.md b/operator/docs/designs/design-objectstore.md index 355c1072c0..7cb88255c1 100644 --- a/operator/docs/designs/design-objectstore.md +++ b/operator/docs/designs/design-objectstore.md @@ -243,18 +243,25 @@ Reaching this Service from outside the cluster is not this design's concern (§2 ▼ (re-enters Provisioning only via Degraded, never directly from Ready) + Degraded ← reached by refusing to act; not retried on a timer + │ a Secret/ConfigMap named in spec.envFrom is created or changes, + │ or the owned Certificate reports Ready + ▼ + Provisioning (fresh phaseDeadline) + deletion requested at any phase │ ▼ owned objects garbage-collected; no finalizer, no Deleting phase ``` -| Condition | Phase | Result | -|----------------------------------------------------------------------------------------------------------------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------| -| The gateway image cannot be pulled, or the Deployment's pods crash-loop | Provisioning | Stays `Provisioning` past its deadline, then `Degraded`, `DeploymentAvailable` `False` with the pod's own reason | -| The TLS provider cannot issue a certificate (cert-manager `Issuer` missing, OpenShift serving-cert controller not running) | Provisioning | `Degraded`, `CertificateReady` `False` naming the cause | -| Operator restarts mid-`Provisioning` | Provisioning | Resumes from `status`: re-reads the Deployment, Service, and Certificate rather than restarting from `Pending` | -| `spec.replicas` lowered while gateway pods are serving traffic | Ready | Ordinary `Deployment` rolling scale-down. This design adds no draining beyond what the gateway's own readiness probe already gives kubelet | +| Condition | Phase | Result | +|-----------------------------------------------------------------------------------------------------------------------------|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------| +| The gateway image cannot be pulled, or the Deployment's pods crash-loop | Provisioning | Stays `Provisioning` past its deadline, then `Degraded`, `DeploymentAvailable` `False` with the pod's own reason | +| The TLS provider cannot issue a certificate (cert-manager `Issuer` missing, OpenShift serving-cert controller not running) | Provisioning | `Degraded`, `CertificateReady` `False` naming the cause | +| Operator restarts mid-`Provisioning` | Provisioning | Resumes from `status`: re-reads the Deployment, Service, and Certificate rather than restarting from `Pending` | +| The cause of a `Degraded` is fixed (missing `envFrom` reference created, `Issuer` created so the `Certificate` turns Ready) | Degraded | Returns to `Provisioning` with a fresh deadline, noticed by the watch on the `envFrom` reference or a once-a-minute read of the `Certificate` | +| `spec.replicas` lowered while gateway pods are serving traffic | Ready | Ordinary `Deployment` rolling scale-down. This design adds no draining beyond what the gateway's own readiness probe already gives kubelet | --- @@ -301,7 +308,7 @@ None. This design calls no `sbcli` endpoint: the gateway binary's own interactio |---------------------------------------------------------------------------------------------|---------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | `spec.image` does not exist or cannot be pulled | Pod `ImagePullBackOff` | `Degraded`, `DeploymentAvailable` `False`, event naming the image | | `spec.tlsProvider: cert-manager` with no matching `Issuer`/`ClusterIssuer` in the namespace | `Certificate` stays `False` | `Degraded`, `CertificateReady` `False`, event naming the missing issuer | -| `spec.envFrom` names a `Secret`/`ConfigMap` that does not exist | Pod stays `CreateContainerConfigError` | `Degraded`, `DeploymentAvailable` `False`, event naming the missing reference | +| `spec.envFrom` names a `Secret`/`ConfigMap` that does not exist | Pod stays `CreateContainerConfigError` | `Degraded`, `DeploymentAvailable` `False`, event naming the missing reference. Creating the reference returns the `ObjectStore` to `Provisioning` (§6) | | A gateway pod crashes under live S3 traffic | `Deployment`'s own `Pod` restart, `readyReplicas` drops | Ordinary Kubernetes pod restart. `S3Bucket`'s own mount delivery (`design-bucket-provisioning.md` §5) is unaffected, since it targets the node, not the pod | --- diff --git a/operator/docs/tests/test-plan-objectstore.md b/operator/docs/tests/test-plan-objectstore.md index a579acf71b..9cf8e43321 100644 --- a/operator/docs/tests/test-plan-objectstore.md +++ b/operator/docs/tests/test-plan-objectstore.md @@ -46,6 +46,17 @@ File: `internal/controllers/objectstore/objectstore_phase_unit_test.go` | U-07 | `Ready`, `spec.replicas` changed → reconciles in place, never returns to `Pending` | Positive | `TestReadyObjectStoreReconcilesReplicasInPlace` | | U-08 | Operator restart mid-`Provisioning` → resumes from `status`, does not recreate the Deployment | Positive | `TestRestartMidProvisioningDoesNotRecreateTheDeployment` | +### Recovery from Degraded (§6) + +File: `internal/controllers/objectstore/objectstore_recovery_unit_test.go` + +| # | Scenario | Type | Test | +|------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|--------------------------------------------------------------| +| U-20 | `Degraded` on `DeploymentAvailable`, the `envFrom` `Secret` created afterward → `Provisioning` with a fresh deadline. Regression: 2026-11-23-objectstore-degraded-never-recovers (CI run 45100042373, S3MissingEnvFromSecretK8s: the ObjectStore stayed `Degraded` after the `Secret` was created) | Regression | `TestDegradedObjectStoreRecoversWhenItsEnvFromSecretAppears` | +| U-21 | `Degraded`, no referenced object changed since → stays `Degraded` | Negative | `TestDegradedObjectStoreStaysDegradedWhileNothingChanged` | +| U-22 | `Degraded` on `CertificateReady`, the `Certificate` now `Ready` → `Provisioning` | Positive | `TestDegradedObjectStoreRecoversWhenItsCertificateIsReady` | +| U-23 | An event on a `Secret` enqueues the `ObjectStore`s whose `envFrom` names it, and no other | Positive | `TestEnvFromReferenceEnqueuesTheObjectStoresNamingIt` | + ### Object Construction (§4, §5) File: `internal/controllers/objectstore/objectstore_build_unit_test.go` @@ -149,11 +160,11 @@ repository's concern entirely (`design-objectstore.md` Open Question 2). ## 6. Coverage Summary -| Class | Scenarios | Covered | Not covered | -|-------------|-----------------------------------------|---------|-------------| -| Unit | 18 (U-16 dropped, U-17/U-18/U-19 added) | 18 | — | -| Integration | 7 | 5 | I-05, I-07 | -| E2E | 3 | 0 | E-01 … E-03 | +| Class | Scenarios | Covered | Not covered | +|-------------|--------------------------------------|---------|-------------| +| Unit | 22 (U-16 dropped, U-17 … U-23 added) | 22 | — | +| Integration | 7 | 5 | I-05, I-07 | +| E2E | 3 | 0 | E-01 … E-03 | --- diff --git a/operator/internal/controllers/objectstore/objectstore_controller.go b/operator/internal/controllers/objectstore/objectstore_controller.go index 9468e95f77..a2c8ad41e0 100644 --- a/operator/internal/controllers/objectstore/objectstore_controller.go +++ b/operator/internal/controllers/objectstore/objectstore_controller.go @@ -28,6 +28,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/apiutil" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/log" "github.com/simplyblock/atlas/statemachine" @@ -94,6 +95,7 @@ type ObjectStoreReconciler struct { // +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=cert-manager.io,resources=certificates,verbs=get;list;watch;create;update;delete // +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups="",resources=secrets;configmaps,verbs=get;list;watch // +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=roles;rolebindings,verbs=get;list;watch;create;update;patch;delete func (r *ObjectStoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -104,11 +106,11 @@ func (r *ObjectStoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, client.IgnoreNotFound(err) } - // Degraded is terminal on purpose, the same reason S3Bucket's and - // NFSExport's own are: it is reached by refusing to act, and retrying - // the refusal on a timer would bury the event that explains it. + // Degraded is reached by refusing to act, and retrying the refusal on a + // timer would bury the event that explains it. It is left only when the + // object it was waiting on changes (design §6). if store.Status.Phase == osPhaseDegraded { - return ctrl.Result{}, nil + return r.reconcileDegraded(ctx, &store) } sm, err := r.restore(ctx, &store) @@ -459,11 +461,10 @@ func (r *ObjectStoreReconciler) restore( } // objectStorePhases is the declared graph. An edge not written here is an -// error at the transition rather than a silent status write. Ready and -// Degraded both have no exits: Ready reconciles routine spec changes in -// place without leaving it (design §6), and Degraded is reached by refusing -// to act, the same shape S3Bucket's and NFSExport's own Degraded already -// have in this manager. +// error at the transition rather than a silent status write. Ready has no +// exit: it reconciles routine spec changes in place without leaving it +// (design §6). Degraded returns to Provisioning, with a fresh deadline, once +// the object it was waiting on changes (reconcileDegraded). func objectStorePhases() statemachine.Config[osPhase] { return statemachine.Config[osPhase]{ Initial: osPhasePending, @@ -476,7 +477,7 @@ func objectStorePhases() statemachine.Config[osPhase] { }, }, osPhaseReady: {To: []osPhase{}}, - osPhaseDegraded: {}, + osPhaseDegraded: {To: []osPhase{osPhaseProvisioning}}, }, } } @@ -556,7 +557,9 @@ func unstructuredConditionTrue(obj *unstructured.Unstructured, condType string) // SetupWithManager wires the controller. Owns the Deployment, the Service, // and the gateway's ServiceAccount, Role, and RoleBinding it creates, so a manual edit or delete of either is noticed and -// repaired on the ObjectStore's own reconcile. The certificate is +// repaired on the ObjectStore's own reconcile. Watches Secrets and ConfigMaps +// and enqueues the ObjectStores whose envFrom names them, which is what lets +// a Degraded ObjectStore notice a missing reference being created. The certificate is // unstructured and owned the same way the Deployment and the Service are // (an owner reference, set in applyCertificate), but is not watched: this // manager has no cert-manager scheme registered to decode it as a typed @@ -570,6 +573,135 @@ func (r *ObjectStoreReconciler) SetupWithManager(mgr ctrl.Manager) error { Owns(&corev1.ServiceAccount{}). Owns(&rbacv1.Role{}). Owns(&rbacv1.RoleBinding{}). + Watches(&corev1.Secret{}, handler.EnqueueRequestsFromMapFunc(r.storesReferencingEnvFrom)). + Watches(&corev1.ConfigMap{}, handler.EnqueueRequestsFromMapFunc(r.storesReferencingEnvFrom)). WithOptions(objectStoreControllerOptions()). Complete(r) } + +// objectStoreDegradedCertificatePoll is how often an ObjectStore Degraded on +// its certificate re-reads it. The Certificate is unstructured and not +// watched (SetupWithManager), so a poll is what notices it turning Ready. +const objectStoreDegradedCertificatePoll = time.Minute + +// reconcileDegraded returns the ObjectStore to Provisioning when the cause it +// degraded on may be gone: a Secret or ConfigMap named in spec.envFrom was +// created or changed after the ObjectStore degraded, or, when it degraded on +// its certificate, the Certificate now reports Ready. Otherwise, it stays +// Degraded, so the event that explains the refusal is not buried under +// retries. +func (r *ObjectStoreReconciler) reconcileDegraded( + ctx context.Context, store *simplyblockv1alpha2.ObjectStore, +) (ctrl.Result, error) { + since, onCertificate := degradedSince(store) + recovered, err := r.envFromChangedSince(ctx, store, since) + if err != nil { + return ctrl.Result{}, err + } + if !recovered && onCertificate { + if recovered, err = r.certificateReady(ctx, store); err != nil { + return ctrl.Result{}, err + } + } + if !recovered { + if onCertificate { + return ctrl.Result{RequeueAfter: objectStoreDegradedCertificatePoll}, nil + } + return ctrl.Result{}, nil + } + + sm, err := r.restore(ctx, store) + if err != nil { + return ctrl.Result{}, err + } + defer sm.Close() + if err := sm.TransitionTo(ctx, osPhaseProvisioning); err != nil { + return ctrl.Result{}, fmt.Errorf("transition to Provisioning: %w", err) + } + r.event(store, corev1.EventTypeNormal, "Recovering", + "the object this ObjectStore was waiting on changed, provisioning again") + if err := r.writeStatus(ctx, store, func(s *simplyblockv1alpha2.ObjectStoreStatus) { + s.Phase = osPhaseProvisioning + s.Message = "" + setObjectStoreDeadline(s, sm) + }); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: objectStoreFreshCopyRequeue}, nil +} + +// degradedSince is when the ObjectStore degraded, read from the condition +// toDegraded set False, and whether that condition is the certificate's. +func degradedSince(store *simplyblockv1alpha2.ObjectStore) (since time.Time, onCertificate bool) { + for _, condType := range []string{conditionDeploymentAvailable, conditionCertificateReady} { + cond := meta.FindStatusCondition(store.Status.Conditions, condType) + if cond != nil && cond.Status == metav1.ConditionFalse && cond.LastTransitionTime.After(since) { + since, onCertificate = cond.LastTransitionTime.Time, condType == conditionCertificateReady + } + } + return since, onCertificate +} + +// envFromChangedSince reports whether a Secret or ConfigMap named in +// spec.envFrom was created or last written after since. A reference that +// still does not exist has not changed. +func (r *ObjectStoreReconciler) envFromChangedSince( + ctx context.Context, store *simplyblockv1alpha2.ObjectStore, since time.Time, +) (bool, error) { + for _, ref := range store.Spec.EnvFrom { + var obj client.Object + switch { + case ref.SecretRef != nil: + obj = &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: ref.SecretRef.Name}} + case ref.ConfigMapRef != nil: + obj = &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: ref.ConfigMapRef.Name}} + default: + continue + } + err := r.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: obj.GetName()}, obj) + if apierrors.IsNotFound(err) { + continue + } + if err != nil { + return false, err + } + if lastWritten(obj).After(since) { + return true, nil + } + } + return false, nil +} + +// lastWritten is the later of obj's creation and its newest managed-fields +// write. +func lastWritten(obj client.Object) time.Time { + latest := obj.GetCreationTimestamp().Time + for _, entry := range obj.GetManagedFields() { + if entry.Time != nil && entry.Time.After(latest) { + latest = entry.Time.Time + } + } + return latest +} + +// storesReferencingEnvFrom maps a Secret or ConfigMap to the ObjectStores in +// its namespace whose spec.envFrom names it. +func (r *ObjectStoreReconciler) storesReferencingEnvFrom(ctx context.Context, obj client.Object) []ctrl.Request { + var stores simplyblockv1alpha2.ObjectStoreList + if err := r.List(ctx, &stores, client.InNamespace(obj.GetNamespace())); err != nil { + log.FromContext(ctx).Error(err, "listing ObjectStores for an envFrom reference", "name", obj.GetName()) + return nil + } + _, isSecret := obj.(*corev1.Secret) + var requests []ctrl.Request + for i := range stores.Items { + for _, ref := range stores.Items[i].Spec.EnvFrom { + if isSecret && ref.SecretRef != nil && ref.SecretRef.Name == obj.GetName() || + !isSecret && ref.ConfigMapRef != nil && ref.ConfigMapRef.Name == obj.GetName() { + requests = append(requests, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(&stores.Items[i])}) + break + } + } + } + return requests +} diff --git a/operator/internal/controllers/objectstore/objectstore_recovery_unit_test.go b/operator/internal/controllers/objectstore/objectstore_recovery_unit_test.go new file mode 100644 index 0000000000..176bba0a49 --- /dev/null +++ b/operator/internal/controllers/objectstore/objectstore_recovery_unit_test.go @@ -0,0 +1,109 @@ +// The Degraded → Provisioning edge (design-objectstore.md §6), proved against +// a fake client: a Degraded ObjectStore returns to Provisioning once the +// object it was waiting on appears, and stays Degraded while nothing changed. + +package objectstore + +import ( + "context" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + simplyblockv1alpha2 "github.com/simplyblock/simplyblock-operator/api/v1alpha2" + "github.com/simplyblock/simplyblock-operator/internal/utils" +) + +// degradedStore is an ObjectStore Degraded at degradedAt for conditionType, +// with spec.envFrom naming the Secret gateway-env. +func degradedStore(degradedAt time.Time, conditionType, reason string, mutate ...func(*simplyblockv1alpha2.ObjectStore)) *simplyblockv1alpha2.ObjectStore { + return testStore(append([]func(*simplyblockv1alpha2.ObjectStore){func(o *simplyblockv1alpha2.ObjectStore) { + o.Spec.EnvFrom = []corev1.EnvFromSource{{ + SecretRef: &corev1.SecretEnvSource{LocalObjectReference: corev1.LocalObjectReference{Name: "gateway-env"}}, + }} + o.Status.Phase = osPhaseDegraded + o.Status.Conditions = []metav1.Condition{{ + Type: conditionType, Status: metav1.ConditionFalse, Reason: reason, + LastTransitionTime: metav1.NewTime(degradedAt), + }} + }}, mutate...)...) +} + +// envSecret is the Secret degradedStore's envFrom names, created at createdAt. +func envSecret(createdAt time.Time) *corev1.Secret { + return &corev1.Secret{ObjectMeta: metav1.ObjectMeta{ + Name: "gateway-env", Namespace: testObjectStoreNamespace, CreationTimestamp: metav1.NewTime(createdAt), + }} +} + +// U-20: a Degraded ObjectStore whose envFrom Secret was created after it +// degraded returns to Provisioning with a fresh deadline. +// +// Regression: 2026-11-23-objectstore-degraded-never-recovers. Degraded had no +// exit, so creating the Secret an ObjectStore's envFrom named left it +// Degraded until it was deleted and recreated (CI run 45100042373, +// S3MissingEnvFromSecretK8s). +func TestDegradedObjectStoreRecoversWhenItsEnvFromSecretAppears(t *testing.T) { + degradedAt := time.Now().Add(-time.Minute) + store := degradedStore(degradedAt, conditionDeploymentAvailable, "DeploymentNotAvailable") + cli := newTestClient(t, store, availableDeployment(store, false, 0), envSecret(degradedAt.Add(30*time.Second))) + + got := reconcileStore(t, cli, store) + + if got.Status.Phase != osPhaseProvisioning { + t.Fatalf("phase = %q, want Provisioning", got.Status.Phase) + } + if got.Status.PhaseDeadline == nil || !got.Status.PhaseDeadline.After(time.Now()) { + t.Errorf("phaseDeadline = %v, want a fresh deadline in the future", got.Status.PhaseDeadline) + } +} + +// U-21: a Degraded ObjectStore whose referenced objects have not changed +// since it degraded stays Degraded, so a refusal is not retried on every +// event that happens to touch the ObjectStore. +func TestDegradedObjectStoreStaysDegradedWhileNothingChanged(t *testing.T) { + degradedAt := time.Now().Add(-time.Minute) + store := degradedStore(degradedAt, conditionDeploymentAvailable, "DeploymentNotAvailable") + cli := newTestClient(t, store, availableDeployment(store, false, 0), envSecret(degradedAt.Add(-time.Hour))) + + got := reconcileStore(t, cli, store) + + if got.Status.Phase != osPhaseDegraded { + t.Errorf("phase = %q, want Degraded", got.Status.Phase) + } +} + +// U-22: an ObjectStore Degraded on its certificate returns to Provisioning +// once the Certificate reports Ready, for example, after the missing Issuer +// was created. +func TestDegradedObjectStoreRecoversWhenItsCertificateIsReady(t *testing.T) { + degradedAt := time.Now().Add(-time.Minute) + store := degradedStore(degradedAt, conditionCertificateReady, "CertificateNotReady", func(o *simplyblockv1alpha2.ObjectStore) { + o.Spec.TLSProvider = utils.TLSProviderCertManager + }) + cli := newTestClient(t, store, availableDeployment(store, true, 1), readyCertificate(store, true), envSecret(degradedAt.Add(-time.Hour))) + + got := reconcileStore(t, cli, store) + + if got.Status.Phase != osPhaseProvisioning { + t.Errorf("phase = %q, want Provisioning", got.Status.Phase) + } +} + +// U-23: an event on a Secret or ConfigMap enqueues every ObjectStore in its +// namespace whose envFrom names it, and no other. +func TestEnvFromReferenceEnqueuesTheObjectStoresNamingIt(t *testing.T) { + naming := degradedStore(time.Now(), conditionDeploymentAvailable, "DeploymentNotAvailable") + other := testStore(func(o *simplyblockv1alpha2.ObjectStore) { o.Name = "other-store" }) + cli := newTestClient(t, naming, other) + r := &ObjectStoreReconciler{Client: cli, Scheme: cli.Scheme()} + + requests := r.storesReferencingEnvFrom(context.Background(), envSecret(time.Now())) + + if len(requests) != 1 || requests[0].NamespacedName != client.ObjectKeyFromObject(naming) { + t.Errorf("enqueued %v, want only %s", requests, client.ObjectKeyFromObject(naming)) + } +} From 94b2f44e1a7024a89a33b631a0939dd343c46c7e Mon Sep 17 00:00:00 2001 From: Max Schettler Date: Mon, 23 Nov 2026 12:22:34 +0100 Subject: [PATCH 6/6] fix(objectstore): hold an ObjectStore's delete while buckets reference it (TC-S3-002) Deleting an ObjectStore removed its gateway Deployment and Service while the S3Buckets that named it stayed Ready, so nothing served them and nothing said so. In CI run 45100042373 tc002a was still Ready after its ObjectStore and every gateway pod were gone. The decision is that deletion is blocked until the buckets are gone. The ObjectStore now carries the finalizer storage.simplyblock.io/objectstore-buckets. On delete, the reconciler lists the S3Buckets that reference it, keeps the finalizer while any remain, and sets BucketsRemaining True naming them. The phase is unchanged and the owned objects stay, so the gateway keeps serving. The controller watches S3Buckets and enqueues the ObjectStore each names, so the last bucket's deletion releases the finalizer. An S3Bucket whose ObjectStore is being deleted now counts it as missing and degrades with ObjectStoreNotFound, so a new bucket cannot hold the delete open indefinitely. The design docs record the decision. I-08 and I-16 were red against the unchanged tree (the ObjectStore vanished with a bucket still referencing it; the new bucket never degraded) and are green with the fix. I-04 now asserts that a delete with no buckets completes once the finalizer is released. --- .../designs/design-bucket-provisioning.md | 2 +- operator/docs/designs/design-objectstore.md | 9 ++- .../tests/test-plan-bucket-provisioning.md | 11 +-- operator/docs/tests/test-plan-objectstore.md | 49 ++++++------ .../objectstore/objectstore_controller.go | 74 +++++++++++++++++- .../objectstore_controller_test.go | 76 +++++++++++++++++-- .../objectstore/s3bucket_controller.go | 6 +- .../objectstore/s3bucket_controller_test.go | 47 ++++++++++++ 8 files changed, 230 insertions(+), 44 deletions(-) diff --git a/operator/docs/designs/design-bucket-provisioning.md b/operator/docs/designs/design-bucket-provisioning.md index 2327a51c40..66ce66ebb7 100644 --- a/operator/docs/designs/design-bucket-provisioning.md +++ b/operator/docs/designs/design-bucket-provisioning.md @@ -335,7 +335,7 @@ None. This design calls no `sbcli` endpoint directly. Every control-plane intera |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | StorageClass does not exist or does not select `fstype: pnfs` | PVC stays unbound, `events` on the PVC | `S3Bucket` stays `Pending`, event `PersistentVolumeClaimNotBound` on the `S3Bucket` | | `NFSExport` never found for the bound PV (CSI controller did not create one: StorageClass misconfigured) | Reconcile finds no `NFSExport` with a matching `spec.volumeRef` after a bound PVC | `Degraded`, `ExportReady` `False`, reason `NoMatchingExport` | -| `ObjectStore` referenced by `spec.objectStoreRef` does not exist | Deployment lookup fails | `Degraded`, event `ObjectStoreNotFound` | +| `ObjectStore` referenced by `spec.objectStoreRef` does not exist or is being deleted | Deployment lookup fails | `Degraded`, event `ObjectStoreNotFound` | | A node's `csi-link` session is down, or its `DeliverBucket` call returns an error | The RPC fails or times out | `Provisioning` past deadline, then `Degraded`, `MountDelivered` `False` naming the node | | A node's CSI node plugin reports a bucket delivered, but its stack record has drifted from what is actually mounted (after the plugin's own restart, a node reboot, or a fabric repair race, §5.2) | Not detectable from this reconciler's own view: it only observes what `DeliverBucket` last reported, not what a gateway pod's filesystem actually shows. The gateway's own readiness probe (`kubernetes/gateway/internal/readiness`) does observe it, by `stat`-comparing each bucket directory's device against the root's | Mitigated, not resolved. The reconciler now re-asserts `DeliverBucket` to every node a bucket is desired on every `s3BucketMountResyncInterval` (5 minutes), not only on a node-set change, which self-heals a drifted mount within that bound instead of never. The gateway's readiness probe fails while a bucket directory is not actually mounted, so Kubernetes stops routing to that pod for the window before the resync catches it, instead of it serving silently wrong reads and writes. See Open Question 6 | diff --git a/operator/docs/designs/design-objectstore.md b/operator/docs/designs/design-objectstore.md index 7cb88255c1..c1c3a374e6 100644 --- a/operator/docs/designs/design-objectstore.md +++ b/operator/docs/designs/design-objectstore.md @@ -184,7 +184,7 @@ type ObjectStorePhase string ReadyReplicas int32 `json:"readyReplicas,omitempty"` ``` -The whole type is in Appendix A. No finalizer: the Deployment, the Service, and the `Certificate` (or the OpenShift serving-cert annotation, which needs none) are all owned via `ownerReferences` and garbage-collected by Kubernetes on delete, and nothing outside this design's own objects needs cleanup. Deleting an `ObjectStore` while an `S3Bucket` still names it in `spec.objectStoreRef` is not blocked: `design-bucket-provisioning.md` §6 already tolerates a gateway Deployment disappearing out from under existing buckets ("Mount-holders... existing deliveries are left in place... until the `S3Bucket` itself is deleted"), so an `ObjectStore`'s own deletion needs no stronger guarantee than that design already assumes. +The whole type is in Appendix A. The Deployment, the Service, and the `Certificate` (or the OpenShift serving-cert annotation, which needs none) are all owned via `ownerReferences` and garbage-collected by Kubernetes on delete. Deleting an `ObjectStore` while an `S3Bucket` still names it in `spec.objectStoreRef` is blocked by the finalizer `storage.simplyblock.io/objectstore-buckets`. The delete request itself succeeds and sets `deletionTimestamp`, but the finalizer stays until no `S3Bucket` in the namespace references the `ObjectStore`. Until then the owned objects are not garbage-collected, so the gateway keeps serving the remaining buckets, and the condition `BucketsRemaining` `True` names them. The reconciler watches `S3Bucket` objects and maps each to the `ObjectStore` it references, so the last bucket's deletion releases the finalizer within one reconcile. A bucket left without a gateway is not a supported state: an `S3Bucket` reports `Ready` while nothing serves it, which no status field can make honest short of re-deriving gateway presence on every bucket. A CR as it exists once `Ready`: @@ -252,7 +252,11 @@ Reaching this Service from outside the cluster is not this design's concern (§2 deletion requested at any phase │ ▼ - owned objects garbage-collected; no finalizer, no Deleting phase + finalizer held while any S3Bucket references this ObjectStore + │ (phase unchanged, BucketsRemaining True, gateway keeps serving) + │ last referencing S3Bucket deleted + ▼ + finalizer removed, owned objects garbage-collected; no Deleting phase ``` | Condition | Phase | Result | @@ -261,6 +265,7 @@ Reaching this Service from outside the cluster is not this design's concern (§2 | The TLS provider cannot issue a certificate (cert-manager `Issuer` missing, OpenShift serving-cert controller not running) | Provisioning | `Degraded`, `CertificateReady` `False` naming the cause | | Operator restarts mid-`Provisioning` | Provisioning | Resumes from `status`: re-reads the Deployment, Service, and Certificate rather than restarting from `Pending` | | The cause of a `Degraded` is fixed (missing `envFrom` reference created, `Issuer` created so the `Certificate` turns Ready) | Degraded | Returns to `Provisioning` with a fresh deadline, noticed by the watch on the `envFrom` reference or a once-a-minute read of the `Certificate` | +| `ObjectStore` deleted while `S3Bucket`s still reference it | Any | Finalizer held, phase unchanged, `BucketsRemaining` `True` naming the buckets, gateway keeps serving until the last one is deleted | | `spec.replicas` lowered while gateway pods are serving traffic | Ready | Ordinary `Deployment` rolling scale-down. This design adds no draining beyond what the gateway's own readiness probe already gives kubelet | --- diff --git a/operator/docs/tests/test-plan-bucket-provisioning.md b/operator/docs/tests/test-plan-bucket-provisioning.md index 790874287a..d69ef0a2a5 100644 --- a/operator/docs/tests/test-plan-bucket-provisioning.md +++ b/operator/docs/tests/test-plan-bucket-provisioning.md @@ -84,10 +84,11 @@ Run the full controller reconciliation loop against a real Kubernetes API via `e ### Capacity (CRD `capacityBytes`) -| # | Scenario | Type | Test | -|------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|---------------------------------------------| -| I-14 | `capacityBytes` raised on a `Ready` bucket → PVC requested storage raised to match, bucket stays `Ready`. Regression: 2026-11-23-s3bucket-capacity-never-expands (CI run 45100042373, TC-S3-004: the PVC stayed at its creation size) | Regression | `TestS3BucketCapacityIncreaseExpandsThePVC` | -| I-15 | `capacityBytes` lowered → rejected at admission by the CRD's transition rule | Negative | `TestS3BucketCapacityDecreaseIsRejected` | +| # | Scenario | Type | Test | +|------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|--------------------------------------------------------| +| I-14 | `capacityBytes` raised on a `Ready` bucket → PVC requested storage raised to match, bucket stays `Ready`. Regression: 2026-11-23-s3bucket-capacity-never-expands (CI run 45100042373, TC-S3-004: the PVC stayed at its creation size) | Regression | `TestS3BucketCapacityIncreaseExpandsThePVC` | +| I-15 | `capacityBytes` lowered → rejected at admission by the CRD's transition rule | Negative | `TestS3BucketCapacityDecreaseIsRejected` | +| I-16 | `spec.objectStoreRef` names an `ObjectStore` that is being deleted → `Degraded`, `ObjectStoreNotFound`, so a new bucket cannot hold the delete open | Negative | `TestS3BucketDegradesWhenItsObjectStoreIsBeingDeleted` | ### Bucket Delivery Reconciliation (§5.3, §7.3) @@ -196,7 +197,7 @@ Run against a live simplyblock cluster with the pNFS path actually deployed (`de | Class | Scenarios | Covered | Not covered | |-------------|---------------------------------------------|---------|-------------| | Unit | 20 (U-19 moved to `csi-driver`'s own suite) | 20 | — | -| Integration | 15 | 13 | I-08, I-11 | +| Integration | 16 | 14 | I-08, I-11 | | E2E | 8 (E-09 obsolete) | 0 | E-01 … E-08 | | Manual | 2 (both resolved) | 2 | — | diff --git a/operator/docs/tests/test-plan-objectstore.md b/operator/docs/tests/test-plan-objectstore.md index 9cf8e43321..7e072e8da0 100644 --- a/operator/docs/tests/test-plan-objectstore.md +++ b/operator/docs/tests/test-plan-objectstore.md @@ -95,15 +95,16 @@ directly, since `envtest` runs no kubelet and no cert-manager controller either. File: `internal/controllers/objectstore/objectstore_controller_test.go` -| # | Scenario | Type | Test | -|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| I-01 | `ObjectStore` created → Deployment, Service, and (cert-manager provider) `Certificate` all created, owned via `ownerReferences` | Positive | `TestObjectStoreCreatesItsOwnedObjects` | -| I-02 | Deployment and Certificate faked as ready → `ObjectStore` reaches `Ready`, `status.readyReplicas` mirrors the Deployment | Positive | `TestObjectStoreReachesReadyOnceDeploymentAndCertificateAreReady` | -| I-03 | `spec.replicas` updated on an existing `ObjectStore` → Deployment's replica count updates, no Service or Certificate churn | Positive | `TestObjectStoreReplicaChangeUpdatesTheDeploymentInPlace` | -| I-04 | `ObjectStore` deleted while `Ready` → no finalizer blocks the delete | Positive | `TestObjectStoreDeletionIsNotBlockedByAFinalizer` (narrower than first scoped: see §7) | -| I-05 | Two reconciles triggered concurrently for the same object → converge to one Deployment/Service/Certificate, no duplicates | Positive | — (design §7.3: the standard controller-runtime guarantee that one object's key is never processed by two workers at once, the same reasoning design-bucket-provisioning.md §7.3 states for its own I-08; a test driving two direct `Reconcile` calls would only reprove controller-runtime's own workqueue) | -| I-06 | Operator process restarted mid-`Provisioning` (envtest manager stopped and restarted) → resumes from `status` without re-creating owned objects | Positive | `TestObjectStoreResumesMidProvisioningWithoutRecreatingTheDeployment` | -| I-07 | `spec.envFrom` names a `Secret` that does not exist → `Degraded`, event naming the missing reference (this reconciler does not validate the `Secret`'s existence, and kubelet reports its absence instead) | Negative | — (needs a real kubelet to produce `CreateContainerConfigError`; `envtest` runs none, same boundary §9's own failure-table row draws) | +| # | Scenario | Type | Test | +|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| I-01 | `ObjectStore` created → Deployment, Service, and (cert-manager provider) `Certificate` all created, owned via `ownerReferences` | Positive | `TestObjectStoreCreatesItsOwnedObjects` | +| I-02 | Deployment and Certificate faked as ready → `ObjectStore` reaches `Ready`, `status.readyReplicas` mirrors the Deployment | Positive | `TestObjectStoreReachesReadyOnceDeploymentAndCertificateAreReady` | +| I-03 | `spec.replicas` updated on an existing `ObjectStore` → Deployment's replica count updates, no Service or Certificate churn | Positive | `TestObjectStoreReplicaChangeUpdatesTheDeploymentInPlace` | +| I-04 | `ObjectStore` deleted with no `S3Bucket` referencing it → the finalizer is released and the delete completes | Positive | `TestObjectStoreDeletionWithNoBucketsCompletes` (narrower than first scoped: see §7) | +| I-05 | Two reconciles triggered concurrently for the same object → converge to one Deployment/Service/Certificate, no duplicates | Positive | — (design §7.3: the standard controller-runtime guarantee that one object's key is never processed by two workers at once, the same reasoning design-bucket-provisioning.md §7.3 states for its own I-08; a test driving two direct `Reconcile` calls would only reprove controller-runtime's own workqueue) | +| I-06 | Operator process restarted mid-`Provisioning` (envtest manager stopped and restarted) → resumes from `status` without re-creating owned objects | Positive | `TestObjectStoreResumesMidProvisioningWithoutRecreatingTheDeployment` | +| I-07 | `spec.envFrom` names a `Secret` that does not exist → `Degraded`, event naming the missing reference (this reconciler does not validate the `Secret`'s existence, and kubelet reports its absence instead) | Negative | — (needs a real kubelet to produce `CreateContainerConfigError`; `envtest` runs none, same boundary §9's own failure-table row draws) | +| I-08 | `ObjectStore` deleted while an `S3Bucket` references it → the finalizer holds it, phase unchanged, `BucketsRemaining` `True` naming the bucket, delete completes once the bucket is gone. Regression: 2026-11-23-objectstore-deleted-under-its-buckets (CI run 45100042373, TC-S3-002: the gateway went away while its buckets stayed `Ready`) | Regression | `TestObjectStoreDeletionIsHeldWhileABucketReferencesIt` | --- @@ -148,13 +149,13 @@ repository's concern entirely (`design-objectstore.md` Open Question 2). ## 5. Axis Coverage -| Axis | Values covered | IDs | Not covered | -|---------------------|------------------------------------------------------------|------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| TLS provider | `OpenShift`, `cert-manager` | U-14, U-15, E-01, E-02 | — | -| Replica count | 1 (default), 2+, scaled in place | U-11, I-03 | 0 (rejected by CRD validation, not a runtime scenario) | -| Namespace scope | single namespace | I-01 | multi-namespace (no cross-namespace behavior exists to test) | -| Lifecycle / restart | mid-`Provisioning` operator restart, concurrent reconciles | U-08, I-05, I-06 | — | -| Deletion | `Ready` → deleted, no finalizer | I-04 | deletion while an `S3Bucket` still references it (that invariant belongs to `design-bucket-provisioning.md`'s own test plan, not this one); actual garbage collection of the owned objects (needs a real cluster, §7) | +| Axis | Values covered | IDs | Not covered | +|---------------------|------------------------------------------------------------------------|------------------------|---------------------------------------------------------------------------| +| TLS provider | `OpenShift`, `cert-manager` | U-14, U-15, E-01, E-02 | — | +| Replica count | 1 (default), 2+, scaled in place | U-11, I-03 | 0 (rejected by CRD validation, not a runtime scenario) | +| Namespace scope | single namespace | I-01 | multi-namespace (no cross-namespace behavior exists to test) | +| Lifecycle / restart | mid-`Provisioning` operator restart, concurrent reconciles | U-08, I-05, I-06 | — | +| Deletion | `Ready` → deleted with no bucket, deleted while a bucket references it | I-04, I-08 | actual garbage collection of the owned objects (needs a real cluster, §7) | --- @@ -163,17 +164,17 @@ repository's concern entirely (`design-objectstore.md` Open Question 2). | Class | Scenarios | Covered | Not covered | |-------------|--------------------------------------|---------|-------------| | Unit | 22 (U-16 dropped, U-17 … U-23 added) | 22 | — | -| Integration | 7 | 5 | I-05, I-07 | +| Integration | 8 | 6 | I-05, I-07 | | E2E | 3 | 0 | E-01 … E-03 | --- ## 7. What Is Not Yet Covered -| # | Gap | Reason | -|------|------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| I-05 | Two concurrent reconciles converge to one set of owned objects | Design §7.3's own "standard controller-runtime guarantee," the same reasoning design-bucket-provisioning.md's I-08 is not covered for | -| I-07 | `spec.envFrom` naming a missing `Secret` degrades, naming the reference | Needs a real kubelet to produce `CreateContainerConfigError`; `envtest` runs none | -| I-04 | Deleting a `Ready` `ObjectStore` actually garbage-collects its owned objects | `envtest` has no garbage-collector controller; only `TestObjectStoreDeletionIsNotBlockedByAFinalizer`'s narrower claim (no finalizer blocks the delete) is proven here | -| — | Graceful shutdown / in-flight request draining during a rolling update | Open Question 2 in the design: not designed here, may be entirely the gateway binary's concern | -| — | E-01 … E-03 | Need a live cluster with both TLS providers available, which this session has no access to | +| # | Gap | Reason | +|------|------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| I-05 | Two concurrent reconciles converge to one set of owned objects | Design §7.3's own "standard controller-runtime guarantee," the same reasoning design-bucket-provisioning.md's I-08 is not covered for | +| I-07 | `spec.envFrom` naming a missing `Secret` degrades, naming the reference | Needs a real kubelet to produce `CreateContainerConfigError`; `envtest` runs none | +| I-04 | Deleting a `Ready` `ObjectStore` actually garbage-collects its owned objects | `envtest` has no garbage-collector controller; only `TestObjectStoreDeletionWithNoBucketsCompletes`'s narrower claim (the finalizer is released) is proven here | +| — | Graceful shutdown / in-flight request draining during a rolling update | Open Question 2 in the design: not designed here, may be entirely the gateway binary's concern | +| — | E-01 … E-03 | Need a live cluster with both TLS providers available, which this session has no access to | diff --git a/operator/internal/controllers/objectstore/objectstore_controller.go b/operator/internal/controllers/objectstore/objectstore_controller.go index a2c8ad41e0..18c57d5604 100644 --- a/operator/internal/controllers/objectstore/objectstore_controller.go +++ b/operator/internal/controllers/objectstore/objectstore_controller.go @@ -1,15 +1,17 @@ // ObjectStoreReconciler drives one S3 gateway's workload from creation to // Ready: the Deployment, the ClusterIP Service, that Service's serving // certificate (design-objectstore.md), and the gateway's ServiceAccount, -// Role, and RoleBinding. No finalizer: every owned object is -// garbage-collected by Kubernetes on delete (§4.2), and nothing outside them -// needs cleanup. +// Role, and RoleBinding. Every owned object is garbage-collected by Kubernetes +// on delete. A finalizer holds the delete while S3Buckets still reference the +// ObjectStore, so its gateway keeps serving them until they are gone (§4.2). package objectstore import ( "context" "fmt" + "sort" + "strings" "time" appsv1 "k8s.io/api/apps/v1" @@ -52,8 +54,15 @@ const ( const ( conditionDeploymentAvailable = "DeploymentAvailable" conditionCertificateReady = "CertificateReady" + // BucketsRemaining is True while a requested delete is held because + // S3Buckets still reference the ObjectStore (design §4.2). + conditionBucketsRemaining = "BucketsRemaining" ) +// objectStoreBucketsFinalizer holds an ObjectStore's delete until no S3Bucket +// references it. +const objectStoreBucketsFinalizer = "storage.simplyblock.io/objectstore-buckets" + // The controller's cadence, in one place so it can be read and tuned. const ( // How long Provisioning may wait on the Deployment reporting Available @@ -106,6 +115,17 @@ func (r *ObjectStoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) return ctrl.Result{}, client.IgnoreNotFound(err) } + if !store.DeletionTimestamp.IsZero() { + return ctrl.Result{}, r.reconcileDelete(ctx, &store) + } + // Update refreshes store in place, so this pass continues on the copy + // the finalizer write returned. + if controllerutil.AddFinalizer(&store, objectStoreBucketsFinalizer) { + if err := r.Update(ctx, &store); err != nil { + return ctrl.Result{}, err + } + } + // Degraded is reached by refusing to act, and retrying the refusal on a // timer would bury the event that explains it. It is left only when the // object it was waiting on changes (design §6). @@ -559,7 +579,9 @@ func unstructuredConditionTrue(obj *unstructured.Unstructured, condType string) // and the gateway's ServiceAccount, Role, and RoleBinding it creates, so a manual edit or delete of either is noticed and // repaired on the ObjectStore's own reconcile. Watches Secrets and ConfigMaps // and enqueues the ObjectStores whose envFrom names them, which is what lets -// a Degraded ObjectStore notice a missing reference being created. The certificate is +// a Degraded ObjectStore notice a missing reference being created. Watches +// S3Buckets and enqueues the ObjectStore each names, so a held delete +// completes when the last bucket is gone. The certificate is // unstructured and owned the same way the Deployment and the Service are // (an owner reference, set in applyCertificate), but is not watched: this // manager has no cert-manager scheme registered to decode it as a typed @@ -573,6 +595,7 @@ func (r *ObjectStoreReconciler) SetupWithManager(mgr ctrl.Manager) error { Owns(&corev1.ServiceAccount{}). Owns(&rbacv1.Role{}). Owns(&rbacv1.RoleBinding{}). + Watches(&simplyblockv1alpha2.S3Bucket{}, handler.EnqueueRequestsFromMapFunc(storeOfBucket)). Watches(&corev1.Secret{}, handler.EnqueueRequestsFromMapFunc(r.storesReferencingEnvFrom)). Watches(&corev1.ConfigMap{}, handler.EnqueueRequestsFromMapFunc(r.storesReferencingEnvFrom)). WithOptions(objectStoreControllerOptions()). @@ -705,3 +728,46 @@ func (r *ObjectStoreReconciler) storesReferencingEnvFrom(ctx context.Context, ob } return requests } + +// reconcileDelete holds the delete while S3Buckets reference the ObjectStore, +// saying so in BucketsRemaining, and releases the finalizer once none do. +// The phase is left as it is: the gateway keeps serving the remaining +// buckets until then. +func (r *ObjectStoreReconciler) reconcileDelete(ctx context.Context, store *simplyblockv1alpha2.ObjectStore) error { + if !controllerutil.ContainsFinalizer(store, objectStoreBucketsFinalizer) { + return nil + } + var buckets simplyblockv1alpha2.S3BucketList + if err := r.List(ctx, &buckets, client.InNamespace(store.Namespace)); err != nil { + return fmt.Errorf("listing the S3Buckets that may reference %s: %w", store.Name, err) + } + var remaining []string + for i := range buckets.Items { + if buckets.Items[i].Spec.ObjectStoreRef == store.Name { + remaining = append(remaining, buckets.Items[i].Name) + } + } + if len(remaining) > 0 { + sort.Strings(remaining) + message := fmt.Sprintf("deletion waits for S3Buckets still referencing this ObjectStore: %s", strings.Join(remaining, ", ")) + if cond := meta.FindStatusCondition(store.Status.Conditions, conditionBucketsRemaining); cond == nil || cond.Message != message { + r.event(store, corev1.EventTypeNormal, conditionBucketsRemaining, message) + } + return r.writeStatus(ctx, store, func(s *simplyblockv1alpha2.ObjectStoreStatus) { + meta.SetStatusCondition(&s.Conditions, metav1.Condition{ + Type: conditionBucketsRemaining, Status: metav1.ConditionTrue, Reason: conditionBucketsRemaining, Message: message, + }) + }) + } + controllerutil.RemoveFinalizer(store, objectStoreBucketsFinalizer) + return client.IgnoreNotFound(r.Update(ctx, store)) +} + +// storeOfBucket maps an S3Bucket to the ObjectStore it references. +func storeOfBucket(_ context.Context, obj client.Object) []ctrl.Request { + bucket, ok := obj.(*simplyblockv1alpha2.S3Bucket) + if !ok || bucket.Spec.ObjectStoreRef == "" { + return nil + } + return []ctrl.Request{{NamespacedName: client.ObjectKey{Namespace: bucket.Namespace, Name: bucket.Spec.ObjectStoreRef}}} +} diff --git a/operator/internal/controllers/objectstore/objectstore_controller_test.go b/operator/internal/controllers/objectstore/objectstore_controller_test.go index a5c9a7b627..6c39d3f31e 100644 --- a/operator/internal/controllers/objectstore/objectstore_controller_test.go +++ b/operator/internal/controllers/objectstore/objectstore_controller_test.go @@ -8,6 +8,7 @@ package objectstore import ( "context" + "strings" "testing" "time" @@ -245,12 +246,11 @@ func TestObjectStoreReplicaChangeUpdatesTheDeploymentInPlace(t *testing.T) { } } -// I-04: deleting a Ready ObjectStore completes immediately, since it has no -// finalizer of its own (design §4.2: owned objects are garbage-collected by -// Kubernetes, not this reconciler). Whether that garbage collection itself -// actually runs is not exercised here: envtest has no garbage-collector +// I-04: deleting an ObjectStore no S3Bucket references completes once the +// reconciler releases its finalizer. Whether garbage collection of the owned +// objects then runs is not exercised here: envtest has no garbage-collector // controller, only a real cluster does (E-01..E-03's own scope). -func TestObjectStoreDeletionIsNotBlockedByAFinalizer(t *testing.T) { +func TestObjectStoreDeletionWithNoBucketsCompletes(t *testing.T) { cli := apiServer(t) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) @@ -268,11 +268,75 @@ func TestObjectStoreDeletionIsNotBlockedByAFinalizer(t *testing.T) { if err := cli.Delete(ctx, store); err != nil { t.Fatalf("deleting the ObjectStore: %v", err) } + if _, err := r.Reconcile(ctx, ctrlRequestKey(key)); err != nil { + t.Fatalf("Reconcile: %v", err) + } var got simplyblockv1alpha2.ObjectStore err := cli.Get(ctx, key, &got) if !apierrorsIsNotFound(err) { - t.Errorf("Get after delete = %v, want NotFound (no finalizer should hold it back)", err) + t.Errorf("Get after delete = %v, want NotFound (no bucket references the ObjectStore)", err) + } +} + +// I-08: deleting an ObjectStore an S3Bucket still references is held by the +// finalizer, with BucketsRemaining naming the bucket, until the bucket is +// gone. +// +// Regression: 2026-11-23-objectstore-deleted-under-its-buckets. Deleting an +// ObjectStore removed its gateway while its buckets stayed Ready, so nothing +// served them and nothing reported it (CI run 45100042373, TC-S3-002). +func TestObjectStoreDeletionIsHeldWhileABucketReferencesIt(t *testing.T) { + cli := apiServer(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + store := testObjectStoreFixture("os-i08-store") + if err := cli.Create(ctx, store); err != nil { + t.Fatalf("creating the ObjectStore: %v", err) + } + bucket := &simplyblockv1alpha2.S3Bucket{ + ObjectMeta: metav1.ObjectMeta{Name: "os-i08-bucket", Namespace: store.Namespace}, + Spec: simplyblockv1alpha2.S3BucketSpec{ + ObjectStoreRef: store.Name, BucketName: "os-i08-bucket", + CapacityBytes: 50 * 1 << 20, StorageClassName: "any", + }, + } + if err := cli.Create(ctx, bucket); err != nil { + t.Fatalf("creating the bucket: %v", err) + } + r := &ObjectStoreReconciler{Client: cli, Scheme: cli.Scheme()} + key := client.ObjectKeyFromObject(store) + reconcileStoreUntil(t, r, key, func(o *simplyblockv1alpha2.ObjectStore) bool { + return o.Status.Phase == osPhaseProvisioning + }) + + if err := cli.Delete(ctx, store); err != nil { + t.Fatalf("deleting the ObjectStore: %v", err) + } + if _, err := r.Reconcile(ctx, ctrlRequestKey(key)); err != nil { + t.Fatalf("Reconcile: %v", err) + } + var held simplyblockv1alpha2.ObjectStore + if err := cli.Get(ctx, key, &held); err != nil { + t.Fatalf("ObjectStore gone while %s still references it: %v", bucket.Name, err) + } + cond := findCondition(held.Status.Conditions, conditionBucketsRemaining) + if cond == nil || cond.Status != metav1.ConditionTrue || !strings.Contains(cond.Message, bucket.Name) { + t.Errorf("BucketsRemaining condition = %+v, want True naming %s", cond, bucket.Name) + } + if held.Status.Phase != osPhaseProvisioning { + t.Errorf("phase = %q while the delete is held, want it unchanged (Provisioning)", held.Status.Phase) + } + + if err := cli.Delete(ctx, bucket); err != nil { + t.Fatalf("deleting the bucket: %v", err) + } + if _, err := r.Reconcile(ctx, ctrlRequestKey(key)); err != nil { + t.Fatalf("Reconcile: %v", err) + } + if err := cli.Get(ctx, key, &held); !apierrorsIsNotFound(err) { + t.Errorf("Get after the last bucket was deleted = %v, want NotFound", err) } } diff --git a/operator/internal/controllers/objectstore/s3bucket_controller.go b/operator/internal/controllers/objectstore/s3bucket_controller.go index 902e6256e6..e03fc4c489 100644 --- a/operator/internal/controllers/objectstore/s3bucket_controller.go +++ b/operator/internal/controllers/objectstore/s3bucket_controller.go @@ -505,7 +505,7 @@ func (r *S3BucketReconciler) boundVolumeHandle( } // objectStoreExists reports whether spec.objectStoreRef names an ObjectStore -// in the bucket's own namespace. +// in the bucket's own namespace that is not being deleted. func (r *S3BucketReconciler) objectStoreExists( ctx context.Context, bucket *simplyblockv1alpha2.S3Bucket, ) (bool, error) { @@ -513,7 +513,9 @@ func (r *S3BucketReconciler) objectStoreExists( err := r.Get(ctx, client.ObjectKey{Namespace: bucket.Namespace, Name: bucket.Spec.ObjectStoreRef}, &store) switch { case err == nil: - return true, nil + // An ObjectStore being deleted counts as missing: a new bucket must + // not hold its delete open indefinitely (design §9). + return store.DeletionTimestamp.IsZero(), nil case apierrors.IsNotFound(err): return false, nil default: diff --git a/operator/internal/controllers/objectstore/s3bucket_controller_test.go b/operator/internal/controllers/objectstore/s3bucket_controller_test.go index ddd97e83da..57d484f98e 100644 --- a/operator/internal/controllers/objectstore/s3bucket_controller_test.go +++ b/operator/internal/controllers/objectstore/s3bucket_controller_test.go @@ -523,3 +523,50 @@ func TestS3BucketCapacityDecreaseIsRejected(t *testing.T) { t.Error("lowering capacityBytes was admitted, want it rejected") } } + +// I-16: an S3Bucket naming an ObjectStore that is being deleted degrades +// with ObjectStoreNotFound, so a new bucket cannot keep a deleting +// ObjectStore alive indefinitely. +func TestS3BucketDegradesWhenItsObjectStoreIsBeingDeleted(t *testing.T) { + cli := apiServer(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + startFakeCSIBinder(ctx, t, cli) + + store := testObjectStoreNamed("i16-store") + // A finalizer of the test's own keeps the deleted ObjectStore around + // with deletionTimestamp set, as the operator's finalizer would. + store.Finalizers = []string{"test.simplyblock.io/hold"} + if err := cli.Create(ctx, store); err != nil { + t.Fatalf("creating the ObjectStore: %v", err) + } + if err := cli.Delete(ctx, store); err != nil { + t.Fatalf("deleting the ObjectStore: %v", err) + } + t.Cleanup(func() { + var o simplyblockv1alpha2.ObjectStore + if cli.Get(context.Background(), client.ObjectKeyFromObject(store), &o) == nil { + o.Finalizers = nil + _ = cli.Update(context.Background(), &o) + } + }) + + bucket := &simplyblockv1alpha2.S3Bucket{ + ObjectMeta: metav1.ObjectMeta{Name: "i16-bucket", Namespace: store.Namespace}, + Spec: simplyblockv1alpha2.S3BucketSpec{ + ObjectStoreRef: store.Name, BucketName: "i16-bucket", + CapacityBytes: 50 * 1 << 20, StorageClassName: fakeStorageClassName, + }, + } + if err := cli.Create(ctx, bucket); err != nil { + t.Fatalf("creating the bucket: %v", err) + } + r := &S3BucketReconciler{Client: cli, Scheme: cli.Scheme(), Recorder: events.NewFakeRecorder(16)} + got := reconcileBucketUntil(t, r, client.ObjectKeyFromObject(bucket), func(b *simplyblockv1alpha2.S3Bucket) bool { + return b.Status.Phase == phaseDegraded || b.Status.Phase == phaseReady + }) + cond := findCondition(got.Status.Conditions, conditionObjectStoreOK) + if got.Status.Phase != phaseDegraded || cond == nil || cond.Reason != reasonObjectStoreNotFound { + t.Errorf("phase = %q, ObjectStoreOK = %+v, want Degraded with reason ObjectStoreNotFound", got.Status.Phase, cond) + } +}