diff --git a/docs/resources.md b/docs/resources.md index d2efeb57a05..d73bfc07cc1 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -51,7 +51,6 @@ For example: - [Cluster Resource](#cluster-resource) - [Storage Resource](#storage-resource) - [GCS Storage Resource](#gcs-storage-resource) - - [Cloud Event Resource](#cloud-event-resource) - [Why Aren't PipelineResources in Beta?](#why-aren-t-pipelineresources-in-beta) ## Syntax @@ -925,70 +924,6 @@ service account. -------------------------------------------------------------------------------- -### Cloud Event Resource - -The `cloudevent` resource represents a -[cloud event](https://github.com/cloudevents/spec) that is sent to a target -`URI` upon completion of a `TaskRun`. The `cloudevent` resource sends Tekton -specific events; the body of the event includes the entire `TaskRun` spec plus -status; the types of events defined for now are: - -- dev.tekton.event.task.unknown -- dev.tekton.event.task.successful -- dev.tekton.event.task.failed - -`cloudevent` resources are useful to notify a third party upon the completion -and status of a `TaskRun`. In combinations with the -[Tekton triggers](https://github.com/tektoncd/triggers) project they can be used -to link `Task/PipelineRuns` asynchronously. - -To create a CloudEvent resource using the `PipelineResource` CRD: - -```yaml -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: event-to-sink -spec: - type: cloudEvent - params: - - name: targetURI - value: http://sink:8080 -``` - -The content of an event is for example: - -```yaml -Context Attributes, - SpecVersion: 0.2 - Type: dev.tekton.event.task.successful - Source: /apis/tekton.dev/v1beta1/namespaces/default/taskruns/pipeline-run-api-16aa55-source-to-image-task-rpndl - ID: pipeline-run-api-16aa55-source-to-image-task-rpndl - Time: 2019-07-04T11:03:53.058694712Z - ContentType: application/json -Transport Context, - URI: / - Host: my-sink.default.my-cluster.containers.appdomain.cloud - Method: POST -Data, - { - "taskRun": { - "metadata": {...} - "spec": { - "inputs": {...} - "outputs": {...} - "serviceAccount": "default", - "taskRef": { - "name": "source-to-image", - "kind": "Task" - }, - "timeout": "1h0m0s" - }, - "status": {...} - } - } -``` - ## Why Aren't PipelineResources in Beta? The short answer is that they're not ready to be given a Beta level of support by Tekton's developers. The long answer is, well, longer: diff --git a/examples/v1beta1/taskruns/cloud-event.yaml b/examples/v1beta1/taskruns/cloud-event.yaml deleted file mode 100644 index 1302233b2ed..00000000000 --- a/examples/v1beta1/taskruns/cloud-event.yaml +++ /dev/null @@ -1,184 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: sink -spec: - selector: - app: cloudevent - ports: - - protocol: TCP - port: 8080 - targetPort: 8080 ---- -apiVersion: v1 -kind: Pod -metadata: - labels: - app: cloudevent - name: message-sink -spec: - containers: - - env: - - name: PORT - value: "8080" - name: cloudeventlistener - image: python:3-alpine - imagePullPolicy: IfNotPresent - command: ["/bin/sh"] - args: - - -ce - - | - cat <

POST!

') - - def do_GET(self): - with open("content.txt", mode="rb") as f: - content = f.read() - self.send_response(200 if content else 404) - self.send_header('Content-type', 'text/plain') - self.end_headers() - self.wfile.write(content) - - if __name__ == "__main__": - open("content.txt", 'a').close() - httpd = HTTPServer(('', $PORT), GetAndPostHandler) - print('Starting httpd...') - httpd.serve_forever() - EOF - ports: - - containerPort: 8080 - name: user-port - protocol: TCP ---- -apiVersion: tekton.dev/v1beta1 -kind: Task -metadata: - name: send-cloud-event-task - -spec: - resources: - outputs: - - name: myimage - type: image - - name: notification - type: cloudEvent - steps: - - name: wait-for-sink - image: python:3-alpine - imagePullPolicy: IfNotPresent - script: | - #!/usr/bin/env python3 - import http.client - import json - import sys - import time - - while True: - conn = http.client.HTTPConnection("sink:8080") - try: - conn.request("GET", "/") - break - except: - # Perhaps the service is not setup yet, so service name does not - # resolve or it does not accept connections on 8080 yet - print("Not yet...") - time.sleep(10) - - name: build-index-json - image: busybox - script: | - set -e - cat < $(resources.outputs.myimage.path)/index.json - { - "schemaVersion": 2, - "manifests": [ - { - "mediaType": "application/vnd.oci.image.index.v1+json", - "size": 314, - "digest": "sha256:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" - } - ] - } ---- -apiVersion: tekton.dev/v1beta1 -kind: Task -metadata: - name: poll-for-content-task -spec: - steps: - - name: polling - image: python:3-alpine - imagePullPolicy: IfNotPresent - script: | - #!/usr/bin/env python3 - import http.client - import json - import sys - import time - - while True: - conn = http.client.HTTPConnection("sink:8080") - try: - conn.request("GET", "/") - except: - # Perhaps the service is not setup yet, so service name does not - # resolve or it does not accept connections on 8080 yet - print("Not yet...") - time.sleep(10) - continue - response = conn.getresponse() - if response.status == 200: - print("Got it!") - taskrun = json.loads(response.read().decode('utf-8')) - digest = taskrun['taskRun']['status']['resourcesResult'][0]['value'] - image_name = taskrun['taskRun']['status']['resourcesResult'][0]['resourceName'] - print("Got digest %s for image %s" % (digest, image_name)) - if image_name == "myimage" and digest: - break - else: - sys.exit(1) - else: - print("Not yet...") - time.sleep(10) ---- -# `PipelineResources` are deprecated, consider using `Tasks` and other replacement features instead -# https://github.com/tektoncd/pipeline/blob/main/docs/migrating-v1alpha1-to-v1beta1.md#replacing-pipelineresources-with-tasks -apiVersion: tekton.dev/v1beta1 -kind: TaskRun -metadata: - name: send-cloud-event -spec: - resources: - outputs: - - name: myimage - resourceSpec: - type: image - params: - - name: url - value: fake-registry/test/fake-image - - name: notification - resourceSpec: - type: cloudEvent - params: - - name: targetURI - value: http://sink.default:8080 - taskRef: - name: send-cloud-event-task ---- -apiVersion: tekton.dev/v1beta1 -kind: TaskRun -metadata: - name: poll-for-content-run -spec: - taskRef: - name: poll-for-content-task diff --git a/pkg/apis/pipeline/v1beta1/resource_types.go b/pkg/apis/pipeline/v1beta1/resource_types.go index 9a1602c27f5..6294bfcf88d 100644 --- a/pkg/apis/pipeline/v1beta1/resource_types.go +++ b/pkg/apis/pipeline/v1beta1/resource_types.go @@ -51,9 +51,6 @@ const ( // PipelineResourceTypePullRequest indicates that this source is a SCM Pull Request. PipelineResourceTypePullRequest PipelineResourceType = resource.PipelineResourceTypePullRequest - - // PipelineResourceTypeCloudEvent indicates that this source is a cloud event URI - PipelineResourceTypeCloudEvent PipelineResourceType = resource.PipelineResourceTypeCloudEvent ) // AllResourceTypes can be used for validation to check if a provided Resource type is one of the known types. diff --git a/pkg/apis/resource/resource.go b/pkg/apis/resource/resource.go index eb6580fe474..9014605eb91 100644 --- a/pkg/apis/resource/resource.go +++ b/pkg/apis/resource/resource.go @@ -22,7 +22,6 @@ import ( "github.com/tektoncd/pipeline/pkg/apis/pipeline" pipelinev1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" resourcev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1/cloudevent" "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1/cluster" "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1/git" "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1/image" @@ -45,8 +44,6 @@ func FromType(name string, r *resourcev1alpha1.PipelineResource, images pipeline return storage.NewResource(name, images, r) case resourcev1alpha1.PipelineResourceTypePullRequest: return pullrequest.NewResource(name, images.PRImage, r) - case resourcev1alpha1.PipelineResourceTypeCloudEvent: - return cloudevent.NewResource(name, r) } return nil, fmt.Errorf("%s is an invalid or unimplemented PipelineResource", r.Spec.Type) } diff --git a/pkg/apis/resource/v1alpha1/cloudevent/cloud_event_resource.go b/pkg/apis/resource/v1alpha1/cloudevent/cloud_event_resource.go deleted file mode 100644 index ce97be0ef2c..00000000000 --- a/pkg/apis/resource/v1alpha1/cloudevent/cloud_event_resource.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2019-2020 The Tekton Authors. - -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 cloudevent - -import ( - "fmt" - "strings" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" -) - -// Resource is an event sink to which events are delivered when a TaskRun has finished -type Resource struct { - // Name is the name used to reference to the PipelineResource - Name string `json:"name"` - // Type must be `PipelineResourceTypeCloudEvent` - Type resource.PipelineResourceType `json:"type"` - // TargetURI is the URI of the sink which the cloud event is develired to - TargetURI string `json:"targetURI"` -} - -// NewResource creates a new CloudEvent resource to pass to a Task -func NewResource(name string, r *resource.PipelineResource) (*Resource, error) { - if r.Spec.Type != resource.PipelineResourceTypeCloudEvent { - return nil, fmt.Errorf("cloudevent.Resource: Cannot create a Cloud Event resource from a %s Pipeline Resource", r.Spec.Type) - } - var targetURI string - var targetURISpecified bool - - for _, param := range r.Spec.Params { - if strings.EqualFold(param.Name, "TargetURI") { - targetURI = param.Value - if param.Value != "" { - targetURISpecified = true - } - } - } - - if !targetURISpecified { - return nil, fmt.Errorf("cloudevent.Resource: Need URI to be specified in order to create a CloudEvent resource %s", r.Name) - } - return &Resource{ - Name: name, - Type: r.Spec.Type, - TargetURI: targetURI, - }, nil -} - -// GetName returns the name of the resource -func (s Resource) GetName() string { - return s.Name -} - -// GetType returns the type of the resource, in this case "cloudEvent" -func (s Resource) GetType() resource.PipelineResourceType { - return resource.PipelineResourceTypeCloudEvent -} - -// Replacements is used for template replacement on an CloudEventResource inside of a Taskrun. -func (s *Resource) Replacements() map[string]string { - return map[string]string{ - "name": s.Name, - "type": s.Type, - "target-uri": s.TargetURI, - } -} - -// GetInputTaskModifier returns the TaskModifier to be used when this resource is an input. -func (s *Resource) GetInputTaskModifier(_ *v1beta1.TaskSpec, _ string) (v1beta1.TaskModifier, error) { - return &v1beta1.InternalTaskModifier{}, nil -} - -// GetOutputTaskModifier returns a No-op TaskModifier. -func (s *Resource) GetOutputTaskModifier(_ *v1beta1.TaskSpec, _ string) (v1beta1.TaskModifier, error) { - return &v1beta1.InternalTaskModifier{}, nil -} diff --git a/pkg/apis/resource/v1alpha1/cloudevent/cloud_event_resource_test.go b/pkg/apis/resource/v1alpha1/cloudevent/cloud_event_resource_test.go deleted file mode 100644 index 389c8dbfe12..00000000000 --- a/pkg/apis/resource/v1alpha1/cloudevent/cloud_event_resource_test.go +++ /dev/null @@ -1,148 +0,0 @@ -/* -Copyright 2019 The Tekton Authors. - -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 cloudevent_test - -import ( - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resourcev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1/cloudevent" - "github.com/tektoncd/pipeline/test/diff" -) - -func TestNewResource_Invalid(t *testing.T) { - testcases := []struct { - name string - pipelineResource *resourcev1alpha1.PipelineResource - }{{ - name: "create resource with no parameter", - pipelineResource: &resourcev1alpha1.PipelineResource{ - ObjectMeta: metav1.ObjectMeta{ - Name: "cloud-event-resource-no-uri", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - }, - }, - }, { - name: "create resource with invalid type", - pipelineResource: &resourcev1alpha1.PipelineResource{ - ObjectMeta: metav1.ObjectMeta{ - Name: "git-resource", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeGit, - Params: []resourcev1alpha1.ResourceParam{ - { - Name: "URL", - Value: "git://fake/repo", - }, - { - Name: "Revision", - Value: "fake_rev", - }, - }, - }, - }, - }} - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - _, err := cloudevent.NewResource("test-resource", tc.pipelineResource) - if err == nil { - t.Error("Expected error creating CloudEvent resource") - } - }) - } -} - -func TestNewResource_Valid(t *testing.T) { - pr := &resourcev1alpha1.PipelineResource{ - ObjectMeta: metav1.ObjectMeta{ - Name: "cloud-event-resource-uri", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - Params: []resourcev1alpha1.ResourceParam{{ - Name: "TargetURI", - Value: "http://fake-sink", - }}, - }, - } - expectedResource := &cloudevent.Resource{ - Name: "test-resource", - TargetURI: "http://fake-sink", - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - } - - r, err := cloudevent.NewResource("test-resource", pr) - if err != nil { - t.Fatalf("Unexpected error creating CloudEvent resource: %s", err) - } - if d := cmp.Diff(expectedResource, r); d != "" { - t.Errorf("Mismatch of CloudEvent resource %s", diff.PrintWantGot(d)) - } -} - -func TestCloudEvent_GetReplacements(t *testing.T) { - r := &cloudevent.Resource{ - Name: "cloud-event-resource", - TargetURI: "http://fake-uri", - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - } - expectedReplacementMap := map[string]string{ - "name": "cloud-event-resource", - "type": "cloudEvent", - "target-uri": "http://fake-uri", - } - if d := cmp.Diff(r.Replacements(), expectedReplacementMap); d != "" { - t.Errorf("CloudEvent Replacement map mismatch: %s", d) - } -} - -func TestCloudEvent_InputContainerSpec(t *testing.T) { - r := &cloudevent.Resource{ - Name: "cloud-event-resource", - TargetURI: "http://fake-uri", - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - } - d, e := r.GetInputTaskModifier(&v1beta1.TaskSpec{}, "") - if d.GetStepsToPrepend() != nil { - t.Errorf("Did not expect a download container for Resource") - } - if e != nil { - t.Errorf("Did not expect an error %s when getting a download container for Resource", e) - } -} - -func TestCloudEvent_OutputContainerSpec(t *testing.T) { - r := &cloudevent.Resource{ - Name: "cloud-event-resource", - TargetURI: "http://fake-uri", - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - } - d, e := r.GetOutputTaskModifier(&v1beta1.TaskSpec{}, "") - if d.GetStepsToAppend() != nil { - t.Errorf("Did not expect an upload container for Resource") - } - if e != nil { - t.Errorf("Did not expect an error %s when getting an upload container for Resource", e) - } -} diff --git a/pkg/apis/resource/v1alpha1/pipeline_resource_types.go b/pkg/apis/resource/v1alpha1/pipeline_resource_types.go index 9d1f2ff6e32..332791cf0e5 100644 --- a/pkg/apis/resource/v1alpha1/pipeline_resource_types.go +++ b/pkg/apis/resource/v1alpha1/pipeline_resource_types.go @@ -49,15 +49,12 @@ const ( // PipelineResourceTypePullRequest indicates that this source is a SCM Pull Request. PipelineResourceTypePullRequest PipelineResourceType = "pullRequest" - // PipelineResourceTypeCloudEvent indicates that this source is a cloud event URI - PipelineResourceTypeCloudEvent PipelineResourceType = "cloudEvent" - // PipelineResourceTypeGCS is the subtype for the GCSResources, which is backed by a GCS blob/directory. PipelineResourceTypeGCS PipelineResourceType = "gcs" ) // AllResourceTypes can be used for validation to check if a provided Resource type is one of the known types. -var AllResourceTypes = []PipelineResourceType{PipelineResourceTypeGit, PipelineResourceTypeStorage, PipelineResourceTypeImage, PipelineResourceTypeCluster, PipelineResourceTypePullRequest, PipelineResourceTypeCloudEvent} +var AllResourceTypes = []PipelineResourceType{PipelineResourceTypeGit, PipelineResourceTypeStorage, PipelineResourceTypeImage, PipelineResourceTypeCluster, PipelineResourceTypePullRequest} // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/pkg/reconciler/events/cloudevent/cloud_event_controller.go b/pkg/reconciler/events/cloudevent/cloud_event_controller.go index 85087f84301..c3663237d73 100644 --- a/pkg/reconciler/events/cloudevent/cloud_event_controller.go +++ b/pkg/reconciler/events/cloudevent/cloud_event_controller.go @@ -22,60 +22,18 @@ import ( "time" cloudevents "github.com/cloudevents/sdk-go/v2" - "github.com/hashicorp/go-multierror" "github.com/tektoncd/pipeline/pkg/apis/config" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1/cloudevent" "github.com/tektoncd/pipeline/pkg/reconciler/events/cache" - "go.uber.org/zap" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/utils/clock" "knative.dev/pkg/apis" controller "knative.dev/pkg/controller" "knative.dev/pkg/logging" ) -// InitializeCloudEvents initializes the CloudEvents part of the -// TaskRunStatus from a slice of PipelineResources -func InitializeCloudEvents(tr *v1beta1.TaskRun, prs map[string]*resource.PipelineResource) { - // If there are no cloud event resources, this check will run on every reconcile - if len(tr.Status.CloudEvents) == 0 { - var targets []string - for name, output := range prs { - if output.Spec.Type == resource.PipelineResourceTypeCloudEvent { - cer, _ := cloudevent.NewResource(name, output) - targets = append(targets, cer.TargetURI) - } - } - if len(targets) > 0 { - tr.Status.CloudEvents = cloudEventDeliveryFromTargets(targets) - } - } -} - -func cloudEventDeliveryFromTargets(targets []string) []v1beta1.CloudEventDelivery { - if len(targets) > 0 { - initialState := v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - RetryCount: 0, - } - events := make([]v1beta1.CloudEventDelivery, len(targets)) - for idx, target := range targets { - events[idx] = v1beta1.CloudEventDelivery{ - Target: target, - Status: initialState, - } - } - return events - } - return nil -} - // EmitCloudEvents emits CloudEvents (only) for object func EmitCloudEvents(ctx context.Context, object runtime.Object) { logger := logging.FromContext(ctx) @@ -113,50 +71,6 @@ func EmitCloudEventsWhenConditionChange(ctx context.Context, beforeCondition *ap } } -// SendCloudEvents is used by the TaskRun controller to send cloud events once -// the TaskRun is complete. `tr` is used to obtain the list of targets -func SendCloudEvents(tr *v1beta1.TaskRun, ceclient CEClient, logger *zap.SugaredLogger, c clock.PassiveClock) error { - logger = logger.With(zap.String("taskrun", tr.Name)) - - // Make the event we would like to send: - event, err := eventForTaskRun(tr) - if err != nil || event == nil { - logger.With(zap.Error(err)).Error("failed to produce a cloudevent from TaskRun.") - return err - } - - // Using multierror here so we can attempt to send all cloud events defined, - // regardless of whether they fail or not, and report all failed ones - var merr *multierror.Error - for idx, cloudEventDelivery := range tr.Status.CloudEvents { - eventStatus := &(tr.Status.CloudEvents[idx].Status) - // Skip events that have already been sent (successfully or unsuccessfully) - // Ensure we try to send all events once (possibly through different reconcile calls) - if eventStatus.Condition != v1beta1.CloudEventConditionUnknown || eventStatus.RetryCount > 0 { - continue - } - - // Send the event. - result := ceclient.Send(cloudevents.ContextWithTarget(cloudevents.ContextWithRetriesExponentialBackoff(context.Background(), 10*time.Millisecond, 10), cloudEventDelivery.Target), *event) - - // Record the result. - eventStatus.SentAt = &metav1.Time{Time: c.Now()} - eventStatus.RetryCount++ - if !cloudevents.IsACK(result) { - merr = multierror.Append(merr, result) - eventStatus.Condition = v1beta1.CloudEventConditionFailed - eventStatus.Error = merr.Error() - } else { - logger.Infow("Event sent.", zap.String("target", cloudEventDelivery.Target)) - eventStatus.Condition = v1beta1.CloudEventConditionSent - } - } - if merr != nil && merr.Len() > 0 { - logger.With(zap.Error(merr)).Errorw("Failed to send events for TaskRun.", zap.Int("count", merr.Len())) - } - return merr.ErrorOrNil() -} - // SendCloudEventWithRetries sends a cloud event for the specified resource. // It does not block and it perform retries with backoff using the cloudevents // sdk-go capabilities. diff --git a/pkg/reconciler/events/cloudevent/cloud_event_controller_test.go b/pkg/reconciler/events/cloudevent/cloud_event_controller_test.go index 0f154711c0c..adc4837e22e 100644 --- a/pkg/reconciler/events/cloudevent/cloud_event_controller_test.go +++ b/pkg/reconciler/events/cloudevent/cloud_event_controller_test.go @@ -19,532 +19,22 @@ package cloudevent import ( "context" "testing" - "time" "github.com/google/go-cmp/cmp" "github.com/tektoncd/pipeline/pkg/apis/config" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resourcev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" "github.com/tektoncd/pipeline/pkg/reconciler/events/k8sevent" "github.com/tektoncd/pipeline/test/diff" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/record" - clock "k8s.io/utils/clock/testing" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/controller" - "knative.dev/pkg/logging" rtesting "knative.dev/pkg/reconciler/testing" ) -var now = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC) -var testClock = clock.NewFakePassiveClock(now) - -func TestCloudEventDeliveryFromTargets(t *testing.T) { - tests := []struct { - name string - targets []string - wantCloudEvents []v1beta1.CloudEventDelivery - }{{ - name: "testWithNilTarget", - targets: nil, - wantCloudEvents: nil, - }, { - name: "testWithEmptyListTarget", - targets: make([]string, 0), - wantCloudEvents: nil, - }, { - name: "testWithTwoTargets", - targets: []string{"target1", "target2"}, - wantCloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: "target1", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - SentAt: nil, - Error: "", - RetryCount: 0, - }, - }, - { - Target: "target2", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - SentAt: nil, - Error: "", - RetryCount: 0, - }, - }, - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - gotCloudEvents := cloudEventDeliveryFromTargets(tc.targets) - if d := cmp.Diff(tc.wantCloudEvents, gotCloudEvents); d != "" { - t.Errorf("Wrong Cloud Events %s", diff.PrintWantGot(d)) - } - }) - } -} - -func TestSendCloudEvents(t *testing.T) { - tests := []struct { - name string - taskRun *v1beta1.TaskRun - wantTaskRun *v1beta1.TaskRun - }{{ - name: "testWithMultipleMixedCloudEvents", - taskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-multiple-cloudeventdelivery", - Namespace: "foo", - SelfLink: "/task/1234", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - }, - Status: v1beta1.TaskRunStatus{ - Status: duckv1.Status{ - Conditions: duckv1.Conditions{apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown, - Reason: "somethingelse", - }}, - }, - TaskRunStatusFields: v1beta1.TaskRunStatusFields{ - CloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: "http//notattemptedunknown", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - { - Target: "http//notattemptedfailed", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionFailed, - Error: "somehow", - }, - }, - { - Target: "http//notattemptedsucceeded", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - }, - }, - { - Target: "http//attemptedunknown", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - RetryCount: 1, - }, - }, - { - Target: "http//attemptedfailed", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionFailed, - Error: "iknewit", - RetryCount: 1, - }, - }, - { - Target: "http//attemptedsucceeded", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - }, - }, - }, - }, - wantTaskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-multiple-cloudeventdelivery", - Namespace: "foo", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - }, - Status: v1beta1.TaskRunStatus{ - Status: duckv1.Status{ - Conditions: duckv1.Conditions{apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown, - Reason: "somethingelse", - }}, - }, - TaskRunStatusFields: v1beta1.TaskRunStatusFields{ - CloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: "http//notattemptedunknown", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - { - Target: "http//notattemptedfailed", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionFailed, - Error: "somehow", - }, - }, - { - Target: "http//notattemptedsucceeded", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - }, - }, - { - Target: "http//attemptedunknown", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - RetryCount: 1, - }, - }, - { - Target: "http//attemptedfailed", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionFailed, - Error: "iknewit", - RetryCount: 1, - }, - }, - { - Target: "http//attemptedsucceeded", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - }, - }, - }, - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - logger, _ := logging.NewLogger("", "") - successfulBehaviour := FakeClientBehaviour{ - SendSuccessfully: true, - } - err := SendCloudEvents(tc.taskRun, newFakeClient(&successfulBehaviour, len(tc.wantTaskRun.Status.CloudEvents)), logger, testClock) - if err != nil { - t.Fatalf("Unexpected error sending cloud events: %v", err) - } - opts := GetCloudEventDeliveryCompareOptions() - if d := cmp.Diff(tc.wantTaskRun.Status, tc.taskRun.Status, opts...); d != "" { - t.Errorf("Wrong Cloud Events Status %s", diff.PrintWantGot(d)) - } - }) - } -} - -func TestSendCloudEventsErrors(t *testing.T) { - tests := []struct { - name string - taskRun *v1beta1.TaskRun - wantTaskRun *v1beta1.TaskRun - }{{ - name: "testWithMultipleMixedCloudEvents", - taskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-multiple-cloudeventdelivery", - Namespace: "foo", - SelfLink: "/task/1234", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - }, - Status: v1beta1.TaskRunStatus{ - Status: duckv1.Status{ - Conditions: duckv1.Conditions{apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown, - Reason: "somethingelse", - }}, - }, - TaskRunStatusFields: v1beta1.TaskRunStatusFields{ - CloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: "http//sink1", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - { - Target: "http//sink2", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - }, - }, - }, - }, - wantTaskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-multiple-cloudeventdelivery", - Namespace: "foo", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - }, - Status: v1beta1.TaskRunStatus{ - Status: duckv1.Status{ - Conditions: duckv1.Conditions{apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown, - Reason: "somethingelse", - }}, - }, - TaskRunStatusFields: v1beta1.TaskRunStatusFields{ - CloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: "http//sink1", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionFailed, - RetryCount: 1, - }, - }, - { - Target: "http//sink2", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionFailed, - RetryCount: 1, - }, - }, - }, - }, - }, - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - logger, _ := logging.NewLogger("", "") - unsuccessfulBehaviour := FakeClientBehaviour{ - SendSuccessfully: false, - } - err := SendCloudEvents(tc.taskRun, newFakeClient(&unsuccessfulBehaviour, len(tc.wantTaskRun.Status.CloudEvents)), logger, testClock) - if err == nil { - t.Fatalf("Unexpected success sending cloud events: %v", err) - } - opts := GetCloudEventDeliveryCompareOptions() - if d := cmp.Diff(tc.wantTaskRun.Status, tc.taskRun.Status, opts...); d != "" { - t.Errorf("Wrong Cloud Events Status %s", diff.PrintWantGot(d)) - } - }) - } -} - -func TestInitializeCloudEvents(t *testing.T) { - tests := []struct { - name string - taskRun *v1beta1.TaskRun - pipelineResources []*resourcev1alpha1.PipelineResource - wantTaskRun *v1beta1.TaskRun - }{{ - name: "testWithMultipleMixedResources", - taskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-multiple-mixed-resources", - Namespace: "foo", - SelfLink: "/task/1234", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - Resources: &v1beta1.TaskRunResources{ - Outputs: []v1beta1.TaskResourceBinding{ - { - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "ce1", - ResourceRef: &v1beta1.PipelineResourceRef{ - Name: "ce1", - }, - }, - }, - { - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "git", - ResourceRef: &v1beta1.PipelineResourceRef{ - Name: "git", - }, - }, - }, - { - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "ce2", - ResourceRef: &v1beta1.PipelineResourceRef{ - Name: "ce2", - }, - }, - }, - }, - }, - }, - }, - pipelineResources: []*resourcev1alpha1.PipelineResource{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "ce1", - Namespace: "foo", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - Params: []resourcev1alpha1.ResourceParam{{ - Name: "TargetURI", - Value: "http://foosink", - }}, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "ce2", - Namespace: "foo", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - Params: []resourcev1alpha1.ResourceParam{{ - Name: "TargetURI", - Value: "http://barsink", - }}, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "git", - Namespace: "foo", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeGit, - Params: []resourcev1alpha1.ResourceParam{ - { - Name: "URL", - Value: "http://git.fake", - }, - { - Name: "Revision", - Value: "abcd", - }, - }, - }, - }, - }, - wantTaskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-multiple-mixed-resources", - Namespace: "foo", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - }, - Status: v1beta1.TaskRunStatus{ - TaskRunStatusFields: v1beta1.TaskRunStatusFields{ - CloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: "http://barsink", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - { - Target: "http://foosink", - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - }, - }, - }, - }, - }, { - name: "testWithNoCloudEventResources", - taskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-no-cloudevent-resources", - Namespace: "foo", - SelfLink: "/task/1234", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - Resources: &v1beta1.TaskRunResources{ - Outputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "git", - ResourceRef: &v1beta1.PipelineResourceRef{ - Name: "git", - }, - }, - }}, - }, - }, - }, - pipelineResources: []*resourcev1alpha1.PipelineResource{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "git", - Namespace: "foo", - }, - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeGit, - Params: []resourcev1alpha1.ResourceParam{ - { - Name: "URL", - Value: "http://git.fake", - }, - { - Name: "Revision", - Value: "abcd", - }, - }, - }, - }, - }, - wantTaskRun: &v1beta1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-no-cloudevent-resources", - Namespace: "foo", - }, - Spec: v1beta1.TaskRunSpec{ - TaskRef: &v1beta1.TaskRef{ - Name: "fakeTaskName", - }, - }, - Status: v1beta1.TaskRunStatus{}, - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - prMap := map[string]*resourcev1alpha1.PipelineResource{} - for _, pr := range tc.pipelineResources { - prMap[pr.Name] = pr - } - InitializeCloudEvents(tc.taskRun, prMap) - opts := GetCloudEventDeliveryCompareOptions() - if d := cmp.Diff(tc.wantTaskRun.Status, tc.taskRun.Status, opts...); d != "" { - t.Errorf("Wrong Cloud Events Status %s", diff.PrintWantGot(d)) - } - }) - } -} - func TestSendCloudEventWithRetries(t *testing.T) { objectStatus := duckv1.Status{ Conditions: []apis.Condition{{ diff --git a/pkg/reconciler/taskrun/taskrun.go b/pkg/reconciler/taskrun/taskrun.go index ccc5349c1a2..9498232f966 100644 --- a/pkg/reconciler/taskrun/taskrun.go +++ b/pkg/reconciler/taskrun/taskrun.go @@ -138,16 +138,6 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, tr *v1beta1.TaskRun) pkg // and may not have had all of the assumed default specified. tr.SetDefaults(ctx) - // Try to send cloud events first - cloudEventErr := cloudevent.SendCloudEvents(tr, c.cloudEventClient, logger, c.Clock) - // Regardless of `err`, we must write back any status update that may have - // been generated by `sendCloudEvents` - if cloudEventErr != nil { - // Let's keep timeouts and sidecars running as long as we're trying to - // send cloud events. So we stop here an return errors encountered this far. - return cloudEventErr - } - if err := c.stopSidecars(ctx, tr); err != nil { return err } @@ -442,13 +432,6 @@ func (c *Reconciler) prepare(ctx context.Context, tr *v1beta1.TaskRun) (*v1beta1 return nil, nil, controller.NewPermanentError(err) } - // Initialize the cloud events if at least a CloudEventResource is defined - // and they have not been initialized yet. - // FIXME(afrittoli) This resource specific logic will have to be replaced - // once we have a custom PipelineResource framework in place. - logger.Debugf("Cloud Events: %s", tr.Status.CloudEvents) - cloudevent.InitializeCloudEvents(tr, rtr.Outputs) - return taskSpec, rtr, nil } diff --git a/pkg/reconciler/taskrun/taskrun_test.go b/pkg/reconciler/taskrun/taskrun_test.go index 6c8d0fa5c59..34576bb69ab 100644 --- a/pkg/reconciler/taskrun/taskrun_test.go +++ b/pkg/reconciler/taskrun/taskrun_test.go @@ -117,8 +117,6 @@ var ( ignoreEnvVarOrdering = cmpopts.SortSlices(func(x, y corev1.EnvVar) bool { return x.Name < y.Name }) volumeSort = cmpopts.SortSlices(func(i, j corev1.Volume) bool { return i.Name < j.Name }) volumeMountSort = cmpopts.SortSlices(func(i, j corev1.VolumeMount) bool { return i.Name < j.Name }) - cloudEventTarget1 = "https://foo" - cloudEventTarget2 = "https://bar" simpleStep = v1beta1.Step{ Name: "simple-step", @@ -299,29 +297,6 @@ var ( }, } - twoOutputsTask = &v1beta1.Task{ - ObjectMeta: objectMeta("test-two-output-task", "foo"), - Spec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{simpleStep}, - Resources: &v1beta1.TaskResources{ - Outputs: []v1beta1.TaskResource{ - { - ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: cloudEventResource.Name, - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - }, - }, - { - ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: anotherCloudEventResource.Name, - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - }, - }, - }, - }, - }, - } - gitResource = &resourcev1alpha1.PipelineResource{ ObjectMeta: objectMeta("git-resource", "foo"), Spec: resourcev1alpha1.PipelineResourceSpec{ @@ -352,26 +327,6 @@ var ( }}, }, } - cloudEventResource = &resourcev1alpha1.PipelineResource{ - ObjectMeta: objectMeta("cloud-event-resource", "foo"), - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - Params: []resourcev1alpha1.ResourceParam{{ - Name: "TargetURI", - Value: cloudEventTarget1, - }}, - }, - } - anotherCloudEventResource = &resourcev1alpha1.PipelineResource{ - ObjectMeta: objectMeta("another-cloud-event-resource", "foo"), - Spec: resourcev1alpha1.PipelineResourceSpec{ - Type: resourcev1alpha1.PipelineResourceTypeCloudEvent, - Params: []resourcev1alpha1.ResourceParam{{ - Name: "TargetURI", - Value: cloudEventTarget2, - }}, - }, - } binVolume = corev1.Volume{ Name: "tekton-internal-bin", @@ -3139,295 +3094,6 @@ status: }) } } - -func TestReconcileCloudEvents(t *testing.T) { - taskRunWithNoCEResources := parse.MustParseV1beta1TaskRun(t, ` -metadata: - name: test-taskrun-no-ce-resources - namespace: foo -spec: - taskRef: - apiVersion: a1 - name: test-task -`) - taskRunWithTwoCEResourcesNoInit := parse.MustParseV1beta1TaskRun(t, ` -metadata: - name: test-taskrun-two-ce-resources-no-init - namespace: foo -spec: - resources: - outputs: - - name: cloud-event-resource - resourceRef: - name: cloud-event-resource - - name: another-cloud-event-resource - resourceRef: - name: another-cloud-event-resource - taskRef: - name: test-two-output-task -`) - taskRunWithTwoCEResourcesInit := parse.MustParseV1beta1TaskRun(t, ` -metadata: - name: test-taskrun-two-ce-resources-init - namespace: foo -spec: - resources: - outputs: - - name: cloud-event-resource - resourceRef: - name: cloud-event-resource - - name: another-cloud-event-resource - resourceRef: - name: another-cloud-event-resource - taskRef: - name: test-two-output-task -status: - cloudEvents: - - status: - condition: Unknown - target: https://foo - - status: - condition: Unknown - target: https://bar -`) - taskRunWithCESucceded := parse.MustParseV1beta1TaskRun(t, ` -metadata: - name: test-taskrun-ce-succeeded - namespace: foo - selfLink: /task/1234 -spec: - resources: - outputs: - - name: cloud-event-resource - resourceRef: - name: cloud-event-resource - - name: another-cloud-event-resource - resourceRef: - name: another-cloud-event-resource - taskRef: - name: test-two-output-task -status: - cloudEvents: - - status: - condition: Unknown - target: https://foo - - status: - condition: Unknown - target: https://bar - conditions: - - status: "True" - type: Succeeded -`) - taskRunWithCEFailed := parse.MustParseV1beta1TaskRun(t, ` -metadata: - name: test-taskrun-ce-failed - namespace: foo - selfLink: /task/1234 -spec: - resources: - outputs: - - name: cloud-event-resource - resourceRef: - name: cloud-event-resource - - name: another-cloud-event-resource - resourceRef: - name: another-cloud-event-resource - taskRef: - name: test-two-output-task -status: - cloudEvents: - - status: - condition: Unknown - target: https://foo - - status: - condition: Unknown - target: https://bar - conditions: - - status: "False" - type: Succeeded -`) - taskRunWithCESuccededOneAttempt := parse.MustParseV1beta1TaskRun(t, ` -metadata: - name: test-taskrun-ce-succeeded-one-attempt - namespace: foo - selfLink: /task/1234 -spec: - resources: - outputs: - - name: cloud-event-resource - resourceRef: - name: cloud-event-resource - - name: another-cloud-event-resource - resourceRef: - name: another-cloud-event-resource - taskRef: - name: test-two-output-task -status: - cloudEvents: - - status: - condition: Unknown - retryCount: 1 - target: https://foo - - status: - condition: Unknown - message: fakemessage - target: https://bar - conditions: - - status: "True" - type: Succeeded -`) - taskruns := []*v1beta1.TaskRun{ - taskRunWithNoCEResources, taskRunWithTwoCEResourcesNoInit, - taskRunWithTwoCEResourcesInit, taskRunWithCESucceded, taskRunWithCEFailed, - taskRunWithCESuccededOneAttempt, - } - - d := test.Data{ - TaskRuns: taskruns, - Tasks: []*v1beta1.Task{simpleTask, twoOutputsTask}, - ClusterTasks: []*v1beta1.ClusterTask{}, - PipelineResources: []*resourcev1alpha1.PipelineResource{cloudEventResource, anotherCloudEventResource}, - } - for _, tc := range []struct { - name string - taskRun *v1beta1.TaskRun - wantCloudEvents []v1beta1.CloudEventDelivery - }{{ - name: "no-ce-resources", - taskRun: taskRunWithNoCEResources, - wantCloudEvents: taskRunWithNoCEResources.Status.CloudEvents, - }, { - name: "ce-resources-no-init", - taskRun: taskRunWithTwoCEResourcesNoInit, - wantCloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: cloudEventTarget1, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - { - Target: cloudEventTarget2, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - }, - }, { - name: "ce-resources-init", - taskRun: taskRunWithTwoCEResourcesInit, - wantCloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: cloudEventTarget1, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - { - Target: cloudEventTarget2, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - }, - }, - }, - }, { - name: "ce-resources-init-task-successful", - taskRun: taskRunWithCESucceded, - wantCloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: cloudEventTarget1, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - { - Target: cloudEventTarget2, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - }, - }, { - name: "ce-resources-init-task-failed", - taskRun: taskRunWithCEFailed, - wantCloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: cloudEventTarget1, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - { - Target: cloudEventTarget2, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - }, - }, - }, - }, { - name: "ce-resources-init-task-successful-one-attempt", - taskRun: taskRunWithCESuccededOneAttempt, - wantCloudEvents: []v1beta1.CloudEventDelivery{ - { - Target: cloudEventTarget1, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionUnknown, - RetryCount: 1, - }, - }, - { - Target: cloudEventTarget2, - Status: v1beta1.CloudEventDeliveryState{ - Condition: v1beta1.CloudEventConditionSent, - RetryCount: 1, - Error: "fakemessage", - }, - }, - }, - }} { - t.Run(tc.name, func(t *testing.T) { - d.ExpectedCloudEventCount = len(tc.wantCloudEvents) - testAssets, cancel := getTaskRunController(t, d) - defer cancel() - c := testAssets.Controller - clients := testAssets.Clients - - saName := tc.taskRun.Spec.ServiceAccountName - if saName == "" { - saName = "default" - } - if _, err := clients.Kube.CoreV1().ServiceAccounts(tc.taskRun.Namespace).Create(testAssets.Ctx, &corev1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: saName, - Namespace: tc.taskRun.Namespace, - }, - }, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - - if err := c.Reconciler.Reconcile(testAssets.Ctx, getRunName(tc.taskRun)); err == nil { - // No error is ok. - } else if ok, _ := controller.IsRequeueKey(err); !ok { - t.Errorf("expected no error. Got error %v", err) - } - - tr, err := clients.Pipeline.TektonV1beta1().TaskRuns(tc.taskRun.Namespace).Get(testAssets.Ctx, tc.taskRun.Name, metav1.GetOptions{}) - if err != nil { - t.Fatalf("getting updated taskrun: %v", err) - } - opts := cloudevent.GetCloudEventDeliveryCompareOptions() - t.Log(tr.Status.CloudEvents) - if d := cmp.Diff(tc.wantCloudEvents, tr.Status.CloudEvents, opts...); d != "" { - t.Errorf("Unexpected status of cloud events %s", diff.PrintWantGot(d)) - } - }) - } -} - func TestReconcile_Single_SidecarState(t *testing.T) { runningState := corev1.ContainerStateRunning{StartedAt: metav1.Time{Time: now}} taskRun := parse.MustParseV1beta1TaskRun(t, `