Skip to content

Commit

Permalink
feat(STONEINTG-488): react to application component deletion
Browse files Browse the repository at this point in the history
Creation of component controller to watch for component deletion events.
When a component is deleted, IS will create a new snapshot to reflect
those changes as well as update snapshotenvironmentbindings.

Signed-off-by: Josh Everett <[email protected]>
  • Loading branch information
Josh-Everett committed Aug 11, 2023
1 parent f412ea6 commit b5c6eb3
Show file tree
Hide file tree
Showing 7 changed files with 545 additions and 1 deletion.
138 changes: 138 additions & 0 deletions controllers/component/component_adapter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package component

import (
"context"
"fmt"
"reflect"
ctrl "sigs.k8s.io/controller-runtime"

applicationapiv1alpha1 "github.com/redhat-appstudio/application-api/api/v1alpha1"
"github.com/redhat-appstudio/integration-service/gitops"
h "github.com/redhat-appstudio/integration-service/helpers"
"github.com/redhat-appstudio/integration-service/loader"
"github.com/redhat-appstudio/integration-service/metrics"
"github.com/redhat-appstudio/integration-service/status"
"github.com/redhat-appstudio/operator-toolkit/controller"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// Adapter holds the objects needed to reconcile a integration PipelineRun.
type Adapter struct {
component *applicationapiv1alpha1.Component
application *applicationapiv1alpha1.Application
loader loader.ObjectLoader
logger h.IntegrationLogger
client client.Client
context context.Context
status status.Status
}

// NewAdapter creates and returns an Adapter instance.
func NewAdapter(component *applicationapiv1alpha1.Component, application *applicationapiv1alpha1.Application, logger h.IntegrationLogger, loader loader.ObjectLoader, client client.Client,
context context.Context) *Adapter {
return &Adapter{
component: component,
application: application,
logger: logger,
loader: loader,
client: client,
context: context,
status: status.NewAdapter(logger.Logger, client),
}
}

// EnsureSnapshotIsFresh is an operation that will ensure that any snapshots associated with components
// marked for deletion are recreated without said component
func (a *Adapter) EnsureSnapshotIsFresh() (controller.OperationResult, error) {
if !HasComponentBeenDeleted(a.component) {
return controller.ContinueProcessing()
}
applicationSnapshots, err := a.loader.GetAllSnapshots(a.client, a.context, a.application)
if err != nil {
return controller.RequeueWithError(err)
}
for _, snapshot := range *applicationSnapshots {
for _, snapshotComponent := range snapshot.Spec.Components {
if reflect.DeepEqual(a.component, snapshotComponent) {
// create new snapshot
// prepare new component list for snapshot
var updatedComponents []applicationapiv1alpha1.SnapshotComponent
for i := 0; i < len(snapshot.Spec.Components); i++ {
if reflect.DeepEqual(a.component, snapshot.Spec.Components[i]) {
updatedComponents = append(snapshot.Spec.Components[:i], snapshot.Spec.Components[i+1:]...)
}
}

var refreshedSnapshot, err = RefreshSnapshot(a.client, a.application, &updatedComponents)
if err != nil {
a.logger.Error(err, "Failed to refresh snapshot after component deletion detected")
return controller.RequeueWithError(err)
}

// TODO create new seb
a.loader.GetAllEnvironments(a.client, a.context, a.application)

// mark snapshot as failed
existingSnapshot, err := gitops.MarkSnapshotAsFailed(a.client, a.context, &snapshot, "Associated snapshot components deleted.")
if err != nil {
a.logger.Error(err, "Failed to Update Snapshot AppStudioTestSucceeded status")
return controller.RequeueWithError(err)
}
a.logger.LogAuditEvent("Snapshot integration status condition marked as failed, an associated snapshot components deleted.",
existingSnapshot, h.LogActionUpdate)

// looks like potential things to do after we create the snapshot need some clarity on
// TODO understand controller reference
// TODO understand RegisterNewSnapshot
// TODO better understand labels and annotations
// copy old label and annotation?
h.CopyLabelsByPrefix(&snapshot.ObjectMeta, &refreshedSnapshot.ObjectMeta, gitops.PipelinesAsCodePrefix, gitops.PipelinesAsCodePrefix)
h.CopyAnnotationsByPrefix(&snapshot.ObjectMeta, &refreshedSnapshot.ObjectMeta, gitops.PipelinesAsCodePrefix, gitops.PipelinesAsCodePrefix)
go metrics.RegisterNewSnapshot()

//break
}
}
}

return controller.ContinueProcessing()
}

// RefreshSnapshot prepares the Snapshot for a given application, components and the updated component (if any).
// In case the Snapshot can't be created, an error will be returned.
func RefreshSnapshot(adapterClient client.Client, application *applicationapiv1alpha1.Application, remainingComponents *[]applicationapiv1alpha1.SnapshotComponent) (*applicationapiv1alpha1.Snapshot, error) {
if len(*remainingComponents) == 0 {
return nil, fmt.Errorf("failed to prepare snapshot due to missing valid digest in containerImage for all components of application")
}
snapshot := gitops.NewSnapshot(application, remainingComponents)

err := ctrl.SetControllerReference(application, snapshot, adapterClient.Scheme())
if err != nil {
return nil, err
}

return snapshot, nil
}

func HasComponentBeenDeleted(object client.Object) bool {
if comp, ok := object.(*applicationapiv1alpha1.Component); ok {
return !comp.ObjectMeta.DeletionTimestamp.IsZero()
}
return false
}
1 change: 1 addition & 0 deletions controllers/component/component_adapter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package component
116 changes: 116 additions & 0 deletions controllers/component/component_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions andF
limitations under the License.
*/

package component

import (
"context"
"fmt"

"github.com/go-logr/logr"
applicationapiv1alpha1 "github.com/redhat-appstudio/application-api/api/v1alpha1"
"github.com/redhat-appstudio/integration-service/helpers"
"github.com/redhat-appstudio/integration-service/loader"
"github.com/redhat-appstudio/operator-toolkit/controller"
tektonv1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)

// Reconciler reconciles a component object
type Reconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
}

