Skip to content

Commit

Permalink
Added status
Browse files Browse the repository at this point in the history
Improve reconcile flows
  • Loading branch information
Juansasa committed Feb 26, 2025
1 parent c0e0be0 commit d1c37e5
Show file tree
Hide file tree
Showing 13 changed files with 411 additions and 179 deletions.
45 changes: 45 additions & 0 deletions api/v1alpha1/condition.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package v1alpha1

import (
"github.com/redhat-cop/operator-utils/pkg/util/apis"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Conditions struct {
// +patchMergeKey=type
// +patchStrategy=merge
// +listType=map
// +listMapKey=type
Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"`
}

func getOpt(idx int, opts ...string) string {
if len(opts) < idx+1 {
return ""
}

return opts[idx]
}

func (s *Conditions) UpdateCondition(conditionType string, conditionStatus metav1.ConditionStatus, opts ...string) {
s.Conditions = apis.AddOrReplaceCondition(metav1.Condition{
Type: conditionType,
Status: conditionStatus,
LastTransitionTime: metav1.Now(),
Reason: getOpt(0, opts...),
Message: getOpt(1, opts...),
}, s.Conditions)
}

func (s *Conditions) SetReady(conditionStatus metav1.ConditionStatus, msg ...string) {
s.UpdateCondition(apis.ReconcileSuccess, conditionStatus, apis.ReconcileSuccessReason, getOpt(0, msg...))
}

func (s *Conditions) IsReady() bool {
c, exists := apis.GetCondition(apis.ReconcileSuccess, s.Conditions)
if !exists {
return false
}

return c.Status == metav1.ConditionTrue
}
6 changes: 1 addition & 5 deletions api/v1alpha1/keycloak_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,7 @@ type SecretOption struct {

// KeycloakStatus defines the observed state of Keycloak
type KeycloakStatus struct {
// +patchMergeKey=type
// +patchStrategy=merge
// +listType=map
// +listMapKey=type
Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"`
Conditions `json:",inline"`
}

//+kubebuilder:object:root=true
Expand Down
17 changes: 16 additions & 1 deletion api/v1alpha1/keycloakimport_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,29 @@ type KeycloakImportSpec struct {
OverrideIfExists bool `json:"overrideIfExists,omitempty"`
}

func (ki *KeycloakImportSpec) HasSecretReference(secretName string) bool {
for _, substitution := range ki.Substitutions {
if substitution.Secret.Name == secretName {
return true
}
}

return false
}

type KeycloakInstance struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
}

const (
RHBKReadiness string = "RHBKIsReady"
)

// KeycloakImportStatus defines the observed state of KeycloakImport
type KeycloakImportStatus struct {
Version VersionedStatus `json:"version,omitempty"`
Version VersionedStatus `json:"version,omitempty"`
Conditions `json:",inline"`
}

//+kubebuilder:object:root=true
Expand Down
41 changes: 29 additions & 12 deletions api/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

72 changes: 72 additions & 0 deletions config/crd/bases/sso.stakater.com_keycloakimports.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,78 @@ spec:
status:
description: KeycloakImportStatus defines the observed state of KeycloakImport
properties:
conditions:
items:
description: "Condition contains details for one aspect of the current
state of this API Resource.\n---\nThis struct is intended for
direct use as an array at the field path .status.conditions. For
example,\n\n\n\ttype FooStatus struct{\n\t // Represents the
observations of a foo's current state.\n\t // Known .status.conditions.type
are: \"Available\", \"Progressing\", and \"Degraded\"\n\t //
+patchMergeKey=type\n\t // +patchStrategy=merge\n\t // +listType=map\n\t
\ // +listMapKey=type\n\t Conditions []metav1.Condition `json:\"conditions,omitempty\"
patchStrategy:\"merge\" patchMergeKey:\"type\" protobuf:\"bytes,1,rep,name=conditions\"`\n\n\n\t
\ // other fields\n\t}"
properties:
lastTransitionTime:
description: |-
lastTransitionTime is the last time the condition transitioned from one status to another.
This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.
format: date-time
type: string
message:
description: |-
message is a human readable message indicating details about the transition.
This may be an empty string.
maxLength: 32768
type: string
observedGeneration:
description: |-
observedGeneration represents the .metadata.generation that the condition was set based upon.
For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date
with respect to the current state of the instance.
format: int64
minimum: 0
type: integer
reason:
description: |-
reason contains a programmatic identifier indicating the reason for the condition's last transition.
Producers of specific condition types may define expected values and meanings for this field,
and whether the values are considered a guaranteed API.
The value should be a CamelCase string.
This field may not be empty.
maxLength: 1024
minLength: 1
pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$
type: string
status:
description: status of the condition, one of True, False, Unknown.
enum:
- "True"
- "False"
- Unknown
type: string
type:
description: |-
type of condition in CamelCase or in foo.example.com/CamelCase.
---
Many .condition.type values are consistent across resources like Available, but because arbitrary conditions can be
useful (see .node.status.conditions), the ability to deconflict is important.
The regex it matches is (dns1123SubdomainFmt/)?(qualifiedNameFmt)
maxLength: 316
pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$
type: string
required:
- lastTransitionTime
- message
- reason
- status
- type
type: object
type: array
x-kubernetes-list-map-keys:
- type
x-kubernetes-list-type: map
version:
properties:
resourceVersions:
Expand Down
8 changes: 4 additions & 4 deletions config/samples/sso_v1alpha1_keycloakimport.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ metadata:
spec:
keycloakInstance:
name: keycloak-sample
namespace: rhsso
namespace: rhbk
substitutions:
- name: DISPLAY_NAME
secret:
name: test-realm-secret
key: displayName
name: realm-secret
key: secretKey1
overrideIfExists: true
json: |
{
"realm": "test-realm",
"displayName": "%.DISPLAY_NAME% changed again"
"displayName": "%.DISPLAY_NAME%"
}
1 change: 1 addition & 0 deletions internal/constants/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ package constants

const RHBKWatchedResourceLabel = "sso.stakater.com/watched"
const RHBKRealmImportLabel = "realm.stakater.com/import"
const RHBKRealmImportRevisionLabel = "realm.stakater.com/import-rev"
48 changes: 20 additions & 28 deletions internal/controller/keycloak_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package controller

import (
"context"

v12 "github.com/openshift/api/route/v1"
"github.com/redhat-cop/operator-utils/pkg/util/apis"
ssov1alpha1 "github.com/stakater/rhbk-operator/api/v1alpha1"
Expand All @@ -31,6 +30,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/kustomize/kstatus/status"
Expand Down Expand Up @@ -68,7 +68,7 @@ func (r *KeycloakReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
}
err = serviceResource.CreateOrUpdate(ctx, r.Client)
if err != nil {
return ctrl.Result{Requeue: true}, err
return ctrl.Result{}, err
}

routeResource := resources.RHBKRoute{
Expand All @@ -78,7 +78,7 @@ func (r *KeycloakReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c

err = routeResource.CreateOrUpdate(ctx, r.Client)
if err != nil {
return ctrl.Result{Requeue: true}, err
return ctrl.Result{}, err
}

discoveryServiceResource := resources.RHBKDiscoveryService{
Expand All @@ -87,7 +87,7 @@ func (r *KeycloakReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
}
err = discoveryServiceResource.CreateOrUpdate(ctx, r.Client)
if err != nil {
return ctrl.Result{Requeue: true}, err
return ctrl.Result{}, err
}

statefulSetResource := &resources.RHBKStatefulSet{
Expand All @@ -96,37 +96,18 @@ func (r *KeycloakReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
Scheme: r.Scheme,
}
err = statefulSetResource.CreateOrUpdate(ctx, r.Client)
if err != nil {
return ctrl.Result{Requeue: true}, err
}

if err != nil {
return ctrl.Result{}, err
}

println(resources.CheckStatus(statefulSetResource.Resource))

originalCR := cr.DeepCopy()
if resources.CheckStatus(statefulSetResource.Resource) == status.CurrentStatus {
cr.Status.Conditions = resources.AddOrReplaceCondition(v14.Condition{
Type: apis.ReconcileSuccess,
Status: v14.ConditionTrue,
ObservedGeneration: statefulSetResource.Resource.Generation,
LastTransitionTime: v14.Now(),
Reason: apis.ReconcileSuccessReason,
Message: "All resources are ready",
}, cr.Status.Conditions)
cr.Status.Conditions.UpdateCondition(apis.ReconcileSuccess, v14.ConditionTrue, apis.ReconcileSuccessReason, "All resources are ready")
} else {
cr.Status.Conditions = resources.AddOrReplaceCondition(v14.Condition{
Type: apis.ReconcileSuccess,
Status: v14.ConditionFalse,
ObservedGeneration: statefulSetResource.Resource.Generation,
LastTransitionTime: v14.Now(),
Reason: "Reconciling",
Message: "Waiting for resources to be ready",
}, cr.Status.Conditions)
cr.Status.Conditions.UpdateCondition(apis.ReconcileSuccess, v14.ConditionFalse, "Reconciling", "Waiting for resources to be ready")
}

return ctrl.Result{}, r.Status().Update(ctx, cr)
return ctrl.Result{}, r.Status().Patch(ctx, cr, client.MergeFrom(originalCR))
}

// SetupWithManager sets up the controller with the Manager.
Expand All @@ -135,6 +116,17 @@ func (r *KeycloakReconciler) SetupWithManager(mgr ctrl.Manager) error {
For(&ssov1alpha1.Keycloak{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})).
Owns(&v1.Service{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})).
Owns(&v12.Route{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})).
Owns(&v13.StatefulSet{}).
Owns(&v13.StatefulSet{}, builder.WithPredicates(predicate.Funcs{
CreateFunc: func(e event.TypedCreateEvent[client.Object]) bool {
return false
},
DeleteFunc: func(e event.TypedDeleteEvent[client.Object]) bool {
return true
},
UpdateFunc: func(e event.TypedUpdateEvent[client.Object]) bool {
current := e.ObjectNew.(*v13.StatefulSet)
return resources.CheckStatus(current) == status.CurrentStatus
},
})).
Complete(r)
}
Loading

0 comments on commit d1c37e5

Please sign in to comment.