-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
STONEBLD-1844 Add controller for PipelineRuns
This controller looks for build PipelineRuns and will record an event that a downstream component should be 'nudged'. This is the first part of STONEBLD-1756.
- Loading branch information
1 parent
9ddc35a
commit ea5e6b5
Showing
6 changed files
with
449 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,220 @@ | ||
/* | ||
Copyright 2021-2023 Red Hat, Inc. | ||
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 controllers | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
tektonapi "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" | ||
v12 "k8s.io/api/core/v1" | ||
"k8s.io/apimachinery/pkg/types" | ||
"k8s.io/client-go/tools/record" | ||
"k8s.io/utils/strings/slices" | ||
"knative.dev/pkg/apis" | ||
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" | ||
ctrllog "sigs.k8s.io/controller-runtime/pkg/log" | ||
"sigs.k8s.io/controller-runtime/pkg/predicate" | ||
"time" | ||
|
||
"github.com/go-logr/logr" | ||
applicationapiv1alpha1 "github.com/redhat-appstudio/application-api/api/v1alpha1" | ||
"k8s.io/apimachinery/pkg/api/errors" | ||
"k8s.io/apimachinery/pkg/runtime" | ||
ctrl "sigs.k8s.io/controller-runtime" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
) | ||
|
||
const ( | ||
contextTimeout = 300 * time.Second | ||
// PipelineRunTypeLabelName contains the type of the PipelineRunTypeLabelName. | ||
PipelineRunTypeLabelName = "pipelines.appstudio.openshift.io/type" | ||
// PipelineRunBuildType is the type denoting a build PipelineRun. | ||
PipelineRunBuildType = "build" | ||
NudgeProcessedAnnotationName = "build.appstudio.openshift.io/component-nudge-processed" | ||
|
||
// PipelineRunComponentLabelName is the label denoting the application. | ||
PipelineRunComponentLabelName = "appstudio.openshift.io/component" | ||
NudgeFinalizer = "appstudio.openshift.io/build-nudge-finalizer" | ||
|
||
PacEventTypeLabelName = "pipelinesascode.tekton.dev/event-type" | ||
PacEventPush = "push" | ||
ComponentNudged = "ComponentNudged" | ||
ImageUrlParam = "IMAGE_URL" | ||
ImageDigestParam = "IMAGE_DIGEST" | ||
) | ||
|
||
// ComponentDependencyUpdateReconciler reconciles a PipelineRun object | ||
type ComponentDependencyUpdateReconciler struct { | ||
client.Client | ||
Scheme *runtime.Scheme | ||
EventRecorder record.EventRecorder | ||
} | ||
|
||
// SetupController creates a new Integration reconciler and adds it to the Manager. | ||
func (r *ComponentDependencyUpdateReconciler) SetupWithManager(manager ctrl.Manager) error { | ||
return setupControllerWithManager(manager, r) | ||
} | ||
|
||
// setupControllerWithManager sets up the controller with the Manager which monitors new PipelineRuns and filters | ||
// out status updates. | ||
func setupControllerWithManager(manager ctrl.Manager, reconciler *ComponentDependencyUpdateReconciler) error { | ||
|
||
return ctrl.NewControllerManagedBy(manager). | ||
For(&tektonapi.PipelineRun{}). | ||
WithEventFilter(predicate.NewPredicateFuncs(IsBuildPushPipelineRun)). | ||
Complete(reconciler) | ||
} | ||
|
||
// +kubebuilder:rbac:groups=appstudio.redhat.com,resources=components,verbs=get;list;watch;update;patch | ||
// +kubebuilder:rbac:groups=appstudio.redhat.com,resources=components/status,verbs=get;list;watch | ||
// +kubebuilder:rbac:groups=tekton.dev,resources=pipelineruns,verbs=get;list;watch;create;update;patch;delete;deletecollection | ||
// +kubebuilder:rbac:groups=tekton.dev,resources=pipelineruns/status,verbs=get;update;patch | ||
// +kubebuilder:rbac:groups=tekton.dev,resources=pipelineruns/finalizers,verbs=update | ||
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch | ||
func (r *ComponentDependencyUpdateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { | ||
var cancel context.CancelFunc | ||
ctx, cancel = context.WithTimeout(ctx, contextTimeout) | ||
defer cancel() | ||
log := ctrllog.FromContext(ctx).WithName("ComponentNudge").WithValues("namespace", req.NamespacedName.Namespace, "resource", req.Name) | ||
ctx = ctrllog.IntoContext(ctx, log) | ||
|
||
pipelineRun := &tektonapi.PipelineRun{} | ||
err := r.Get(ctx, req.NamespacedName, pipelineRun) | ||
if err != nil { | ||
log.Error(err, "Failed to get pipelineRun") | ||
if errors.IsNotFound(err) { | ||
return ctrl.Result{}, nil | ||
} | ||
return ctrl.Result{}, err | ||
} | ||
|
||
component, err := GetComponentFromPipelineRun(r.Client, ctx, pipelineRun) | ||
if err != nil || component == nil { | ||
log.Error(err, "failed to get component") | ||
return ctrl.Result{}, err | ||
} | ||
|
||
if len(component.Spec.BuildNudgesRef) == 0 { | ||
log.Info(fmt.Sprintf("component %s has no BuildNudgesRef set", component.Name)) | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
if pipelineRun.IsDone() || pipelineRun.DeletionTimestamp != nil { | ||
if controllerutil.ContainsFinalizer(pipelineRun, NudgeFinalizer) || pipelineRun.Annotations == nil || pipelineRun.Annotations[NudgeProcessedAnnotationName] == "" { | ||
// Pipeline run is done and we have not cleared the finalizer yet | ||
// We need to perform our nudge | ||
return r.handleCompletedBuild(ctx, log, pipelineRun, component) | ||
} | ||
} else if !controllerutil.ContainsFinalizer(pipelineRun, NudgeFinalizer) { | ||
// We add a finalizer to make sure we see the run before it is deleted | ||
// As tekton results should aggressivly delete when pruning is enabled | ||
controllerutil.AddFinalizer(pipelineRun, NudgeFinalizer) | ||
err := r.Client.Update(ctx, pipelineRun) | ||
if err != nil { | ||
log.Error(err, "failed to add finalizer") | ||
return ctrl.Result{}, err | ||
} | ||
} | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
func (r *ComponentDependencyUpdateReconciler) handleCompletedBuild(ctx context.Context, log logr.Logger, pipelineRun *tektonapi.PipelineRun, updatedComponent *applicationapiv1alpha1.Component) (ctrl.Result, error) { | ||
|
||
// Note that we do this eagerly, as we only realy have one chance to do the nudge | ||
// We don't want to get stuck in a nudge loop, or fail to remove the finalizer | ||
if pipelineRun.Annotations == nil { | ||
pipelineRun.Annotations[NudgeProcessedAnnotationName] = "true" | ||
} | ||
controllerutil.RemoveFinalizer(pipelineRun, NudgeFinalizer) | ||
err := r.Client.Update(ctx, pipelineRun) | ||
if err != nil { | ||
return ctrl.Result{}, err | ||
} | ||
|
||
success := pipelineRun.Status.GetCondition(apis.ConditionSucceeded).IsTrue() | ||
if !success { | ||
log.Error(err, "Not performing nudge as pipeline failed") | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
components := applicationapiv1alpha1.ComponentList{} | ||
err = r.Client.List(ctx, &components, client.InNamespace(pipelineRun.Namespace)) | ||
if err != nil { | ||
log.Error(err, "failed to list components in namespace") | ||
return ctrl.Result{}, err | ||
} | ||
|
||
image := "" | ||
digest := "" | ||
for _, r := range pipelineRun.Status.Results { | ||
if r.Name == ImageDigestParam { | ||
digest = r.Value.StringVal | ||
} else if r.Name == ImageUrlParam { | ||
image = r.Value.StringVal | ||
} | ||
} | ||
if image == "" { | ||
log.Error(fmt.Errorf("unable to find %s param on PipelineRun, not performing nudge", ImageUrlParam), "no image url result") | ||
return ctrl.Result{}, nil | ||
} | ||
if digest == "" { | ||
log.Error(fmt.Errorf("unable to find %s param on PipelineRun, not performing nudge", ImageDigestParam), "no image digest result") | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
for i := range components.Items { | ||
comp := components.Items[i] | ||
if comp.Spec.Application == updatedComponent.Spec.Application && slices.Contains(updatedComponent.Spec.BuildNudgesRef, comp.Name) { | ||
//TODO: Do the nudge | ||
log.Info(fmt.Sprintf("Nudging %s due to successful build of %s", comp.Name, updatedComponent.Name)) | ||
//TODO: do we want the event? It's just for unit testing at the moment | ||
r.EventRecorder.Event(&comp, v12.EventTypeNormal, ComponentNudged, fmt.Sprintf("component %s.%s was nudged by successful build of %s that produces image %s@%s", comp.Namespace, comp.Name, updatedComponent.Name, image, digest)) | ||
} | ||
} | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
func IsBuildPushPipelineRun(object client.Object) bool { | ||
if pipelineRun, ok := object.(*tektonapi.PipelineRun); ok { | ||
if pipelineRun.Labels != nil && pipelineRun.Annotations != nil { | ||
if pipelineRun.Labels[PipelineRunTypeLabelName] == PipelineRunBuildType && pipelineRun.Annotations[PacEventTypeLabelName] == PacEventPush { | ||
return true | ||
} | ||
} | ||
} | ||
return false | ||
} | ||
|
||
// GetComponentFromPipelineRun loads from the cluster the Component referenced in the given PipelineRun. If the PipelineRun doesn't | ||
// specify a Component or this is not found in the cluster, an error will be returned. | ||
func GetComponentFromPipelineRun(c client.Client, ctx context.Context, pipelineRun *tektonapi.PipelineRun) (*applicationapiv1alpha1.Component, error) { | ||
if componentName, found := pipelineRun.Labels[PipelineRunComponentLabelName]; found { | ||
component := &applicationapiv1alpha1.Component{} | ||
err := c.Get(ctx, types.NamespacedName{ | ||
Namespace: pipelineRun.Namespace, | ||
Name: componentName, | ||
}, component) | ||
|
||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return component, nil | ||
} | ||
|
||
return nil, nil | ||
} |
Oops, something went wrong.