Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/330/add destination status #343

Merged
merged 5 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions api/v1alpha1/destination_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,13 @@ func (d *Destination) GetCleanup() string {

// DestinationStatus defines the observed state of Destination
type DestinationStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of destination
// Important: Run "make" to regenerate code after modifying this file
Conditions []metav1.Condition `json:"conditions,omitempty"`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

love that we still have scaffolded code from 3 years ago

}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
//+kubebuilder:resource:scope=Cluster,path=destinations,categories=kratix
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster,path=destinations,categories=kratix
// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status`,description="Indicates the destination is ready to use"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice touch for the additional printed column!

// Destination is the Schema for the Destinations API
type Destination struct {
Expand Down
9 changes: 8 additions & 1 deletion api/v1alpha1/zz_generated.deepcopy.go

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

64 changes: 63 additions & 1 deletion config/crd/bases/platform.kratix.io_destinations.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ spec:
singular: destination
scope: Cluster
versions:
- name: v1alpha1
- additionalPrinterColumns:
- description: Indicates the destination is ready to use
jsonPath: .status.conditions[?(@.type=="Ready")].status
name: Ready
type: string
name: v1alpha1
schema:
openAPIV3Schema:
description: Destination is the Schema for the Destinations API
Expand Down Expand Up @@ -117,6 +122,63 @@ spec:
type: object
status:
description: DestinationStatus defines the observed state of Destination
properties:
conditions:
items:
description: Condition contains details for one aspect of the current
state of this API Resource.
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.
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
type: object
type: object
served: true
Expand Down
118 changes: 106 additions & 12 deletions controllers/destination_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,44 @@ package controllers

import (
"context"
"fmt"
"path/filepath"

"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/predicate"

v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

"sigs.k8s.io/yaml"

"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"

"github.com/go-logr/logr"
"github.com/syntasso/kratix/api/v1alpha1"
"github.com/syntasso/kratix/lib/writers"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

const (
canaryWorkload = "kratix-canary"
destinationCleanupFinalizer = v1alpha1.KratixPrefix + "destination-cleanup"
stateStoreRefNameField = "spec.stateStoreRef.name"
)

// DestinationReconciler reconciles a Destination object
type DestinationReconciler struct {
Client client.Client
Log logr.Logger
Scheduler *Scheduler
Client client.Client
Log logr.Logger
Scheduler *Scheduler
EventRecorder record.EventRecorder
}

//+kubebuilder:rbac:groups=platform.kratix.io,resources=destinations,verbs=get;list;watch;create;update;patch;delete
Expand Down Expand Up @@ -83,8 +93,8 @@ func (r *DestinationReconciler) Reconcile(ctx context.Context, req ctrl.Request)

writer, err := newWriter(opts, *destination)
if err != nil {
if errors.IsNotFound(err) {
return defaultRequeue, nil
if condErr := r.updateReadyCondition(destination, err); condErr != nil {
return ctrl.Result{}, condErr
}
return ctrl.Result{}, err
}
Expand All @@ -98,17 +108,16 @@ func (r *DestinationReconciler) Reconcile(ctx context.Context, req ctrl.Request)
logger = logger.WithValues("path", path)
filePathMode := destination.GetFilepathMode()

if err = r.createDependenciesPathWithExample(writer, filePathMode); err != nil {
logger.Error(err, "unable to write dependencies to state store")
return defaultRequeue, nil
var writeErr error
if writeErr = r.writeTestFiles(writer, filePathMode); writeErr != nil {
logger.Error(writeErr, "unable to write dependencies to state store")
}

if err = r.createResourcePathWithExample(writer, filePathMode); err != nil {
logger.Error(err, "unable to write dependencies to state store")
return defaultRequeue, nil
if condErr := r.updateReadyCondition(destination, writeErr); condErr != nil {
return ctrl.Result{}, condErr
}

return ctrl.Result{}, nil
return ctrl.Result{}, writeErr
}

func (r *DestinationReconciler) needsFinalizerUpdate(destination *v1alpha1.Destination) bool {
Expand All @@ -128,6 +137,17 @@ func (r *DestinationReconciler) needsFinalizerUpdate(destination *v1alpha1.Desti
return false
}

func (r *DestinationReconciler) writeTestFiles(writer writers.StateStoreWriter, filePathMode string) error {
if err := r.createDependenciesPathWithExample(writer, filePathMode); err != nil {
return err
}

if err := r.createResourcePathWithExample(writer, filePathMode); err != nil {
return err
}
return nil
}

func (r *DestinationReconciler) createResourcePathWithExample(writer writers.StateStoreWriter, filePathMode string) error {
kratixConfigMap := &v1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Expand Down Expand Up @@ -233,9 +253,83 @@ func (r *DestinationReconciler) deleteDestinationWorkplacements(o opts, destinat
return true, nil
}

func (r *DestinationReconciler) updateReadyCondition(destination *v1alpha1.Destination, err error) error {
eventType := v1.EventTypeNormal
eventReason := "Ready"
eventMessage := fmt.Sprintf("Destination %q is ready", destination.Name)

condition := metav1.Condition{
Type: "Ready",
Status: metav1.ConditionTrue,
Reason: "TestDocumentsWritten",
Message: "Test documents written to State Store",
LastTransitionTime: metav1.Now(),
}

if err != nil {
condition.Status = metav1.ConditionFalse
condition.Reason = "StateStoreWriteFailed"
condition.Message = "Unable to write test documents to State Store"

// Update event parameters for failure
eventType = v1.EventTypeWarning
eventReason = "DestinationNotReady"
eventMessage = fmt.Sprintf("Failed to write test documents to Destination %q: %s", destination.Name, err)
}

changed := meta.SetStatusCondition(&destination.Status.Conditions, condition)
if !changed {
return nil
}

r.EventRecorder.Eventf(destination, eventType, eventReason, eventMessage)

return r.Client.Status().Update(context.Background(), destination)
}

func (r *DestinationReconciler) findDestinationsForStateStore(ctx context.Context, stateStore client.Object) []reconcile.Request {
destinationList := &v1alpha1.DestinationList{}
if err := r.Client.List(ctx, destinationList, client.MatchingFields{
stateStoreRefNameField: stateStore.GetName(),
}); err != nil {
r.Log.Error(err, "error listing destinations for state store")
return nil
}

var requests []reconcile.Request
for _, destination := range destinationList.Items {
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: destination.Namespace,
Name: destination.Name,
},
})
}
return requests
}

// SetupWithManager sets up the controller with the Manager.
func (r *DestinationReconciler) SetupWithManager(mgr ctrl.Manager) error {
// Create an index on the state store reference
err := mgr.GetFieldIndexer().IndexField(context.Background(), &v1alpha1.Destination{}, stateStoreRefNameField, func(rawObj client.Object) []string {
destination := rawObj.(*v1alpha1.Destination)
return []string{destination.Spec.StateStoreRef.Name}
})

if err != nil {
return err
}

return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.Destination{}).
Watches(
&v1alpha1.BucketStateStore{},
handler.EnqueueRequestsFromMapFunc(r.findDestinationsForStateStore),
).
Watches(
&v1alpha1.GitStateStore{},
handler.EnqueueRequestsFromMapFunc(r.findDestinationsForStateStore),
).
WithEventFilter(predicate.GenerationChangedPredicate{}).
Complete(r)
}
Loading