// NewComponentReconciler creates and returns a Reconciler.
func NewComponentReconciler(client client.Client, logger *logr.Logger, scheme *runtime.Scheme) *Reconciler {
return &Reconciler{
Client: client,
Log: logger.WithName("integration pipeline"),
Scheme: scheme,
}
}

//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=components,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=components/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=appstudio.redhat.com,resources=components/finalizers,verbs=update
//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch
//+kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := helpers.IntegrationLogger{Logger: r.Log.WithValues("component", req.NamespacedName)}
loader := loader.NewLoader()

component := &applicationapiv1alpha1.Component{}
err := r.Get(ctx, req.NamespacedName, component)
if err != nil {
logger.Error(err, "Failed to get component for", "req", req.NamespacedName)
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}

return ctrl.Result{}, err
}

application := &applicationapiv1alpha1.Application{}
application, err = loader.GetApplicationFromComponent(r.Client, ctx, component)
if err != nil {
logger.Error(err, "Failed to get Application from the component",
"Component.Name", component.Name)
return ctrl.Result{}, err
}

if application == nil {
err := fmt.Errorf("failed to get Application")
logger.Error(err, "reconcile cannot resolve application")
return ctrl.Result{}, err
}
logger = logger.WithApp(*application)

adapter := NewAdapter(component, application, logger, loader, r.Client, ctx)

return controller.ReconcileHandler([]controller.Operation{
adapter.EnsureSnapshotIsFresh,
})
}

// AdapterInterface is an interface defining all the operations that should be defined in an Integration adapter.
type AdapterInterface interface {
EnsureSnapshotIsFresh() (controller.OperationResult, error)
}

// SetupController creates a new Component controller and adds it to the Manager.
func SetupController(manager ctrl.Manager, log *logr.Logger) error {
return setupControllerWithManager(manager, NewComponentReconciler(manager.GetClient(), log, manager.GetScheme()))

}

// setupControllerWithManager sets up the controller with the Manager which monitors new PipelineRuns and filters
// out status updates.
func setupControllerWithManager(manager ctrl.Manager, controller *Reconciler) error {
return ctrl.NewControllerManagedBy(manager).
For(&tektonv1beta1.PipelineRun{}).
WithEventFilter(predicate.Or(
ComponentDeletedPredicate())).
Complete(controller)
}
Loading

0 comments on commit b5c6eb3

Please sign in to comment.