diff --git a/gateway/go.mod b/gateway/go.mod index a2fa17a8e..1feb4c6a4 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 21a24956f..03bee1e6f 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 000000000..3b5c5b675 --- /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 000000000..f9fec14e2 --- /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) + } + }) + } +} 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 9be73f295..6b2a07029 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/helm-charts/charts/simplyblock-operator/templates/roles/manager_role.yaml b/helm-charts/charts/simplyblock-operator/templates/roles/manager_role.yaml index 2f393cf4c..03a3331bc 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/helm-charts/charts/simplyblock-operator/templates/simplyblock-operator.yaml b/helm-charts/charts/simplyblock-operator/templates/simplyblock-operator.yaml index 797636b22..5a8ebf189 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 50fbeef98..64520901c 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/operator/api/v1alpha2/s3bucket_types.go b/operator/api/v1alpha2/s3bucket_types.go index 572c9cf3d..2ddcfb9ab 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 9be73f295..6b2a07029 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/config/rbac/role.yaml b/operator/config/rbac/role.yaml index 6c67bf781..53ad6676f 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/docs/designs/design-bucket-provisioning.md b/operator/docs/designs/design-bucket-provisioning.md index 2327a51c4..66ce66ebb 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 355c1072c..c1c3a374e 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`: @@ -243,18 +243,30 @@ 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 + 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 | -|----------------------------------------------------------------------------------------------------------------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------| -| 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` | +| `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 | --- @@ -301,7 +313,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-bucket-provisioning.md b/operator/docs/tests/test-plan-bucket-provisioning.md index 95f0c2c0f..d69ef0a2a 100644 --- a/operator/docs/tests/test-plan-bucket-provisioning.md +++ b/operator/docs/tests/test-plan-bucket-provisioning.md @@ -82,6 +82,14 @@ 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` | +| 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) | # | Scenario | Type | Test | @@ -189,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 | 13 | 11 | 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 a579acf71..7e072e8da 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` @@ -84,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` | --- @@ -137,32 +149,32 @@ 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) | --- ## 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 | 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 a632def58..18c57d560 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" @@ -28,6 +30,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" @@ -51,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 @@ -89,10 +99,12 @@ 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 // +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) { @@ -103,11 +115,22 @@ 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. + 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). if store.Status.Phase == osPhaseDegraded { - return ctrl.Result{}, nil + return r.reconcileDegraded(ctx, &store) } sm, err := r.restore(ctx, &store) @@ -458,11 +481,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, @@ -475,7 +497,7 @@ func objectStorePhases() statemachine.Config[osPhase] { }, }, osPhaseReady: {To: []osPhase{}}, - osPhaseDegraded: {}, + osPhaseDegraded: {To: []osPhase{osPhaseProvisioning}}, }, } } @@ -555,7 +577,11 @@ 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. 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 @@ -569,6 +595,179 @@ 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()). 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 +} + +// 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 a5c9a7b62..6c39d3f31 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/objectstore_recovery_unit_test.go b/operator/internal/controllers/objectstore/objectstore_recovery_unit_test.go new file mode 100644 index 000000000..176bba0a4 --- /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)) + } +} diff --git a/operator/internal/controllers/objectstore/s3bucket_controller.go b/operator/internal/controllers/objectstore/s3bucket_controller.go index a3954bb6b..e03fc4c48 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 @@ -465,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) { @@ -473,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 61a09680c..57d484f98 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,147 @@ 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") + } +} + +// 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) + } +} diff --git a/support-tool/internal/helmvalues/chart/values.yaml b/support-tool/internal/helmvalues/chart/values.yaml index 50fbeef98..64520901c 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"