From 0e9ea1a3b3293263041b0464124158763aac2337 Mon Sep 17 00:00:00 2001 From: Jonathan Grahl Date: Thu, 30 Apr 2026 21:46:46 -0700 Subject: [PATCH 1/3] refactor(api): replace phase strings with conditions across CRDs --- api/v1alpha1/branch_types.go | 38 ++---- api/v1alpha1/cluster_types.go | 46 ++----- api/v1alpha1/pageserver_types.go | 39 ++---- api/v1alpha1/project_types.go | 39 ++---- api/v1alpha1/safekeeper_types.go | 39 ++---- api/v1alpha1/status_funcs.go | 51 ++++++++ api/v1alpha1/zz_generated.deepcopy.go | 16 --- .../bases/neon.oltp.molnett.org_branches.yaml | 20 +++- .../bases/neon.oltp.molnett.org_clusters.yaml | 33 +++--- .../neon.oltp.molnett.org_pageservers.yaml | 25 ++-- .../bases/neon.oltp.molnett.org_projects.yaml | 20 +++- .../neon.oltp.molnett.org_safekeepers.yaml | 25 ++-- internal/controller/branch_controller.go | 96 +++++++++++---- internal/controller/cluster_controller.go | 73 +++++++++--- internal/controller/pageserver_controller.go | 27 ++--- internal/controller/project_controller.go | 112 ++++++++++++------ internal/controller/safekeeper_controller.go | 27 ++--- specs/pageserver/pod.go | 3 - 18 files changed, 402 insertions(+), 327 deletions(-) create mode 100644 api/v1alpha1/status_funcs.go diff --git a/api/v1alpha1/branch_types.go b/api/v1alpha1/branch_types.go index 86ad94b..621d2d9 100644 --- a/api/v1alpha1/branch_types.go +++ b/api/v1alpha1/branch_types.go @@ -38,20 +38,20 @@ type BranchSpec struct { // BranchStatus defines the observed state of Branch. type BranchStatus struct { - Conditions []metav1.Condition `json:"conditions,omitempty,omitzero"` + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` - Phase string `json:"phase,omitempty"` + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` } -const ( - BranchPhaseCreating = "Creating" - BranchPhaseReady = "Ready" - BranchPhaseCannotCreateResources = "CannotCreateResources" - BranchPhaseTimelineCreationFailed = "TimelineCreationFailed" -) - // +kubebuilder:object:root=true // +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Available",type=string,JSONPath=".status.conditions[?(@.type==\"Available\")].status" +// +kubebuilder:printcolumn:name="Progressing",type=string,JSONPath=".status.conditions[?(@.type==\"Progressing\")].status" +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=".metadata.creationTimestamp" // Branch is the Schema for the branches API type Branch struct { @@ -79,26 +79,6 @@ type BranchList struct { Items []Branch `json:"items"` } -// GetConditions returns the conditions for the branch status -func (b *BranchStatus) GetConditions() []metav1.Condition { - return b.Conditions -} - -// SetConditions sets the conditions for the branch status -func (b *BranchStatus) SetConditions(conditions []metav1.Condition) { - b.Conditions = conditions -} - -// GetPhase returns the phase for the branch status -func (b *BranchStatus) GetPhase() string { - return b.Phase -} - -// SetPhase sets the phase for the branch status -func (b *BranchStatus) SetPhase(phase string) { - b.Phase = phase -} - func init() { SchemeBuilder.Register(&Branch{}, &BranchList{}) } diff --git a/api/v1alpha1/cluster_types.go b/api/v1alpha1/cluster_types.go index f3ea954..323e643 100644 --- a/api/v1alpha1/cluster_types.go +++ b/api/v1alpha1/cluster_types.go @@ -46,32 +46,20 @@ type ClusterSpec struct { // ClusterStatus defines the observed state of Cluster. type ClusterStatus struct { - Conditions []metav1.Condition `json:"conditions,omitempty"` - // +optional - StorageBrokerStatus StorageBrokerStatus `json:"storageBrokerStatus,omitzero"` + ObservedGeneration int64 `json:"observedGeneration,omitempty"` // +optional - Phase string `json:"phase,omitempty"` - - // +optional - PhaseReason string `json:"phaseReason,omitempty"` -} - -const ( - ClusterPhaseCreating = "Creating cluster" - ClusterPhaseReady = "Ready" - ClusterPhaseCannotCreateClusterResources = "Unable to create all necessary cluster resources" -) - -// Represents the current state of the storage broker. -type StorageBrokerStatus struct { - // Total number of ready Storage Brokers instances in the cluster. - ReadyInstances int32 `json:"readyInstances"` + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` } // +kubebuilder:object:root=true // +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Available",type=string,JSONPath=".status.conditions[?(@.type==\"Available\")].status" +// +kubebuilder:printcolumn:name="Progressing",type=string,JSONPath=".status.conditions[?(@.type==\"Progressing\")].status" +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=".metadata.creationTimestamp" // Cluster is the Schema for the clusters API type Cluster struct { @@ -99,26 +87,6 @@ type ClusterList struct { Items []Cluster `json:"items"` } -// GetConditions returns the conditions for the cluster status -func (c *ClusterStatus) GetConditions() []metav1.Condition { - return c.Conditions -} - -// SetConditions sets the conditions for the cluster status -func (c *ClusterStatus) SetConditions(conditions []metav1.Condition) { - c.Conditions = conditions -} - -// GetPhase returns the phase for the cluster status -func (c *ClusterStatus) GetPhase() string { - return c.Phase -} - -// SetPhase sets the phase for the cluster status -func (c *ClusterStatus) SetPhase(phase string) { - c.Phase = phase -} - func init() { SchemeBuilder.Register(&Cluster{}, &ClusterList{}) } diff --git a/api/v1alpha1/pageserver_types.go b/api/v1alpha1/pageserver_types.go index 1fb8b95..95e7c9a 100644 --- a/api/v1alpha1/pageserver_types.go +++ b/api/v1alpha1/pageserver_types.go @@ -39,41 +39,20 @@ type PageserverSpec struct { // PageserverStatus defines the observed state of Pageserver. type PageserverStatus struct { - Conditions []metav1.Condition `json:"conditions"` - - Phase string `json:"phase"` - PhaseReason string `json:"phaseReason,omitempty"` -} - -// GetConditions returns the conditions for the pageserver status -func (b *PageserverStatus) GetConditions() []metav1.Condition { - return b.Conditions -} - -// SetConditions sets the conditions for the pageserver status -func (b *PageserverStatus) SetConditions(conditions []metav1.Condition) { - b.Conditions = conditions -} - -// GetPhase returns the phase for the pageserver status -func (b *PageserverStatus) GetPhase() string { - return b.Phase -} + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` -// SetPhase sets the phase for the pageserver status -func (b *PageserverStatus) SetPhase(phase string) { - b.Phase = phase + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` } -const ( - PageserverPhaseCreating = "Creating pageserver" - PageserverPhaseReady = "Ready" - PageserverPhaseInvalidSpec = "Invalid spec" - PageserverPhaseCannotCreateResources = "Unable to create all necessary pageserver resources" -) - // +kubebuilder:object:root=true // +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Available",type=string,JSONPath=".status.conditions[?(@.type==\"Available\")].status" +// +kubebuilder:printcolumn:name="Progressing",type=string,JSONPath=".status.conditions[?(@.type==\"Progressing\")].status" +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=".metadata.creationTimestamp" // Pageserver is the Schema for the pageservers API type Pageserver struct { diff --git a/api/v1alpha1/project_types.go b/api/v1alpha1/project_types.go index 0358c85..9b3350b 100644 --- a/api/v1alpha1/project_types.go +++ b/api/v1alpha1/project_types.go @@ -37,21 +37,20 @@ type ProjectSpec struct { // ProjectStatus defines the observed state of Project. type ProjectStatus struct { - Conditions []metav1.Condition `json:"conditions,omitempty,omitzero"` + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` - Phase string `json:"phase,omitempty"` + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` } -const ( - ProjectPhasePending = "Pending" - ProjectPhaseCreating = "Creating" - ProjectPhaseReady = "Ready" - ProjectPhaseTenantCreationFailed = "TenantCreationFailed" - ProjectPhasePageserverConnectionError = "PageserverConnectionError" -) - // +kubebuilder:object:root=true // +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Available",type=string,JSONPath=".status.conditions[?(@.type==\"Available\")].status" +// +kubebuilder:printcolumn:name="Progressing",type=string,JSONPath=".status.conditions[?(@.type==\"Progressing\")].status" +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=".metadata.creationTimestamp" // Project is the Schema for the projects API type Project struct { @@ -79,26 +78,6 @@ type ProjectList struct { Items []Project `json:"items"` } -// GetConditions returns the conditions for the project status -func (p *ProjectStatus) GetConditions() []metav1.Condition { - return p.Conditions -} - -// SetConditions sets the conditions for the project status -func (p *ProjectStatus) SetConditions(conditions []metav1.Condition) { - p.Conditions = conditions -} - -// GetPhase returns the phase for the project status -func (p *ProjectStatus) GetPhase() string { - return p.Phase -} - -// SetPhase sets the phase for the project status -func (p *ProjectStatus) SetPhase(phase string) { - p.Phase = phase -} - func init() { SchemeBuilder.Register(&Project{}, &ProjectList{}) } diff --git a/api/v1alpha1/safekeeper_types.go b/api/v1alpha1/safekeeper_types.go index fd30ecf..0241cad 100644 --- a/api/v1alpha1/safekeeper_types.go +++ b/api/v1alpha1/safekeeper_types.go @@ -45,21 +45,20 @@ type SafekeeperSpec struct { // SafekeeperStatus defines the observed state of Safekeeper. type SafekeeperStatus struct { - Conditions []metav1.Condition `json:"conditions"` + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` - Phase string `json:"phase"` - PhaseReason string `json:"phaseReason,omitempty"` + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` } -const ( - SafekeeperPhaseCreating = "Creating safekeeper" - SafekeeperPhaseReady = "Ready" - SafekeeperPhaseInvalidSpec = "Invalid spec" - SafekeeperPhaseCannotCreateResources = "Unable to create all necessary safekeeper resources" -) - // +kubebuilder:object:root=true // +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Available",type=string,JSONPath=".status.conditions[?(@.type==\"Available\")].status" +// +kubebuilder:printcolumn:name="Progressing",type=string,JSONPath=".status.conditions[?(@.type==\"Progressing\")].status" +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=".metadata.creationTimestamp" // Safekeeper is the Schema for the safekeepers API type Safekeeper struct { @@ -78,26 +77,6 @@ type Safekeeper struct { Status SafekeeperStatus `json:"status,omitzero"` } -// GetConditions returns the conditions for the safekeeper status -func (b *SafekeeperStatus) GetConditions() []metav1.Condition { - return b.Conditions -} - -// SetConditions sets the conditions for the safekeeper status -func (b *SafekeeperStatus) SetConditions(conditions []metav1.Condition) { - b.Conditions = conditions -} - -// GetPhase returns the phase for the safekeeper status -func (b *SafekeeperStatus) GetPhase() string { - return b.Phase -} - -// SetPhase sets the phase for the safekeeper status -func (b *SafekeeperStatus) SetPhase(phase string) { - b.Phase = phase -} - // +kubebuilder:object:root=true // SafekeeperList contains a list of Safekeeper diff --git a/api/v1alpha1/status_funcs.go b/api/v1alpha1/status_funcs.go new file mode 100644 index 0000000..ef1da50 --- /dev/null +++ b/api/v1alpha1/status_funcs.go @@ -0,0 +1,51 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func (c *Cluster) StatusValue() any { return c.Status } +func (c *Cluster) StatusConditions() *[]metav1.Condition { return &c.Status.Conditions } +func (c *Cluster) SetObservedGeneration(g int64) { c.Status.ObservedGeneration = g } +func (c *Cluster) AssignStatusFrom(o client.Object) { + if other, ok := o.(*Cluster); ok { + c.Status = other.Status + } +} + +func (p *Project) StatusValue() any { return p.Status } +func (p *Project) StatusConditions() *[]metav1.Condition { return &p.Status.Conditions } +func (p *Project) SetObservedGeneration(g int64) { p.Status.ObservedGeneration = g } +func (p *Project) AssignStatusFrom(o client.Object) { + if other, ok := o.(*Project); ok { + p.Status = other.Status + } +} + +func (b *Branch) StatusValue() any { return b.Status } +func (b *Branch) StatusConditions() *[]metav1.Condition { return &b.Status.Conditions } +func (b *Branch) SetObservedGeneration(g int64) { b.Status.ObservedGeneration = g } +func (b *Branch) AssignStatusFrom(o client.Object) { + if other, ok := o.(*Branch); ok { + b.Status = other.Status + } +} + +func (p *Pageserver) StatusValue() any { return p.Status } +func (p *Pageserver) StatusConditions() *[]metav1.Condition { return &p.Status.Conditions } +func (p *Pageserver) SetObservedGeneration(g int64) { p.Status.ObservedGeneration = g } +func (p *Pageserver) AssignStatusFrom(o client.Object) { + if other, ok := o.(*Pageserver); ok { + p.Status = other.Status + } +} + +func (s *Safekeeper) StatusValue() any { return s.Status } +func (s *Safekeeper) StatusConditions() *[]metav1.Condition { return &s.Status.Conditions } +func (s *Safekeeper) SetObservedGeneration(g int64) { s.Status.ObservedGeneration = g } +func (s *Safekeeper) AssignStatusFrom(o client.Object) { + if other, ok := o.(*Safekeeper); ok { + s.Status = other.Status + } +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index cf8b422..630688b 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -216,7 +216,6 @@ func (in *ClusterStatus) DeepCopyInto(out *ClusterStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } - out.StorageBrokerStatus = in.StorageBrokerStatus } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterStatus. @@ -524,21 +523,6 @@ func (in *SafekeeperStatus) DeepCopy() *SafekeeperStatus { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *StorageBrokerStatus) DeepCopyInto(out *StorageBrokerStatus) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StorageBrokerStatus. -func (in *StorageBrokerStatus) DeepCopy() *StorageBrokerStatus { - if in == nil { - return nil - } - out := new(StorageBrokerStatus) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StorageConfig) DeepCopyInto(out *StorageConfig) { *out = *in diff --git a/config/crd/bases/neon.oltp.molnett.org_branches.yaml b/config/crd/bases/neon.oltp.molnett.org_branches.yaml index 0256092..ce1bbf8 100644 --- a/config/crd/bases/neon.oltp.molnett.org_branches.yaml +++ b/config/crd/bases/neon.oltp.molnett.org_branches.yaml @@ -14,7 +14,17 @@ spec: singular: branch scope: Namespaced versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - jsonPath: .status.conditions[?(@.type=="Progressing")].status + name: Progressing + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: Branch is the Schema for the branches API @@ -116,8 +126,12 @@ spec: - type type: object type: array - phase: - type: string + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + observedGeneration: + format: int64 + type: integer type: object required: - spec diff --git a/config/crd/bases/neon.oltp.molnett.org_clusters.yaml b/config/crd/bases/neon.oltp.molnett.org_clusters.yaml index a864aa1..5b91f24 100644 --- a/config/crd/bases/neon.oltp.molnett.org_clusters.yaml +++ b/config/crd/bases/neon.oltp.molnett.org_clusters.yaml @@ -14,7 +14,17 @@ spec: singular: cluster scope: Namespaced versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - jsonPath: .status.conditions[?(@.type=="Progressing")].status + name: Progressing + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: Cluster is the Schema for the clusters API @@ -160,21 +170,12 @@ spec: - type type: object type: array - phase: - type: string - phaseReason: - type: string - storageBrokerStatus: - description: Represents the current state of the storage broker. - properties: - readyInstances: - description: Total number of ready Storage Brokers instances in - the cluster. - format: int32 - type: integer - required: - - readyInstances - type: object + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + observedGeneration: + format: int64 + type: integer type: object required: - metadata diff --git a/config/crd/bases/neon.oltp.molnett.org_pageservers.yaml b/config/crd/bases/neon.oltp.molnett.org_pageservers.yaml index 7ff1056..c1db1f1 100644 --- a/config/crd/bases/neon.oltp.molnett.org_pageservers.yaml +++ b/config/crd/bases/neon.oltp.molnett.org_pageservers.yaml @@ -14,7 +14,17 @@ spec: singular: pageserver scope: Namespaced versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - jsonPath: .status.conditions[?(@.type=="Progressing")].status + name: Progressing + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: Pageserver is the Schema for the pageservers API @@ -142,13 +152,12 @@ spec: - type type: object type: array - phase: - type: string - phaseReason: - type: string - required: - - conditions - - phase + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + observedGeneration: + format: int64 + type: integer type: object required: - spec diff --git a/config/crd/bases/neon.oltp.molnett.org_projects.yaml b/config/crd/bases/neon.oltp.molnett.org_projects.yaml index 8988af5..99d2428 100644 --- a/config/crd/bases/neon.oltp.molnett.org_projects.yaml +++ b/config/crd/bases/neon.oltp.molnett.org_projects.yaml @@ -14,7 +14,17 @@ spec: singular: project scope: Namespaced versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - jsonPath: .status.conditions[?(@.type=="Progressing")].status + name: Progressing + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: Project is the Schema for the projects API @@ -112,8 +122,12 @@ spec: - type type: object type: array - phase: - type: string + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + observedGeneration: + format: int64 + type: integer type: object required: - spec diff --git a/config/crd/bases/neon.oltp.molnett.org_safekeepers.yaml b/config/crd/bases/neon.oltp.molnett.org_safekeepers.yaml index a24657a..88099b9 100644 --- a/config/crd/bases/neon.oltp.molnett.org_safekeepers.yaml +++ b/config/crd/bases/neon.oltp.molnett.org_safekeepers.yaml @@ -14,7 +14,17 @@ spec: singular: safekeeper scope: Namespaced versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Available")].status + name: Available + type: string + - jsonPath: .status.conditions[?(@.type=="Progressing")].status + name: Progressing + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: Safekeeper is the Schema for the safekeepers API @@ -127,13 +137,12 @@ spec: - type type: object type: array - phase: - type: string - phaseReason: - type: string - required: - - conditions - - phase + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + observedGeneration: + format: int64 + type: integer type: object required: - spec diff --git a/internal/controller/branch_controller.go b/internal/controller/branch_controller.go index 725e3e9..4a1eaff 100644 --- a/internal/controller/branch_controller.go +++ b/internal/controller/branch_controller.go @@ -28,6 +28,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" @@ -99,14 +100,6 @@ func (r *BranchReconciler) getBranch(ctx context.Context, req ctrl.Request) (*ne func (r *BranchReconciler) reconcile(ctx context.Context, branch *neonv1alpha1.Branch) (ctrl.Result, error) { log := logf.FromContext(ctx) - if branch.Status.Phase == "" { - if err := utils.SetPhases(ctx, r.Client, branch, utils.SetBranchCreatingStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting default Status: %w", err) - } - log.Info("Branch phase set to creating") - } - - // Generate timeline_id if not set if branch.Spec.TimelineID == "" { if err := r.updateTimelineID(ctx, branch); err != nil { return ctrl.Result{}, fmt.Errorf("failed to update timelineID: %w", err) @@ -114,38 +107,93 @@ func (r *BranchReconciler) reconcile(ctx context.Context, branch *neonv1alpha1.B return ctrl.Result{RequeueAfter: time.Second}, nil } - // Get the project for this branch project, err := r.getProject(ctx, branch.Spec.ProjectID, branch.Namespace) if err != nil { log.Error(err, "failed to get project", "projectID", branch.Spec.ProjectID) return ctrl.Result{}, err } - // Create timeline on storage controller - if err := r.ensureTimeline(ctx, branch, project); err != nil { - log.Error(err, "failed to ensure timeline") - return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + timelineErr := r.ensureTimeline(ctx, branch, project) + if timelineErr != nil { + log.Error(timelineErr, "failed to ensure timeline") } - // Create branch resources - if err := r.createBranchResources(ctx, branch, project); err != nil { - log.Error(err, "error while creating branch resources") - if setErr := utils.SetPhases(ctx, r.Client, branch, utils.SetBranchCannotCreateResourcesStatus); setErr != nil { - log.Error(setErr, "failed to set branch status") + var createErr error + if timelineErr == nil { + createErr = r.createBranchResources(ctx, branch, project) + if createErr != nil { + log.Error(createErr, "error while creating branch resources") } - return ctrl.Result{}, fmt.Errorf("not able to create branch resources: %w", err) } - // Set branch to ready status after successful resource creation - if err := utils.SetPhases(ctx, r.Client, branch, utils.SetBranchReadyStatus); err != nil { - log.Error(err, "failed to set branch ready status") - return ctrl.Result{}, fmt.Errorf("failed to update branch status to ready: %w", err) + if statusErr := r.updateStatus(ctx, branch, timelineErr, createErr); statusErr != nil { + log.Error(statusErr, "failed to update branch status") + return ctrl.Result{}, statusErr } - log.Info("Branch status set to ready") + if timelineErr != nil { + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + } + if createErr != nil { + return ctrl.Result{}, fmt.Errorf("not able to create branch resources: %w", createErr) + } return ctrl.Result{}, nil } +func (r *BranchReconciler) updateStatus(ctx context.Context, branch *neonv1alpha1.Branch, timelineErr, createErr error) error { + deploymentName := fmt.Sprintf("%s-compute-node", branch.Name) + dep := &appsv1.Deployment{} + depErr := r.Get(ctx, types.NamespacedName{Name: deploymentName, Namespace: branch.Namespace}, dep) + + return utils.PatchStatus(ctx, r.Client, branch, func(b *neonv1alpha1.Branch) { + b.Status.ObservedGeneration = b.Generation + conds := &b.Status.Conditions + + if b.Spec.TimelineID != "" { + utils.SetCondition(b, conds, utils.ConditionTimelineIDAssigned, metav1.ConditionTrue, utils.ReasonAsExpected, "Timeline ID is assigned") + } else { + utils.SetCondition(b, conds, utils.ConditionTimelineIDAssigned, metav1.ConditionFalse, utils.ReasonTimelineIDPending, "Timeline ID has not been generated yet") + } + + if timelineErr != nil { + utils.SetCondition(b, conds, utils.ConditionTimelineCreated, metav1.ConditionFalse, utils.ReasonTimelineCreationFailed, timelineErr.Error()) + } else { + utils.SetCondition(b, conds, utils.ConditionTimelineCreated, metav1.ConditionTrue, utils.ReasonAsExpected, "Timeline created on storage controller") + } + + computeReady := metav1.ConditionFalse + computeReason := utils.ReasonReconciling + computeMessage := "Compute Deployment is not Available yet" + switch { + case createErr != nil: + computeReason = utils.ReasonResourceCreateFailed + computeMessage = createErr.Error() + case apierrors.IsNotFound(depErr): + computeReason = utils.ReasonChildResourceMissing + computeMessage = "Compute Deployment has not been observed yet" + case depErr != nil: + computeReady = metav1.ConditionUnknown + computeReason = utils.ReasonChildResourceMissing + computeMessage = depErr.Error() + case utils.IsDeploymentAvailable(dep): + computeReady = metav1.ConditionTrue + computeReason = utils.ReasonAsExpected + computeMessage = "Compute Deployment is Available" + default: + computeReason = utils.ReasonChildDeploymentNotAvailable + } + utils.SetCondition(b, conds, utils.ConditionComputeReady, computeReady, computeReason, computeMessage) + + if timelineErr == nil && computeReady == metav1.ConditionTrue { + utils.SetCondition(b, conds, utils.ConditionAvailable, metav1.ConditionTrue, utils.ReasonAsExpected, "Branch is Available") + utils.SetCondition(b, conds, utils.ConditionProgressing, metav1.ConditionFalse, utils.ReasonAsExpected, "Branch is at desired state") + } else { + utils.SetCondition(b, conds, utils.ConditionAvailable, metav1.ConditionFalse, computeReason, computeMessage) + utils.SetCondition(b, conds, utils.ConditionProgressing, metav1.ConditionTrue, utils.ReasonReconciling, "Working toward desired state") + } + }) +} + func (r *BranchReconciler) updateTimelineID(ctx context.Context, branch *neonv1alpha1.Branch) error { log := logf.FromContext(ctx) diff --git a/internal/controller/cluster_controller.go b/internal/controller/cluster_controller.go index 37fe342..c5df743 100644 --- a/internal/controller/cluster_controller.go +++ b/internal/controller/cluster_controller.go @@ -24,7 +24,9 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" @@ -86,32 +88,67 @@ func (r *ClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct func (r *ClusterReconciler) reconcile(ctx context.Context, cluster *neonv1alpha1.Cluster) (ctrl.Result, error) { log := logf.FromContext(ctx) - if cluster.Status.Phase == "" { - if err := utils.SetPhases(ctx, r.Client, cluster, utils.SetClusterCreatingStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting default Status: %w", err) - } - log.Info("Cluster phase set to creating") + createErr := r.createClusterResources(ctx, cluster) + if createErr != nil { + log.Error(createErr, "error while creating cluster resources") } - err := r.createClusterResources(ctx, cluster) - if err != nil { - log.Error(err, "error while creating cluster resources") - if setErr := utils.SetPhases(ctx, r.Client, cluster, utils.SetClusterCannotCreateResourcesStatus); setErr != nil { - log.Error(setErr, "failed to set cluster status") - } - return ctrl.Result{}, fmt.Errorf("not able to create cluster resources: %w", err) + if err := r.updateStatus(ctx, cluster, createErr); err != nil { + log.Error(err, "failed to update cluster status") + return ctrl.Result{}, err } - // Set cluster to ready status after successful resource creation - if err := utils.SetPhases(ctx, r.Client, cluster, utils.SetClusterReadyStatus); err != nil { - log.Error(err, "failed to set cluster ready status") - return ctrl.Result{}, fmt.Errorf("failed to update cluster status to ready: %w", err) + if createErr != nil { + return ctrl.Result{}, fmt.Errorf("not able to create cluster resources: %w", createErr) } - log.Info("Cluster status set to ready") - return ctrl.Result{}, nil } +func (r *ClusterReconciler) updateStatus(ctx context.Context, cluster *neonv1alpha1.Cluster, reconcileErr error) error { + scAvailable, scReason, scMessage := r.deploymentState(ctx, cluster, fmt.Sprintf("%s-storage-controller", cluster.Name), "Storage controller") + sbAvailable, sbReason, sbMessage := r.deploymentState(ctx, cluster, fmt.Sprintf("%s-storage-broker", cluster.Name), "Storage broker") + + return utils.PatchStatus(ctx, r.Client, cluster, func(c *neonv1alpha1.Cluster) { + c.Status.ObservedGeneration = c.Generation + conds := &c.Status.Conditions + + if reconcileErr != nil { + utils.SetCondition(c, conds, utils.ConditionAvailable, metav1.ConditionFalse, utils.ReasonResourceCreateFailed, reconcileErr.Error()) + utils.SetCondition(c, conds, utils.ConditionProgressing, metav1.ConditionTrue, utils.ReasonReconciling, "Retrying after resource creation failure") + utils.SetCondition(c, conds, utils.ConditionStorageControllerAvailable, scAvailable, scReason, scMessage) + utils.SetCondition(c, conds, utils.ConditionStorageBrokerAvailable, sbAvailable, sbReason, sbMessage) + return + } + + utils.SetCondition(c, conds, utils.ConditionStorageControllerAvailable, scAvailable, scReason, scMessage) + utils.SetCondition(c, conds, utils.ConditionStorageBrokerAvailable, sbAvailable, sbReason, sbMessage) + + switch { + case scAvailable == metav1.ConditionTrue && sbAvailable == metav1.ConditionTrue: + utils.SetCondition(c, conds, utils.ConditionAvailable, metav1.ConditionTrue, utils.ReasonAsExpected, "Cluster components are Available") + utils.SetCondition(c, conds, utils.ConditionProgressing, metav1.ConditionFalse, utils.ReasonAsExpected, "Cluster is at desired state") + default: + utils.SetCondition(c, conds, utils.ConditionAvailable, metav1.ConditionFalse, utils.ReasonChildDeploymentNotAvailable, "One or more cluster components are not Available") + utils.SetCondition(c, conds, utils.ConditionProgressing, metav1.ConditionTrue, utils.ReasonReconciling, "Waiting for child Deployments to become Available") + } + }) +} + +func (r *ClusterReconciler) deploymentState(ctx context.Context, cluster *neonv1alpha1.Cluster, name, label string) (metav1.ConditionStatus, string, string) { + dep := &appsv1.Deployment{} + err := r.Get(ctx, types.NamespacedName{Name: name, Namespace: cluster.Namespace}, dep) + switch { + case apierrors.IsNotFound(err): + return metav1.ConditionFalse, utils.ReasonChildResourceMissing, fmt.Sprintf("%s Deployment has not been observed yet", label) + case err != nil: + return metav1.ConditionUnknown, utils.ReasonChildResourceMissing, err.Error() + case utils.IsDeploymentAvailable(dep): + return metav1.ConditionTrue, utils.ReasonAsExpected, fmt.Sprintf("%s Deployment is Available", label) + default: + return metav1.ConditionFalse, utils.ReasonChildDeploymentNotAvailable, fmt.Sprintf("%s Deployment is not yet Available", label) + } +} + func (r *ClusterReconciler) getCluster(ctx context.Context, req ctrl.Request) (*neonv1alpha1.Cluster, error) { log := logf.FromContext(ctx) cluster := &neonv1alpha1.Cluster{} diff --git a/internal/controller/pageserver_controller.go b/internal/controller/pageserver_controller.go index e6853e9..4d3a49a 100644 --- a/internal/controller/pageserver_controller.go +++ b/internal/controller/pageserver_controller.go @@ -90,29 +90,20 @@ func (r *PageserverReconciler) getPageserver(ctx context.Context, req ctrl.Reque func (r *PageserverReconciler) reconcile(ctx context.Context, pageserver *neonv1alpha1.Pageserver) (ctrl.Result, error) { log := logf.FromContext(ctx) - if pageserver.Status.Phase == "" { - if err := utils.SetPhases(ctx, r.Client, pageserver, utils.SetPageserverCreatingStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting default Status: %w", err) - } - log.Info("Pageserver phase set to creating") + createErr := r.createPageserverResources(ctx, pageserver) + if createErr != nil { + log.Error(createErr, "error while creating pageserver resources") } - err := r.createPageserverResources(ctx, pageserver) - if err != nil { - log.Error(err, "error while creating pageserver resources") - if setErr := utils.SetPhases(ctx, r.Client, pageserver, utils.SetPageserverCannotCreateResourcesStatus); setErr != nil { - log.Error(setErr, "failed to set pageserver status") - } - return ctrl.Result{}, fmt.Errorf("not able to create pageserver resources: %w", err) + podName := fmt.Sprintf("%s-pageserver-%d", pageserver.Spec.Cluster, pageserver.Spec.ID) + if err := utils.UpdatePodBackedStatus(ctx, r.Client, pageserver, podName, "Pageserver", createErr); err != nil { + log.Error(err, "failed to update pageserver status") + return ctrl.Result{}, err } - // Set pageserver to ready status after successful resource creation - if err := utils.SetPhases(ctx, r.Client, pageserver, utils.SetPageserverReadyStatus); err != nil { - log.Error(err, "failed to set pageserver ready status") - return ctrl.Result{}, fmt.Errorf("failed to update pageserver status to ready: %w", err) + if createErr != nil { + return ctrl.Result{}, fmt.Errorf("not able to create pageserver resources: %w", createErr) } - log.Info("Pageserver status set to ready") - return ctrl.Result{}, nil } diff --git a/internal/controller/project_controller.go b/internal/controller/project_controller.go index 0c78ba6..23acaec 100644 --- a/internal/controller/project_controller.go +++ b/internal/controller/project_controller.go @@ -21,12 +21,17 @@ import ( "context" "errors" "fmt" + "io" + "net" "net/http" + "syscall" "time" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + utilnet "k8s.io/apimachinery/pkg/util/net" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" @@ -35,6 +40,11 @@ import ( "oltp.molnett.org/neon-operator/utils" ) +type projectStatusInputs struct { + TenantIDErr error + AttachErr error +} + // ProjectReconciler reconciles a Project object type ProjectReconciler struct { client.Client @@ -79,48 +89,92 @@ func (r *ProjectReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct func (r *ProjectReconciler) reconcile(ctx context.Context, project *neonv1alpha1.Project) (ctrl.Result, error) { log := logf.FromContext(ctx) - if project.Status.Phase == "" { - if err := utils.SetPhases(ctx, r.Client, project, utils.SetProjectPendingStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting pending status: %w", err) - } - log.Info("Project phase set to pending") - } - if project.Spec.TenantID == "" { tenantID := utils.GenerateNeonID() - - if err := utils.SetPhases(ctx, r.Client, project, utils.SetProjectCreatingStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting creating status: %w", err) - } - if err := r.updateTenantID(ctx, project, tenantID); err != nil { log.Error(err, "Failed to update tenant ID") - if setErr := utils.SetPhases(ctx, r.Client, project, func(p *neonv1alpha1.Project) { - utils.SetProjectTenantCreationFailedStatus(p, fmt.Sprintf("Failed to update tenant ID: %v", err)) - }); setErr != nil { - log.Error(setErr, "failed to set project status") + if statusErr := r.updateStatus(ctx, project, projectStatusInputs{TenantIDErr: fmt.Errorf("failed to update tenant ID: %w", err)}); statusErr != nil { + log.Error(statusErr, "failed to update project status") } return ctrl.Result{}, fmt.Errorf("failed to update tenant ID: %w", err) } - log.Info("Generated and set tenant ID", "tenantID", tenantID) return ctrl.Result{RequeueAfter: time.Second}, ErrRequeueAfterChange } - err := r.ensureTenantOnPageserver(ctx, project) - if err != nil { - log.Error(err, "Failed to ensure tenant on pageserver") - return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + attachErr := r.ensureTenantOnPageserver(ctx, project) + if attachErr != nil { + log.Error(attachErr, "Failed to ensure tenant on pageserver") } - if err := utils.SetPhases(ctx, r.Client, project, utils.SetProjectReadyStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting ready status: %w", err) + if statusErr := r.updateStatus(ctx, project, projectStatusInputs{AttachErr: attachErr}); statusErr != nil { + log.Error(statusErr, "failed to update project status") + return ctrl.Result{}, statusErr } - log.Info("Project is ready") + if attachErr != nil { + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + } return ctrl.Result{}, nil } +func (r *ProjectReconciler) updateStatus(ctx context.Context, project *neonv1alpha1.Project, in projectStatusInputs) error { + return utils.PatchStatus(ctx, r.Client, project, func(p *neonv1alpha1.Project) { + p.Status.ObservedGeneration = p.Generation + conds := &p.Status.Conditions + + switch { + case in.TenantIDErr != nil: + utils.SetCondition(p, conds, utils.ConditionTenantIDAssigned, metav1.ConditionFalse, utils.ReasonTenantIDPending, in.TenantIDErr.Error()) + case p.Spec.TenantID != "": + utils.SetCondition(p, conds, utils.ConditionTenantIDAssigned, metav1.ConditionTrue, utils.ReasonAsExpected, "Tenant ID is assigned") + default: + utils.SetCondition(p, conds, utils.ConditionTenantIDAssigned, metav1.ConditionFalse, utils.ReasonTenantIDPending, "Tenant ID has not been generated yet") + } + + switch { + case in.TenantIDErr != nil: + utils.SetCondition(p, conds, utils.ConditionAttached, metav1.ConditionFalse, utils.ReasonTenantIDPending, "Tenant ID assignment failed") + case in.AttachErr != nil: + reason := utils.ReasonAttachFailed + if isConnectionError(in.AttachErr) { + reason = utils.ReasonStorageControllerUnreachable + } + utils.SetCondition(p, conds, utils.ConditionAttached, metav1.ConditionFalse, reason, in.AttachErr.Error()) + case p.Spec.TenantID == "": + utils.SetCondition(p, conds, utils.ConditionAttached, metav1.ConditionFalse, utils.ReasonTenantIDPending, "Tenant ID has not been assigned") + default: + utils.SetCondition(p, conds, utils.ConditionAttached, metav1.ConditionTrue, utils.ReasonAsExpected, "Tenant attached on storage controller") + } + + if in.TenantIDErr == nil && in.AttachErr == nil && p.Spec.TenantID != "" { + utils.SetCondition(p, conds, utils.ConditionAvailable, metav1.ConditionTrue, utils.ReasonAsExpected, "Project is Available") + utils.SetCondition(p, conds, utils.ConditionProgressing, metav1.ConditionFalse, utils.ReasonAsExpected, "Project is at desired state") + } else { + utils.SetCondition(p, conds, utils.ConditionAvailable, metav1.ConditionFalse, utils.ReasonReconciling, "Project is not yet Available") + utils.SetCondition(p, conds, utils.ConditionProgressing, metav1.ConditionTrue, utils.ReasonReconciling, "Working toward desired state") + } + }) +} + +func isConnectionError(err error) bool { + if err == nil { + return false + } + if utilnet.IsConnectionRefused(err) || utilnet.IsConnectionReset(err) { + return true + } + if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, io.EOF) { + return true + } + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + return true + } + var dnsErr *net.DNSError + return errors.As(err, &dnsErr) +} + func (r *ProjectReconciler) getProject(ctx context.Context, req ctrl.Request) (*neonv1alpha1.Project, error) { log := logf.FromContext(ctx) project := &neonv1alpha1.Project{} @@ -175,11 +229,6 @@ func (r *ProjectReconciler) ensureTenantOnPageserver(ctx context.Context, projec resp, err := httpClient.Do(req) if err != nil { log.Info("Failed to connect to storage controller, will retry", "error", err, "url", storageControllerURL) - if setErr := utils.SetPhases(ctx, r.Client, project, func(p *neonv1alpha1.Project) { - utils.SetProjectPageserverConnectionErrorStatus(p, fmt.Sprintf("Failed to connect to pageserver: %v", err)) - }); setErr != nil { - log.Error(setErr, "failed to set project status") - } return err } defer func() { @@ -190,11 +239,6 @@ func (r *ProjectReconciler) ensureTenantOnPageserver(ctx context.Context, projec if resp.StatusCode < 200 || resp.StatusCode >= 300 { log.Info("Storage controller returned error status", "status", resp.Status) - if setErr := utils.SetPhases(ctx, r.Client, project, func(p *neonv1alpha1.Project) { - utils.SetProjectTenantCreationFailedStatus(p, fmt.Sprintf("Pageserver returned status: %s", resp.Status)) - }); setErr != nil { - log.Error(setErr, "failed to set project status") - } return fmt.Errorf("pageserver returned status: %s", resp.Status) } diff --git a/internal/controller/safekeeper_controller.go b/internal/controller/safekeeper_controller.go index 3af794f..93d5fe0 100644 --- a/internal/controller/safekeeper_controller.go +++ b/internal/controller/safekeeper_controller.go @@ -89,29 +89,20 @@ func (r *SafekeeperReconciler) getSafekeeper(ctx context.Context, req ctrl.Reque func (r *SafekeeperReconciler) reconcile(ctx context.Context, safekeeper *neonv1alpha1.Safekeeper) (ctrl.Result, error) { log := logf.FromContext(ctx) - if safekeeper.Status.Phase == "" { - if err := utils.SetPhases(ctx, r.Client, safekeeper, utils.SetSafekeeperCreatingStatus); err != nil { - return ctrl.Result{}, fmt.Errorf("error setting default Status: %w", err) - } - log.Info("Safekeeper phase set to creating") + createErr := r.createSafekeeperResources(ctx, safekeeper) + if createErr != nil { + log.Error(createErr, "error while creating safekeeper resources") } - err := r.createSafekeeperResources(ctx, safekeeper) - if err != nil { - log.Error(err, "error while creating safekeeper resources") - if setErr := utils.SetPhases(ctx, r.Client, safekeeper, utils.SetSafekeeperCannotCreateResourcesStatus); setErr != nil { - log.Error(setErr, "failed to set safekeeper status") - } - return ctrl.Result{}, fmt.Errorf("not able to create safekeeper resources: %w", err) + podName := fmt.Sprintf("%s-safekeeper-%d", safekeeper.Spec.Cluster, safekeeper.Spec.ID) + if err := utils.UpdatePodBackedStatus(ctx, r.Client, safekeeper, podName, "Safekeeper", createErr); err != nil { + log.Error(err, "failed to update safekeeper status") + return ctrl.Result{}, err } - // Set safekeeper to ready status after successful resource creation - if err := utils.SetPhases(ctx, r.Client, safekeeper, utils.SetSafekeeperReadyStatus); err != nil { - log.Error(err, "failed to set safekeeper ready status") - return ctrl.Result{}, fmt.Errorf("failed to update safekeeper status to ready: %w", err) + if createErr != nil { + return ctrl.Result{}, fmt.Errorf("not able to create safekeeper resources: %w", createErr) } - log.Info("Safekeeper status set to ready") - return ctrl.Result{}, nil } diff --git a/specs/pageserver/pod.go b/specs/pageserver/pod.go index 9eb6429..4e742f7 100644 --- a/specs/pageserver/pod.go +++ b/specs/pageserver/pod.go @@ -24,9 +24,6 @@ func Pod(pageserver *v1alpha1.Pageserver, image string) *corev1.Pod { "molnett.org/component": "pageserver", "molnett.org/pageserver": pageserver.Name, }, - Finalizers: []string{ - "pageserver.neon.io/finalizer", - }, }, Spec: corev1.PodSpec{ SecurityContext: &corev1.PodSecurityContext{ From fa804917a61fb5952a9c08b3c58bc227fd1e16ad Mon Sep 17 00:00:00 2001 From: Jonathan Grahl Date: Thu, 30 Apr 2026 21:49:03 -0700 Subject: [PATCH 2/3] fix(utils): add missing status helpers and tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These files were left out of the previous commit and broke compilation on CI — the api/v1alpha1 types no longer expose Phase/SetPhase, but the old utils/status.go still referenced them. --- utils/status.go | 405 +++++++++--------------- utils/status_test.go | 735 ++++--------------------------------------- 2 files changed, 207 insertions(+), 933 deletions(-) diff --git a/utils/status.go b/utils/status.go index fc8b6ad..f89734a 100644 --- a/utils/status.go +++ b/utils/status.go @@ -18,305 +18,196 @@ package utils import ( "context" + "fmt" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" logf "sigs.k8s.io/controller-runtime/pkg/log" +) + +const ( + ConditionAvailable = "Available" + ConditionProgressing = "Progressing" + ConditionStorageControllerAvailable = "StorageControllerAvailable" + ConditionStorageBrokerAvailable = "StorageBrokerAvailable" + ConditionTenantIDAssigned = "TenantIDAssigned" + ConditionAttached = "Attached" + ConditionTimelineIDAssigned = "TimelineIDAssigned" + ConditionTimelineCreated = "TimelineCreated" + ConditionComputeReady = "ComputeReady" + ConditionResourcesReady = "ResourcesReady" +) - neonv1alpha1 "oltp.molnett.org/neon-operator/api/v1alpha1" +const ( + ReasonAsExpected = "AsExpected" + ReasonReconciling = "Reconciling" + ReasonChildPodNotReady = "ChildPodNotReady" + ReasonChildDeploymentNotAvailable = "ChildDeploymentNotAvailable" + ReasonChildResourceMissing = "ChildResourceMissing" + ReasonResourceCreateFailed = "ResourceCreateFailed" + ReasonStorageControllerUnreachable = "StorageControllerUnreachable" + ReasonAttachFailed = "AttachFailed" + ReasonTenantIDPending = "TenantIDPending" + ReasonTimelineIDPending = "TimelineIDPending" + ReasonTimelineCreationFailed = "TimelineCreationFailed" ) -// StatusWithConditions defines the interface for status objects that have Conditions and Phase -type StatusWithConditions interface { - GetConditions() []metav1.Condition - SetConditions([]metav1.Condition) - GetPhase() string - SetPhase(string) +// StatusObject is implemented by every CRD with a Status subresource so PatchStatus +// can compare and copy status without a central type switch. +type StatusObject interface { + client.Object + StatusValue() any + AssignStatusFrom(client.Object) } -// SetPhases updates the resource status using provided functions -func SetPhases[T client.Object](ctx context.Context, c client.Client, obj T, statusfns ...func(T)) error { - log := logf.FromContext(ctx) +// PodBackedStatus is implemented by CRDs whose readiness derives from a single +// owned Pod (Pageserver, Safekeeper). +type PodBackedStatus interface { + StatusObject + StatusConditions() *[]metav1.Condition + SetObservedGeneration(int64) +} - log.Info("Setting resource phases") +// SetCondition wraps meta.SetStatusCondition; it preserves LastTransitionTime +// when only ObservedGeneration / Reason / Message change. +func SetCondition(obj client.Object, conds *[]metav1.Condition, t string, status metav1.ConditionStatus, reason, message string) { + meta.SetStatusCondition(conds, metav1.Condition{ + Type: t, + Status: status, + Reason: reason, + Message: message, + ObservedGeneration: obj.GetGeneration(), + }) +} - original := obj.DeepCopyObject().(T) +// PatchStatus runs mutate on a fresh copy of obj and patches the status +// subresource if the resulting status differs. +func PatchStatus[T StatusObject](ctx context.Context, c client.Client, obj T, mutate func(T)) error { + log := logf.FromContext(ctx) current := obj.DeepCopyObject().(T) if err := c.Get(ctx, types.NamespacedName{Name: obj.GetName(), Namespace: obj.GetNamespace()}, current); err != nil { - log.Info("Error getting resource", "error", err) return err } updated := current.DeepCopyObject().(T) + mutate(updated) - for _, statusfn := range statusfns { - statusfn(updated) - } - - originalStatus := getOriginalStatusForComparison(original) - updatedStatus := getOriginalStatusForComparison(updated) - - if equality.Semantic.DeepEqual(originalStatus, updatedStatus) { - log.Info("Resource status unchanged") + if equality.Semantic.DeepEqual(current.StatusValue(), updated.StatusValue()) { return nil } patchOptions := client.MergeFromWithOptions(current, client.MergeFromWithOptimisticLock{}) if err := c.Status().Patch(ctx, updated, patchOptions); err != nil { - log.Error(err, "error while updating resource status") + log.Error(err, "failed to patch status") return err } - copyUpdatedStatus(obj, updated) - + obj.AssignStatusFrom(updated) return nil } -// getOriginalStatusForComparison extracts status for comparison -func getOriginalStatusForComparison(obj client.Object) any { - switch v := obj.(type) { - case *neonv1alpha1.Cluster: - return v.Status - case *neonv1alpha1.Project: - return v.Status - case *neonv1alpha1.Branch: - return v.Status - case *neonv1alpha1.Safekeeper: - return v.Status - case *neonv1alpha1.Pageserver: - return v.Status - default: - return nil - } -} +// UpdatePodBackedStatus applies the standard pod-backed condition pattern: +// ResourcesReady reflects reconcileErr; Available + Progressing roll up the +// child Pod's Ready condition. Used by Pageserver and Safekeeper. +func UpdatePodBackedStatus[T PodBackedStatus](ctx context.Context, c client.Client, obj T, podName, label string, reconcileErr error) error { + pod := &corev1.Pod{} + podErr := c.Get(ctx, types.NamespacedName{Name: podName, Namespace: obj.GetNamespace()}, pod) -// copyUpdatedStatus copies the status from updated object to the original -func copyUpdatedStatus(original client.Object, updated client.Object) { - switch orig := original.(type) { - case *neonv1alpha1.Cluster: - if upd, ok := updated.(*neonv1alpha1.Cluster); ok { - orig.Status = upd.Status - } - case *neonv1alpha1.Project: - if upd, ok := updated.(*neonv1alpha1.Project); ok { - orig.Status = upd.Status - } - case *neonv1alpha1.Branch: - if upd, ok := updated.(*neonv1alpha1.Branch); ok { - orig.Status = upd.Status - } - case *neonv1alpha1.Safekeeper: - if upd, ok := updated.(*neonv1alpha1.Safekeeper); ok { - orig.Status = upd.Status + return PatchStatus(ctx, c, obj, func(o T) { + o.SetObservedGeneration(o.GetGeneration()) + conds := o.StatusConditions() + + if reconcileErr != nil { + SetCondition(o, conds, ConditionResourcesReady, metav1.ConditionFalse, ReasonResourceCreateFailed, reconcileErr.Error()) + SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, ReasonResourceCreateFailed, reconcileErr.Error()) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, "Retrying after resource creation failure") + return } - case *neonv1alpha1.Pageserver: - if upd, ok := updated.(*neonv1alpha1.Pageserver); ok { - orig.Status = upd.Status + + SetCondition(o, conds, ConditionResourcesReady, metav1.ConditionTrue, ReasonAsExpected, "Child resources reconciled") + + switch { + case apierrors.IsNotFound(podErr): + SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, ReasonChildResourceMissing, fmt.Sprintf("%s Pod has not been observed yet", label)) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, "Waiting for child Pod to appear") + case podErr != nil: + SetCondition(o, conds, ConditionAvailable, metav1.ConditionUnknown, ReasonChildResourceMissing, podErr.Error()) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, "Could not read child Pod") + case IsPodReady(pod): + SetCondition(o, conds, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, fmt.Sprintf("%s Pod is Ready", label)) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionFalse, ReasonAsExpected, fmt.Sprintf("%s is at desired state", label)) + default: + reason, message := PodNotReadyDetail(pod) + if reason == "" { + reason = ReasonChildPodNotReady + message = fmt.Sprintf("%s Pod is not Ready", label) + } + SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, reason, message) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, fmt.Sprintf("Waiting for %s Pod readiness", label)) } - } + }) } -// getObjectStatus extracts the status from any of our CRD objects -func getObjectStatus(obj client.Object) StatusWithConditions { - switch v := obj.(type) { - case *neonv1alpha1.Cluster: - return &v.Status - case *neonv1alpha1.Project: - return &v.Status - case *neonv1alpha1.Branch: - return &v.Status - case *neonv1alpha1.Safekeeper: - return &v.Status - case *neonv1alpha1.Pageserver: - return &v.Status - default: - return nil +func IsPodReady(pod *corev1.Pod) bool { + if pod == nil { + return false } + for _, c := range pod.Status.Conditions { + if c.Type == corev1.PodReady { + return c.Status == corev1.ConditionTrue + } + } + return false } -// SetPhase sets a generic creating phase with Ready condition false -func SetPhase[T client.Object](obj T, phase string) { - status := getObjectStatus(obj) - status.SetPhase(phase) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionFalse, - Reason: "ResourceIsNotReady", - Message: "Resource Is Not Ready", - LastTransitionTime: metav1.Now(), - })) - -} - -// SetError sets a generic error phase with Ready condition false and error message -func SetError[T client.Object](obj T, phase, reason, message string) { - status := getObjectStatus(obj) - status.SetPhase(phase) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionFalse, - Reason: reason, - Message: message, - LastTransitionTime: metav1.Now(), - })) -} - -// SetClusterCreatingStatus sets the cluster to creating phase with Ready condition false -func SetClusterCreatingStatus(c *neonv1alpha1.Cluster) { - SetPhase(c, neonv1alpha1.ClusterPhaseCreating) -} - -// SetClusterCannotCreateResourcesStatus sets the cluster to cannot create resources phase with Ready condition false -func SetClusterCannotCreateResourcesStatus(c *neonv1alpha1.Cluster) { - SetError(c, neonv1alpha1.ClusterPhaseCannotCreateClusterResources, "ClusterIsNotReady", "Cluster Is Not Ready") -} - -// SetClusterReadyStatus sets the cluster to ready phase with Ready condition true -func SetClusterReadyStatus(c *neonv1alpha1.Cluster) { - status := getObjectStatus(c) - status.SetPhase(neonv1alpha1.ClusterPhaseReady) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionTrue, - Reason: "ClusterIsReady", - Message: "Cluster is ready", - LastTransitionTime: metav1.Now(), - })) -} - -// SetSafekeeperCreatingStatus sets the safekeeper to creating phase with Ready condition false -func SetSafekeeperCreatingStatus(sk *neonv1alpha1.Safekeeper) { - SetPhase(sk, neonv1alpha1.SafekeeperPhaseCreating) -} - -// SetSafekeeperInvalidSpecStatus sets the safekeeper to cannot create resources phase with Ready condition false -func SetSafekeeperInvalidSpecStatus(c *neonv1alpha1.Safekeeper) { - SetError(c, neonv1alpha1.SafekeeperPhaseInvalidSpec, "SafekeeperIsNotReady", "Safekeeper Is Not Ready") -} - -// SetSafekeeperCannotCreateResourcesStatus sets the cluster to cannot create resources phase with Ready condition false -func SetSafekeeperCannotCreateResourcesStatus(c *neonv1alpha1.Safekeeper) { - SetError(c, neonv1alpha1.SafekeeperPhaseCannotCreateResources, "SafekeeperIsNotReady", "Safekeeper Is Not Ready") -} - -// SetSafekeeperReadyStatus sets the safekeeper to ready phase with Ready condition true -func SetSafekeeperReadyStatus(sk *neonv1alpha1.Safekeeper) { - status := getObjectStatus(sk) - status.SetPhase(neonv1alpha1.SafekeeperPhaseReady) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionTrue, - Reason: "SafekeeperIsReady", - Message: "Safekeeper is ready", - LastTransitionTime: metav1.Now(), - })) -} - -// SetPageserverCreatingStatus sets the pageserver to creating phase with Ready condition false -func SetPageserverCreatingStatus(ps *neonv1alpha1.Pageserver) { - SetPhase(ps, neonv1alpha1.PageserverPhaseCreating) -} - -// SetPageserverInvalidSpecStatus sets the pageserver to cannot create resources phase with Ready condition false -func SetPageserverInvalidSpecStatus(ps *neonv1alpha1.Pageserver) { - SetError(ps, neonv1alpha1.PageserverPhaseInvalidSpec, "PageserverIsNotReady", "Pageserver Is Not Ready") -} - -// SetPageserverCannotCreateResourcesStatus sets the pageserver to cannot create resources phase -// with Ready condition false -func SetPageserverCannotCreateResourcesStatus(ps *neonv1alpha1.Pageserver) { - SetError(ps, neonv1alpha1.PageserverPhaseCannotCreateResources, "PageserverIsNotReady", "Pageserver Is Not Ready") -} - -// SetPageserverReadyStatus sets the pageserver to ready phase with Ready condition true -func SetPageserverReadyStatus(ps *neonv1alpha1.Pageserver) { - status := getObjectStatus(ps) - status.SetPhase(neonv1alpha1.PageserverPhaseReady) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionTrue, - Reason: "PageserverIsReady", - Message: "Pageserver is ready", - LastTransitionTime: metav1.Now(), - })) -} - -// SetProjectPendingStatus sets the project to pending phase with Ready condition false -func SetProjectPendingStatus(p *neonv1alpha1.Project) { - SetPhase(p, neonv1alpha1.ProjectPhasePending) -} - -// SetProjectCreatingStatus sets the project to creating phase with Ready condition false -func SetProjectCreatingStatus(p *neonv1alpha1.Project) { - SetPhase(p, neonv1alpha1.ProjectPhaseCreating) -} - -// SetProjectReadyStatus sets the project to ready phase with Ready condition true -func SetProjectReadyStatus(p *neonv1alpha1.Project) { - status := getObjectStatus(p) - status.SetPhase(neonv1alpha1.ProjectPhaseReady) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionTrue, - Reason: "ProjectIsReady", - Message: "Project is ready", - LastTransitionTime: metav1.Now(), - })) -} - -// SetProjectTenantCreationFailedStatus sets the project to tenant creation failed phase with Ready condition false -func SetProjectTenantCreationFailedStatus(p *neonv1alpha1.Project, message string) { - SetError(p, neonv1alpha1.ProjectPhaseTenantCreationFailed, "TenantCreationFailed", message) -} - -// SetProjectPageserverConnectionErrorStatus sets the project to pageserver connection error phase -// with Ready condition false -func SetProjectPageserverConnectionErrorStatus(p *neonv1alpha1.Project, message string) { - SetError(p, neonv1alpha1.ProjectPhasePageserverConnectionError, "PageserverConnectionError", message) -} - -// SetBranchCreatingStatus sets the branch to creating phase with Ready condition false -func SetBranchCreatingStatus(b *neonv1alpha1.Branch) { - SetPhase(b, neonv1alpha1.BranchPhaseCreating) -} - -// SetBranchReadyStatus sets the branch to ready phase with Ready condition true -func SetBranchReadyStatus(b *neonv1alpha1.Branch) { - status := getObjectStatus(b) - status.SetPhase(neonv1alpha1.BranchPhaseReady) - status.SetConditions(updateCondition(status.GetConditions(), metav1.Condition{ - Type: "Ready", - Status: metav1.ConditionTrue, - Reason: "BranchIsReady", - Message: "Branch is ready", - LastTransitionTime: metav1.Now(), - })) -} - -// SetBranchCannotCreateResourcesStatus sets the branch to cannot create resources phase with Ready condition false -func SetBranchCannotCreateResourcesStatus(b *neonv1alpha1.Branch) { - SetError(b, neonv1alpha1.BranchPhaseCannotCreateResources, "BranchIsNotReady", "Branch Is Not Ready") -} - -// SetBranchTimelineCreationFailedStatus sets the branch to timeline creation failed phase with Ready condition false -func SetBranchTimelineCreationFailedStatus(b *neonv1alpha1.Branch, message string) { - SetError(b, neonv1alpha1.BranchPhaseTimelineCreationFailed, "TimelineCreationFailed", message) +// PodNotReadyDetail returns a kubelet-supplied (reason, message) describing why +// a Pod isn't Ready: the first informative Waiting or non-zero Terminated state +// across init and main containers. Returns ("", "") when nothing actionable is +// surfaced — callers should fall back to a generic message. +func PodNotReadyDetail(pod *corev1.Pod) (reason, message string) { + if pod == nil { + return "", "" + } + for _, statuses := range [][]corev1.ContainerStatus{pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses} { + for _, cs := range statuses { + if w := cs.State.Waiting; w != nil && w.Reason != "" { + msg := w.Message + if msg == "" { + msg = fmt.Sprintf("container %q is %s", cs.Name, w.Reason) + } + return w.Reason, msg + } + if t := cs.State.Terminated; t != nil && t.ExitCode != 0 { + reason := t.Reason + if reason == "" { + reason = "ContainerTerminated" + } + msg := t.Message + if msg == "" { + msg = fmt.Sprintf("container %q exited with code %d", cs.Name, t.ExitCode) + } + return reason, msg + } + } + } + return "", "" } -// updateCondition updates or adds a condition to the conditions slice -func updateCondition(conditions []metav1.Condition, newCondition metav1.Condition) []metav1.Condition { - // Find existing condition with the same type - for i, condition := range conditions { - if condition.Type == newCondition.Type { - // Update existing condition - conditions[i] = newCondition - return conditions +func IsDeploymentAvailable(dep *appsv1.Deployment) bool { + if dep == nil { + return false + } + for _, c := range dep.Status.Conditions { + if c.Type == appsv1.DeploymentAvailable { + return c.Status == corev1.ConditionTrue } } - - // Add new condition if not found - return append(conditions, newCondition) + return false } diff --git a/utils/status_test.go b/utils/status_test.go index 0bdc35b..022e299 100644 --- a/utils/status_test.go +++ b/utils/status_test.go @@ -3,718 +3,101 @@ package utils import ( "testing" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" neonv1alpha1 "oltp.molnett.org/neon-operator/api/v1alpha1" ) -const ( - conditionTypeReady = "Ready" -) - -func TestStatusWithConditions_Interface(t *testing.T) { - tests := []struct { - name string - status StatusWithConditions - }{ - { - name: "ClusterStatus implements StatusWithConditions", - status: &neonv1alpha1.ClusterStatus{}, - }, - { - name: "ProjectStatus implements StatusWithConditions", - status: &neonv1alpha1.ProjectStatus{}, - }, - { - name: "BranchStatus implements StatusWithConditions", - status: &neonv1alpha1.BranchStatus{}, - }, - { - name: "SafekeeperStatus implements StatusWithConditions", - status: &neonv1alpha1.SafekeeperStatus{}, - }, - { - name: "PageserverStatus implements StatusWithConditions", - status: &neonv1alpha1.PageserverStatus{}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Test GetPhase/SetPhase - tt.status.SetPhase("test-phase") - if got := tt.status.GetPhase(); got != "test-phase" { - t.Errorf("expected phase 'test-phase', got '%s'", got) - } - - // Test GetConditions/SetConditions - conditions := []metav1.Condition{ - { - Type: conditionTypeReady, - Status: metav1.ConditionTrue, - Reason: "TestReason", - }, - } - tt.status.SetConditions(conditions) - gotConditions := tt.status.GetConditions() - if len(gotConditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(gotConditions)) - } - if gotConditions[0].Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, gotConditions[0].Type) - } - }) - } -} - -func TestGetObjectStatus(t *testing.T) { - tests := []struct { - name string - obj client.Object - expected string - }{ - { - name: "Cluster returns ClusterStatus", - obj: &neonv1alpha1.Cluster{ - Status: neonv1alpha1.ClusterStatus{ - Phase: "test-phase", - }, - }, - expected: "test-phase", - }, - { - name: "Project returns ProjectStatus", - obj: &neonv1alpha1.Project{ - Status: neonv1alpha1.ProjectStatus{ - Phase: "project-phase", - }, - }, - expected: "project-phase", - }, - { - name: "Branch returns BranchStatus", - obj: &neonv1alpha1.Branch{ - Status: neonv1alpha1.BranchStatus{ - Phase: "branch-phase", - }, - }, - expected: "branch-phase", - }, - { - name: "Safekeeper returns SafekeeperStatus", - obj: &neonv1alpha1.Safekeeper{ - Status: neonv1alpha1.SafekeeperStatus{ - Phase: "safekeeper-phase", - }, - }, - expected: "safekeeper-phase", - }, - { - name: "Pageserver returns PageserverStatus", - obj: &neonv1alpha1.Pageserver{ - Status: neonv1alpha1.PageserverStatus{ - Phase: "pageserver-phase", - }, - }, - expected: "pageserver-phase", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := getObjectStatus(tt.obj) - if got == nil { - t.Fatal("expected non-nil status") - } - - if got.GetPhase() != tt.expected { - t.Errorf("expected phase '%s', got '%s'", tt.expected, got.GetPhase()) - } - }) - } -} - -func TestGetObjectStatus_UnsupportedType(t *testing.T) { - // Test with an unsupported type (Pod is a valid client.Object but not one of our CRDs) - unsupported := &corev1.Pod{} - result := getObjectStatus(unsupported) - if result != nil { - t.Errorf("expected nil for unsupported type, got %v", result) - } -} - -func TestUpdateCondition(t *testing.T) { - tests := []struct { - name string - existing []metav1.Condition - newCondition metav1.Condition - expected int - expectUpdate bool - }{ - { - name: "Add new condition to empty slice", - existing: []metav1.Condition{}, - newCondition: metav1.Condition{ - Type: conditionTypeReady, - Status: metav1.ConditionTrue, - }, - expected: 1, - expectUpdate: false, - }, - { - name: "Update existing condition", - existing: []metav1.Condition{ - { - Type: conditionTypeReady, - Status: metav1.ConditionFalse, - Reason: "OldReason", - }, - }, - newCondition: metav1.Condition{ - Type: conditionTypeReady, - Status: metav1.ConditionTrue, - Reason: "NewReason", - }, - expected: 1, - expectUpdate: true, - }, - { - name: "Add new condition type", - existing: []metav1.Condition{ - { - Type: conditionTypeReady, - Status: metav1.ConditionTrue, - }, - }, - newCondition: metav1.Condition{ - Type: "Available", - Status: metav1.ConditionTrue, - }, - expected: 2, - expectUpdate: false, - }, +func TestSetCondition_AddsCondition(t *testing.T) { + cluster := &neonv1alpha1.Cluster{ + ObjectMeta: metav1.ObjectMeta{Generation: 3}, } + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, "Cluster is Available") - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := updateCondition(tt.existing, tt.newCondition) - - if len(result) != tt.expected { - t.Errorf("expected %d conditions, got %d", tt.expected, len(result)) - } - - // Find the updated condition - var found *metav1.Condition - for i := range result { - if result[i].Type == tt.newCondition.Type { - found = &result[i] - break - } - } - - if found == nil { - t.Errorf("condition type '%s' not found in result", tt.newCondition.Type) - return - } - - if found.Status != tt.newCondition.Status { - t.Errorf("expected status '%s', got '%s'", tt.newCondition.Status, found.Status) - } - - if tt.newCondition.Reason != "" && found.Reason != tt.newCondition.Reason { - t.Errorf("expected reason '%s', got '%s'", tt.newCondition.Reason, found.Reason) - } - }) - } -} - -func TestUpdateCondition_PreservesOtherConditions(t *testing.T) { - existing := []metav1.Condition{ - { - Type: conditionTypeReady, - Status: metav1.ConditionTrue, - Reason: "AllGood", - }, - { - Type: "Available", - Status: metav1.ConditionFalse, - Reason: "NotAvailable", - }, + if len(cluster.Status.Conditions) != 1 { + t.Fatalf("expected 1 condition, got %d", len(cluster.Status.Conditions)) } - - newCondition := metav1.Condition{ - Type: conditionTypeReady, - Status: metav1.ConditionFalse, - Reason: "NotReady", + c := cluster.Status.Conditions[0] + if c.Type != ConditionAvailable { + t.Errorf("expected type %s, got %s", ConditionAvailable, c.Type) } - - result := updateCondition(existing, newCondition) - - if len(result) != 2 { - t.Errorf("expected 2 conditions, got %d", len(result)) + if c.Status != metav1.ConditionTrue { + t.Errorf("expected status True, got %s", c.Status) } - - // Check that Available condition is preserved - var availableCondition *metav1.Condition - var readyCondition *metav1.Condition - - for i := range result { - if result[i].Type == "Available" { - availableCondition = &result[i] - } - if result[i].Type == conditionTypeReady { - readyCondition = &result[i] - } + if c.Reason != ReasonAsExpected { + t.Errorf("expected reason %s, got %s", ReasonAsExpected, c.Reason) } - - if availableCondition == nil { - t.Error("Available condition should be preserved") - } else { - if availableCondition.Status != metav1.ConditionFalse { - t.Errorf("Available condition status should be preserved as False, got %s", availableCondition.Status) - } - if availableCondition.Reason != "NotAvailable" { - t.Errorf("Available condition reason should be preserved as 'NotAvailable', got '%s'", availableCondition.Reason) - } + if c.ObservedGeneration != 3 { + t.Errorf("expected ObservedGeneration 3, got %d", c.ObservedGeneration) } - - if readyCondition == nil { - t.Error("Ready condition should exist") - } else { - if readyCondition.Status != metav1.ConditionFalse { - t.Errorf("Ready condition should be updated to False, got %s", readyCondition.Status) - } - if readyCondition.Reason != "NotReady" { - t.Errorf("Ready condition should be updated to 'NotReady', got '%s'", readyCondition.Reason) - } + if c.LastTransitionTime.IsZero() { + t.Error("expected LastTransitionTime to be set") } } -func TestSetClusterCreatingStatus(t *testing.T) { - cluster := &neonv1alpha1.Cluster{} - - SetClusterCreatingStatus(cluster) - - if cluster.Status.Phase != neonv1alpha1.ClusterPhaseCreating { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.ClusterPhaseCreating, cluster.Status.Phase) +func TestSetCondition_PreservesLastTransitionTimeOnUnchangedStatus(t *testing.T) { + cluster := &neonv1alpha1.Cluster{ + ObjectMeta: metav1.ObjectMeta{Generation: 1}, } + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, "first") + first := cluster.Status.Conditions[0].LastTransitionTime - if len(cluster.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(cluster.Status.Conditions)) - } + cluster.Generation = 2 + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, "second") + second := cluster.Status.Conditions[0].LastTransitionTime - condition := cluster.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) + if !first.Equal(&second) { + t.Errorf("LastTransitionTime should not change when Status stays the same: %v vs %v", first, second) } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) + if cluster.Status.Conditions[0].ObservedGeneration != 2 { + t.Errorf("ObservedGeneration should update to 2, got %d", cluster.Status.Conditions[0].ObservedGeneration) } } -func TestSetClusterCannotCreateResourcesStatus(t *testing.T) { +func TestSetCondition_UpdatesLastTransitionTimeOnStatusFlip(t *testing.T) { cluster := &neonv1alpha1.Cluster{} + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionFalse, ReasonReconciling, "wait") + first := cluster.Status.Conditions[0].LastTransitionTime - SetClusterCannotCreateResourcesStatus(cluster) + cluster.Status.Conditions[0].LastTransitionTime = metav1.NewTime(first.Add(-1)) - if cluster.Status.Phase != neonv1alpha1.ClusterPhaseCannotCreateClusterResources { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.ClusterPhaseCannotCreateClusterResources, cluster.Status.Phase) - } + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, "ready") + second := cluster.Status.Conditions[0].LastTransitionTime - if len(cluster.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(cluster.Status.Conditions)) + if !second.After(cluster.Status.Conditions[0].LastTransitionTime.Add(-1)) { + t.Errorf("LastTransitionTime should advance when Status flips") } - - condition := cluster.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } - if condition.Reason != "ClusterIsNotReady" { - t.Errorf("expected reason 'ClusterIsNotReady', got '%s'", condition.Reason) + if cluster.Status.Conditions[0].Status != metav1.ConditionTrue { + t.Errorf("expected status True after flip, got %s", cluster.Status.Conditions[0].Status) } } -// Test Cluster Ready Status -func TestSetClusterReadyStatus(t *testing.T) { +func TestSetCondition_PreservesOtherConditions(t *testing.T) { cluster := &neonv1alpha1.Cluster{} + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, "") + SetCondition(cluster, &cluster.Status.Conditions, ConditionProgressing, metav1.ConditionFalse, ReasonAsExpected, "") - SetClusterReadyStatus(cluster) - - if cluster.Status.Phase != neonv1alpha1.ClusterPhaseReady { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.ClusterPhaseReady, cluster.Status.Phase) - } - - if len(cluster.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(cluster.Status.Conditions)) - } - - condition := cluster.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionTrue { - t.Errorf("expected condition status 'True', got '%s'", condition.Status) - } - if condition.Reason != "ClusterIsReady" { - t.Errorf("expected reason 'ClusterIsReady', got '%s'", condition.Reason) - } - if condition.Message != "Cluster is ready" { - t.Errorf("expected message 'Cluster is ready', got '%s'", condition.Message) - } -} - -// Test Safekeeper Status Functions -func TestSetSafekeeperCreatingStatus(t *testing.T) { - safekeeper := &neonv1alpha1.Safekeeper{} - - SetSafekeeperCreatingStatus(safekeeper) - - if safekeeper.Status.Phase != neonv1alpha1.SafekeeperPhaseCreating { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.SafekeeperPhaseCreating, safekeeper.Status.Phase) - } - - if len(safekeeper.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(safekeeper.Status.Conditions)) - } - - condition := safekeeper.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } -} - -func TestSetSafekeeperInvalidSpecStatus(t *testing.T) { - safekeeper := &neonv1alpha1.Safekeeper{} - - SetSafekeeperInvalidSpecStatus(safekeeper) - - if safekeeper.Status.Phase != neonv1alpha1.SafekeeperPhaseInvalidSpec { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.SafekeeperPhaseInvalidSpec, safekeeper.Status.Phase) - } - - if len(safekeeper.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(safekeeper.Status.Conditions)) - } - - condition := safekeeper.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } - if condition.Reason != "SafekeeperIsNotReady" { - t.Errorf("expected reason 'SafekeeperIsNotReady', got '%s'", condition.Reason) - } -} - -func TestSetSafekeeperCannotCreateResourcesStatus(t *testing.T) { - safekeeper := &neonv1alpha1.Safekeeper{} - - SetSafekeeperCannotCreateResourcesStatus(safekeeper) - - if safekeeper.Status.Phase != neonv1alpha1.SafekeeperPhaseCannotCreateResources { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.SafekeeperPhaseCannotCreateResources, safekeeper.Status.Phase) - } - - if len(safekeeper.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(safekeeper.Status.Conditions)) - } - - condition := safekeeper.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } - if condition.Reason != "SafekeeperIsNotReady" { - t.Errorf("expected reason 'SafekeeperIsNotReady', got '%s'", condition.Reason) - } -} - -func TestSetSafekeeperReadyStatus(t *testing.T) { - safekeeper := &neonv1alpha1.Safekeeper{} - - SetSafekeeperReadyStatus(safekeeper) - - if safekeeper.Status.Phase != neonv1alpha1.SafekeeperPhaseReady { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.SafekeeperPhaseReady, safekeeper.Status.Phase) - } - - if len(safekeeper.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(safekeeper.Status.Conditions)) - } + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionFalse, ReasonReconciling, "") - condition := safekeeper.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) + if len(cluster.Status.Conditions) != 2 { + t.Fatalf("expected 2 conditions, got %d", len(cluster.Status.Conditions)) } - if condition.Status != metav1.ConditionTrue { - t.Errorf("expected condition status 'True', got '%s'", condition.Status) - } - if condition.Reason != "SafekeeperIsReady" { - t.Errorf("expected reason 'SafekeeperIsReady', got '%s'", condition.Reason) - } - if condition.Message != "Safekeeper is ready" { - t.Errorf("expected message 'Safekeeper is ready', got '%s'", condition.Message) - } -} - -// Test Pageserver Status Functions -func TestSetPageserverCreatingStatus(t *testing.T) { - pageserver := &neonv1alpha1.Pageserver{} - - SetPageserverCreatingStatus(pageserver) - - if pageserver.Status.Phase != neonv1alpha1.PageserverPhaseCreating { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.PageserverPhaseCreating, pageserver.Status.Phase) - } - - if len(pageserver.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(pageserver.Status.Conditions)) - } - - condition := pageserver.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } -} - -func TestSetPageserverInvalidSpecStatus(t *testing.T) { - pageserver := &neonv1alpha1.Pageserver{} - - SetPageserverInvalidSpecStatus(pageserver) - - if pageserver.Status.Phase != neonv1alpha1.PageserverPhaseInvalidSpec { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.PageserverPhaseInvalidSpec, pageserver.Status.Phase) - } - - if len(pageserver.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(pageserver.Status.Conditions)) - } - - condition := pageserver.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } - if condition.Reason != "PageserverIsNotReady" { - t.Errorf("expected reason 'PageserverIsNotReady', got '%s'", condition.Reason) - } -} - -func TestSetPageserverCannotCreateResourcesStatus(t *testing.T) { - pageserver := &neonv1alpha1.Pageserver{} - - SetPageserverCannotCreateResourcesStatus(pageserver) - - if pageserver.Status.Phase != neonv1alpha1.PageserverPhaseCannotCreateResources { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.PageserverPhaseCannotCreateResources, pageserver.Status.Phase) - } - - if len(pageserver.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(pageserver.Status.Conditions)) - } - - condition := pageserver.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } - if condition.Reason != "PageserverIsNotReady" { - t.Errorf("expected reason 'PageserverIsNotReady', got '%s'", condition.Reason) - } -} - -func TestSetPageserverReadyStatus(t *testing.T) { - pageserver := &neonv1alpha1.Pageserver{} - - SetPageserverReadyStatus(pageserver) - - if pageserver.Status.Phase != neonv1alpha1.PageserverPhaseReady { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.PageserverPhaseReady, pageserver.Status.Phase) - } - - if len(pageserver.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(pageserver.Status.Conditions)) - } - - condition := pageserver.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionTrue { - t.Errorf("expected condition status 'True', got '%s'", condition.Status) - } - if condition.Reason != "PageserverIsReady" { - t.Errorf("expected reason 'PageserverIsReady', got '%s'", condition.Reason) - } - if condition.Message != "Pageserver is ready" { - t.Errorf("expected message 'Pageserver is ready', got '%s'", condition.Message) - } -} - -// Test Branch Status Functions -func TestSetBranchCreatingStatus(t *testing.T) { - branch := &neonv1alpha1.Branch{} - - SetBranchCreatingStatus(branch) - - if branch.Status.Phase != neonv1alpha1.BranchPhaseCreating { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.BranchPhaseCreating, branch.Status.Phase) - } - - if len(branch.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(branch.Status.Conditions)) - } - - condition := branch.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } -} - -func TestSetBranchReadyStatus(t *testing.T) { - branch := &neonv1alpha1.Branch{} - - SetBranchReadyStatus(branch) - - if branch.Status.Phase != neonv1alpha1.BranchPhaseReady { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.BranchPhaseReady, branch.Status.Phase) - } - - if len(branch.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(branch.Status.Conditions)) - } - - condition := branch.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionTrue { - t.Errorf("expected condition status 'True', got '%s'", condition.Status) - } - if condition.Reason != "BranchIsReady" { - t.Errorf("expected reason 'BranchIsReady', got '%s'", condition.Reason) - } - if condition.Message != "Branch is ready" { - t.Errorf("expected message 'Branch is ready', got '%s'", condition.Message) - } -} - -func TestSetBranchCannotCreateResourcesStatus(t *testing.T) { - branch := &neonv1alpha1.Branch{} - - SetBranchCannotCreateResourcesStatus(branch) - - if branch.Status.Phase != neonv1alpha1.BranchPhaseCannotCreateResources { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.BranchPhaseCannotCreateResources, branch.Status.Phase) - } - - if len(branch.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(branch.Status.Conditions)) - } - - condition := branch.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } - if condition.Reason != "BranchIsNotReady" { - t.Errorf("expected reason 'BranchIsNotReady', got '%s'", condition.Reason) - } -} - -// Test Project Status Functions -func TestSetProjectPendingStatus(t *testing.T) { - project := &neonv1alpha1.Project{} - - SetProjectPendingStatus(project) - - if project.Status.Phase != neonv1alpha1.ProjectPhasePending { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.ProjectPhasePending, project.Status.Phase) - } - - if len(project.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(project.Status.Conditions)) - } - - condition := project.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } -} - -func TestSetProjectCreatingStatus(t *testing.T) { - project := &neonv1alpha1.Project{} - - SetProjectCreatingStatus(project) - - if project.Status.Phase != neonv1alpha1.ProjectPhaseCreating { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.ProjectPhaseCreating, project.Status.Phase) - } - - if len(project.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(project.Status.Conditions)) - } - - condition := project.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) - } - if condition.Status != metav1.ConditionFalse { - t.Errorf("expected condition status 'False', got '%s'", condition.Status) - } -} - -func TestSetProjectReadyStatus(t *testing.T) { - project := &neonv1alpha1.Project{} - - SetProjectReadyStatus(project) - - if project.Status.Phase != neonv1alpha1.ProjectPhaseReady { - t.Errorf("expected phase '%s', got '%s'", neonv1alpha1.ProjectPhaseReady, project.Status.Phase) - } - - if len(project.Status.Conditions) != 1 { - t.Errorf("expected 1 condition, got %d", len(project.Status.Conditions)) - } - - condition := project.Status.Conditions[0] - if condition.Type != conditionTypeReady { - t.Errorf("expected condition type '%s', got '%s'", conditionTypeReady, condition.Type) + var available, progressing *metav1.Condition + for i := range cluster.Status.Conditions { + switch cluster.Status.Conditions[i].Type { + case ConditionAvailable: + available = &cluster.Status.Conditions[i] + case ConditionProgressing: + progressing = &cluster.Status.Conditions[i] + } } - if condition.Status != metav1.ConditionTrue { - t.Errorf("expected condition status 'True', got '%s'", condition.Status) + if available == nil || progressing == nil { + t.Fatal("expected both Available and Progressing conditions") } - if condition.Reason != "ProjectIsReady" { - t.Errorf("expected reason 'ProjectIsReady', got '%s'", condition.Reason) + if available.Status != metav1.ConditionFalse { + t.Errorf("expected Available False, got %s", available.Status) } - if condition.Message != "Project is ready" { - t.Errorf("expected message 'Project is ready', got '%s'", condition.Message) + if progressing.Status != metav1.ConditionFalse { + t.Errorf("expected Progressing to remain False, got %s", progressing.Status) } } From 077487b2b02c5972f9d75c0d49f48d12cc79ac9e Mon Sep 17 00:00:00 2001 From: Jonathan Grahl Date: Thu, 30 Apr 2026 22:01:24 -0700 Subject: [PATCH 3/3] fix(lint): wrap long lines in utils and drop ineffectual assignment CI lint flagged 10 lines in utils/* exceeding the 120-char limit (lll excludes api/* and internal/* but not utils/*) and one ineffectual assignment in branch_controller.go computeReason that every switch branch immediately overwrote. --- internal/controller/branch_controller.go | 4 +-- utils/status.go | 45 +++++++++++++++++------- utils/status_test.go | 3 +- 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/internal/controller/branch_controller.go b/internal/controller/branch_controller.go index 4a1eaff..feaef62 100644 --- a/internal/controller/branch_controller.go +++ b/internal/controller/branch_controller.go @@ -162,7 +162,7 @@ func (r *BranchReconciler) updateStatus(ctx context.Context, branch *neonv1alpha } computeReady := metav1.ConditionFalse - computeReason := utils.ReasonReconciling + computeReason := utils.ReasonChildDeploymentNotAvailable computeMessage := "Compute Deployment is not Available yet" switch { case createErr != nil: @@ -179,8 +179,6 @@ func (r *BranchReconciler) updateStatus(ctx context.Context, branch *neonv1alpha computeReady = metav1.ConditionTrue computeReason = utils.ReasonAsExpected computeMessage = "Compute Deployment is Available" - default: - computeReason = utils.ReasonChildDeploymentNotAvailable } utils.SetCondition(b, conds, utils.ConditionComputeReady, computeReady, computeReason, computeMessage) diff --git a/utils/status.go b/utils/status.go index f89734a..eb408b0 100644 --- a/utils/status.go +++ b/utils/status.go @@ -76,7 +76,13 @@ type PodBackedStatus interface { // SetCondition wraps meta.SetStatusCondition; it preserves LastTransitionTime // when only ObservedGeneration / Reason / Message change. -func SetCondition(obj client.Object, conds *[]metav1.Condition, t string, status metav1.ConditionStatus, reason, message string) { +func SetCondition( + obj client.Object, + conds *[]metav1.Condition, + t string, + status metav1.ConditionStatus, + reason, message string, +) { meta.SetStatusCondition(conds, metav1.Condition{ Type: t, Status: status, @@ -116,7 +122,13 @@ func PatchStatus[T StatusObject](ctx context.Context, c client.Client, obj T, mu // UpdatePodBackedStatus applies the standard pod-backed condition pattern: // ResourcesReady reflects reconcileErr; Available + Progressing roll up the // child Pod's Ready condition. Used by Pageserver and Safekeeper. -func UpdatePodBackedStatus[T PodBackedStatus](ctx context.Context, c client.Client, obj T, podName, label string, reconcileErr error) error { +func UpdatePodBackedStatus[T PodBackedStatus]( + ctx context.Context, + c client.Client, + obj T, + podName, label string, + reconcileErr error, +) error { pod := &corev1.Pod{} podErr := c.Get(ctx, types.NamespacedName{Name: podName, Namespace: obj.GetNamespace()}, pod) @@ -125,24 +137,32 @@ func UpdatePodBackedStatus[T PodBackedStatus](ctx context.Context, c client.Clie conds := o.StatusConditions() if reconcileErr != nil { - SetCondition(o, conds, ConditionResourcesReady, metav1.ConditionFalse, ReasonResourceCreateFailed, reconcileErr.Error()) - SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, ReasonResourceCreateFailed, reconcileErr.Error()) - SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, "Retrying after resource creation failure") + msg := reconcileErr.Error() + SetCondition(o, conds, ConditionResourcesReady, metav1.ConditionFalse, ReasonResourceCreateFailed, msg) + SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, ReasonResourceCreateFailed, msg) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, + "Retrying after resource creation failure") return } - SetCondition(o, conds, ConditionResourcesReady, metav1.ConditionTrue, ReasonAsExpected, "Child resources reconciled") + SetCondition(o, conds, ConditionResourcesReady, metav1.ConditionTrue, ReasonAsExpected, + "Child resources reconciled") switch { case apierrors.IsNotFound(podErr): - SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, ReasonChildResourceMissing, fmt.Sprintf("%s Pod has not been observed yet", label)) - SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, "Waiting for child Pod to appear") + SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, ReasonChildResourceMissing, + fmt.Sprintf("%s Pod has not been observed yet", label)) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, + "Waiting for child Pod to appear") case podErr != nil: SetCondition(o, conds, ConditionAvailable, metav1.ConditionUnknown, ReasonChildResourceMissing, podErr.Error()) - SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, "Could not read child Pod") + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, + "Could not read child Pod") case IsPodReady(pod): - SetCondition(o, conds, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, fmt.Sprintf("%s Pod is Ready", label)) - SetCondition(o, conds, ConditionProgressing, metav1.ConditionFalse, ReasonAsExpected, fmt.Sprintf("%s is at desired state", label)) + SetCondition(o, conds, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, + fmt.Sprintf("%s Pod is Ready", label)) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionFalse, ReasonAsExpected, + fmt.Sprintf("%s is at desired state", label)) default: reason, message := PodNotReadyDetail(pod) if reason == "" { @@ -150,7 +170,8 @@ func UpdatePodBackedStatus[T PodBackedStatus](ctx context.Context, c client.Clie message = fmt.Sprintf("%s Pod is not Ready", label) } SetCondition(o, conds, ConditionAvailable, metav1.ConditionFalse, reason, message) - SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, fmt.Sprintf("Waiting for %s Pod readiness", label)) + SetCondition(o, conds, ConditionProgressing, metav1.ConditionTrue, ReasonReconciling, + fmt.Sprintf("Waiting for %s Pod readiness", label)) } }) } diff --git a/utils/status_test.go b/utils/status_test.go index 022e299..74c1866 100644 --- a/utils/status_test.go +++ b/utils/status_test.go @@ -12,7 +12,8 @@ func TestSetCondition_AddsCondition(t *testing.T) { cluster := &neonv1alpha1.Cluster{ ObjectMeta: metav1.ObjectMeta{Generation: 3}, } - SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, ReasonAsExpected, "Cluster is Available") + SetCondition(cluster, &cluster.Status.Conditions, ConditionAvailable, metav1.ConditionTrue, + ReasonAsExpected, "Cluster is Available") if len(cluster.Status.Conditions) != 1 { t.Fatalf("expected 1 condition, got %d", len(cluster.Status.Conditions))