diff --git a/cmd/webhook/main.go b/cmd/webhook/main.go index 980f2d94199..71d3e8135fc 100644 --- a/cmd/webhook/main.go +++ b/cmd/webhook/main.go @@ -23,9 +23,9 @@ import ( "os" defaultconfig "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline" "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" "k8s.io/apimachinery/pkg/runtime/schema" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" @@ -46,12 +46,7 @@ import ( var types = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ // v1alpha1 - v1alpha1.SchemeGroupVersion.WithKind("Pipeline"): &v1alpha1.Pipeline{}, - v1alpha1.SchemeGroupVersion.WithKind("Task"): &v1alpha1.Task{}, - v1alpha1.SchemeGroupVersion.WithKind("ClusterTask"): &v1alpha1.ClusterTask{}, - v1alpha1.SchemeGroupVersion.WithKind("TaskRun"): &v1alpha1.TaskRun{}, - v1alpha1.SchemeGroupVersion.WithKind("PipelineRun"): &v1alpha1.PipelineRun{}, - v1alpha1.SchemeGroupVersion.WithKind("PipelineResource"): &v1alpha1.PipelineResource{}, + v1alpha1.SchemeGroupVersion.WithKind("PipelineResource"): &resourcev1alpha1.PipelineResource{}, v1alpha1.SchemeGroupVersion.WithKind("Run"): &v1alpha1.Run{}, // v1beta1 v1beta1.SchemeGroupVersion.WithKind("Pipeline"): &v1beta1.Pipeline{}, @@ -131,59 +126,12 @@ func newConfigValidationController(ctx context.Context, cmw configmap.Watcher) * } func newConversionController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - // nolint: revive - var ( - v1alpha1GroupVersion = v1alpha1.SchemeGroupVersion.Version - v1beta1GroupVersion = v1beta1.SchemeGroupVersion.Version - ) - return conversion.NewConversionController(ctx, // The path on which to serve the webhook "/resource-conversion", // Specify the types of custom resource definitions that should be converted - map[schema.GroupKind]conversion.GroupKindConversion{ - v1beta1.Kind("Task"): { - DefinitionName: pipeline.TaskResource.String(), - HubVersion: v1alpha1GroupVersion, - Zygotes: map[string]conversion.ConvertibleObject{ - v1alpha1GroupVersion: &v1alpha1.Task{}, - v1beta1GroupVersion: &v1beta1.Task{}, - }, - }, - v1beta1.Kind("ClusterTask"): { - DefinitionName: pipeline.ClusterTaskResource.String(), - HubVersion: v1alpha1GroupVersion, - Zygotes: map[string]conversion.ConvertibleObject{ - v1alpha1GroupVersion: &v1alpha1.ClusterTask{}, - v1beta1GroupVersion: &v1beta1.ClusterTask{}, - }, - }, - v1beta1.Kind("TaskRun"): { - DefinitionName: pipeline.TaskRunResource.String(), - HubVersion: v1alpha1GroupVersion, - Zygotes: map[string]conversion.ConvertibleObject{ - v1alpha1GroupVersion: &v1alpha1.TaskRun{}, - v1beta1GroupVersion: &v1beta1.TaskRun{}, - }, - }, - v1beta1.Kind("Pipeline"): { - DefinitionName: pipeline.PipelineResource.String(), - HubVersion: v1alpha1GroupVersion, - Zygotes: map[string]conversion.ConvertibleObject{ - v1alpha1GroupVersion: &v1alpha1.Pipeline{}, - v1beta1GroupVersion: &v1beta1.Pipeline{}, - }, - }, - v1beta1.Kind("PipelineRun"): { - DefinitionName: pipeline.PipelineRunResource.String(), - HubVersion: v1alpha1GroupVersion, - Zygotes: map[string]conversion.ConvertibleObject{ - v1alpha1GroupVersion: &v1alpha1.PipelineRun{}, - v1beta1GroupVersion: &v1beta1.PipelineRun{}, - }, - }, - }, + map[schema.GroupKind]conversion.GroupKindConversion{}, // A function that infuses the context passed to ConvertTo/ConvertFrom/SetDefaults with custom metadata func(ctx context.Context) context.Context { diff --git a/examples/v1alpha1/pipelineruns/clustertask-pipelinerun.yaml b/examples/v1alpha1/pipelineruns/clustertask-pipelinerun.yaml deleted file mode 100644 index c9bf0d776af..00000000000 --- a/examples/v1alpha1/pipelineruns/clustertask-pipelinerun.yaml +++ /dev/null @@ -1,30 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: ClusterTask -metadata: - name: cluster-task-pipeline-4-v1alpha1 -spec: - steps: - - name: task-two-step-one - image: ubuntu - command: ["/bin/bash"] - args: ['-c', 'echo success'] ---- -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: sample-pipeline-cluster-task-4 -spec: - tasks: - - name: cluster-task-pipeline-4 - taskRef: - name: cluster-task-pipeline-4-v1alpha1 - kind: ClusterTask ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: demo-pipeline-run-4 -spec: - pipelineRef: - name: sample-pipeline-cluster-task-4 - serviceAccountName: 'default' diff --git a/examples/v1alpha1/pipelineruns/no-ci/.keep b/examples/v1alpha1/pipelineruns/no-ci/.keep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/examples/v1alpha1/pipelineruns/no-ci/limitrange.yaml b/examples/v1alpha1/pipelineruns/no-ci/limitrange.yaml deleted file mode 100644 index 3cca0f9b16a..00000000000 --- a/examples/v1alpha1/pipelineruns/no-ci/limitrange.yaml +++ /dev/null @@ -1,56 +0,0 @@ -apiVersion: v1 -kind: LimitRange -metadata: - name: limit-mem-cpu-per-container -spec: - limits: - - max: - cpu: "800m" - memory: "1Gi" - min: - cpu: "100m" - memory: "99Mi" - default: - cpu: "700m" - memory: "900Mi" - defaultRequest: - cpu: "110m" - memory: "111Mi" - type: Container ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: echo-hello-world -spec: - steps: - - name: echo - image: ubuntu - command: - - echo - args: - - "hello world" ---- -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: pipeline-hello -spec: - tasks: - - name: hello-world-1 - taskRef: - name: echo-hello-world - - name: hello-world-2 - taskRef: - name: echo-hello-world - runAfter: - - hello-world-1 ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - generateName: pipeline-hello-run- -spec: - pipelineRef: - name: pipeline-hello -status: {} \ No newline at end of file diff --git a/examples/v1alpha1/pipelineruns/no-ci/pipeline-timeout.yaml b/examples/v1alpha1/pipelineruns/no-ci/pipeline-timeout.yaml deleted file mode 100644 index 5a2c704ea5b..00000000000 --- a/examples/v1alpha1/pipelineruns/no-ci/pipeline-timeout.yaml +++ /dev/null @@ -1,56 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: task-echo-message -spec: - inputs: - params: - - name: MESSAGE - type: string - default: "Hello World" - steps: - - name: echo - image: ubuntu - command: - - sleep 90s - args: - - "$(inputs.params.MESSAGE)" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: pipelinerun-timeout -spec: - # 1 hour and half timeout - timeout: 1h30m - pipelineSpec: - params: - - name: MORNING_GREETINGS - description: "morning greetings, default is Good Morning!" - type: string - default: "Good Morning!" - - name: NIGHT_GREETINGS - description: "Night greetings, default is Good Night!" - type: string - default: "Good Night!" - tasks: - # Task to display morning greetings - - name: echo-good-morning - taskRef: - name: task-echo-message - params: - - name: MESSAGE - value: $(params.MORNING_GREETINGS) - # Task to display night greetings - - name: echo-good-night - taskRef: - name: task-echo-message - params: - - name: MESSAGE - value: $(params.NIGHT_GREETINGS) - params: - - name: MORNING_GREETINGS - value: "Good Morning, Bob!" - - name: NIGHT_GREETINGS - value: "Good Night, Bob!" diff --git a/examples/v1alpha1/pipelineruns/output-pipelinerun.yaml b/examples/v1alpha1/pipelineruns/output-pipelinerun.yaml deleted file mode 100644 index 2346bb13664..00000000000 --- a/examples/v1alpha1/pipelineruns/output-pipelinerun.yaml +++ /dev/null @@ -1,105 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-git-output-pipelinerun -spec: - type: git - params: - - name: revision - value: v0.32.0 - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -# Task writes "some stuff" to a predefined path in the workspace git PipelineResource -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: create-file -spec: - inputs: - resources: - - name: workspace - type: git - targetPath: damnworkspace - outputs: - resources: - - name: workspace - type: git - steps: - - name: read-docs-old - image: ubuntu - command: ["/bin/bash"] - args: ['-c', 'ls -la /workspace/damnworkspace/docs/README.md'] # tests that targetpath works - - name: write-new-stuff - image: ubuntu - command: ['bash'] - args: ['-c', 'ln -s /workspace/damnworkspace /workspace/output/workspace && echo some stuff > /workspace/output/workspace/stuff'] ---- -# Reads a file from a predefined path in the workspace git PipelineResource -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: check-stuff-file-exists -spec: - inputs: - resources: - - name: workspace - type: git - targetPath: newworkspace - params: - - name: args - type: array - steps: - - name: read - image: ubuntu - command: ["/bin/bash"] - args: ['$(inputs.params.args[*])'] # tests that new targetpath and previous task output is dumped ---- -# The Output of the first Task (git resource) create-file is given as an `Input` -# to the next `Task` check-stuff-file-exists using`from` clause. - -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: output-pipeline -spec: - resources: - - name: source-repo - type: git - tasks: - - name: first-create-file # 1. create file - taskRef: - name: create-file - resources: - inputs: - - name: workspace - resource: source-repo - outputs: - - name: workspace - resource: source-repo - - name: then-check # 2. check file exists - taskRef: - name: check-stuff-file-exists - params: - - name: args - value: - - '-c' - - 'cat /workspace/newworkspace/stuff' - resources: - inputs: - - name: workspace - resource: source-repo - from: [first-create-file] ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: output-pipeline-run -spec: - pipelineRef: - name: output-pipeline - serviceAccountName: 'default' - resources: - - name: source-repo - resourceRef: - name: skaffold-git-output-pipelinerun diff --git a/examples/v1alpha1/pipelineruns/pipelinerun-with-params.yaml b/examples/v1alpha1/pipelineruns/pipelinerun-with-params.yaml deleted file mode 100644 index 2674b9cd4db..00000000000 --- a/examples/v1alpha1/pipelineruns/pipelinerun-with-params.yaml +++ /dev/null @@ -1,92 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: pipeline-with-params -spec: - params: - - name: pl-param-x - type: string - default: "1" - - name: pl-param-y - type: string - default: "1" - tasks: - - name: sum-params - taskRef: - name: sum-params - params: - - name: a - value: "$(params.pl-param-x)" - - name: b - value: "$(params.pl-param-y)" - - name: multiply-params - taskRef: - name: multiply-params - params: - - name: a - value: "$(params.pl-param-x)" - - name: b - value: "$(params.pl-param-y)" ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: sum-params - annotations: - description: | - A simple task that sums the two provided integers -spec: - inputs: - params: - - name: a - type: string - default: "1" - description: The first integer - - name: b - type: string - default: "1" - description: The second integer - steps: - - name: sum - image: bash:latest - script: | - #!/usr/bin/env bash - echo -n $(( "$(inputs.params.a)" + "$(inputs.params.b)" )) ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: multiply-params - annotations: - description: | - A simple task that multiplies the two provided integers -spec: - inputs: - params: - - name: a - type: string - default: "1" - description: The first integer - - name: b - type: string - default: "1" - description: The second integer - steps: - - name: product - image: bash:latest - script: | - #!/usr/bin/env bash - echo -n $(( "$(inputs.params.a)" * "$(inputs.params.b)" )) ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: pipelinerun-with-params -spec: - params: - - name: pl-param-x - value: "100" - - name: pl-param-y - value: "500" - pipelineRef: - name: pipeline-with-params diff --git a/examples/v1alpha1/pipelineruns/pipelinerun-with-pipelinespec-and-taskspec.yaml b/examples/v1alpha1/pipelineruns/pipelinerun-with-pipelinespec-and-taskspec.yaml deleted file mode 100644 index c6de5a7728b..00000000000 --- a/examples/v1alpha1/pipelineruns/pipelinerun-with-pipelinespec-and-taskspec.yaml +++ /dev/null @@ -1,81 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: pipelinerun-with-taskspec-to-echo-good-morning -spec: - pipelineSpec: - tasks: - - name: echo-good-morning - taskSpec: - steps: - - name: echo - image: ubuntu - script: | - #!/usr/bin/env bash - echo "Good Morning!" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: pipelinerun-with-taskspec-to-echo-message -spec: - pipelineSpec: - params: - - name: MESSAGE - description: "Message, default is Hello World!" - type: string - default: "Hello World!" - tasks: - - name: echo-message - taskSpec: - inputs: - params: - - name: MESSAGE - type: string - default: "Hello World!" - steps: - - name: echo - image: ubuntu - script: | - #!/usr/bin/env bash - echo "$(inputs.params.MESSAGE)" - params: - - name: MESSAGE - value: $(params.MESSAGE) - params: - - name: MESSAGE - value: "Good Morning!" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: pipelinerun-with-taskspec-to-echo-greetings -spec: - pipelineSpec: - params: - - name: GREETINGS - description: "Greetings, default is Hello World!" - type: string - default: "Hello World!" - tasks: - - name: echo-greetings - taskSpec: - inputs: - params: - - name: MESSAGE - type: string - default: "Hello World!" - steps: - - name: echo - image: ubuntu - script: | - #!/usr/bin/env bash - echo "$(inputs.params.MESSAGE)" - params: - - name: MESSAGE - value: $(params.GREETINGS) - params: - - name: GREETINGS - value: "Good Morning!" diff --git a/examples/v1alpha1/pipelineruns/pipelinerun-with-pipelinespec.yaml b/examples/v1alpha1/pipelineruns/pipelinerun-with-pipelinespec.yaml deleted file mode 100644 index 1268357223b..00000000000 --- a/examples/v1alpha1/pipelineruns/pipelinerun-with-pipelinespec.yaml +++ /dev/null @@ -1,54 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: task-echo-message -spec: - inputs: - params: - - name: MESSAGE - type: string - default: "Hello World" - steps: - - name: echo - image: ubuntu - command: - - echo - args: - - "$(inputs.params.MESSAGE)" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: pipelinerun-echo-greetings -spec: - pipelineSpec: - params: - - name: MORNING_GREETINGS - description: "morning greetings, default is Good Morning!" - type: string - default: "Good Morning!" - - name: NIGHT_GREETINGS - description: "Night greetings, default is Good Night!" - type: string - default: "Good Night!" - tasks: - # Task to display morning greetings - - name: echo-good-morning - taskRef: - name: task-echo-message - params: - - name: MESSAGE - value: $(params.MORNING_GREETINGS) - # Task to display night greetings - - name: echo-good-night - taskRef: - name: task-echo-message - params: - - name: MESSAGE - value: $(params.NIGHT_GREETINGS) - params: - - name: MORNING_GREETINGS - value: "Good Morning, Bob!" - - name: NIGHT_GREETINGS - value: "Good Night, Bob!" diff --git a/examples/v1alpha1/pipelineruns/pipelinerun-with-resourcespec.yaml b/examples/v1alpha1/pipelineruns/pipelinerun-with-resourcespec.yaml deleted file mode 100644 index e2c8aad8f3b..00000000000 --- a/examples/v1alpha1/pipelineruns/pipelinerun-with-resourcespec.yaml +++ /dev/null @@ -1,75 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: task-to-list-files -spec: - inputs: - resources: - - name: pipeline-git - type: git - outputs: - resources: - - name: pipeline-git - type: git - steps: - - name: list - image: ubuntu - command: - - bash - args: - - -c - - | - ls -al $(inputs.resources.pipeline-git.path) ---- - -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: pipeline-to-list-files -spec: - resources: - - name: pipeline-git - type: git - params: - - name: "path" - default: "README.md" - tasks: - - name: list-files - taskRef: - name: task-to-list-files - resources: - inputs: - - name: pipeline-git - resource: pipeline-git - outputs: - - name: pipeline-git - resource: pipeline-git - - name: second-list-files - taskRef: - name: task-to-list-files - resources: - inputs: - - name: pipeline-git - resource: pipeline-git - outputs: - - name: pipeline-git - resource: pipeline-git ---- - -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: demo-pipelinerun-with-resourcespec -spec: - pipelineRef: - name: pipeline-to-list-files - serviceAccountName: 'default' - resources: - - name: pipeline-git - resourceSpec: - type: git - params: - - name: revision - value: main - - name: url - value: https://github.com/tektoncd/pipeline diff --git a/examples/v1alpha1/pipelineruns/pipelinerun.yaml b/examples/v1alpha1/pipelineruns/pipelinerun.yaml deleted file mode 100644 index 30ced63633c..00000000000 --- a/examples/v1alpha1/pipelineruns/pipelinerun.yaml +++ /dev/null @@ -1,263 +0,0 @@ ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-image-leeroy-app -spec: - type: image - params: - - name: url - value: gcr.io/christiewilson-catfactory/leeroy-app ---- -# This demo modifies the cluster (deploys to it) you must use a service -# account with permission to admin the cluster (or make your default user an admin -# of the `default` namespace with default-cluster-admin. - -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - generateName: default-cluster-admin- -subjects: - - kind: ServiceAccount - name: default - namespace: default -roleRef: - kind: ClusterRole - name: cluster-admin - apiGroup: rbac.authorization.k8s.io ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-image-leeroy-web-pipelinerun -spec: - type: image - params: - - name: url - value: gcr.io/christiewilson-catfactory/leeroy-web ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-git-pipelinerun -spec: - type: git - params: - - name: revision - value: v1.32.0 - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: unit-tests -spec: - inputs: - resources: - - name: workspace - type: git - targetPath: go/src/github.com/GoogleContainerTools/skaffold - steps: - - name: run-tests - image: golang - env: - - name: GOPATH - value: /workspace/go - workingDir: /workspace/go/src/github.com/GoogleContainerTools/skaffold - command: - - echo - args: - - "pass" ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: build-push -spec: - inputs: - resources: - - name: workspace - type: git - params: - - name: pathToDockerFile - description: The path to the dockerfile to build - default: /workspace/workspace/Dockerfile - - name: pathToContext - description: The build context used by Kaniko (https://github.com/GoogleContainerTools/kaniko#kaniko-build-contexts) - default: /workspace/workspace - - name: baseImage - description: Base image for GoogleContainerTools/skaffold microservice apps - default: BASE=alpine:3.9 - outputs: - resources: - - name: builtImage - type: image - steps: - - name: build-and-push - image: gcr.io/kaniko-project/executor:v1.3.0 - # specifying DOCKER_CONFIG is required to allow kaniko to detect docker credential - env: - - name: "DOCKER_CONFIG" - value: "/tekton/home/.docker/" - command: - - /kaniko/executor - args: - - --dockerfile=$(inputs.params.pathToDockerFile) - - --destination=$(outputs.resources.builtImage.url) - - --context=$(inputs.params.pathToContext) - - --build-arg=$(inputs.params.baseImage) ---- -# This task deploys with kubectl apply -f -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: demo-deploy-kubectl -spec: - inputs: - resources: - - name: workspace - type: git - - name: image - type: image - params: - - name: path - description: Path to the manifest to apply - - name: yqArg - description: Okay this is a hack, but I didn't feel right hard-codeing `-d1` down below - - name: yamlPathToImage - description: The path to the image to replace in the yaml manifest (arg to yq) - steps: - - name: replace-image - image: mikefarah/yq:3 - command: ['yq'] - args: - - "w" - - "-i" - - "$(inputs.params.yqArg)" - - "$(inputs.params.path)" - - "$(inputs.params.yamlPathToImage)" - - "$(inputs.resources.image.url)" - - name: run-kubectl - image: lachlanevenson/k8s-kubectl - command: ['kubectl'] - args: - - 'apply' - - '-f' - - '$(inputs.params.path)' ---- -# This Pipeline Builds two microservice images(https://github.com/GoogleContainerTools/skaffold/tree/master/examples/microservices) -# from the Skaffold repo (https://github.com/GoogleContainerTools/skaffold) and deploys them to the repo currently running Tekton Pipelines. - -# **Note** : It does this using the k8s `Deployment` in the skaffold repos's existing yaml -# files, so at the moment there is no guarantee that the image that are built and -# pushed are the ones that are deployed (that would require using the digest of -# the built image, see https://github.com/tektoncd/pipeline/issues/216). - -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: demo-pipeline -spec: - resources: - - name: source-repo - type: git - - name: web-image - type: image - - name: app-image - type: image - tasks: - - name: skaffold-unit-tests - taskRef: - name: unit-tests - resources: - inputs: - - name: workspace - resource: source-repo - - name: build-skaffold-web - runAfter: [skaffold-unit-tests] - taskRef: - name: build-push - params: - - name: pathToDockerFile - value: Dockerfile - - name: pathToContext - value: /workspace/workspace/examples/microservices/leeroy-web - resources: - inputs: - - name: workspace - resource: source-repo - outputs: - - name: builtImage - resource: web-image - - name: build-skaffold-app - runAfter: [skaffold-unit-tests] - taskRef: - name: build-push - params: - - name: pathToDockerFile - value: Dockerfile - - name: pathToContext - value: /workspace/workspace/examples/microservices/leeroy-app - resources: - inputs: - - name: workspace - resource: source-repo - outputs: - - name: builtImage - resource: app-image - - name: deploy-app - taskRef: - name: demo-deploy-kubectl - resources: - inputs: - - name: workspace - resource: source-repo - - name: image - resource: app-image - from: - - build-skaffold-app - params: - - name: path - value: /workspace/workspace/examples/microservices/leeroy-app/kubernetes/deployment.yaml - - name: yqArg - value: "-d1" - - name: yamlPathToImage - value: "spec.template.spec.containers[0].image" - - name: deploy-web - taskRef: - name: demo-deploy-kubectl - resources: - inputs: - - name: workspace - resource: source-repo - - name: image - resource: web-image - from: - - build-skaffold-web - params: - - name: path - value: /workspace/workspace/examples/microservices/leeroy-web/kubernetes/deployment.yaml - - name: yqArg - value: "-d0" - - name: yamlPathToImage - value: "spec.template.spec.containers[0].image" ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - name: demo-pipeline-run-1 -spec: - pipelineRef: - name: demo-pipeline - serviceAccountName: 'default' - resources: - - name: source-repo - resourceRef: - name: skaffold-git-pipelinerun - - name: web-image - resourceRef: - name: skaffold-image-leeroy-web-pipelinerun - - name: app-image - resourceRef: - name: skaffold-image-leeroy-app diff --git a/examples/v1alpha1/pipelineruns/task_results_example.yaml b/examples/v1alpha1/pipelineruns/task_results_example.yaml deleted file mode 100644 index d635de86df6..00000000000 --- a/examples/v1alpha1/pipelineruns/task_results_example.yaml +++ /dev/null @@ -1,93 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: sum-and-multiply-pipeline -spec: - params: - - name: a - type: string - default: "1" - - name: b - type: string - default: "1" - tasks: - - name: sum-inputs - taskRef: - name: sum - params: - - name: a - value: "$(params.a)" - - name: b - value: "$(params.b)" - - name: multiply-inputs - taskRef: - name: multiply - params: - - name: a - value: "$(params.a)" - - name: b - value: "$(params.b)" - - name: sum-and-multiply - taskRef: - name: sum - params: - - name: a - value: "$(tasks.multiply-inputs.results.product)$(tasks.sum-inputs.results.sum)" - - name: b - value: "$(tasks.multiply-inputs.results.product)$(tasks.sum-inputs.results.sum)" ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: sum - annotations: - description: | - A simple task that sums the two provided integers -spec: - inputs: - params: - - name: a - type: string - default: "1" - description: The first integer - - name: b - type: string - default: "1" - description: The second integer - results: - - name: sum - description: The sum of the two provided integers - steps: - - name: sum - image: bash:latest - script: | - #!/usr/bin/env bash - echo -n $(( "$(inputs.params.a)" + "$(inputs.params.b)" )) | tee $(results.sum.path) ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: multiply - annotations: - description: | - A simple task that multiplies the two provided integers -spec: - inputs: - params: - - name: a - type: string - default: "1" - description: The first integer - - name: b - type: string - default: "1" - description: The second integer - results: - - name: product - description: The product of the two provided integers - steps: - - name: product - image: bash:latest - script: | - #!/usr/bin/env bash - echo -n $(( "$(inputs.params.a)" * "$(inputs.params.b)" )) | tee $(results.product.path) diff --git a/examples/v1alpha1/pipelineruns/workspaces.yaml b/examples/v1alpha1/pipelineruns/workspaces.yaml deleted file mode 100644 index c9d5457477d..00000000000 --- a/examples/v1alpha1/pipelineruns/workspaces.yaml +++ /dev/null @@ -1,136 +0,0 @@ -# In this contrived example 3 different kinds of workspace volume are used to thread -# data through a pipeline's tasks. -# 1. A ConfigMap is used as source of recipe data. -# 2. A Secret is used to store a password. -# 3. A PVC is used to share data from one task to the next. -# -# The end result is a pipeline that first checks if the password is correct and, if so, -# copies data out of a recipe store onto a shared volume. The recipe data is then read -# by a subsequent task and printed to screen. -apiVersion: v1 -kind: ConfigMap -metadata: - name: sensitive-recipe-storage -data: - brownies: | - 1. Heat oven to 325 degrees F - 2. Melt 1/2 cup butter w/ 1/2 cup cocoa, stirring smooth. - 3. Remove from heat, allow to cool for a few minutes. - 4. Transfer to bowl. - 5. Whisk in 2 eggs, one at a time. - 6. Stir in vanilla. - 7. Separately combine 1 cup sugar, 1/4 cup flour, 1 cup chopped - walnuts and pinch of salt - 8. Combine mixtures. - 9. Bake in greased pan for 30 minutes. Watch carefully for - appropriate level of gooeyness. ---- -apiVersion: v1 -kind: Secret -metadata: - name: secret-password -type: Opaque -data: - password: aHVudGVyMg== ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: shared-task-storage -spec: - resources: - requests: - storage: 16Mi - volumeMode: Filesystem - accessModes: - - ReadWriteOnce ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: fetch-secure-data -spec: - workspaces: - - name: super-secret-password - - name: secure-store - - name: filedrop - steps: - - name: fetch-and-write - image: ubuntu - script: | - if [ "hunter2" = "$(cat $(workspaces.super-secret-password.path)/password)" ]; then - cp $(workspaces.secure-store.path)/recipe.txt $(workspaces.filedrop.path) - else - echo "wrong password!" - exit 1 - fi ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: print-data -spec: - workspaces: - - name: storage - readOnly: true - inputs: - params: - - name: filename - steps: - - name: print-secrets - image: ubuntu - script: cat $(workspaces.storage.path)/$(inputs.params.filename) ---- -apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -metadata: - name: fetch-and-print-recipe -spec: - workspaces: - - name: password-vault - - name: recipe-store - - name: shared-data - tasks: - - name: fetch-the-recipe - taskRef: - name: fetch-secure-data - workspaces: - - name: super-secret-password - workspace: password-vault - - name: secure-store - workspace: recipe-store - - name: filedrop - workspace: shared-data - - name: print-the-recipe - taskRef: - name: print-data - # Note: this is currently required to ensure order of write / read on PVC is correct. - runAfter: - - fetch-the-recipe - params: - - name: filename - value: recipe.txt - workspaces: - - name: storage - workspace: shared-data ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -metadata: - generateName: recipe-time- -spec: - pipelineRef: - name: fetch-and-print-recipe - workspaces: - - name: password-vault - secret: - secretName: secret-password - - name: recipe-store - configMap: - name: sensitive-recipe-storage - items: - - key: brownies - path: recipe.txt - - name: shared-data - persistentVolumeClaim: - claimName: shared-task-storage diff --git a/examples/v1alpha1/taskruns/build-push-kaniko.yaml b/examples/v1alpha1/taskruns/build-push-kaniko.yaml deleted file mode 100644 index 0e64604518a..00000000000 --- a/examples/v1alpha1/taskruns/build-push-kaniko.yaml +++ /dev/null @@ -1,87 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-image-leeroy-web-build-push-kaniko -spec: - type: image - params: - - name: url - value: localhost:5000/leeroy-web ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-git-build-push-kaniko -spec: - type: git - params: - - name: revision - value: v1.32.0 - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -# Builds an image via kaniko and pushes it to registry. -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: build-push-kaniko -spec: - inputs: - resources: - - name: workspace - type: git - params: - - name: pathToDockerFile - description: The path to the dockerfile to build - default: /workspace/workspace/Dockerfile - - name: pathToContext - description: The build context used by Kaniko (https://github.com/GoogleContainerTools/kaniko#kaniko-build-contexts) - default: /workspace/workspace - - name: baseImage - description: Base image for GoogleContainerTools/skaffold microservice apps - default: BASE=alpine:3.9 - outputs: - resources: - - name: builtImage - type: image - steps: - - name: build-and-push - image: gcr.io/kaniko-project/executor:v1.3.0 - # specifying DOCKER_CONFIG is required to allow kaniko to detect docker credential - env: - - name: "DOCKER_CONFIG" - value: "/tekton/home/.docker/" - args: - - --dockerfile=$(inputs.params.pathToDockerFile) - - --destination=$(outputs.resources.builtImage.url) - - --context=$(inputs.params.pathToContext) - - --oci-layout-path=$(inputs.resources.builtImage.path) - - --build-arg=$(inputs.params.baseImage) - securityContext: - runAsUser: 0 - sidecars: - - image: registry - name: registry ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: build-push-kaniko -spec: - taskRef: - name: build-push-kaniko - inputs: - resources: - - name: workspace - resourceRef: - name: skaffold-git-build-push-kaniko - params: - - name: pathToDockerFile - value: Dockerfile - - name: pathToContext - value: /workspace/workspace/examples/microservices/leeroy-web - outputs: - resources: - - name: builtImage - resourceRef: - name: skaffold-image-leeroy-web-build-push-kaniko diff --git a/examples/v1alpha1/taskruns/cloud-event.yaml b/examples/v1alpha1/taskruns/cloud-event.yaml deleted file mode 100644 index 1dc3c401a11..00000000000 --- a/examples/v1alpha1/taskruns/cloud-event.yaml +++ /dev/null @@ -1,180 +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 < $(outputs.resources.myimage.path)/index.json - { - "schemaVersion": 2, - "manifests": [ - { - "mediaType": "application/vnd.oci.image.index.v1+json", - "size": 314, - "digest": "sha256:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" - } - ] - } ---- -apiVersion: tekton.dev/v1alpha1 -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) ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: send-cloud-event -spec: - outputs: - resources: - - 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/v1alpha1 -kind: TaskRun -metadata: - name: poll-for-content-run -spec: - taskRef: - name: poll-for-content-task diff --git a/examples/v1alpha1/taskruns/clustertask.yaml b/examples/v1alpha1/taskruns/clustertask.yaml deleted file mode 100644 index 876f5a35f6d..00000000000 --- a/examples/v1alpha1/taskruns/clustertask.yaml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: ClusterTask -metadata: - name: clustertask-v1alpha1 -spec: - steps: - - image: ubuntu - script: echo hello ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: clustertask- -spec: - taskRef: - name: clustertask-v1alpha1 - kind: ClusterTask diff --git a/examples/v1alpha1/taskruns/configmap.yaml b/examples/v1alpha1/taskruns/configmap.yaml deleted file mode 100644 index cd0c80ea2cb..00000000000 --- a/examples/v1alpha1/taskruns/configmap.yaml +++ /dev/null @@ -1,32 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: config-for-testing-configmaps -data: - test.data: tasks are my jam ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: configmap- -spec: - taskSpec: - steps: - - name: secret - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $(cat /config/test.data) == $TEST_DATA ]] - env: - - name: TEST_DATA - valueFrom: - configMapKeyRef: - name: config-for-testing-configmaps - key: test.data - volumeMounts: - - name: config-volume - mountPath: /config - volumes: - - name: config-volume - configMap: - name: config-for-testing-configmaps diff --git a/examples/v1alpha1/taskruns/custom-env.yaml b/examples/v1alpha1/taskruns/custom-env.yaml deleted file mode 100644 index 5fc18f7176c..00000000000 --- a/examples/v1alpha1/taskruns/custom-env.yaml +++ /dev/null @@ -1,14 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: custom-env- -spec: - taskSpec: - steps: - - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $MY_VAR1 == foo ]] - env: - - name: MY_VAR1 - value: foo diff --git a/examples/v1alpha1/taskruns/custom-volume.yaml b/examples/v1alpha1/taskruns/custom-volume.yaml deleted file mode 100644 index 8ad01afa57d..00000000000 --- a/examples/v1alpha1/taskruns/custom-volume.yaml +++ /dev/null @@ -1,26 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: custom-volume- -spec: - taskSpec: - steps: - - name: write - image: ubuntu - script: | - #!/usr/bin/env bash - echo some stuff > /im/a/custom/mount/path/file - volumeMounts: - - name: custom - mountPath: /im/a/custom/mount/path - - name: read - image: ubuntu - script: | - #!/usr/bin/env bash - cat /short/and/stout/file | grep stuff - volumeMounts: - - name: custom - mountPath: /short/and/stout - volumes: - - name: custom - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/dind-sidecar.yaml b/examples/v1alpha1/taskruns/dind-sidecar.yaml deleted file mode 100644 index 3cc1f3a220b..00000000000 --- a/examples/v1alpha1/taskruns/dind-sidecar.yaml +++ /dev/null @@ -1,70 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: dind-sidecar- -spec: - taskSpec: - steps: - - image: docker - name: client - env: - # Connect to the sidecar over TCP, with TLS. - - name: DOCKER_HOST - value: tcp://localhost:2376 - # Verify TLS. - - name: DOCKER_TLS_VERIFY - value: '1' - # Use the certs generated by the sidecar daemon. - - name: DOCKER_CERT_PATH - value: /certs/client - workingDir: /workspace - script: | - #!/usr/bin/env sh - set -e - # Run a Docker container. - docker run busybox echo hello - - # Write a Dockerfile and `docker build` it. - cat > Dockerfile << EOF - FROM ubuntu - RUN apt-get update - ENTRYPOINT ["echo", "hello"] - EOF - docker build -t hello . - docker images - - # ...then run it! - docker run hello - volumeMounts: - - mountPath: /certs/client - name: dind-certs - - sidecars: - - image: docker:dind - name: server - args: - - --storage-driver=vfs - - --userland-proxy=false - - --debug - resources: - requests: - memory: "512Mi" - securityContext: - privileged: true - env: - # Write generated certs to the path shared with the client. - - name: DOCKER_TLS_CERTDIR - value: /certs - volumeMounts: - - mountPath: /certs/client - name: dind-certs - # Wait for the dind daemon to generate the certs it will share with the - # client. - readinessProbe: - periodSeconds: 1 - exec: - command: ['ls', '/certs/client/ca.pem'] - - volumes: - - name: dind-certs - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/gcs-resource.yaml b/examples/v1alpha1/taskruns/gcs-resource.yaml deleted file mode 100644 index 0c8d8f85bb3..00000000000 --- a/examples/v1alpha1/taskruns/gcs-resource.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: gcs-resource- -spec: - taskSpec: - inputs: - resources: - - name: source - type: storage - steps: - - image: alpine - workingDir: /workspace - script: unzip source/archive.zip && cat file.txt - inputs: - resources: - - name: source - resourceSpec: - type: storage - params: - - name: location - value: gs://build-crd-tests/archive.zip - - name: type - value: gcs diff --git a/examples/v1alpha1/taskruns/git-resource.yaml b/examples/v1alpha1/taskruns/git-resource.yaml deleted file mode 100644 index 4d1c402ddd5..00000000000 --- a/examples/v1alpha1/taskruns/git-resource.yaml +++ /dev/null @@ -1,131 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: git-resource-tag- -spec: - taskSpec: - inputs: - resources: - - name: skaffold - type: git - steps: - - image: ubuntu - workingDir: /workspace - script: cat skaffold/README.md - inputs: - resources: - - name: skaffold - resourceSpec: - type: git - params: - - name: revision - value: v0.32.0 - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: git-resource-branch- -spec: - taskSpec: - inputs: - resources: - - name: skaffold - type: git - steps: - - image: ubuntu - workingDir: /workspace - script: cat skaffold/README.md - inputs: - resources: - - name: skaffold - resourceSpec: - type: git - params: - - name: revision - value: master - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: git-resource-ref- -spec: - taskSpec: - inputs: - resources: - - name: skaffold - type: git - steps: - - image: ubuntu - workingDir: /workspace - script: cat skaffold/README.md - inputs: - resources: - - name: skaffold - resourceSpec: - type: git - params: - - name: revision - value: pull/2932/head - - name: url - value: https://github.com/GoogleContainerTools/skaffold - ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: git-resource-sslverify- -spec: - taskSpec: - inputs: - resources: - - name: skaffold - type: git - steps: - - image: ubuntu - workingDir: /workspace - script: cat skaffold/README.md - inputs: - resources: - - name: skaffold - resourceSpec: - type: git - params: - - name: revision - value: master - - name: url - value: https://github.com/GoogleContainerTools/skaffold - - name: sslVerify - value: "false" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: git-resource-no-proxy- -spec: - taskSpec: - inputs: - resources: - - name: skaffold - type: git - steps: - - image: ubuntu - workingDir: /workspace - script: cat skaffold/README.md - inputs: - resources: - - name: skaffold - resourceSpec: - type: git - params: - - name: revision - value: master - - name: url - value: https://github.com/GoogleContainerTools/skaffold - - name: noProxy - value: "google.com" ---- diff --git a/examples/v1alpha1/taskruns/git-ssh-creds.yaml b/examples/v1alpha1/taskruns/git-ssh-creds.yaml deleted file mode 100644 index 80f0f478a96..00000000000 --- a/examples/v1alpha1/taskruns/git-ssh-creds.yaml +++ /dev/null @@ -1,50 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: git-ssh - annotations: - tekton.dev/git-0: github.com -type: kubernetes.io/ssh-auth -data: - # Generated by: - # cat id_rsa | base64 -w 0 - # This deploy key has read-only permissions on github.com/knative/build - ssh-privatekey: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlKSndJQkFBS0NBZ0VBc0YrY3ZIdUlKRjBwNWZNVDBUUVZhMWpTZVBNVlhtUWhGa1F0andsamJFSXVKaVh5CmVrU1I0WUtDbFZIZVo0M2VOa2p5SzFwTDVmVnZnY3J2bkVUMXE5dmFmOThtNzdHWjZUdnJGY0RyZjViZDFIZGUKTU1MTFZRRU8vN1lkcEJFeVJ1UjA4RXRzbWp0RUVaNERVZnBUWGQ5RnAyTU5UWTYwVzFpa0p0Mm53dGhWVlF0OApubFcxTTRvc1d0SHE1OVFDbnhqUkVmNzNhdHdtUTZ6enlXcCtJM3ZBRFRJUmZpTWcvSjc0UDJHOWlwL0U1U0YrCnNuRmRnU2x0cjhyd0tmTE5jTDVYandOSE53aHErQ2NJRHBUZGhuVTBUaEFZNlRsa25KWFJudXRicGNRajA4MjAKMyt1aXRxaXhJcnIwQmkrU2NDQ21GNERxZGdRUXIwRzdieXRKemJkdjJOL3dGbGFpWmVOTWtXSVd5TzRpdnU4TQoxbGUyajVHeDZFaVQ0TG5sNitoRHd3aXozUGR4Y1I0S0VxZzVqRmQ3QjNDcHQ0cUswRDFHVVhnMmx1ZHRsMU40CjVoNUJaNEZZcWF0VU1LQkVjeHd4ekZVVE1iNFZmdFhuMEJOSHkyVXlxUkx6VnBMZWgyRHRYcmtaZnRnTlFCeFAKNkNKc2FnYkpuRmZ1Mk1IaTh5VkE3UFZnUXExS3hPWnF0c0JKb3RvSzJXb0lONldpbnl0d0lwUFhsblJrZ3duYgo4dVBZdmhoZDB0ZVllZ2pYNW85azcwaDhFOEFpZGtqaFpKRkwzakRjc0NFdGJQSWtBMHp3bCs0UFN5aWV2UXpVCldFTkFTSzhXc1NxSk40bUtNSEJMbDU2WWZpTnBJNXVEUGx6eC9hS3hnQis2RExYL25GRzB0Y2ZTYlJFQ0F3RUEKQVFLQ0FnQnRjQlpZR2FxakxhK213RXFHbi9PK2RSRzcvTkZBalk2K096V3RzRnlodXZyWnJ1Z2pGOU1SQTZNMQpOZVJ6aXVMYitpMVIyeWlIR3VEQ3Y0SW9DOTRJY2xYRXpGbGpsMmJ5QXJ6ZTlhTHF1MWtQMGJWL09nOWl3bEpsCk5zSnpvRHY3SXh5d1VZeWtzcXVNNXVnV2dPWWp0RHVMSG5vTnFzT2Nmb2IwbXNyU3F0dGY5czJ2ald6dSt3aUUKbmdaTkxROG5Xd1czVGVhRnh1NXpSYWpMVEtuU0tLSkZUZER1M0t0R05QbkNra3BDN3RvRWR1RWZwaG9uMytYdwprMUtzSkwxMi9KUmw1OW5UZXdTc3o4TS9FUDNYeFhmY0RENzQwQ1R1eUVPV2dXR1BuUUhDRmJ6cXlGSmhWcEQ3CkJOZ1Awb3JoeWxCayt4Z0FmSXRCdzk2aW4xQ2VMZHZKek9TdDNXSUVrY0w3ZVB0bkpzWVpBa1J4eFU1NWF6ajEKbFJHNWRWN010ZzgwWXJTcDdoYXIxamhTQ0JjVzZMUHdueTdXK1psWEd6VG9Gb1o2clIwdytJdGRjNGpPSEhtTgpRVk9tWFd3SFJuZm5rQWZlNXdDQkZQbXpMT2tYbnloWjdaNWxmVlJQaE9lT0hlV09NeHJvWFZoRmJPcTFxemo1Cm85a1dMVGxwTk42YXhrOW41R1N6NlZDVDRHSW1iOUsyWmpQUklOMktQZ3Vxd0RRSFVmd0ViZ0NnTkVUOG5wc2UKelYxRnRpRUJaeVJPa2RwdDhDd2NrbGxHc0Nab0dIa3Z1OXlRSytMUldvV2xJS041WGJXYVljaW01VVhIZlIzUgp4ZGx2QmgxNDl2MW02Y3haMWpzNUFJM09Xb0lpaXlaWjdKUGUxbUIycDE2dUlsUGhsUUtDQVFFQTRNZmNPRVluCkdrQVEzaEdKMm5ia0ZzZ1hJemJrQkQvanIrY1JHd1pjeitBZ2x0cXFZRnQ2Rzh3eElBMGd2V1BLNDFhR1UzU1AKdHVjUEF6VjVEYlR3WklFdjVpY3kycHJlbHJ1ZTB4RkV4WWRZNFFCVGRiVFM4TE9ZWncxTEZpTGRXb1VKVlhiWApTaE4rSktpSDVpM3J1K2dwTHArT0ZHUSthWFdQSFp0TjdjTUZidEpUUkNQUlZqUkVHb25qejY3c2NNcWxZNjAyCkYxaFlURGRkTGNnNnhiN0M3ZmdXc25pdEh4ZWY5UHZFUlZSUWdyRW9RT3lOcFczL0VOU1RQN1IzTzhnNnNHTXYKUXI4SDd1a3RGUlAxUVRqSGNvdmtrdm9aaERHOHRGREd4T0FhbFMxK2phQVpBMmNVdEI4VU5ueHpqMFJFNE43VAp3OHZST3NHbjJ2aG9vd0tDQVFFQXlONmV1d0FFdllpanVlV21pYWNJTUQ0bExaL3JjLzF6T0RUQ3grWm05SHBCCjZyUGMvMG8yR3lGV2Y2aVN3UjhOWlVyM2dvREh6ck8vTHdZUTNyUEhhZFpkRGRFVWh5UXBHeDFuOG9ONXhSU0sKVkVkdnVESkF4SnhHdXRWYk9sNzlDUitadjBqa3hGY2xaOTBaSGdhVEl5TnBlK1dIcTI3Mm1oaENaOXNmK0RTMgppM2V2MEkrQ0t6eXppV2NUdzJKL0ROSlpIN0ZnUlc0U1M3OXBLcDFPOXk0a2hQMk0xQU9nVUp4eFBta0xMc05oCk45dlB0QmpXMENZZmxiei9zWjBYZEVtL1hEUE9xNWVXc0tsZm5XcnpzR3ZZVHRvZkxpN1pVekJhMjRyc1AzT3UKT0JqeFVQWDBhTnQ2bVlOSWVSQkNkVk9BZlFsbGFqSW1hVENNNXZQcXV3S0NBUUF1RXFrZjI3aytGeTJkNXVoagpvQVRtYW9MYmsrK3VzMDIvQzFTbFBtdWRyQ25oNGRZVVJBdkdVTmNzNDZQM1RkSVRRUFB0ZlRITDRwWmdLUUN6Ci80ZGFnbVJILzNiYitleHY1dXNLQmpzYlpiK2c5c2tra2ppK1g0RjRkZkFUREhoa2ltbzhXMHlMZ1cxVXBEcWUKd29EVUZpVUN5bTk3M0lReVo0YzdJVThhMGVOMk1LUWlqbGpsRzNkdUhSOVZ2VnYzVG9JUjZUbnlGUWljTHFqcApybVhsakZFMko2aTNVaWJoL1p5cXdVUWNsY2llMFNNWUU2U0E2UWZqOGo1d1MxUTVLN1JqM1NDZHhMd2lpeWJUCmNERFArb3hlL1MrUHRMV3dNK1dpNi8raDhQRmg3RjVKTnl5SlZ3S1dYTnh1d3BtSkh3d2pMMmttYzh0aUNMbVkKRjF5VEFvSUJBRWpJdWRWaW5WVWNKTTlnVW1jQWVpd1k2Sm5PbjU5bzBBNG11QWw5Q0FOQUpaQm8yZ1E3SEwzWgo1NkRjTVVqKytuaWdvR3pPUXhnMzgyZVRtQnRLSTFETFZ1NkJ1eUY0emRoQVlJRDBlUFFiakVBYm5uU3M2T0VWCkMxLzVuVlBhUlcrLzNwTDhVOEI5SDFXeVBMNnZmVE0zU3FxVk1nTEJjMlBFdEpNelNETkV6bnhjd3YwY2N2czkKeElSZU1FQVUrWnBvd2RpRkNqQStRU3puVDdFY1RSZXR4WmZXMCtlaTVMMHc0cXZObmpxMG13NkZmSTV5amF2ZwpsSU5LZDVBaEx2VjVIM2pHWVBXMk9Pa01obFBoQkNvQitlQWdrem5GeWdPbHV0WmdVVmh3ajBsT2FHcUFwSzQyCkVRZDlGWTZnZ0tSSXZIOFNINGhLWWJhdDIvQjNvNjhDZ2dFQVNnUGZubVdZcXpQTlpwYXh4VFZ3NXl0cXovMGcKUHlhcW41elhDSHFsdDluNkZFYWdRVjE4bjl0bUZzTWtnOFd4MHp1TjY5ajNvcXVDaWVDSkVRTTFDR05GUWg2MQpEV0xrd210R1FPNXZxc0VhcXpLZk9yWktnYTJ5L3BuejY2SkNlUW83UlJEdVVZVHpPY3NpQmtxNmNUNHFLQjY0ClBCVlVhQTROQkVCZlRoc1o5dDhpWHFDQWhUQnVlTDdhQ3pHV0ZjR1k5dndrZkJHNjNacURXbVlqZkZwRGlqSWIKL21ySnJVTTB0a09HcUhESk5aUWhpZXc1VHF6NWp3VElyTDY3YUdZNFpuNEVyODFlb3JOZnpEeDVnak1NYnoweQoyTGZoN1c0MFlWMDA4ZmZJTk5BbXA4VjNqay9qcWFUSFlWYlFQNGxhdTRIWkc5Q2g1Q1VpSmFvN2xBPT0KLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0K - # Generated by: - # ssh-keyscan github.com | base64 -w 0 - known_hosts: Z2l0aHViLmNvbSBzc2gtcnNhIEFBQUFCM056YUMxeWMyRUFBQUFCSXdBQUFRRUFxMkE3aFJHbWRubTl0VURiTzlJRFN3Qks2VGJRYStQWFlQQ1B5NnJiVHJUdHc3UEhrY2NLcnBwMHlWaHA1SGRFSWNLcjZwTGxWREJmT0xYOVFVc3lDT1Ywd3pmaklKTmxHRVlzZGxMSml6SGhibjJtVWp2U0FIUXFaRVRZUDgxZUZ6TFFOblBIdDRFVlZVaDdWZkRFU1U4NEtlem1ENVFsV3BYTG12VTMxL3lNZitTZTh4aEhUdktTQ1pJRkltV3dvRzZtYlVvV2Y5bnpwSW9hU2pCK3dlcXFVVW1wYWFhc1hWYWw3MkorVVgyQisyUlBXM1JjVDBlT3pRZ3FsSkwzUktyVEp2ZHNqRTNKRUF2R3EzbEdIU1pYeTI4RzNza3VhMlNtVmkvdzR5Q0U2Z2JPRHFuVFdsZzcrd0M2MDR5ZEdYQThWSmlTNWFwNDNKWGlVRkZBYVE9PQo= ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: robot-git-ssh -secrets: -- name: git-ssh ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: git-ssh-creds -spec: - serviceAccountName: robot-git-ssh - inputs: - resources: - - name: gitssh - resourceSpec: - type: git - params: - - name: revision - value: main - - name: url - value: git@github.com:tektoncd/pipeline.git - taskSpec: - inputs: - resources: - - name: gitssh - type: git - steps: - - name: config - image: ubuntu - script: | - #!/usr/bin/env bash - cat /workspace/gitssh/README.md diff --git a/examples/v1alpha1/taskruns/git-volume.yaml b/examples/v1alpha1/taskruns/git-volume.yaml deleted file mode 100644 index 3a6001c7a24..00000000000 --- a/examples/v1alpha1/taskruns/git-volume.yaml +++ /dev/null @@ -1,21 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: git-volume- -spec: - taskSpec: - steps: - - name: git - image: gcr.io/cloud-builders/git - workingDir: /path/to/git/rules_docker - args: ["status"] - volumeMounts: - - name: source - mountPath: /path/to/git - - volumes: - - name: source - gitRepo: # https://kubernetes.io/docs/concepts/storage/volumes/#gitrepo - # gitRepo is deprecated. - repository: "https://github.com/bazelbuild/rules_docker.git" - revision: "3caddbe7f75fde6afb2e2c63654b5bbeeeedf2ac" diff --git a/examples/v1alpha1/taskruns/home-is-set.yaml b/examples/v1alpha1/taskruns/home-is-set.yaml deleted file mode 100644 index 0cf478eaf77..00000000000 --- a/examples/v1alpha1/taskruns/home-is-set.yaml +++ /dev/null @@ -1,14 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: home-is-set- -spec: - taskSpec: - steps: - - image: ubuntu - env: - - name: HOME - value: /tekton/home - script: | - #!/usr/bin/env bash - [[ $HOME == /tekton/home ]] diff --git a/examples/v1alpha1/taskruns/home-volume.yaml b/examples/v1alpha1/taskruns/home-volume.yaml deleted file mode 100644 index 2a992e66f5c..00000000000 --- a/examples/v1alpha1/taskruns/home-volume.yaml +++ /dev/null @@ -1,26 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: home-volume- -spec: - taskSpec: - steps: - - name: write - image: ubuntu - script: echo some stuff > /tekton/home/stuff - - name: read - image: ubuntu - script: cat /tekton/home/stuff - - name: override-homevol - image: ubuntu - # /tekton/home/stuff *doesn't* exist, because the specified volumeMount - # conflicts with it, and the user's explicit declaration wins the tie. - script: | - #!/usr/bin/env bash - [[ ! -f /tekton/home/stuff ]] - volumeMounts: - - name: empty - mountPath: /tekton/home - volumes: - - name: empty - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/no-ci/.keep b/examples/v1alpha1/taskruns/no-ci/.keep deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/examples/v1alpha1/taskruns/no-ci/docker-creds.yaml b/examples/v1alpha1/taskruns/no-ci/docker-creds.yaml deleted file mode 100644 index 3061cd53ec0..00000000000 --- a/examples/v1alpha1/taskruns/no-ci/docker-creds.yaml +++ /dev/null @@ -1,42 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: docker-basic - annotations: - tekton.dev/docker-0: https://us.gcr.io - tekton.dev/docker-1: https://eu.gcr.io - tekton.dev/docker-2: https://asia.gcr.io - tekton.dev/docker-3: https://gcr.io - tekton.dev/docker-4: https://reduce-chance-of-selecting-gcr.io -type: kubernetes.io/basic-auth -data: - # Generated by: - # echo -n _json_key | base64 - username: X2pzb25fa2V5 - # Generated by: - # cat /tmp/key.json | base64 -w 0 - # This service account is JUST a storage reader on gcr.io/build-crd-testing - # (it is the same as test/serviceaccount/secret.yaml) - password: ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAiYnVpbGQtY3JkLXRlc3RpbmciLAogICJwcml2YXRlX2tleV9pZCI6ICIwNTAyYTQxYTgxMmZiNjRjZTU2YTY4ZWM1ODMyYWIwYmExMWMxMWU2IiwKICAicHJpdmF0ZV9rZXkiOiAiLS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tXG5NSUlFdlFJQkFEQU5CZ2txaGtpRzl3MEJBUUVGQUFTQ0JLY3dnZ1NqQWdFQUFvSUJBUUM5WDRFWU9BUmJ4UU04XG5EMnhYY2FaVGsrZ1k4ZWp1OTh0THFDUXFUckdNVzlSZVQyeE9ZNUF5Z2FsUFArcDd5WEVja3dCRC9IaE0wZ2xJXG43TVRMZGVlS1dyK3JBMUx3SFp5V0ZXN0gwT25mN3duWUhFSExXVW1jM0JDT1JFRHRIUlo3WnJQQmYxSFRBQS8zXG5Nblc1bFpIU045b2p6U1NGdzZBVnU2ajZheGJCSUlKNzU0THJnS2VBWXVyd2ZJUTJSTFR1MjAxazJJcUxZYmhiXG4zbVNWRzVSK3RiS3oxQ3ZNNTNuSENiN0NmdVZlV3NyQThrazd4SHJyTFFLTW1JOXYyc2dSdWd5TUF6d3ovNnpOXG5oNS9pTXh4Z2VxNVc4eGtWeDNKMm5ZOEpKZEhhZi9UNkFHc09ORW80M3B4ZWlRVmpuUmYvS24xMFRDYzJFc0lZXG5TNDlVc1o3QkFnTUJBQUVDZ2dFQUF1cGxkdWtDUVF1RDVVL2dhbUh0N0dnVzNBTVYxOGVxbkhuQ2EyamxhaCtTXG5BZVVHbmhnSmpOdkUrcE1GbFN2NXVmMnAySzRlZC9veEQ2K0NwOVpYRFJqZ3ZmdEl5cWpsemJ3dkZjZ3p3TnVEXG55Z1VrdXA3SGVjRHNEOFR0ZUFvYlQvVnB3cTZ6S01yQndDdk5rdnk2YlZsb0VqNXgzYlhzYXhlOTVETy95cHU2XG53MFc5N3p4d3dESlk2S1FjSVdNamhyR3h2d1g3bmlVQ2VNNGxlV0JEeUd0dzF6ZUpuNGhFYzZOM2FqUWFjWEtjXG4rNFFseGNpYW1ZcVFXYlBudHhXUWhoUXpjSFdMaTJsOWNGYlpENyt1SkxGNGlONnk4bVZOVTNLM0sxYlJZclNEXG5SVXAzYVVWQlhtRmcrWi8ycHVWTCttVTNqM0xMV1l5Qk9rZXZ1T21kZ1FLQmdRRGUzR0lRa3lXSVMxNFRkTU9TXG5CaUtCQ0R5OGg5NmVoTDBIa0RieU9rU3RQS2RGOXB1RXhaeGh5N29qSENJTTVGVnJwUk4yNXA0c0V6d0ZhYyt2XG5KSUZnRXZxN21YZm1YaVhJTmllUG9FUWFDbm54RHhXZ21yMEhVS0VtUzlvTWRnTGNHVStrQ1ZHTnN6N0FPdW0wXG5LcVkzczIyUTlsUTY3Rk95cWl1OFdGUTdRUUtCZ1FEWmlGaFRFWmtQRWNxWmpud0pwVEI1NlpXUDlLVHNsWlA3XG53VTRiemk2eSttZXlmM01KKzRMMlN5SGMzY3BTTWJqdE5PWkN0NDdiOTA4RlVtTFhVR05oY3d1WmpFUXhGZXkwXG5tNDFjUzVlNFA0OWI5bjZ5TEJqQnJCb3FzMldCYWwyZWdkaE5KU3NDV29pWlA4L1pUOGVnWHZoN2I5MWp6b0syXG5xMlBVbUE0RGdRS0JnQVdMMklqdkVJME95eDJTMTFjbi9lM1dKYVRQZ05QVEc5MDNVcGErcW56aE9JeCtNYXFoXG5QRjRXc3VBeTBBb2dHSndnTkpiTjhIdktVc0VUdkE1d3l5TjM5WE43dzBjaGFyRkwzN29zVStXT0F6RGpuamNzXG5BcTVPN0dQR21YdWI2RUJRQlBKaEpQMXd5NHYvSzFmSGcvRjQ3cTRmNDBMQUpPa2FZUkpENUh6QkFvR0JBTlVoXG5uSUJQSnFxNElNdlE2Y0M5ZzhCKzF4WURlYTkvWWsxdytTbVBHdndyRVh5M0dLeDRLN2xLcGJQejdtNFgzM3N4XG5zRVUvK1kyVlFtd1JhMXhRbS81M3JLN1YybDVKZi9ENDAwalJtNlpmU0FPdmdEVHJ0Wm5VR0pNcno5RTd1Tnc3XG5sZ1VIM0pyaXZ5Ri9meE1JOHFzelFid1hQMCt4bnlxQXhFQWdkdUtCQW9HQUlNK1BTTllXQ1pYeERwU0hJMThkXG5qS2tvQWJ3Mk1veXdRSWxrZXVBbjFkWEZhZDF6c1hRR2RUcm1YeXY3TlBQKzhHWEJrbkJMaTNjdnhUaWxKSVN5XG51Y05yQ01pcU5BU24vZHE3Y1dERlVBQmdqWDE2SkgyRE5GWi9sL1VWRjNOREFKalhDczFYN3lJSnlYQjZveC96XG5hU2xxbElNVjM1REJEN3F4Unl1S3Nnaz1cbi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS1cbiIsCiAgImNsaWVudF9lbWFpbCI6ICJwdWxsLXNlY3JldC10ZXN0aW5nQGJ1aWxkLWNyZC10ZXN0aW5nLmlhbS5nc2VydmljZWFjY291bnQuY29tIiwKICAiY2xpZW50X2lkIjogIjEwNzkzNTg2MjAzMzAyNTI1MTM1MiIsCiAgImF1dGhfdXJpIjogImh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi9hdXRoIiwKICAidG9rZW5fdXJpIjogImh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsCiAgImF1dGhfcHJvdmlkZXJfeDUwOV9jZXJ0X3VybCI6ICJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9vYXV0aDIvdjEvY2VydHMiLAogICJjbGllbnRfeDUwOV9jZXJ0X3VybCI6ICJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9yb2JvdC92MS9tZXRhZGF0YS94NTA5L3B1bGwtc2VjcmV0LXRlc3RpbmclNDBidWlsZC1jcmQtdGVzdGluZy5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIKfQo= ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: robot-docker-basic -secrets: -- name: docker-basic -imagePullSecrets: -- name: docker-basic ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: docker-creds -spec: - serviceAccountName: robot-docker-basic - taskSpec: - steps: - - name: test - image: gcr.io/tekton-releases/dogfooding/skopeo:latest - # Test pulling a private builder container. - script: skopeo copy docker://gcr.io/build-crd-testing/secret-sauce dir:///tmp/ diff --git a/examples/v1alpha1/taskruns/no-ci/limitrange.yaml b/examples/v1alpha1/taskruns/no-ci/limitrange.yaml deleted file mode 100644 index a35e7c23bb7..00000000000 --- a/examples/v1alpha1/taskruns/no-ci/limitrange.yaml +++ /dev/null @@ -1,46 +0,0 @@ -apiVersion: v1 -kind: LimitRange -metadata: - name: limit-mem-cpu-per-container -spec: - limits: - - max: - cpu: "800m" - memory: "1Gi" - min: - cpu: "100m" - memory: "99Mi" - default: - cpu: "700m" - memory: "900Mi" - defaultRequest: - cpu: "110m" - memory: "111Mi" - type: Container ---- -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: echo-hello-world -spec: - steps: - - name: echo - image: ubuntu - command: - - echo - args: - - "hello world" ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: echo-hello-world-run- -spec: - inputs: {} - outputs: {} - serviceAccountName: "" - taskRef: - name: echo-hello-world - timeout: 1h0m0s -status: - podName: "" \ No newline at end of file diff --git a/examples/v1alpha1/taskruns/no-ci/pull-private-image.yaml b/examples/v1alpha1/taskruns/no-ci/pull-private-image.yaml deleted file mode 100644 index 027119e88c7..00000000000 --- a/examples/v1alpha1/taskruns/no-ci/pull-private-image.yaml +++ /dev/null @@ -1,50 +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. - -apiVersion: v1 -kind: Secret -metadata: - name: test-readonly-credentials -type: kubernetes.io/dockercfg -data: - # Generated by: - # kubectl create secret docker-registry regsecret --docker-server=https://gcr.io \ - # --docker-username=_json_key --docker-password="$(cat /tmp/key.json)" \ - # --docker-email=noreply@google.com --dry-run -o yaml - # This service account is JUST a storage reader on gcr.io/build-crd-testing - .dockercfg: eyJodHRwczovL2djci5pbyI6eyJ1c2VybmFtZSI6Il9qc29uX2tleSIsInBhc3N3b3JkIjoie1xuICBcInR5cGVcIjogXCJzZXJ2aWNlX2FjY291bnRcIixcbiAgXCJwcm9qZWN0X2lkXCI6IFwiYnVpbGQtY3JkLXRlc3RpbmdcIixcbiAgXCJwcml2YXRlX2tleV9pZFwiOiBcIjA1MDJhNDFhODEyZmI2NGNlNTZhNjhlYzU4MzJhYjBiYTExYzExZTZcIixcbiAgXCJwcml2YXRlX2tleVwiOiBcIi0tLS0tQkVHSU4gUFJJVkFURSBLRVktLS0tLVxcbk1JSUV2UUlCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQktjd2dnU2pBZ0VBQW9JQkFRQzlYNEVZT0FSYnhRTThcXG5EMnhYY2FaVGsrZ1k4ZWp1OTh0THFDUXFUckdNVzlSZVQyeE9ZNUF5Z2FsUFArcDd5WEVja3dCRC9IaE0wZ2xJXFxuN01UTGRlZUtXcityQTFMd0haeVdGVzdIME9uZjd3bllIRUhMV1VtYzNCQ09SRUR0SFJaN1pyUEJmMUhUQUEvM1xcbk1uVzVsWkhTTjlvanpTU0Z3NkFWdTZqNmF4YkJJSUo3NTRMcmdLZUFZdXJ3ZklRMlJMVHUyMDFrMklxTFliaGJcXG4zbVNWRzVSK3RiS3oxQ3ZNNTNuSENiN0NmdVZlV3NyQThrazd4SHJyTFFLTW1JOXYyc2dSdWd5TUF6d3ovNnpOXFxuaDUvaU14eGdlcTVXOHhrVngzSjJuWThKSmRIYWYvVDZBR3NPTkVvNDNweGVpUVZqblJmL0tuMTBUQ2MyRXNJWVxcblM0OVVzWjdCQWdNQkFBRUNnZ0VBQXVwbGR1a0NRUXVENVUvZ2FtSHQ3R2dXM0FNVjE4ZXFuSG5DYTJqbGFoK1NcXG5BZVVHbmhnSmpOdkUrcE1GbFN2NXVmMnAySzRlZC9veEQ2K0NwOVpYRFJqZ3ZmdEl5cWpsemJ3dkZjZ3p3TnVEXFxueWdVa3VwN0hlY0RzRDhUdGVBb2JUL1Zwd3E2ektNckJ3Q3ZOa3Z5NmJWbG9FajV4M2JYc2F4ZTk1RE8veXB1NlxcbncwVzk3enh3d0RKWTZLUWNJV01qaHJHeHZ3WDduaVVDZU00bGVXQkR5R3R3MXplSm40aEVjNk4zYWpRYWNYS2NcXG4rNFFseGNpYW1ZcVFXYlBudHhXUWhoUXpjSFdMaTJsOWNGYlpENyt1SkxGNGlONnk4bVZOVTNLM0sxYlJZclNEXFxuUlVwM2FVVkJYbUZnK1ovMnB1VkwrbVUzajNMTFdZeUJPa2V2dU9tZGdRS0JnUURlM0dJUWt5V0lTMTRUZE1PU1xcbkJpS0JDRHk4aDk2ZWhMMEhrRGJ5T2tTdFBLZEY5cHVFeFp4aHk3b2pIQ0lNNUZWcnBSTjI1cDRzRXp3RmFjK3ZcXG5KSUZnRXZxN21YZm1YaVhJTmllUG9FUWFDbm54RHhXZ21yMEhVS0VtUzlvTWRnTGNHVStrQ1ZHTnN6N0FPdW0wXFxuS3FZM3MyMlE5bFE2N0ZPeXFpdThXRlE3UVFLQmdRRFppRmhURVprUEVjcVpqbndKcFRCNTZaV1A5S1RzbFpQN1xcbndVNGJ6aTZ5K21leWYzTUorNEwyU3lIYzNjcFNNYmp0Tk9aQ3Q0N2I5MDhGVW1MWFVHTmhjd3VaakVReEZleTBcXG5tNDFjUzVlNFA0OWI5bjZ5TEJqQnJCb3FzMldCYWwyZWdkaE5KU3NDV29pWlA4L1pUOGVnWHZoN2I5MWp6b0syXFxucTJQVW1BNERnUUtCZ0FXTDJJanZFSTBPeXgyUzExY24vZTNXSmFUUGdOUFRHOTAzVXBhK3FuemhPSXgrTWFxaFxcblBGNFdzdUF5MEFvZ0dKd2dOSmJOOEh2S1VzRVR2QTV3eXlOMzlYTjd3MGNoYXJGTDM3b3NVK1dPQXpEam5qY3NcXG5BcTVPN0dQR21YdWI2RUJRQlBKaEpQMXd5NHYvSzFmSGcvRjQ3cTRmNDBMQUpPa2FZUkpENUh6QkFvR0JBTlVoXFxubklCUEpxcTRJTXZRNmNDOWc4QisxeFlEZWE5L1lrMXcrU21QR3Z3ckVYeTNHS3g0SzdsS3BiUHo3bTRYMzNzeFxcbnNFVS8rWTJWUW13UmExeFFtLzUzcks3VjJsNUpmL0Q0MDBqUm02WmZTQU92Z0RUcnRablVHSk1yejlFN3VOdzdcXG5sZ1VIM0pyaXZ5Ri9meE1JOHFzelFid1hQMCt4bnlxQXhFQWdkdUtCQW9HQUlNK1BTTllXQ1pYeERwU0hJMThkXFxuaktrb0FidzJNb3l3UUlsa2V1QW4xZFhGYWQxenNYUUdkVHJtWHl2N05QUCs4R1hCa25CTGkzY3Z4VGlsSklTeVxcbnVjTnJDTWlxTkFTbi9kcTdjV0RGVUFCZ2pYMTZKSDJETkZaL2wvVVZGM05EQUpqWENzMVg3eUlKeVhCNm94L3pcXG5hU2xxbElNVjM1REJEN3F4Unl1S3Nnaz1cXG4tLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tXFxuXCIsXG4gIFwiY2xpZW50X2VtYWlsXCI6IFwicHVsbC1zZWNyZXQtdGVzdGluZ0BidWlsZC1jcmQtdGVzdGluZy5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbVwiLFxuICBcImNsaWVudF9pZFwiOiBcIjEwNzkzNTg2MjAzMzAyNTI1MTM1MlwiLFxuICBcImF1dGhfdXJpXCI6IFwiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tL28vb2F1dGgyL2F1dGhcIixcbiAgXCJ0b2tlbl91cmlcIjogXCJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20vby9vYXV0aDIvdG9rZW5cIixcbiAgXCJhdXRoX3Byb3ZpZGVyX3g1MDlfY2VydF91cmxcIjogXCJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9vYXV0aDIvdjEvY2VydHNcIixcbiAgXCJjbGllbnRfeDUwOV9jZXJ0X3VybFwiOiBcImh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL3JvYm90L3YxL21ldGFkYXRhL3g1MDkvcHVsbC1zZWNyZXQtdGVzdGluZyU0MGJ1aWxkLWNyZC10ZXN0aW5nLmlhbS5nc2VydmljZWFjY291bnQuY29tXCJcbn0iLCJlbWFpbCI6Im5vcmVwbHlAZ29vZ2xlLmNvbSIsImF1dGgiOiJYMnB6YjI1ZmEyVjVPbnNLSUNBaWRIbHdaU0k2SUNKelpYSjJhV05sWDJGalkyOTFiblFpTEFvZ0lDSndjbTlxWldOMFgybGtJam9nSW1KMWFXeGtMV055WkMxMFpYTjBhVzVuSWl3S0lDQWljSEpwZG1GMFpWOXJaWGxmYVdRaU9pQWlNRFV3TW1FME1XRTRNVEptWWpZMFkyVTFObUUyT0dWak5UZ3pNbUZpTUdKaE1URmpNVEZsTmlJc0NpQWdJbkJ5YVhaaGRHVmZhMlY1SWpvZ0lpMHRMUzB0UWtWSFNVNGdVRkpKVmtGVVJTQkxSVmt0TFMwdExWeHVUVWxKUlhaUlNVSkJSRUZPUW1kcmNXaHJhVWM1ZHpCQ1FWRkZSa0ZCVTBOQ1MyTjNaMmRUYWtGblJVRkJiMGxDUVZGRE9WZzBSVmxQUVZKaWVGRk5PRnh1UkRKNFdHTmhXbFJySzJkWk9HVnFkVGs0ZEV4eFExRnhWSEpIVFZjNVVtVlVNbmhQV1RWQmVXZGhiRkJRSzNBM2VWaEZZMnQzUWtRdlNHaE5NR2RzU1Z4dU4wMVVUR1JsWlV0WGNpdHlRVEZNZDBoYWVWZEdWemRJTUU5dVpqZDNibGxJUlVoTVYxVnRZek5DUTA5U1JVUjBTRkphTjFweVVFSm1NVWhVUVVFdk0xeHVUVzVYTld4YVNGTk9PVzlxZWxOVFJuYzJRVloxTm1vMllYaGlRa2xKU2pjMU5FeHlaMHRsUVZsMWNuZG1TVkV5VWt4VWRUSXdNV3N5U1hGTVdXSm9ZbHh1TTIxVFZrYzFVaXQwWWt0Nk1VTjJUVFV6YmtoRFlqZERablZXWlZkemNrRTRhMnMzZUVoeWNreFJTMDF0U1RsMk1uTm5VblZuZVUxQmVuZDZMelo2VGx4dWFEVXZhVTE0ZUdkbGNUVlhPSGhyVm5nelNqSnVXVGhLU21SSVlXWXZWRFpCUjNOUFRrVnZORE53ZUdWcFVWWnFibEptTDB0dU1UQlVRMk15UlhOSldWeHVVelE1VlhOYU4wSkJaMDFDUVVGRlEyZG5SVUZCZFhCc1pIVnJRMUZSZFVRMVZTOW5ZVzFJZERkSFoxY3pRVTFXTVRobGNXNUlia05oTW1wc1lXZ3JVMXh1UVdWVlIyNW9aMHBxVG5aRkszQk5SbXhUZGpWMVpqSndNa3MwWldRdmIzaEVOaXREY0RsYVdFUlNhbWQyWm5SSmVYRnFiSHBpZDNaR1kyZDZkMDUxUkZ4dWVXZFZhM1Z3TjBobFkwUnpSRGhVZEdWQmIySlVMMVp3ZDNFMmVrdE5ja0ozUTNaT2EzWjVObUpXYkc5RmFqVjRNMkpZYzJGNFpUazFSRTh2ZVhCMU5seHVkekJYT1RkNmVIZDNSRXBaTmt0UlkwbFhUV3BvY2tkNGRuZFlOMjVwVlVObFRUUnNaVmRDUkhsSGRIY3hlbVZLYmpSb1JXTTJUak5oYWxGaFkxaExZMXh1S3pSUmJIaGphV0Z0V1hGUlYySlFiblI0VjFGb2FGRjZZMGhYVEdreWJEbGpSbUphUkRjcmRVcE1SalJwVGpaNU9HMVdUbFV6U3pOTE1XSlNXWEpUUkZ4dVVsVndNMkZWVmtKWWJVWm5LMW92TW5CMVZrd3JiVlV6YWpOTVRGZFplVUpQYTJWMmRVOXRaR2RSUzBKblVVUmxNMGRKVVd0NVYwbFRNVFJVWkUxUFUxeHVRbWxMUWtORWVUaG9PVFpsYUV3d1NHdEVZbmxQYTFOMFVFdGtSamx3ZFVWNFduaG9lVGR2YWtoRFNVMDFSbFp5Y0ZKT01qVndOSE5GZW5kR1lXTXJkbHh1U2tsR1owVjJjVGR0V0dadFdHbFlTVTVwWlZCdlJWRmhRMjV1ZUVSNFYyZHRjakJJVlV0RmJWTTViMDFrWjB4alIxVXJhME5XUjA1emVqZEJUM1Z0TUZ4dVMzRlpNM015TWxFNWJGRTJOMFpQZVhGcGRUaFhSbEUzVVZGTFFtZFJSRnBwUm1oVVJWcHJVRVZqY1ZwcWJuZEtjRlJDTlRaYVYxQTVTMVJ6YkZwUU4xeHVkMVUwWW5wcE5ua3JiV1Y1WmpOTlNpczBUREpUZVVoak0yTndVMDFpYW5ST1QxcERkRFEzWWprd09FWlZiVXhZVlVkT2FHTjNkVnBxUlZGNFJtVjVNRnh1YlRReFkxTTFaVFJRTkRsaU9XNDJlVXhDYWtKeVFtOXhjekpYUW1Gc01tVm5aR2hPU2xOelExZHZhVnBRT0M5YVZEaGxaMWgyYURkaU9URnFlbTlMTWx4dWNUSlFWVzFCTkVSblVVdENaMEZYVERKSmFuWkZTVEJQZVhneVV6RXhZMjR2WlROWFNtRlVVR2RPVUZSSE9UQXpWWEJoSzNGdWVtaFBTWGdyVFdGeGFGeHVVRVkwVjNOMVFYa3dRVzluUjBwM1owNUtZazQ0U0haTFZYTkZWSFpCTlhkNWVVNHpPVmhPTjNjd1kyaGhja1pNTXpkdmMxVXJWMDlCZWtScWJtcGpjMXh1UVhFMVR6ZEhVRWR0V0hWaU5rVkNVVUpRU21oS1VERjNlVFIyTDBzeFpraG5MMFkwTjNFMFpqUXdURUZLVDJ0aFdWSktSRFZJZWtKQmIwZENRVTVWYUZ4dWJrbENVRXB4Y1RSSlRYWlJObU5ET1djNFFpc3hlRmxFWldFNUwxbHJNWGNyVTIxUVIzWjNja1ZZZVROSFMzZzBTemRzUzNCaVVIbzNiVFJZTXpOemVGeHVjMFZWTHl0Wk1sWlJiWGRTWVRGNFVXMHZOVE55U3pkV01tdzFTbVl2UkRRd01HcFNiVFphWmxOQlQzWm5SRlJ5ZEZwdVZVZEtUWEo2T1VVM2RVNTNOMXh1YkdkVlNETktjbWwyZVVZdlpuaE5TVGh4YzNwUlluZFlVREFyZUc1NWNVRjRSVUZuWkhWTFFrRnZSMEZKVFN0UVUwNVpWME5hV0hoRWNGTklTVEU0WkZ4dWFrdHJiMEZpZHpKTmIzbDNVVWxzYTJWMVFXNHhaRmhHWVdReGVuTllVVWRrVkhKdFdIbDJOMDVRVUNzNFIxaENhMjVDVEdrelkzWjRWR2xzU2tsVGVWeHVkV05PY2tOTmFYRk9RVk51TDJSeE4yTlhSRVpWUVVKbmFsZ3hOa3BJTWtST1Jsb3ZiQzlWVmtZelRrUkJTbXBZUTNNeFdEZDVTVXA1V0VJMmIzZ3ZlbHh1WVZOc2NXeEpUVll6TlVSQ1JEZHhlRko1ZFV0eloyczlYRzR0TFMwdExVVk9SQ0JRVWtsV1FWUkZJRXRGV1MwdExTMHRYRzRpTEFvZ0lDSmpiR2xsYm5SZlpXMWhhV3dpT2lBaWNIVnNiQzF6WldOeVpYUXRkR1Z6ZEdsdVowQmlkV2xzWkMxamNtUXRkR1Z6ZEdsdVp5NXBZVzB1WjNObGNuWnBZMlZoWTJOdmRXNTBMbU52YlNJc0NpQWdJbU5zYVdWdWRGOXBaQ0k2SUNJeE1EYzVNelU0TmpJd016TXdNalV5TlRFek5USWlMQW9nSUNKaGRYUm9YM1Z5YVNJNklDSm9kSFJ3Y3pvdkwyRmpZMjkxYm5SekxtZHZiMmRzWlM1amIyMHZieTl2WVhWMGFESXZZWFYwYUNJc0NpQWdJblJ2YTJWdVgzVnlhU0k2SUNKb2RIUndjem92TDJGalkyOTFiblJ6TG1kdmIyZHNaUzVqYjIwdmJ5OXZZWFYwYURJdmRHOXJaVzRpTEFvZ0lDSmhkWFJvWDNCeWIzWnBaR1Z5WDNnMU1EbGZZMlZ5ZEY5MWNtd2lPaUFpYUhSMGNITTZMeTkzZDNjdVoyOXZaMnhsWVhCcGN5NWpiMjB2YjJGMWRHZ3lMM1l4TDJObGNuUnpJaXdLSUNBaVkyeHBaVzUwWDNnMU1EbGZZMlZ5ZEY5MWNtd2lPaUFpYUhSMGNITTZMeTkzZDNjdVoyOXZaMnhsWVhCcGN5NWpiMjB2Y205aWIzUXZkakV2YldWMFlXUmhkR0V2ZURVd09TOXdkV3hzTFhObFkzSmxkQzEwWlhOMGFXNW5KVFF3WW5WcGJHUXRZM0prTFhSbGMzUnBibWN1YVdGdExtZHpaWEoyYVdObFlXTmpiM1Z1ZEM1amIyMGlDbjA9In19 ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: test-build-robot -secrets: -- name: test-readonly-credentials -imagePullSecrets: -- name: test-readonly-credentials ---- -# This example contains embedded taskSpec. This taskrun requires the secrets and service accounts to be able to pull the -# private image. Required secret and service account for this run is configured in test-build-robot SA and test-readonly-credentials secret. -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: pull-private-image- -spec: - serviceAccountName: test-build-robot - taskSpec: - steps: - - name: pull - # Private image is just Ubuntu - image: gcr.io/tekton-releases/dogfooding/skopeo:latest - script: skopeo copy docker://gcr.io/build-crd-testing/secret-sauce dir:///tmp/ diff --git a/examples/v1alpha1/taskruns/optional-resources-with-clustertask.yaml b/examples/v1alpha1/taskruns/optional-resources-with-clustertask.yaml deleted file mode 100644 index 53ede3d6979..00000000000 --- a/examples/v1alpha1/taskruns/optional-resources-with-clustertask.yaml +++ /dev/null @@ -1,35 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: ClusterTask -metadata: - name: clustertask-with-optional-resources-v1alpha1 -spec: - inputs: - resources: - - name: git-repo - type: git - optional: true - params: - - name: filename - type: string - default: "README.md" - outputs: - resources: - - name: optionalimage - type: image - optional: true - steps: - - name: task-echo-success - image: ubuntu - script: | - #!/usr/bin/env bash - echo "success" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: clustertask-without-resources -spec: - taskRef: - name: clustertask-with-optional-resources-v1alpha1 - kind: ClusterTask diff --git a/examples/v1alpha1/taskruns/optional-resources.yaml b/examples/v1alpha1/taskruns/optional-resources.yaml deleted file mode 100644 index 32b608701b4..00000000000 --- a/examples/v1alpha1/taskruns/optional-resources.yaml +++ /dev/null @@ -1,133 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: task-check-optional-resources -spec: - inputs: - resources: - - name: git-repo - type: git - description: "The input is code from a git repository" - optional: true - params: - - name: filename - type: string - default: "README.md" - outputs: - resources: - - name: optionalimage - type: image - description: "The output is a Docker image" - optional: true - steps: - - name: check-git-repo - image: ubuntu - script: | - #!/usr/bin/env bash - if [ -d $(inputs.resources.git-repo.path) ]; then - echo "Git repo was cloned at $(inputs.resources.git-repo.path)" - if [ -f $(inputs.resources.git-repo.path)/$(inputs.params.filename) ]; then - echo "$(inputs.params.filename) does exist at $(inputs.resources.git-repo.path)" - else - echo "$(inputs.params.filename) does not exist at $(inputs.resources.git-repo.path)" - fi - else - echo "Git repo was not cloned at $(inputs.resources.git-repo.path)" - fi - if [ "$(outputs.resources.optionalimage.url)" == "" ]; then - echo "Image URL: $(outputs.resources.optionalimage.url)" - else - echo "No image URL specified." - fi - echo "Yay, Input and Output Resources can be Optional!" ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: demo-optional-inputs-resources-with-resources -spec: - inputs: - resources: - - name: git-repo - resourceSpec: - type: git - params: - - name: url - value: https://github.com/tektoncd/pipeline.git - params: - - name: filename - value: "README.md" - outputs: - resources: - - name: optionalimage - resourceSpec: - type: image - params: - - name: url - value: gcr.io/foo/bar - taskRef: - name: task-check-optional-resources ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: demo-optional-inputs-resources-invalid-filename -spec: - inputs: - resources: - - name: git-repo - resourceSpec: - type: git - params: - - name: url - value: https://github.com/tektoncd/pipeline.git - params: - - name: filename - value: "invalid.md" - taskRef: - name: task-check-optional-resources ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: demo-optional-inputs-resources-without-resources -spec: - inputs: - params: - - name: filename - value: "README.md" - taskRef: - name: task-check-optional-resources ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: demo-optional-inputs-resources-without-resources-and-params -spec: - taskRef: - name: task-check-optional-resources ---- - -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: demo-optional-outputs-resources-with-input-resources -spec: - inputs: - resources: - - name: git-repo - resourceSpec: - type: git - params: - - name: url - value: https://github.com/tektoncd/pipeline.git - params: - - name: filename - value: "README.md" - taskRef: - name: task-check-optional-resources ---- diff --git a/examples/v1alpha1/taskruns/pullrequest.yaml b/examples/v1alpha1/taskruns/pullrequest.yaml deleted file mode 100644 index 3714a350ac8..00000000000 --- a/examples/v1alpha1/taskruns/pullrequest.yaml +++ /dev/null @@ -1,33 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: pullrequest- -spec: - inputs: - resources: - - name: pr - resourceSpec: - type: pullRequest - params: - - name: url - # I just picked a random PR. The first couple didn't have any interesting comments or labels. - value: https://github.com/tektoncd/pipeline/pull/100 - taskSpec: - inputs: - resources: - - name: pr - type: pullRequest - steps: - - name: dump-workspace - image: ubuntu - script: find $(inputs.resources.pr.path)/* -type f | xargs tail -n +1 - - - name: ensure-approved - image: ubuntu - script: | - if [ -f "$(inputs.resources.pr.path)/labels/approved" ]; then - echo "PR is approved!" - else - echo "PR is not approved!" - exit 1 - fi diff --git a/examples/v1alpha1/taskruns/secret-env.yaml b/examples/v1alpha1/taskruns/secret-env.yaml deleted file mode 100644 index b7ce1ea3afc..00000000000 --- a/examples/v1alpha1/taskruns/secret-env.yaml +++ /dev/null @@ -1,25 +0,0 @@ -kind: Secret -apiVersion: v1 -metadata: - name: secret-env-password -stringData: - ninja: SECRET_PASSWORD ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: secret-env -spec: - taskSpec: - steps: - - name: secret - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $SECRET_PASSWORD == SECRET_PASSWORD ]] - env: - - name: SECRET_PASSWORD - valueFrom: - secretKeyRef: - name: secret-env-password - key: ninja diff --git a/examples/v1alpha1/taskruns/secret-volume-params.yaml b/examples/v1alpha1/taskruns/secret-volume-params.yaml deleted file mode 100644 index 0cd402b8810..00000000000 --- a/examples/v1alpha1/taskruns/secret-volume-params.yaml +++ /dev/null @@ -1,35 +0,0 @@ -kind: Secret -apiVersion: v1 -metadata: - name: secret-vol-param-password -stringData: - ninja: SECRET_PASSWORD ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: secret-volume-params -spec: - taskSpec: - inputs: - params: - - name: SCNAME - description: Name of secret - type: string - steps: - - image: ubuntu - script: | - #!/usr/bin/env bash - SECRET_PASSWORD=$(cat /var/secret/ninja) - [[ $SECRET_PASSWORD == SECRET_PASSWORD ]] - volumeMounts: - - name: secret-volume - mountPath: /var/secret - volumes: - - name: secret-volume - secret: - secretName: "$(inputs.params.SCNAME)" - inputs: - params: - - name: SCNAME - value: secret-vol-param-password diff --git a/examples/v1alpha1/taskruns/secret-volume.yaml b/examples/v1alpha1/taskruns/secret-volume.yaml deleted file mode 100644 index c83f99471e1..00000000000 --- a/examples/v1alpha1/taskruns/secret-volume.yaml +++ /dev/null @@ -1,26 +0,0 @@ -kind: Secret -apiVersion: v1 -metadata: - name: secret-vol-password -stringData: - ninja: SECRET_PASSWORD ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: secret-volume -spec: - taskSpec: - steps: - - image: ubuntu - script: | - #!/usr/bin/env bash - SECRET_PASSWORD=$(cat /var/secret/ninja) - [[ $SECRET_PASSWORD == SECRET_PASSWORD ]] - volumeMounts: - - name: secret-volume - mountPath: /var/secret - volumes: - - name: secret-volume - secret: - secretName: secret-vol-password diff --git a/examples/v1alpha1/taskruns/sidecar-interp.yaml b/examples/v1alpha1/taskruns/sidecar-interp.yaml deleted file mode 100644 index 9f367bc9a7a..00000000000 --- a/examples/v1alpha1/taskruns/sidecar-interp.yaml +++ /dev/null @@ -1,34 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: sidecar-interp- -spec: - taskSpec: - inputs: - params: - - name: some-input - default: foo - volumes: - - name: shared - emptyDir: {} - sidecars: - - name: value-sidecar - image: ubuntu - command: - - /bin/bash - args: - - -c - - "echo $(inputs.params.some-input) > /shared/value && sleep infinity" - volumeMounts: - - name: shared - mountPath: /shared - steps: - - name: check-value - image: ubuntu - script: | - #!/bin/bash - VALUE=$(cat /shared/value) - [[ $VALUE == 'foo' ]] - volumeMounts: - - name: shared - mountPath: /shared diff --git a/examples/v1alpha1/taskruns/sidecar-ready-script.yaml b/examples/v1alpha1/taskruns/sidecar-ready-script.yaml deleted file mode 100644 index 08f5339820c..00000000000 --- a/examples/v1alpha1/taskruns/sidecar-ready-script.yaml +++ /dev/null @@ -1,28 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: sidecar-ready- -spec: - taskSpec: - sidecars: - - name: slow-sidecar - image: ubuntu - script: | - echo "hello from sidecar" > /shared/message - volumeMounts: - - name: shared - mountPath: /shared - - steps: - - name: check-ready - image: ubuntu - script: cat /shared/message - volumeMounts: - - name: shared - mountPath: /shared - - # Sidecars don't have /workspace mounted by default, so we have to define - # our own shared volume. - volumes: - - name: shared - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/sidecar-ready.yaml b/examples/v1alpha1/taskruns/sidecar-ready.yaml deleted file mode 100644 index 2936879e208..00000000000 --- a/examples/v1alpha1/taskruns/sidecar-ready.yaml +++ /dev/null @@ -1,39 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: sidecar-ready- -spec: - taskSpec: - sidecars: - - name: slow-sidecar - image: ubuntu - command: ['sleep', 'infinity'] - # The sidecar takes 5s to report as Ready, even after it starts. If the - # step runs as soon as the sidecar starts, it will fail because - # /shared/ready isn't available yet. - readinessProbe: - exec: - command: - - sh - - -c - - sleep 5 && touch /shared/ready - timeoutSeconds: 10 - volumeMounts: - - name: shared - mountPath: /shared - - steps: - - name: check-ready - image: ubuntu - # The step will only succeed if the sidecar has written this file, which - # it does 5s after it starts, before it reports Ready. - script: cat /shared/ready - volumeMounts: - - name: shared - mountPath: /shared - - # Sidecars don't have /workspace mounted by default, so we have to define - # our own shared volume. - volumes: - - name: shared - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/step-by-digest.yaml b/examples/v1alpha1/taskruns/step-by-digest.yaml deleted file mode 100644 index c17da5ebbe7..00000000000 --- a/examples/v1alpha1/taskruns/step-by-digest.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: step-by-digest- -spec: - taskSpec: - steps: - # Step images can be specified by digest. - - image: busybox@sha256:1303dbf110c57f3edf68d9f5a16c082ec06c4cf7604831669faf2c712260b5a0 - # NB: command is not set, so it must be looked up from the registry. - args: ['-c', 'echo hello'] diff --git a/examples/v1alpha1/taskruns/step-script.yaml b/examples/v1alpha1/taskruns/step-script.yaml deleted file mode 100644 index bc8b2fe6bc4..00000000000 --- a/examples/v1alpha1/taskruns/step-script.yaml +++ /dev/null @@ -1,133 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: step-script- -spec: - taskSpec: - inputs: - params: - - name: PARAM - default: param-value - - steps: - - name: noshebang - image: ubuntu - script: echo "no shebang" - - name: bash - image: ubuntu - env: - - name: FOO - value: foooooooo - # Test that Pods with containers run as different UIDs - # are able to run scripts regardless of any specific - # Step's UID. - securityContext: - runAsUser: 2000 - script: | - #!/usr/bin/env bash - set -euxo pipefail - echo "Hello from Bash!" - echo FOO is ${FOO} - echo substring is ${FOO:2:4} - for i in {1..10}; do - echo line $i - done - - - name: place-file - image: ubuntu - securityContext: - runAsUser: 8000 - script: | - #!/usr/bin/env bash - echo "echo Hello from script file" > /workspace/hello - chmod +x /workspace/hello - - name: run-file - image: ubuntu - script: | - #!/usr/bin/env bash - /workspace/hello - - - name: contains-eof - image: ubuntu - securityContext: - runAsUser: 16000 - workingDir: /workspace - script: | - #!/usr/bin/env bash - cat > file << EOF - this file has some contents - EOF - cat file - - - name: node - image: node - script: | - #!/usr/bin/env node - console.log("Hello from Node!") - - - name: python - image: python - script: | - #!/usr/bin/env python3 - print("Hello from Python!") - - - name: perl - image: perl - script: | - #!/usr/bin/perl - print "Hello from Perl!" - - # Test that param values are replaced. - - name: params-applied - image: python - script: | - #!/usr/bin/env python3 - v = '$(inputs.params.PARAM)' - if v != 'param-value': - print('Param values not applied') - print('Got: ', v) - exit(1) - - # Test that args are allowed and passed to the script as expected. - - name: args-allowed - image: ubuntu - args: ['hello', 'world'] - script: | - #!/usr/bin/env bash - [[ $# == 2 ]] - [[ $1 == "hello" ]] - [[ $2 == "world" ]] - - # Test that multiple dollar signs next to each other are not replaced by Kubernetes - - name: dollar-signs-allowed - image: python - script: | - #!/usr/bin/env python3 - if '$' != '\u0024': - print('single dollar signs ($) are not passed through as expected :(') - exit(1) - if '$$' != '\u0024\u0024': - print('double dollar signs ($$) are not passed through as expected :(') - exit(2) - if '$$$' != '\u0024\u0024\u0024': - print('three dollar signs ($$$) are not passed through as expected :(') - exit(3) - if '$$$$' != '\u0024\u0024\u0024\u0024': - print('four dollar signs ($$$$) are not passed through as expected :(') - exit(4) - print('dollar signs appear to be handled correctly! :)') - - # Test that bash scripts with variable evaluations work as expected - - name: bash-variable-evaluations - image: bash:5.1.8 - script: | - #!/usr/bin/env bash - set -xe - var1=var1_value - var2=var1 - echo $(eval echo \$$var2) > tmpfile - eval_result=$(cat tmpfile) - if [ "$eval_result" != "var1_value" ] ; then - echo "unexpected eval result: $eval_result" - exit 1 - fi diff --git a/examples/v1alpha1/taskruns/steps-run-in-order.yaml b/examples/v1alpha1/taskruns/steps-run-in-order.yaml deleted file mode 100644 index d5924a05dff..00000000000 --- a/examples/v1alpha1/taskruns/steps-run-in-order.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: steps-run-in-order- -spec: - taskSpec: - steps: - - image: busybox - # NB: command is not set, so it must be looked up from the registry. - args: ['-c', 'sleep 3 && touch foo'] - - image: busybox - args: ['-c', 'ls', 'foo'] diff --git a/examples/v1alpha1/taskruns/steptemplate-env-merge.yaml b/examples/v1alpha1/taskruns/steptemplate-env-merge.yaml deleted file mode 100644 index a991f7c123f..00000000000 --- a/examples/v1alpha1/taskruns/steptemplate-env-merge.yaml +++ /dev/null @@ -1,67 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: steptemplate-env-merge- -spec: - inputs: - params: - - name: FOO - value: foo - - name: BAR - value: bar - taskSpec: - # This template will be applied to all steps - stepTemplate: - env: - - name: QUX - value: original - inputs: - params: - - name: FOO - description: FOO variable - - name: BAR - description: BAR variable - - name: FOOBAR - description: FOOBAR variable - default: foobar - steps: - # Test the environment variables are set in the task - - name: foo - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $FOO == "foo" ]] - env: - - name: FOO - value: $(inputs.params.FOO) - - name: foobar - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $FOOBAR == "foobar" ]] - env: - - name: FOOBAR - value: $(inputs.params.FOOBAR) - - name: bar - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $BAR == "bar" ]] - env: - - name: BAR - value: $(inputs.params.BAR) - # Use the env var from the stepTemplate - - name: qux-no-override - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $QUX == "original" ]] - # Override the env var in the stepTemplate - - name: qux-override - image: ubuntu - script: | - #!/usr/bin/env bash - [[ $QUX == "override" ]] - env: - - name: QUX - value: override diff --git a/examples/v1alpha1/taskruns/task-multiple-output-image.yaml b/examples/v1alpha1/taskruns/task-multiple-output-image.yaml deleted file mode 100644 index 8a6b7405ef3..00000000000 --- a/examples/v1alpha1/taskruns/task-multiple-output-image.yaml +++ /dev/null @@ -1,120 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-image-leeroy-web-1 -spec: - type: image - params: - - name: url - value: gcr.io/dlorenc-vmtest2/leeroy-web # Replace this URL with $KO_DOCKER_REPO ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-image-leeroy-web-2 -spec: - type: image - params: - - name: url - value: gcr.io/christiewilson-catfactory/leeroy-web # Replace this URL with $KO_DOCKER_REPO ---- -# This demo modifies the cluster (deploys to it) you must use a service -# account with permission to admin the cluster (or make your default user an admin -# of the `default` namespace with default-cluster-admin). -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - generateName: default-cluster-admin- -subjects: - - kind: ServiceAccount - name: default - namespace: default -roleRef: - kind: ClusterRole - name: cluster-admin - apiGroup: rbac.authorization.k8s.io ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-git-multiple-output-image -spec: - type: git - params: - - name: revision - value: v0.32.0 - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -# This task is currently hardcoding a index.json file instead of -# building an image since kaniko and other easy to use tools don't -# support exporting this file yet -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: multiple-build-push-kaniko -spec: - inputs: - resources: - - name: sourcerepo - type: git - outputs: - resources: - - name: builtImage1 - type: image - - name: builtImage2 - type: image - steps: - - name: build-and-push-1 - image: busybox - script: | - set -ex - mkdir -p /tekton/home/image-outputs/builtImage1 - cat < /tekton/home/image-outputs/builtImage1/index.json - { - "schemaVersion": 2, - "manifests": [ - { - "mediaType": "application/vnd.oci.image.index.v1+json", - "size": 314, - "digest": "sha256:05f95b26ed10668b7183c1e2da98610e91372fa9f510046d4ce5812addad86b5" - } - ] - } - - name: build-and-push-2 - image: busybox - script: | - set -e - mkdir -p /tekton/home/image-outputs/builtImage2 - cat < /tekton/home/image-outputs/builtImage2/index.json - { - "schemaVersion": 2, - "manifests": [ - { - "mediaType": "application/vnd.oci.image.index.v1+json", - "size": 314, - "digest": "sha256:05f95b26ed10668b7183c1e2da98610e91372fa9f510046d4ce5812addad86b5" - } - ] - } ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: multiple-build-push-kaniko-run -spec: - taskRef: - name: multiple-build-push-kaniko - inputs: - resources: - - name: sourcerepo - resourceRef: - name: skaffold-git-multiple-output-image - outputs: - resources: - - name: builtImage1 - resourceRef: - name: skaffold-image-leeroy-web-1 - - name: builtImage2 - resourceRef: - name: skaffold-image-leeroy-web-2 diff --git a/examples/v1alpha1/taskruns/task-output-image.yaml b/examples/v1alpha1/taskruns/task-output-image.yaml deleted file mode 100644 index bf3a8e1ba1a..00000000000 --- a/examples/v1alpha1/taskruns/task-output-image.yaml +++ /dev/null @@ -1,92 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-image-leeroy-web-output-image -spec: - type: image - params: - - name: url - value: gcr.io/christiewilson-catfactory/leeroy-web # Replace this URL with $KO_DOCKER_REPO ---- -# This demo modifies the cluster (deploys to it) you must use a service -# account with permission to admin the cluster (or make your default user an admin -# of the `default` namespace with default-cluster-admin). -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - generateName: default-cluster-admin- -subjects: - - kind: ServiceAccount - name: default - namespace: default -roleRef: - kind: ClusterRole - name: cluster-admin - apiGroup: rbac.authorization.k8s.io ---- -apiVersion: tekton.dev/v1alpha1 -kind: PipelineResource -metadata: - name: skaffold-git-output-image -spec: - type: git - params: - - name: revision - value: v0.32.0 - - name: url - value: https://github.com/GoogleContainerTools/skaffold ---- -# This task is currently hardcoding a index.json file instead of -# building an image since kaniko and other easy to use tools don't -# support exporting this file yet -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: build-push-kaniko-output-image -spec: - inputs: - resources: - - name: sourcerepo - type: git - outputs: - resources: - - name: builtImage - type: image - targetPath: /workspace/sourcerepo - steps: - - name: build-and-push - image: busybox - script: | - set -e - cat < $(inputs.resources.sourcerepo.path)/index.json - { - "schemaVersion": 2, - "manifests": [ - { - "mediaType": "application/vnd.oci.image.index.v1+json", - "size": 314, - "digest": "sha256:05f95b26ed10668b7183c1e2da98610e91372fa9f510046d4ce5812addad86b5" - } - ] - } - - name: echo - image: busybox - script: cat $(inputs.resources.sourcerepo.path)/index.json ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - name: build-push-run-output-image -spec: - taskRef: - name: build-push-kaniko-output-image - inputs: - resources: - - name: sourcerepo - resourceRef: - name: skaffold-git-output-image - outputs: - resources: - - name: builtImage - resourceRef: - name: skaffold-image-leeroy-web-output-image diff --git a/examples/v1alpha1/taskruns/task-result.yaml b/examples/v1alpha1/taskruns/task-result.yaml deleted file mode 100644 index 935630c52c5..00000000000 --- a/examples/v1alpha1/taskruns/task-result.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: Task -metadata: - name: print-date - annotations: - description: | - A simple task that prints the date. -spec: - results: - - name: current-date-unix-timestamp - description: The current date in unix timestamp format - - name: current-date-human-readable - description: The current date in humand readable format - steps: - - name: print-date-unix-timestamp - image: bash:latest - script: | - #!/usr/bin/env bash - date +%s | tee /tekton/results/current-date-unix-timestamp - - name: print-date-human-readable - image: bash:latest - script: | - #!/usr/bin/env bash - date | tee /tekton/results/current-date-human-readable \ No newline at end of file diff --git a/examples/v1alpha1/taskruns/task-volume-args.yaml b/examples/v1alpha1/taskruns/task-volume-args.yaml deleted file mode 100644 index b04a5639ff3..00000000000 --- a/examples/v1alpha1/taskruns/task-volume-args.yaml +++ /dev/null @@ -1,35 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: config-for-testing-volume-args -data: - test.data: tasks are my jam ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: task-volume-args- -spec: - taskSpec: - inputs: - params: - - name: CFGNAME - description: Name of config map - type: string - steps: - - name: read - image: ubuntu - script: | - #!/usr/bin/env bash - cat /configmap/test.data - volumeMounts: - - name: custom - mountPath: /configmap - volumes: - - name: custom - configMap: - name: "$(inputs.params.CFGNAME)" - inputs: - params: - - name: CFGNAME - value: config-for-testing-volume-args diff --git a/examples/v1alpha1/taskruns/template-volume.yaml b/examples/v1alpha1/taskruns/template-volume.yaml deleted file mode 100644 index 358d69b050d..00000000000 --- a/examples/v1alpha1/taskruns/template-volume.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: template-volume- -spec: - taskSpec: - steps: - - name: write - image: ubuntu - script: | - #!/usr/bin/env bash - echo some stuff > /im/a/custom/mount/path/file - volumeMounts: - - name: custom - mountPath: /im/a/custom/mount/path - - name: read - image: ubuntu - script: | - #!/usr/bin/env bash - cat /short/and/stout/file - volumeMounts: - - name: custom - mountPath: /short/and/stout - podTemplate: - volumes: - - name: custom - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/unnamed-steps.yaml b/examples/v1alpha1/taskruns/unnamed-steps.yaml deleted file mode 100644 index a623a7dedbc..00000000000 --- a/examples/v1alpha1/taskruns/unnamed-steps.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: unnamed-steps- -spec: - taskSpec: - steps: - - image: ubuntu - script: 'true' - - image: ubuntu - script: 'true' - - image: ubuntu - script: 'true' diff --git a/examples/v1alpha1/taskruns/workingdir.yaml b/examples/v1alpha1/taskruns/workingdir.yaml deleted file mode 100644 index d281d46d750..00000000000 --- a/examples/v1alpha1/taskruns/workingdir.yaml +++ /dev/null @@ -1,20 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: workingdir- -spec: - taskSpec: - steps: - - name: default - image: ubuntu - workingDir: /workspace - script: | - #!/usr/bin/env bash - [[ $PWD == /workspace ]] - - - name: override - image: ubuntu - workingDir: '/a/path/too/far' - script: | - #!/usr/bin/env bash - [[ $PWD == /a/path/too/far ]] diff --git a/examples/v1alpha1/taskruns/workspace-readonly.yaml b/examples/v1alpha1/taskruns/workspace-readonly.yaml deleted file mode 100644 index b50619e3766..00000000000 --- a/examples/v1alpha1/taskruns/workspace-readonly.yaml +++ /dev/null @@ -1,47 +0,0 @@ -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: my-pvc-2 -spec: - resources: - requests: - storage: 5Gi - volumeMode: Filesystem - accessModes: - - ReadWriteOnce ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: workspaces-readonly- -spec: - workspaces: - - name: write-allowed - persistentVolumeClaim: - claimName: my-pvc-2 - - name: write-disallowed - persistentVolumeClaim: - claimName: my-pvc-2 - taskSpec: - workspaces: - - name: write-allowed - - name: write-disallowed - readOnly: true - steps: - - name: write-allowed - image: ubuntu - script: echo "hello" > $(workspaces.write-allowed.path)/foo - - name: read-allowed - image: ubuntu - script: cat $(workspaces.write-allowed.path)/foo | grep "hello" - - name: write-disallowed - image: ubuntu - script: - echo "goodbye" > $(workspaces.write-disallowed.path)/foo || touch write-failed.txt - test -f write-failed.txt - - name: read-again - # We should get "hello" when reading again because writing "goodbye" to - # the file should have been disallowed. - image: ubuntu - script: - cat $(workspaces.write-disallowed.path)/foo | grep "hello" diff --git a/examples/v1alpha1/taskruns/workspace-volume.yaml b/examples/v1alpha1/taskruns/workspace-volume.yaml deleted file mode 100644 index 2c59cc1cdd9..00000000000 --- a/examples/v1alpha1/taskruns/workspace-volume.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: workspace-volume- -spec: - taskSpec: - steps: - - name: write - image: ubuntu - script: echo some stuff > /workspace/stuff - - name: read - image: ubuntu - script: cat /workspace/stuff - - - name: override-workspace - image: ubuntu - # /workspace/stuff *doesn't* exist. - script: | - #!/usr/bin/env bash - [[ ! -f /workspace/stuff ]] - volumeMounts: - - name: empty - mountPath: /workspace - - volumes: - - name: empty - emptyDir: {} diff --git a/examples/v1alpha1/taskruns/workspace.yaml b/examples/v1alpha1/taskruns/workspace.yaml deleted file mode 100644 index 8ac77cf38d1..00000000000 --- a/examples/v1alpha1/taskruns/workspace.yaml +++ /dev/null @@ -1,93 +0,0 @@ -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: my-pvc -spec: - resources: - requests: - storage: 5Gi - volumeMode: Filesystem - accessModes: - - ReadWriteOnce ---- -apiVersion: v1 -kind: ConfigMap -metadata: - name: my-configmap -data: - message: hello world ---- -apiVersion: v1 -kind: Secret -metadata: - name: my-secret -type: Opaque -stringData: - username: user -data: - message: aGVsbG8gc2VjcmV0 ---- -apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -metadata: - generateName: custom-volume- -spec: - workspaces: - - name: custom - persistentVolumeClaim: - claimName: my-pvc - subPath: my-subdir - - name: custom2 - persistentVolumeClaim: - claimName: my-pvc - - name: custom3 - emptyDir: {} - subPath: testing - - name: custom4 - configMap: - name: my-configmap - items: - - key: message - path: my-message.txt - - name: custom5 - secret: - secretName: my-secret - taskSpec: - steps: - - name: write - image: ubuntu - script: echo $(workspaces.custom.volume) > $(workspaces.custom.path)/foo - - name: read - image: ubuntu - script: cat $(workspaces.custom.path)/foo | grep $(workspaces.custom.volume) - - name: write2 - image: ubuntu - script: echo $(workspaces.custom2.path) > $(workspaces.custom2.path)/foo - - name: read2 - image: ubuntu - script: cat $(workspaces.custom2.path)/foo | grep $(workspaces.custom2.path) - - name: write3 - image: ubuntu - script: echo $(workspaces.custom3.path) > $(workspaces.custom3.path)/foo - - name: read3 - image: ubuntu - script: cat $(workspaces.custom3.path)/foo | grep $(workspaces.custom3.path) - - name: readconfigmap - image: ubuntu - script: cat $(workspaces.custom4.path)/my-message.txt | grep "hello world" - - name: readsecret - image: ubuntu - script: | - #!/usr/bin/env bash - set -xe - cat $(workspaces.custom5.path)/username | grep "user" - cat $(workspaces.custom5.path)/message | grep "hello secret" - workspaces: - - name: custom - - name: custom2 - mountPath: /foo/bar/baz - - name: custom3 - - name: custom4 - mountPath: /baz/bar/quux - - name: custom5 - mountPath: /my/secret/volume diff --git a/pkg/apis/pipeline/v1alpha1/cluster_task_conversion.go b/pkg/apis/pipeline/v1alpha1/cluster_task_conversion.go deleted file mode 100644 index 976add0d50c..00000000000 --- a/pkg/apis/pipeline/v1alpha1/cluster_task_conversion.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "knative.dev/pkg/apis" -) - -var _ apis.Convertible = (*ClusterTask)(nil) - -// ConvertTo implements api.Convertible -func (ct *ClusterTask) ConvertTo(ctx context.Context, obj apis.Convertible) error { - switch sink := obj.(type) { - case *v1beta1.ClusterTask: - sink.ObjectMeta = ct.ObjectMeta - return ct.Spec.ConvertTo(ctx, &sink.Spec) - default: - return fmt.Errorf("unknown version, got: %T", sink) - } -} - -// ConvertFrom implements api.Convertible -func (ct *ClusterTask) ConvertFrom(ctx context.Context, obj apis.Convertible) error { - switch source := obj.(type) { - case *v1beta1.ClusterTask: - ct.ObjectMeta = source.ObjectMeta - return ct.Spec.ConvertFrom(ctx, &source.Spec) - default: - return fmt.Errorf("unknown version, got: %T", ct) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/cluster_task_conversion_test.go b/pkg/apis/pipeline/v1alpha1/cluster_task_conversion_test.go deleted file mode 100644 index a66207c243b..00000000000 --- a/pkg/apis/pipeline/v1alpha1/cluster_task_conversion_test.go +++ /dev/null @@ -1,315 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestClusterTaskConversionBadType(t *testing.T) { - good, bad := &ClusterTask{}, &Pipeline{} - - if err := good.ConvertTo(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } - - if err := good.ConvertFrom(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } -} - -func TestClusterTaskConversion(t *testing.T) { - versions := []apis.Convertible{&v1beta1.ClusterTask{}} - - tests := []struct { - name string - in *ClusterTask - wantErr bool - }{{ - name: "simple conversion", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - Volumes: []corev1.Volume{{}}, - Params: []v1beta1.ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - }, - }, { - name: "deprecated and non deprecated inputs", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - Inputs: &Inputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - wantErr: true, - }, { - name: "deprecated and non deprecated inputs", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Params: []v1beta1.ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - Inputs: &Inputs{ - Params: []ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - }, - }, - wantErr: true, - }, { - name: "deprecated and non deprecated outputs", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - Outputs: &Outputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - wantErr: true, - }} - - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - if !test.wantErr { - t.Errorf("ConvertTo() = %v", err) - } - return - } - t.Logf("ConvertTo() = %#v", ver) - got := &ClusterTask{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.in, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} - -func TestClusterTaskConversionFromDeprecated(t *testing.T) { - versions := []apis.Convertible{&v1beta1.ClusterTask{}} - tests := []struct { - name string - in *ClusterTask - want *ClusterTask - }{{ - name: "inputs params", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - Inputs: &Inputs{ - Params: []ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - }, - }, - want: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Params: []v1beta1.ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - }, - }, - }, { - name: "inputs resource", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - Inputs: &Inputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - want: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - }, - }, { - name: "outputs resource", - in: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - Outputs: &Outputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - want: &ClusterTask{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - }, - }} - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - t.Errorf("ConvertTo() = %v", err) - } - t.Logf("ConvertTo() = %#v", ver) - got := &ClusterTask{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.want, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} diff --git a/pkg/apis/pipeline/v1alpha1/cluster_task_defaults.go b/pkg/apis/pipeline/v1alpha1/cluster_task_defaults.go deleted file mode 100644 index fe18e3e6976..00000000000 --- a/pkg/apis/pipeline/v1alpha1/cluster_task_defaults.go +++ /dev/null @@ -1,30 +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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -var _ apis.Defaultable = (*ClusterTask)(nil) - -// SetDefaults sets the default values for the ClusterTask's Spec. -func (t *ClusterTask) SetDefaults(ctx context.Context) { - t.Spec.SetDefaults(ctx) -} diff --git a/pkg/apis/pipeline/v1alpha1/cluster_task_types.go b/pkg/apis/pipeline/v1alpha1/cluster_task_types.go deleted file mode 100644 index 1b2ebd27857..00000000000 --- a/pkg/apis/pipeline/v1alpha1/cluster_task_types.go +++ /dev/null @@ -1,64 +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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +genclient:noStatus -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterTask is a Task with a cluster scope. ClusterTasks are used to -// represent Tasks that should be publicly addressable from any namespace in the -// cluster. -type ClusterTask struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec holds the desired state of the Task from the client - // +optional - Spec TaskSpec `json:"spec,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterTaskList contains a list of ClusterTask. -type ClusterTaskList struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - Items []ClusterTask `json:"items"` -} - -// TaskSpec returns the ClusterTask's Spec. -func (t *ClusterTask) TaskSpec() TaskSpec { - return t.Spec -} - -// TaskMetadata returns the ObjectMeta for the ClusterTask. -func (t *ClusterTask) TaskMetadata() metav1.ObjectMeta { - return t.ObjectMeta -} - -// Copy returns a DeepCopy of the ClusterTask. -func (t *ClusterTask) Copy() TaskObject { - return t.DeepCopy() -} diff --git a/pkg/apis/pipeline/v1alpha1/cluster_task_validation.go b/pkg/apis/pipeline/v1alpha1/cluster_task_validation.go deleted file mode 100644 index 77adb5ec12c..00000000000 --- a/pkg/apis/pipeline/v1alpha1/cluster_task_validation.go +++ /dev/null @@ -1,37 +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 v1alpha1 - -import ( - "context" - - "github.com/tektoncd/pipeline/pkg/apis/validate" - "knative.dev/pkg/apis" -) - -var _ apis.Validatable = (*ClusterTask)(nil) - -// Validate performs validation of the metadata and spec of this ClusterTask. -func (t *ClusterTask) Validate(ctx context.Context) *apis.FieldError { - if err := validate.ObjectMetadata(t.GetObjectMeta()); err != nil { - return err.ViaField("metadata") - } - if apis.IsInDelete(ctx) { - return nil - } - return t.Spec.Validate(ctx) -} diff --git a/pkg/apis/pipeline/v1alpha1/container_replacements.go b/pkg/apis/pipeline/v1alpha1/container_replacements.go deleted file mode 100644 index 04541934450..00000000000 --- a/pkg/apis/pipeline/v1alpha1/container_replacements.go +++ /dev/null @@ -1,73 +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 v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/substitution" -) - -// ApplyContainerReplacements replaces ${...} expressions in the container's name, image, args, env, command, workingDir, -// and volumes. -func ApplyContainerReplacements(step *Step, stringReplacements map[string]string, arrayReplacements map[string][]string) { - step.Name = substitution.ApplyReplacements(step.Name, stringReplacements) - step.Image = substitution.ApplyReplacements(step.Image, stringReplacements) - - // Use ApplyArrayReplacements here, as additional args may be added via an array parameter. - var newArgs []string - for _, a := range step.Args { - newArgs = append(newArgs, substitution.ApplyArrayReplacements(a, stringReplacements, arrayReplacements)...) - } - step.Args = newArgs - - for ie, e := range step.Env { - step.Env[ie].Value = substitution.ApplyReplacements(e.Value, stringReplacements) - if step.Env[ie].ValueFrom != nil { - if e.ValueFrom.SecretKeyRef != nil { - step.Env[ie].ValueFrom.SecretKeyRef.LocalObjectReference.Name = substitution.ApplyReplacements(e.ValueFrom.SecretKeyRef.LocalObjectReference.Name, stringReplacements) - step.Env[ie].ValueFrom.SecretKeyRef.Key = substitution.ApplyReplacements(e.ValueFrom.SecretKeyRef.Key, stringReplacements) - } - if e.ValueFrom.ConfigMapKeyRef != nil { - step.Env[ie].ValueFrom.ConfigMapKeyRef.LocalObjectReference.Name = substitution.ApplyReplacements(e.ValueFrom.ConfigMapKeyRef.LocalObjectReference.Name, stringReplacements) - step.Env[ie].ValueFrom.ConfigMapKeyRef.Key = substitution.ApplyReplacements(e.ValueFrom.ConfigMapKeyRef.Key, stringReplacements) - } - } - } - - for ie, e := range step.EnvFrom { - step.EnvFrom[ie].Prefix = substitution.ApplyReplacements(e.Prefix, stringReplacements) - if e.ConfigMapRef != nil { - step.EnvFrom[ie].ConfigMapRef.LocalObjectReference.Name = substitution.ApplyReplacements(e.ConfigMapRef.LocalObjectReference.Name, stringReplacements) - } - if e.SecretRef != nil { - step.EnvFrom[ie].SecretRef.LocalObjectReference.Name = substitution.ApplyReplacements(e.SecretRef.LocalObjectReference.Name, stringReplacements) - } - } - step.WorkingDir = substitution.ApplyReplacements(step.WorkingDir, stringReplacements) - - // Use ApplyArrayReplacements here, as additional commands may be added via an array parameter. - var newCommand []string - for _, c := range step.Command { - newCommand = append(newCommand, substitution.ApplyArrayReplacements(c, stringReplacements, arrayReplacements)...) - } - step.Command = newCommand - - for iv, v := range step.VolumeMounts { - step.VolumeMounts[iv].Name = substitution.ApplyReplacements(v.Name, stringReplacements) - step.VolumeMounts[iv].MountPath = substitution.ApplyReplacements(v.MountPath, stringReplacements) - step.VolumeMounts[iv].SubPath = substitution.ApplyReplacements(v.SubPath, stringReplacements) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/container_replacements_test.go b/pkg/apis/pipeline/v1alpha1/container_replacements_test.go deleted file mode 100644 index 0f2cc766f36..00000000000 --- a/pkg/apis/pipeline/v1alpha1/container_replacements_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 v1alpha1_test - -import ( - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" -) - -func TestApplyContainerReplacements(t *testing.T) { - replacements := map[string]string{ - "replace.me": "replaced!", - } - - arrayReplacements := map[string][]string{ - "array.replace.me": {"val1", "val2"}, - } - - s := v1alpha1.Step{ - Name: "$(replace.me)", - Image: "$(replace.me)", - Command: []string{"$(array.replace.me)"}, - Args: []string{"$(array.replace.me)"}, - WorkingDir: "$(replace.me)", - EnvFrom: []corev1.EnvFromSource{{ - ConfigMapRef: &corev1.ConfigMapEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - }, - SecretRef: &corev1.SecretEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - }, - }}, - Env: []corev1.EnvVar{{ - Name: "not_me", - Value: "$(replace.me)", - ValueFrom: &corev1.EnvVarSource{ - ConfigMapKeyRef: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - Key: "$(replace.me)", - }, - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - Key: "$(replace.me)", - }, - }, - }}, - VolumeMounts: []corev1.VolumeMount{{ - Name: "$(replace.me)", - MountPath: "$(replace.me)", - SubPath: "$(replace.me)", - }}, - } - - expected := v1alpha1.Step{ - Name: "replaced!", - Image: "replaced!", - Command: []string{"val1", "val2"}, - Args: []string{"val1", "val2"}, - WorkingDir: "replaced!", - EnvFrom: []corev1.EnvFromSource{{ - ConfigMapRef: &corev1.ConfigMapEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - }, - SecretRef: &corev1.SecretEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - }, - }}, - Env: []corev1.EnvVar{{ - Name: "not_me", - Value: "replaced!", - ValueFrom: &corev1.EnvVarSource{ - ConfigMapKeyRef: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - Key: "replaced!", - }, - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - Key: "replaced!", - }, - }, - }}, - VolumeMounts: []corev1.VolumeMount{{ - Name: "replaced!", - MountPath: "replaced!", - SubPath: "replaced!", - }}, - } - - v1alpha1.ApplyContainerReplacements(&s, replacements, arrayReplacements) - if d := cmp.Diff(s, expected); d != "" { - t.Errorf("Container replacements failed: %s", diff.PrintWantGot(d)) - } -} - -func TestApplyContainerReplacements_NotDefined(t *testing.T) { - s := v1alpha1.Step{ - Name: "$(params.not.defined)", - } - replacements := map[string]string{ - "replace.me": "replaced!", - } - - arrayReplacements := map[string][]string{ - "array.replace.me": {"val1", "val2"}, - } - - expected := v1alpha1.Step{ - Name: "$(params.not.defined)", - } - v1alpha1.ApplyContainerReplacements(&s, replacements, arrayReplacements) - if d := cmp.Diff(s, expected); d != "" { - t.Errorf("Unexpected container replacement: %s", diff.PrintWantGot(d)) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/conversion_error.go b/pkg/apis/pipeline/v1alpha1/conversion_error.go deleted file mode 100644 index 2ebdba1a1fa..00000000000 --- a/pkg/apis/pipeline/v1alpha1/conversion_error.go +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "knative.dev/pkg/apis" -) - -const ( - // ConditionTypeConvertible is a Warning condition that is set on - // resources when they cannot be converted to warn of a forthcoming - // breakage. - ConditionTypeConvertible apis.ConditionType = v1beta1.ConditionTypeConvertible - // ConversionErrorFieldNotAvailableMsg Conversion Error message for a field not available in v1alpha1 - ConversionErrorFieldNotAvailableMsg = "the specified field/section is not available in v1alpha1" -) diff --git a/pkg/apis/pipeline/v1alpha1/param_types.go b/pkg/apis/pipeline/v1alpha1/param_types.go deleted file mode 100644 index 69b21947c6a..00000000000 --- a/pkg/apis/pipeline/v1alpha1/param_types.go +++ /dev/null @@ -1,49 +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 v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" -) - -// ParamSpec defines arbitrary parameters needed beyond typed inputs (such as -// resources). Parameter values are provided by users as inputs on a TaskRun -// or PipelineRun. -type ParamSpec = v1beta1.ParamSpec - -// Param declares an ArrayOrString to use for the parameter called name. -type Param = v1beta1.Param - -// ParamType indicates the type of an input parameter; -// Used to distinguish between a single string and an array of strings. -type ParamType = v1beta1.ParamType - -// Valid ParamTypes: -const ( - ParamTypeString ParamType = v1beta1.ParamTypeString - ParamTypeArray ParamType = v1beta1.ParamTypeArray -) - -// AllParamTypes can be used for ParamType validation. -var AllParamTypes = v1beta1.AllParamTypes - -// ArrayOrString is modeled after IntOrString in kubernetes/apimachinery: - -// ArrayOrString is a type that can hold a single string or string array. -// Used in JSON unmarshalling so that a single JSON field can accept -// either an individual string or an array of strings. -type ArrayOrString = v1beta1.ArrayOrString diff --git a/pkg/apis/pipeline/v1alpha1/param_types_test.go b/pkg/apis/pipeline/v1alpha1/param_types_test.go deleted file mode 100644 index 9d1aec7c4dd..00000000000 --- a/pkg/apis/pipeline/v1alpha1/param_types_test.go +++ /dev/null @@ -1,241 +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 v1alpha1_test - -import ( - "context" - "encoding/json" - "reflect" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" -) - -func TestParamSpec_SetDefaults(t *testing.T) { - tests := []struct { - name string - before *v1alpha1.ParamSpec - defaultsApplied *v1alpha1.ParamSpec - }{{ - name: "inferred string type", - before: &v1alpha1.ParamSpec{ - Name: "parametername", - }, - defaultsApplied: &v1alpha1.ParamSpec{ - Name: "parametername", - Type: v1alpha1.ParamTypeString, - }, - }, { - name: "inferred type from default value", - before: &v1alpha1.ParamSpec{ - Name: "parametername", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"an", "array"}, - }, - }, - defaultsApplied: &v1alpha1.ParamSpec{ - Name: "parametername", - Type: v1alpha1.ParamTypeArray, - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"an", "array"}, - }, - }, - }, { - name: "fully defined ParamSpec", - before: &v1alpha1.ParamSpec{ - Name: "parametername", - Type: v1alpha1.ParamTypeArray, - Description: "a description", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"an", "array"}, - }, - }, - defaultsApplied: &v1alpha1.ParamSpec{ - Name: "parametername", - Type: v1alpha1.ParamTypeArray, - Description: "a description", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"an", "array"}, - }, - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() - tc.before.SetDefaults(ctx) - if d := cmp.Diff(tc.before, tc.defaultsApplied); d != "" { - t.Errorf("ParamSpec.SetDefaults/%s %s", tc.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestArrayOrString_ApplyReplacements(t *testing.T) { - type args struct { - input *v1alpha1.ArrayOrString - stringReplacements map[string]string - arrayReplacements map[string][]string - } - tests := []struct { - name string - args args - expectedOutput *v1alpha1.ArrayOrString - }{{ - name: "no replacements on array", - args: args{ - input: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"an", "array"}, - }, - stringReplacements: map[string]string{"some": "value", "anotherkey": "value"}, - arrayReplacements: map[string][]string{"arraykey": {"array", "value"}, "sdfdf": {"sdf", "sdfsd"}}, - }, - expectedOutput: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"an", "array"}, - }, - }, { - name: "string replacements on string", - args: args{ - input: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "astring$(some) asdf $(anotherkey)", - }, - stringReplacements: map[string]string{"some": "value", "anotherkey": "value"}, - arrayReplacements: map[string][]string{"arraykey": {"array", "value"}, "sdfdf": {"asdf", "sdfsd"}}, - }, - expectedOutput: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "astringvalue asdf value", - }, - }, { - name: "single array replacement", - args: args{ - input: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"firstvalue", "$(arraykey)", "lastvalue"}, - }, - stringReplacements: map[string]string{"some": "value", "anotherkey": "value"}, - arrayReplacements: map[string][]string{"arraykey": {"array", "value"}, "sdfdf": {"asdf", "sdfsd"}}, - }, - expectedOutput: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"firstvalue", "array", "value", "lastvalue"}, - }, - }, { - name: "multiple array replacement", - args: args{ - input: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"firstvalue", "$(arraykey)", "lastvalue", "$(sdfdf)"}, - }, - stringReplacements: map[string]string{"some": "value", "anotherkey": "value"}, - arrayReplacements: map[string][]string{"arraykey": {"array", "value"}, "sdfdf": {"asdf", "sdfsd"}}, - }, - expectedOutput: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"firstvalue", "array", "value", "lastvalue", "asdf", "sdfsd"}, - }, - }, { - name: "empty array replacement", - args: args{ - input: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"firstvalue", "$(arraykey)", "lastvalue"}, - }, - stringReplacements: map[string]string{"some": "value", "anotherkey": "value"}, - arrayReplacements: map[string][]string{"arraykey": {}}, - }, - expectedOutput: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"firstvalue", "lastvalue"}, - }, - }} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tt.args.input.ApplyReplacements(tt.args.stringReplacements, tt.args.arrayReplacements) - if d := cmp.Diff(tt.expectedOutput, tt.args.input); d != "" { - t.Errorf("ApplyReplacements() output did not match expected value %s", diff.PrintWantGot(d)) - } - }) - } -} - -type ArrayOrStringHolder struct { - AOrS v1alpha1.ArrayOrString `json:"val"` -} - -func TestArrayOrString_UnmarshalJSON(t *testing.T) { - for _, c := range []struct { - input string - want v1alpha1.ArrayOrString - }{{ - input: "{\"val\": \"123\"}", - want: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeString, StringVal: "123"}, - }, { - input: "{\"val\": \"\"}", - want: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeString, StringVal: ""}, - }, { - input: "{\"val\":[]}", - want: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeArray, ArrayVal: []string{}}, - }, { - input: "{\"val\":[\"oneelement\"]}", - want: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeArray, ArrayVal: []string{"oneelement"}}, - }, { - input: "{\"val\":[\"multiple\", \"elements\"]}", - want: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeArray, ArrayVal: []string{"multiple", "elements"}}}, - } { - var got ArrayOrStringHolder - if err := json.Unmarshal([]byte(c.input), &got); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(got.AOrS, c.want) { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.want, got.AOrS) - } - } -} - -func TestArrayOrString_MarshalJSON(t *testing.T) { - for _, c := range []struct { - input v1alpha1.ArrayOrString - want string - }{{ - input: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeString, StringVal: "123"}, - want: "{\"val\":\"123\"}", - }, { - input: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeArray, ArrayVal: []string{"123", "1234"}}, - want: "{\"val\":[\"123\",\"1234\"]}", - }, { - input: v1alpha1.ArrayOrString{Type: v1alpha1.ParamTypeArray, ArrayVal: []string{"a", "a", "a"}}, - want: "{\"val\":[\"a\",\"a\",\"a\"]}", - }} { - input := ArrayOrStringHolder{c.input} - got, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input '%v': %v", input, err) - } - if string(got) != c.want { - t.Errorf("Failed to marshal input '%v': expected: %+v, got %q", input, c.want, string(got)) - } - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_conversion.go b/pkg/apis/pipeline/v1alpha1/pipeline_conversion.go deleted file mode 100644 index b37d62a70b1..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_conversion.go +++ /dev/null @@ -1,175 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -const finallyAnnotationKey = "tekton.dev/v1beta1Finally" - -var _ apis.Convertible = (*Pipeline)(nil) - -// ConvertTo implements api.Convertible -func (p *Pipeline) ConvertTo(ctx context.Context, obj apis.Convertible) error { - switch sink := obj.(type) { - case *v1beta1.Pipeline: - sink.ObjectMeta = p.ObjectMeta - if err := p.Spec.ConvertTo(ctx, &sink.Spec); err != nil { - return err - } - if err := deserializeFinally(&sink.ObjectMeta, &sink.Spec); err != nil { - return err - } - if err := v1beta1.ValidatePipelineTasks(ctx, sink.Spec.Tasks, sink.Spec.Finally); err != nil { - return fmt.Errorf("error converting finally annotation into beta field: %w", err) - } - default: - return fmt.Errorf("unknown version, got: %T", sink) - } - return nil -} - -// ConvertTo implements api.Convertible -func (ps *PipelineSpec) ConvertTo(ctx context.Context, sink *v1beta1.PipelineSpec) error { - sink.Resources = ps.Resources - sink.Params = ps.Params - sink.Workspaces = ps.Workspaces - sink.Description = ps.Description - if len(ps.Tasks) > 0 { - sink.Tasks = make([]v1beta1.PipelineTask, len(ps.Tasks)) - for i := range ps.Tasks { - if err := ps.Tasks[i].ConvertTo(ctx, &sink.Tasks[i]); err != nil { - return err - } - } - } - sink.Finally = nil - return nil -} - -// ConvertTo implements api.Convertible -func (pt *PipelineTask) ConvertTo(ctx context.Context, sink *v1beta1.PipelineTask) error { - sink.Name = pt.Name - sink.TaskRef = pt.TaskRef - if pt.TaskSpec != nil { - sink.TaskSpec = &v1beta1.EmbeddedTask{TaskSpec: v1beta1.TaskSpec{}} - if err := pt.TaskSpec.ConvertTo(ctx, &sink.TaskSpec.TaskSpec); err != nil { - return err - } - } - sink.Retries = pt.Retries - sink.RunAfter = pt.RunAfter - sink.Resources = pt.Resources - sink.Params = pt.Params - sink.Workspaces = pt.Workspaces - sink.Timeout = pt.Timeout - return nil -} - -// ConvertFrom implements api.Convertible -func (p *Pipeline) ConvertFrom(ctx context.Context, obj apis.Convertible) error { - switch source := obj.(type) { - case *v1beta1.Pipeline: - p.ObjectMeta = source.ObjectMeta - if err := serializeFinally(&p.ObjectMeta, source.Spec.Finally); err != nil { - return err - } - return p.Spec.ConvertFrom(ctx, source.Spec) - default: - return fmt.Errorf("unknown version, got: %T", p) - } -} - -// ConvertFrom implements api.Convertible -func (ps *PipelineSpec) ConvertFrom(ctx context.Context, source v1beta1.PipelineSpec) error { - ps.Resources = source.Resources - ps.Params = source.Params - ps.Workspaces = source.Workspaces - ps.Description = source.Description - if len(source.Tasks) > 0 { - ps.Tasks = make([]PipelineTask, len(source.Tasks)) - for i := range source.Tasks { - if err := ps.Tasks[i].ConvertFrom(ctx, source.Tasks[i]); err != nil { - return err - } - } - } - return nil -} - -// ConvertFrom implements api.Convertible -func (pt *PipelineTask) ConvertFrom(ctx context.Context, source v1beta1.PipelineTask) error { - pt.Name = source.Name - pt.TaskRef = source.TaskRef - if source.TaskSpec != nil { - pt.TaskSpec = &TaskSpec{} - if err := pt.TaskSpec.ConvertFrom(ctx, &source.TaskSpec.TaskSpec); err != nil { - return err - } - } - pt.Retries = source.Retries - pt.RunAfter = source.RunAfter - pt.Resources = source.Resources - pt.Params = source.Params - pt.Workspaces = source.Workspaces - pt.Timeout = source.Timeout - return nil -} - -// serializeFinally serializes a list of Finally Tasks to the annotations -// of an object's metadata section. This can then be used to re-instantiate -// the Finally Tasks when converting back up to v1beta1 and beyond. -func serializeFinally(meta *metav1.ObjectMeta, finally []v1beta1.PipelineTask) error { - if len(finally) != 0 { - b, err := json.Marshal(finally) - if err != nil { - return err - } - if meta.Annotations == nil { - meta.Annotations = make(map[string]string) - } - meta.Annotations[finallyAnnotationKey] = string(b) - } - return nil -} - -// deserializeFinally populates a PipelineSpec's Finally list -// from an annotation found on resources that have been previously -// converted down from v1beta1 to v1alpha1. -func deserializeFinally(meta *metav1.ObjectMeta, spec *v1beta1.PipelineSpec) error { - if meta.Annotations != nil { - if str, ok := meta.Annotations[finallyAnnotationKey]; ok { - finally := []v1beta1.PipelineTask{} - if err := json.Unmarshal([]byte(str), &finally); err != nil { - return fmt.Errorf("error converting finally annotation into beta field: %w", err) - } - delete(meta.Annotations, finallyAnnotationKey) - if len(meta.Annotations) == 0 { - meta.Annotations = nil - } - spec.Finally = finally - } - } - return nil -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_conversion_test.go b/pkg/apis/pipeline/v1alpha1/pipeline_conversion_test.go deleted file mode 100644 index 3adaa070b63..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_conversion_test.go +++ /dev/null @@ -1,249 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestPipelineConversionBadType(t *testing.T) { - good, bad := &Pipeline{}, &Task{} - - if err := good.ConvertTo(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } - - if err := good.ConvertFrom(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } -} - -func TestPipelineConversion_Success(t *testing.T) { - versions := []apis.Convertible{&v1beta1.Pipeline{}} - - tests := []struct { - name string - in *Pipeline - }{{ - name: "simple conversion", - in: &Pipeline{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: PipelineSpec{ - Description: "test", - Resources: []PipelineDeclaredResource{{ - Name: "resource1", - Type: resource.PipelineResourceTypeGit, - }, { - Name: "resource2", - Type: resource.PipelineResourceTypeImage, - }}, - Params: []ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - Workspaces: []PipelineWorkspaceDeclaration{{ - Name: "workspace1", - }}, - Tasks: []PipelineTask{{ - Name: "task1", - TaskRef: &TaskRef{ - Name: "taskref", - }, - Retries: 10, - RunAfter: []string{"task1"}, - Resources: &PipelineTaskResources{ - Inputs: []v1beta1.PipelineTaskInputResource{{ - Name: "input1", - Resource: "resource1", - }}, - Outputs: []v1beta1.PipelineTaskOutputResource{{ - Name: "output1", - Resource: "resource2", - }}, - }, - Params: []Param{{ - Name: "param1", - Value: *v1beta1.NewArrayOrString("str"), - }}, - Workspaces: []WorkspacePipelineTaskBinding{{ - Name: "w1", - Workspace: "workspace1", - }}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - }, { - Name: "task2", - TaskSpec: &TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - }}, - RunAfter: []string{"task1"}, - }}, - }, - }, - }} - - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - // convert v1alpha1 Pipeline to v1beta1 Pipeline - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - t.Errorf("ConvertTo() = %v", err) - } - got := &Pipeline{} - // converting it back to v1alpha1 pipeline and storing it in got variable to compare with original input - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - // compare origin input and roundtrip Pipeline i.e. v1alpha1 pipeline converted to v1beta1 and then converted back to v1alpha1 - // this check is making sure that we do not end up with different object than what we started with - if d := cmp.Diff(test.in, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} - -func TestPipelineConversion_Failure(t *testing.T) { - versions := []apis.Convertible{&v1beta1.Pipeline{}} - - tests := []struct { - name string - in *Pipeline - }{{ - name: "simple conversion with task spec error", - in: &Pipeline{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: PipelineSpec{ - Params: []ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - Tasks: []PipelineTask{{ - Name: "task2", - TaskSpec: &TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - Inputs: &Inputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }}, - RunAfter: []string{"task1"}, - }}, - }, - }, - }} - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err == nil { - t.Errorf("Expected ConvertTo to fail but did not produce any error") - } - return - }) - } - } -} - -func TestPipelineConversionFromWithFinally(t *testing.T) { - versions := []apis.Convertible{&v1beta1.Pipeline{}} - p := &Pipeline{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: PipelineSpec{ - Tasks: []PipelineTask{{Name: "mytask", TaskRef: &TaskRef{Name: "task"}}}, - }, - } - for _, version := range versions { - t.Run("finally not available in v1alpha1", func(t *testing.T) { - ver := version - // convert v1alpha1 to v1beta1 - if err := p.ConvertTo(context.Background(), ver); err != nil { - t.Errorf("ConvertTo() = %v", err) - } - source := ver - source.(*v1beta1.Pipeline).Spec.Finally = []v1beta1.PipelineTask{{Name: "finaltask", TaskRef: &TaskRef{Name: "task"}}} - got := &Pipeline{} - if err := got.ConvertFrom(context.Background(), source); err != nil { - t.Errorf("ConvertFrom() should have failed") - } - }) - } -} - -func TestPipelineConversionFromBetaToAlphaWithFinally(t *testing.T) { - p := &v1beta1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: v1beta1.PipelineSpec{ - Tasks: []v1beta1.PipelineTask{{Name: "mytask", TaskRef: &TaskRef{Name: "task"}}}, - Finally: []v1beta1.PipelineTask{{Name: "myfinallytask", TaskRef: &TaskRef{Name: "task"}}}, - }, - } - t.Run("finally stored by v1alpha1 and rehydrated for v1beta1", func(t *testing.T) { - downgrade := &Pipeline{} - if err := downgrade.ConvertFrom(context.Background(), p); err != nil { - t.Errorf("error converting from v1beta1 with finally field to v1alpha1 with finally annotation: %v", err) - } - upgrade := &v1beta1.Pipeline{} - if err := downgrade.ConvertTo(context.Background(), upgrade); err != nil { - t.Errorf("error converting from v1alpha1 with finally annotation to v1beta1 with finally field: %v", err) - } - if d := cmp.Diff(p, upgrade); d != "" { - t.Errorf("unexpected difference between v1beta1 with finally field and round-tripped v1beta1 with finally field: %s", diff.PrintWantGot(d)) - } - }) -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_defaults.go b/pkg/apis/pipeline/v1alpha1/pipeline_defaults.go deleted file mode 100644 index 2bb226c034d..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_defaults.go +++ /dev/null @@ -1,47 +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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -var _ apis.Defaultable = (*Pipeline)(nil) - -// SetDefaults sets default values on the Pipeline's Spec -func (p *Pipeline) SetDefaults(ctx context.Context) { - p.Spec.SetDefaults(ctx) -} - -// SetDefaults sets default values for the PipelineSpec's Params and Tasks -func (ps *PipelineSpec) SetDefaults(ctx context.Context) { - for _, pt := range ps.Tasks { - if pt.TaskRef != nil { - if pt.TaskRef.Kind == "" { - pt.TaskRef.Kind = NamespacedTaskKind - } - } - if pt.TaskSpec != nil { - pt.TaskSpec.SetDefaults(ctx) - } - } - for i := range ps.Params { - ps.Params[i].SetDefaults(ctx) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_interface.go b/pkg/apis/pipeline/v1alpha1/pipeline_interface.go deleted file mode 100644 index 70e14bb7749..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_interface.go +++ /dev/null @@ -1,26 +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 v1alpha1 - -import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - -// PipelineObject is implemented by Pipeline and ClusterPipeline -type PipelineObject interface { - PipelineMetadata() metav1.ObjectMeta - PipelineSpec() PipelineSpec - Copy() PipelineObject -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_resource_types.go b/pkg/apis/pipeline/v1alpha1/pipeline_resource_types.go deleted file mode 100644 index d35e41bf1b4..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_resource_types.go +++ /dev/null @@ -1,74 +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 v1alpha1 - -import ( - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" -) - -// PipelineResourceType represents the type of endpoint the pipelineResource is, so that the -// controller will know this pipelineResource should be fetched and optionally what -// additional metatdata should be provided for it. -type PipelineResourceType = resource.PipelineResourceType - -const ( - // PipelineResourceTypeGit indicates that this source is a Git repo. - PipelineResourceTypeGit PipelineResourceType = resource.PipelineResourceTypeGit - - // PipelineResourceTypeStorage indicates that this source is a storage blob resource. - PipelineResourceTypeStorage PipelineResourceType = resource.PipelineResourceTypeStorage - - // PipelineResourceTypeImage indicates that this source is a docker Image. - PipelineResourceTypeImage PipelineResourceType = resource.PipelineResourceTypeImage - - // PipelineResourceTypeCluster indicates that this source is a k8s cluster Image. - PipelineResourceTypeCluster PipelineResourceType = resource.PipelineResourceTypeCluster - - // 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. -var AllResourceTypes = resource.AllResourceTypes - -// PipelineResource describes a resource that is an input to or output from a -// Task. -// -type PipelineResource = resource.PipelineResource - -// PipelineResourceSpec defines an individual resources used in the pipeline. -type PipelineResourceSpec = resource.PipelineResourceSpec - -// SecretParam indicates which secret can be used to populate a field of the resource -type SecretParam = resource.SecretParam - -// ResourceParam declares a string value to use for the parameter called Name, and is used in -// the specific context of PipelineResources. -type ResourceParam = resource.ResourceParam - -// ResourceDeclaration defines an input or output PipelineResource declared as a requirement -// by another type such as a Task or Condition. The Name field will be used to refer to these -// PipelineResources within the type's definition, and when provided as an Input, the Name will be the -// path to the volume mounted containing this PipelineResource as an input (e.g. -// an input Resource named `workspace` will be mounted at `/workspace`). -type ResourceDeclaration = resource.ResourceDeclaration - -// PipelineResourceList contains a list of PipelineResources -type PipelineResourceList = resource.PipelineResourceList diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_types.go b/pkg/apis/pipeline/v1alpha1/pipeline_types.go deleted file mode 100644 index 6067f2d971a..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_types.go +++ /dev/null @@ -1,236 +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 v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// PipelineSpec defines the desired state of Pipeline. -type PipelineSpec struct { - // Description is a user-facing description of the pipeline that may be - // used to populate a UI. - // +optional - Description string `json:"description,omitempty"` - // Resources declares the names and types of the resources given to the - // Pipeline's tasks as inputs and outputs. - Resources []PipelineDeclaredResource `json:"resources,omitempty"` - // Tasks declares the graph of Tasks that execute when this Pipeline is run. - Tasks []PipelineTask `json:"tasks,omitempty"` - // Params declares a list of input parameters that must be supplied when - // this Pipeline is run. - Params []ParamSpec `json:"params,omitempty"` - // Workspaces declares a set of named workspaces that are expected to be - // provided by a PipelineRun. - // +optional - Workspaces []PipelineWorkspaceDeclaration `json:"workspaces,omitempty"` - // Results are values that this pipeline can output once run - // +optional - Results []PipelineResult `json:"results,omitempty"` -} - -// PipelineResult used to describe the results of a pipeline -type PipelineResult = v1beta1.PipelineResult - -// Check that Pipeline may be validated and defaulted. - -// TaskKind defines the type of Task used by the pipeline. -type TaskKind = v1beta1.TaskKind - -const ( - // NamespacedTaskKind indicates that the task type has a namepace scope. - NamespacedTaskKind TaskKind = v1beta1.NamespacedTaskKind - // ClusterTaskKind indicates that task type has a cluster scope. - ClusterTaskKind TaskKind = v1beta1.ClusterTaskKind -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +genclient:noStatus - -// Pipeline describes a list of Tasks to execute. It expresses how outputs -// of tasks feed into inputs of subsequent tasks. -// +k8s:openapi-gen=true -type Pipeline struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec holds the desired state of the Pipeline from the client - // +optional - Spec PipelineSpec `json:"spec"` - - // Status is deprecated. - // It usually is used to communicate the observed state of the Pipeline from - // the controller, but was unused as there is no controller for Pipeline. - // +optional - Status *PipelineStatus `json:"status,omitempty"` -} - -// PipelineStatus does not contain anything because Pipelines on their own -// do not have a status, they just hold data which is later used by a -// PipelineRun. -// Deprecated -type PipelineStatus struct { -} - -// PipelineMetadata returns the Pipeline's ObjectMeta, implementing PipelineObject. -func (p *Pipeline) PipelineMetadata() metav1.ObjectMeta { - return p.ObjectMeta -} - -// PipelineSpec returns the Pipeline's Spec, implementing PipelineObject. -func (p *Pipeline) PipelineSpec() PipelineSpec { - return p.Spec -} - -// Copy returns a deep copy of the Pipeline, implementing PipelineObject. -func (p *Pipeline) Copy() PipelineObject { - return p.DeepCopy() -} - -// PipelineTask defines a task in a Pipeline, passing inputs from both -// Params and from the output of previous tasks. -type PipelineTask struct { - // Name is the name of this task within the context of a Pipeline. Name is - // used as a coordinate with the `from` and `runAfter` fields to establish - // the execution order of tasks relative to one another. - Name string `json:"name,omitempty"` - - // TaskRef is a reference to a task definition. - // +optional - TaskRef *TaskRef `json:"taskRef,omitempty"` - - // TaskSpec is specification of a task - // +optional - TaskSpec *TaskSpec `json:"taskSpec,omitempty"` - - // Retries represents how many times this task should be retried in case of task failure: ConditionSucceeded set to False - // +optional - Retries int `json:"retries,omitempty"` - - // RunAfter is the list of PipelineTask names that should be executed before - // this Task executes. (Used to force a specific ordering in graph execution.) - // +optional - RunAfter []string `json:"runAfter,omitempty"` - - // Resources declares the resources given to this task as inputs and - // outputs. - // +optional - Resources *PipelineTaskResources `json:"resources,omitempty"` - // Parameters declares parameters passed to this task. - // +optional - Params []Param `json:"params,omitempty"` - - // Workspaces maps workspaces from the pipeline spec to the workspaces - // declared in the Task. - // +optional - Workspaces []WorkspacePipelineTaskBinding `json:"workspaces,omitempty"` - - // Time after which the TaskRun times out. Defaults to 1 hour. - // Specified TaskRun timeout should be less than 24h. - // Refer Go's ParseDuration documentation for expected format: https://golang.org/pkg/time/#ParseDuration - // +optional - Timeout *metav1.Duration `json:"timeout,omitempty"` -} - -// HashKey is used as the key for this PipelineTask in the DAG -func (pt PipelineTask) HashKey() string { - return pt.Name -} - -// Deps returns all other PipelineTask dependencies of this PipelineTask, based on resource usage or ordering -func (pt PipelineTask) Deps() []string { - deps := []string{} - deps = append(deps, pt.RunAfter...) - if pt.Resources != nil { - for _, rd := range pt.Resources.Inputs { - deps = append(deps, rd.From...) - } - } - // Add any dependents from task results - for _, param := range pt.Params { - expressions, ok := v1beta1.GetVarSubstitutionExpressionsForParam(param) - if ok { - resultRefs := v1beta1.NewResultRefs(expressions) - for _, resultRef := range resultRefs { - deps = append(deps, resultRef.PipelineTask) - } - } - } - - return deps -} - -// PipelineTaskList is a list of PipelineTasks -type PipelineTaskList []PipelineTask - -// Items returns a slice of all tasks in the PipelineTaskList, converted to dag.Tasks -func (l PipelineTaskList) Items() []dag.Task { - tasks := []dag.Task{} - for _, t := range l { - tasks = append(tasks, dag.Task(t)) - } - return tasks -} - -// Deps returns a map with key as name of a pipelineTask and value as a list of its dependencies -func (l PipelineTaskList) Deps() map[string][]string { - deps := map[string][]string{} - for _, pt := range l { - deps[pt.HashKey()] = pt.Deps() - } - return deps -} - -// PipelineTaskParam is used to provide arbitrary string parameters to a Task. -type PipelineTaskParam = v1beta1.PipelineTaskParam - -// PipelineDeclaredResource is used by a Pipeline to declare the types of the -// PipelineResources that it will required to run and names which can be used to -// refer to these PipelineResources in PipelineTaskResourceBindings. -type PipelineDeclaredResource = v1beta1.PipelineDeclaredResource - -// PipelineTaskResources allows a Pipeline to declare how its DeclaredPipelineResources -// should be provided to a Task as its inputs and outputs. -type PipelineTaskResources = v1beta1.PipelineTaskResources - -// PipelineTaskInputResource maps the name of a declared PipelineResource input -// dependency in a Task to the resource in the Pipeline's DeclaredPipelineResources -// that should be used. This input may come from a previous task. -type PipelineTaskInputResource = v1beta1.PipelineTaskInputResource - -// PipelineTaskOutputResource maps the name of a declared PipelineResource output -// dependency in a Task to the resource in the Pipeline's DeclaredPipelineResources -// that should be used. -type PipelineTaskOutputResource = v1beta1.PipelineTaskOutputResource - -// TaskRef can be used to refer to a specific instance of a task. -// Copied from CrossVersionObjectReference: https://github.com/kubernetes/kubernetes/blob/169df7434155cbbc22f1532cba8e0a9588e29ad8/pkg/apis/autoscaling/types.go#L64 -type TaskRef = v1beta1.TaskRef - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// PipelineList contains a list of Pipeline -type PipelineList struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - Items []Pipeline `json:"items"` -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_validation.go b/pkg/apis/pipeline/v1alpha1/pipeline_validation.go deleted file mode 100644 index 7d8f985b1ae..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_validation.go +++ /dev/null @@ -1,325 +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 v1alpha1 - -import ( - "context" - "fmt" - "strings" - - "github.com/tektoncd/pipeline/pkg/apis/validate" - "github.com/tektoncd/pipeline/pkg/list" - "github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag" - "github.com/tektoncd/pipeline/pkg/substitution" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/validation" - "knative.dev/pkg/apis" -) - -var _ apis.Validatable = (*Pipeline)(nil) - -// Validate checks that the Pipeline structure is valid but does not validate -// that any references resources exist, that is done at run time. -func (p *Pipeline) Validate(ctx context.Context) *apis.FieldError { - if err := validate.ObjectMetadata(p.GetObjectMeta()); err != nil { - return err.ViaField("metadata") - } - if apis.IsInDelete(ctx) { - return nil - } - return p.Spec.Validate(ctx) -} - -func validateDeclaredResources(ps *PipelineSpec) error { - encountered := sets.NewString() - for _, r := range ps.Resources { - if encountered.Has(r.Name) { - return fmt.Errorf("resource with name %q appears more than once", r.Name) - } - encountered.Insert(r.Name) - } - required := []string{} - for _, t := range ps.Tasks { - if t.Resources != nil { - for _, input := range t.Resources.Inputs { - required = append(required, input.Resource) - } - for _, output := range t.Resources.Outputs { - required = append(required, output.Resource) - } - } - } - - provided := make([]string, 0, len(ps.Resources)) - for _, resource := range ps.Resources { - provided = append(provided, resource.Name) - } - missing := list.DiffLeft(required, provided) - if len(missing) > 0 { - return fmt.Errorf("pipeline declared resources didn't match usage in Tasks: Didn't provide required values: %s", missing) - } - - return nil -} - -func isOutput(outputs []PipelineTaskOutputResource, resource string) bool { - for _, output := range outputs { - if output.Resource == resource { - return true - } - } - return false -} - -// validateFrom ensures that the `from` values make sense: that they rely on values from Tasks -// that ran previously, and that the PipelineResource is actually an output of the Task it should come from. -func validateFrom(tasks []PipelineTask) *apis.FieldError { - taskOutputs := map[string][]PipelineTaskOutputResource{} - for _, task := range tasks { - var to []PipelineTaskOutputResource - if task.Resources != nil { - to = make([]PipelineTaskOutputResource, len(task.Resources.Outputs)) - copy(to, task.Resources.Outputs) - } - taskOutputs[task.Name] = to - } - for _, t := range tasks { - inputResources := []PipelineTaskInputResource{} - if t.Resources != nil { - inputResources = append(inputResources, t.Resources.Inputs...) - } - - for _, rd := range inputResources { - for _, pt := range rd.From { - outputs, found := taskOutputs[pt] - if !found { - return apis.ErrInvalidValue(fmt.Sprintf("expected resource %s to be from task %s, but task %s doesn't exist", rd.Resource, pt, pt), - "spec.tasks.resources.inputs.from") - } - if !isOutput(outputs, rd.Resource) { - return apis.ErrInvalidValue(fmt.Sprintf("the resource %s from %s must be an output but is an input", rd.Resource, pt), - "spec.tasks.resources.inputs.from") - } - } - } - } - return nil -} - -// validateGraph ensures the Pipeline's dependency Graph (DAG) make sense: that there is no dependency -// cycle or that they rely on values from Tasks that ran previously, and that the PipelineResource -// is actually an output of the Task it should come from. -func validateGraph(tasks []PipelineTask) error { - if _, err := dag.Build(PipelineTaskList(tasks), PipelineTaskList(tasks).Deps()); err != nil { - return err - } - return nil -} - -// Validate checks that taskNames in the Pipeline are valid and that the graph -// of Tasks expressed in the Pipeline makes sense. -func (ps *PipelineSpec) Validate(ctx context.Context) *apis.FieldError { - if equality.Semantic.DeepEqual(ps, &PipelineSpec{}) { - return apis.ErrGeneric("expected at least one, got none", "spec.description", "spec.params", "spec.resources", "spec.tasks", "spec.workspaces") - } - - // PipelineTask must have a valid unique label and at least one of taskRef or taskSpec should be specified - if err := validatePipelineTasks(ctx, ps.Tasks); err != nil { - return err - } - - // All declared resources should be used, and the Pipeline shouldn't try to use any resources - // that aren't declared - if err := validateDeclaredResources(ps); err != nil { - return apis.ErrInvalidValue(err.Error(), "spec.resources") - } - - // The from values should make sense - if err := validateFrom(ps.Tasks); err != nil { - return err - } - - // Validate the pipeline task graph - if err := validateGraph(ps.Tasks); err != nil { - return apis.ErrInvalidValue(err.Error(), "spec.tasks") - } - - // The parameter variables should be valid - if err := validatePipelineParameterVariables(ps.Tasks, ps.Params); err != nil { - return err - } - - // Validate the pipeline's workspaces. - return validatePipelineWorkspaces(ps.Workspaces, ps.Tasks) -} - -func validatePipelineTasks(ctx context.Context, tasks []PipelineTask) *apis.FieldError { - // Names cannot be duplicated - taskNames := sets.NewString() - var err *apis.FieldError - for i, t := range tasks { - if err = validatePipelineTaskName(ctx, "spec.tasks", i, t, taskNames); err != nil { - return err - } - } - return nil -} - -func validatePipelineTaskName(ctx context.Context, prefix string, i int, t PipelineTask, taskNames sets.String) *apis.FieldError { - if errs := validation.IsDNS1123Label(t.Name); len(errs) > 0 { - return &apis.FieldError{ - Message: fmt.Sprintf("invalid value %q", t.Name), - Paths: []string{fmt.Sprintf(prefix+"[%d].name", i)}, - Details: "Pipeline Task name must be a valid DNS Label." + - "For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - } - } - // can't have both taskRef and taskSpec at the same time - if (t.TaskRef != nil && t.TaskRef.Name != "") && t.TaskSpec != nil { - return apis.ErrMultipleOneOf(fmt.Sprintf(prefix+"[%d].taskRef", i), fmt.Sprintf(prefix+"[%d].taskSpec", i)) - } - // Check that one of TaskRef and TaskSpec is present - if (t.TaskRef == nil || (t.TaskRef != nil && t.TaskRef.Name == "")) && t.TaskSpec == nil { - return apis.ErrMissingOneOf(fmt.Sprintf(prefix+"[%d].taskRef", i), fmt.Sprintf(prefix+"[%d].taskSpec", i)) - } - // Validate TaskSpec if it's present - if t.TaskSpec != nil { - if err := t.TaskSpec.Validate(ctx); err != nil { - return err - } - } - if t.TaskRef != nil && t.TaskRef.Name != "" { - // Task names are appended to the container name, which must exist and - // must be a valid k8s name - if errSlice := validation.IsQualifiedName(t.Name); len(errSlice) != 0 { - return apis.ErrInvalidValue(strings.Join(errSlice, ","), fmt.Sprintf(prefix+"[%d].name", i)) - } - // TaskRef name must be a valid k8s name - if errSlice := validation.IsQualifiedName(t.TaskRef.Name); len(errSlice) != 0 { - return apis.ErrInvalidValue(strings.Join(errSlice, ","), fmt.Sprintf(prefix+"[%d].taskRef.name", i)) - } - if _, ok := taskNames[t.Name]; ok { - return apis.ErrMultipleOneOf(fmt.Sprintf(prefix+"[%d].name", i)) - } - taskNames[t.Name] = struct{}{} - } - return nil -} - -func validatePipelineWorkspaces(wss []PipelineWorkspaceDeclaration, pts []PipelineTask) *apis.FieldError { - // Workspace names must be non-empty and unique. - wsTable := sets.NewString() - for i, ws := range wss { - if ws.Name == "" { - return apis.ErrInvalidValue(fmt.Sprintf("workspace %d has empty name", i), "spec.workspaces") - } - if wsTable.Has(ws.Name) { - return apis.ErrInvalidValue(fmt.Sprintf("workspace with name %q appears more than once", ws.Name), "spec.workspaces") - } - wsTable.Insert(ws.Name) - } - - // Any workspaces used in PipelineTasks should have their name declared in the Pipeline's - // Workspaces list. - for ptIdx, pt := range pts { - for wsIdx, ws := range pt.Workspaces { - if _, ok := wsTable[ws.Workspace]; !ok { - return apis.ErrInvalidValue( - fmt.Sprintf("pipeline task %q expects workspace with name %q but none exists in pipeline spec", pt.Name, ws.Workspace), - fmt.Sprintf("spec.tasks[%d].workspaces[%d]", ptIdx, wsIdx), - ) - } - } - } - return nil -} - -func validatePipelineParameterVariables(tasks []PipelineTask, params []ParamSpec) *apis.FieldError { - parameterNames := sets.NewString() - arrayParameterNames := sets.NewString() - - for _, p := range params { - // Verify that p is a valid type. - validType := false - for _, allowedType := range AllParamTypes { - if p.Type == allowedType { - validType = true - } - } - if !validType { - return apis.ErrInvalidValue(string(p.Type), fmt.Sprintf("spec.params.%s.type", p.Name)) - } - - // If a default value is provided, ensure its type matches param's declared type. - if (p.Default != nil) && (p.Default.Type != p.Type) { - return &apis.FieldError{ - Message: fmt.Sprintf( - "\"%v\" type does not match default value's type: \"%v\"", p.Type, p.Default.Type), - Paths: []string{ - fmt.Sprintf("spec.params.%s.type", p.Name), - fmt.Sprintf("spec.params.%s.default.type", p.Name), - }, - } - } - - // Add parameter name to parameterNames, and to arrayParameterNames if type is array. - parameterNames.Insert(p.Name) - if p.Type == ParamTypeArray { - arrayParameterNames.Insert(p.Name) - } - } - - return validatePipelineVariables(tasks, "params", parameterNames, arrayParameterNames) -} - -func validatePipelineVariables(tasks []PipelineTask, prefix string, paramNames sets.String, arrayParamNames sets.String) *apis.FieldError { - for _, task := range tasks { - for _, param := range task.Params { - if param.Value.Type == ParamTypeString { - if err := validatePipelineVariable(fmt.Sprintf("param[%s]", param.Name), param.Value.StringVal, prefix, paramNames); err != nil { - return err - } - if err := validatePipelineNoArrayReferenced(fmt.Sprintf("param[%s]", param.Name), param.Value.StringVal, prefix, arrayParamNames); err != nil { - return err - } - } else { - for _, arrayElement := range param.Value.ArrayVal { - if err := validatePipelineVariable(fmt.Sprintf("param[%s]", param.Name), arrayElement, prefix, paramNames); err != nil { - return err - } - if err := validatePipelineArraysIsolated(fmt.Sprintf("param[%s]", param.Name), arrayElement, prefix, arrayParamNames); err != nil { - return err - } - } - } - } - } - return nil -} - -func validatePipelineVariable(name, value, prefix string, vars sets.String) *apis.FieldError { - return substitution.ValidateVariable(name, value, prefix, "task parameter", "pipelinespec.params", vars) -} - -func validatePipelineNoArrayReferenced(name, value, prefix string, vars sets.String) *apis.FieldError { - return substitution.ValidateVariableProhibited(name, value, prefix, "task parameter", "pipelinespec.params", vars) -} - -func validatePipelineArraysIsolated(name, value, prefix string, vars sets.String) *apis.FieldError { - return substitution.ValidateVariableIsolated(name, value, prefix, "task parameter", "pipelinespec.params", vars) -} diff --git a/pkg/apis/pipeline/v1alpha1/pipeline_validation_test.go b/pkg/apis/pipeline/v1alpha1/pipeline_validation_test.go deleted file mode 100644 index 4bebf96f8ed..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipeline_validation_test.go +++ /dev/null @@ -1,763 +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 v1alpha1_test - -import ( - "context" - "strings" - "testing" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1beta1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestPipeline_Validate(t *testing.T) { - for _, tt := range []struct { - name string - p *v1alpha1.Pipeline - failureExpected bool - }{{ - name: "valid metadata", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: false, - }, { - name: "comma in name", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipe,line"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline name too long", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: strings.Repeat("a", 64)}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec missing", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - }, - failureExpected: true, - }, { - name: "pipeline spec invalid (duplicate tasks)", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }, { - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec empty task name", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec invalid task name", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "_foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec invalid task name (capital)", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "Foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec invalid taskref name", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "_foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec missing taskfref and taskspec", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec with taskref and taskspec", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "foo", - Image: "bar", - }}, - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec invalid taskspec", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskSpec: &v1alpha1.TaskSpec{}, - }}, - }, - }, - failureExpected: true, - }, { - name: "pipeline spec valid taskspec", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "foo", - Image: "bar", - }}, - }}, - }}, - }, - }, - failureExpected: false, - }, { - name: "no duplicate tasks", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }, { - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - }}, - }, - }, - failureExpected: false, - }, { - // Adding this case because `task.Resources` is a pointer, explicitly making sure this is handled - name: "task without resources", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "wonderful-resource", - Type: v1alpha1.PipelineResourceTypeImage, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "wow-image", Resource: "wonderful-resource", - }}, - }, - }, { - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - }}, - }, - }, - failureExpected: false, - }, { - name: "valid resource declarations and usage", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }, { - Name: "wonderful-resource", - Type: v1alpha1.PipelineResourceTypeImage, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "wow-image", Resource: "wonderful-resource", From: []string{"bar"}, - }}, - }, - }, { - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "some-workspace", Resource: "great-resource", - }}, - Outputs: []v1alpha1.PipelineTaskOutputResource{{ - Name: "some-image", Resource: "wonderful-resource", - }}, - }, - }}, - }, - }, - failureExpected: false, - }, { - name: "valid parameter variables", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeString, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeString, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(baz) and $(foo-is-baz)"), - }}, - }}, - }, - }, - failureExpected: false, - }, { - name: "valid array parameter variables", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("some", "default"), - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(baz)", "and", "$(foo-is-baz)"), - }}, - }}, - }, - }, - failureExpected: false, - }, { - name: "valid star array parameter variables", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("some", "default"), - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(baz[*])", "and", "$(foo-is-baz[*])"), - }}, - }}, - }, - }, - failureExpected: false, - }, { - name: "pipeline parameter nested in task parameter", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeString, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(input.workspace.$(baz))"), - }}, - }}, - }, - }, - failureExpected: false, - }, { - name: "from is on only task", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "the-resource", Resource: "great-resource", From: []string{"bar"}, - }}, - }, - }}, - }, - }, - failureExpected: true, - }, { - name: "from task doesnt exist", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "the-resource", Resource: "great-resource", From: []string{"bazzz"}, - }}, - }, - }, { - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "duplicate resource declaration", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }, { - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "the-resource", Resource: "great-resource", - }}, - }, - }}, - }, - }, - failureExpected: true, - }, { - name: "output resources missing from declaration", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "the-resource", Resource: "great-resource", - }}, - Outputs: []v1alpha1.PipelineTaskOutputResource{{ - Name: "the-magic-resource", Resource: "missing-resource", - }}, - }, - }}, - }, - }, - failureExpected: true, - }, { - name: "input resources missing from declaration", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "the-resource", Resource: "missing-resource", - }}, - Outputs: []v1alpha1.PipelineTaskOutputResource{{ - Name: "the-magic-resource", Resource: "great-resource", - }}, - }, - }}, - }, - }, - failureExpected: true, - }, { - name: "from resource isn't output by task", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Resources: []v1alpha1.PipelineDeclaredResource{{ - Name: "great-resource", - Type: v1alpha1.PipelineResourceTypeGit, - }, { - Name: "wonderful-resource", - Type: v1alpha1.PipelineResourceTypeImage, - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "some-workspace", Resource: "great-resource", - }}, - }, - }, { - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - Resources: &v1alpha1.PipelineTaskResources{ - Inputs: []v1alpha1.PipelineTaskInputResource{{ - Name: "wow-image", Resource: "wonderful-resource", From: []string{"bar"}, - }}, - }, - }}, - }, - }, - failureExpected: true, - }, { - name: "not defined parameter variable", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(params.does-not-exist)"), - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "not defined parameter variable with defined", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "foo", - Type: v1alpha1.ParamTypeString, - Default: v1beta1.NewArrayOrString("something"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(params.foo) and $(params.does-not-exist)"), - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "invalid parameter type", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamType("invalidtype"), - Default: v1beta1.NewArrayOrString("some", "default"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "array parameter mismatching default type", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("astring"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "string parameter mismatching default type", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeString, - Default: v1beta1.NewArrayOrString("an", "array"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "array parameter used as string", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("an", "array"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(params.baz)"), - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "star array parameter used as string", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("an", "array"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("$(params.baz[*])"), - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "array parameter string template not isolated", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "a-param", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("an", "array"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("first", "value: $(params.baz)", "last"), - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "star array parameter string template not isolated", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "a-param", - Type: v1alpha1.ParamTypeArray, - Default: v1beta1.NewArrayOrString("an", "array"), - }}, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Params: []v1alpha1.Param{{ - Name: "a-param", - Value: *v1beta1.NewArrayOrString("first", "value: $(params.baz[*])", "last"), - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "circular dependency graph between the tasks", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - RunAfter: []string{"bar"}, - }, { - Name: "bar", - TaskRef: &v1alpha1.TaskRef{Name: "bar-task"}, - RunAfter: []string{"foo"}, - }}, - }, - }, - failureExpected: true, - }, { - name: "unused pipeline spec workspaces do not cause an error", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Workspaces: []v1alpha1.PipelineWorkspaceDeclaration{ - {Name: "foo"}, - {Name: "bar"}, - }, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: false, - }, { - name: "workspace bindings relying on a non-existent pipeline workspace cause an error", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Workspaces: []v1alpha1.PipelineWorkspaceDeclaration{ - {Name: "foo"}, - }, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - Workspaces: []v1alpha1.WorkspacePipelineTaskBinding{{ - Name: "taskWorkspaceName", Workspace: "pipelineWorkspaceName", - }}, - }}, - }, - }, - failureExpected: true, - }, { - name: "multiple workspaces sharing the same name are not allowed", - p: &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: v1alpha1.PipelineSpec{ - Workspaces: []v1alpha1.PipelineWorkspaceDeclaration{ - {Name: "foo"}, - {Name: "foo"}, - }, - Tasks: []v1alpha1.PipelineTask{{ - Name: "foo", - TaskRef: &v1alpha1.TaskRef{Name: "foo-task"}, - }}, - }, - }, - failureExpected: true, - }} { - t.Run(tt.name, func(t *testing.T) { - err := tt.p.Validate(context.Background()) - if (!tt.failureExpected) && (err != nil) { - t.Errorf("Pipeline.Validate() returned error: %v", err) - } - - if tt.failureExpected && (err == nil) { - t.Error("Pipeline.Validate() did not return error, wanted error") - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_conversion.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_conversion.go deleted file mode 100644 index 6a89f523823..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_conversion.go +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "knative.dev/pkg/apis" -) - -var _ apis.Convertible = (*PipelineRun)(nil) - -// ConvertTo implements api.Convertible -func (pr *PipelineRun) ConvertTo(ctx context.Context, obj apis.Convertible) error { - switch sink := obj.(type) { - case *v1beta1.PipelineRun: - sink.ObjectMeta = pr.ObjectMeta - if err := pr.Spec.ConvertTo(ctx, &sink.Spec); err != nil { - return err - } - sink.Status = pr.Status - - spec := &v1beta1.PipelineSpec{} - if err := deserializeFinally(&sink.ObjectMeta, spec); err != nil { - return err - } - if len(spec.Finally) > 0 { - if sink.Spec.PipelineSpec == nil { - sink.Spec.PipelineSpec = spec - } else { - sink.Spec.PipelineSpec.Finally = spec.Finally - } - } - return nil - default: - return fmt.Errorf("unknown version, got: %T", sink) - } -} - -// ConvertTo implements api.Convertible -func (prs *PipelineRunSpec) ConvertTo(ctx context.Context, sink *v1beta1.PipelineRunSpec) error { - sink.PipelineRef = prs.PipelineRef - if prs.PipelineSpec != nil { - sink.PipelineSpec = &v1beta1.PipelineSpec{} - if err := prs.PipelineSpec.ConvertTo(ctx, sink.PipelineSpec); err != nil { - return err - } - } - sink.Resources = prs.Resources - sink.Params = prs.Params - sink.ServiceAccountName = prs.ServiceAccountName - sink.Status = prs.Status - sink.Timeout = prs.Timeout - sink.PodTemplate = prs.PodTemplate - sink.Workspaces = prs.Workspaces - return nil -} - -// ConvertFrom implements api.Convertible -func (pr *PipelineRun) ConvertFrom(ctx context.Context, obj apis.Convertible) error { - switch source := obj.(type) { - case *v1beta1.PipelineRun: - pr.ObjectMeta = source.ObjectMeta - if err := pr.Spec.ConvertFrom(ctx, &source.Spec); err != nil { - return err - } - pr.Status = source.Status - - ps := source.Spec.PipelineSpec - if ps != nil && ps.Finally != nil { - if err := serializeFinally(&pr.ObjectMeta, ps.Finally); err != nil { - return err - } - } - return nil - default: - return fmt.Errorf("unknown version, got: %T", pr) - } -} - -// ConvertFrom implements api.Convertible -func (prs *PipelineRunSpec) ConvertFrom(ctx context.Context, source *v1beta1.PipelineRunSpec) error { - prs.PipelineRef = source.PipelineRef - if source.PipelineSpec != nil { - prs.PipelineSpec = &PipelineSpec{} - if err := prs.PipelineSpec.ConvertFrom(ctx, *source.PipelineSpec); err != nil { - return err - } - } - prs.Resources = source.Resources - prs.Params = source.Params - prs.ServiceAccountName = source.ServiceAccountName - prs.Status = source.Status - prs.Timeout = source.Timeout - prs.PodTemplate = source.PodTemplate - prs.Workspaces = source.Workspaces - return nil -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_conversion_test.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_conversion_test.go deleted file mode 100644 index 8096c2fc4cd..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_conversion_test.go +++ /dev/null @@ -1,234 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestPipelineRunConversionBadType(t *testing.T) { - good, bad := &PipelineRun{}, &Pipeline{} - - if err := good.ConvertTo(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } - - if err := good.ConvertFrom(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } -} - -func TestPipelineRunConversion(t *testing.T) { - versions := []apis.Convertible{&v1beta1.PipelineRun{}} - - tests := []struct { - name string - in *PipelineRun - wantErr bool - }{{ - name: "simple conversion pipelineref", - in: &PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: PipelineRunSpec{ - PipelineRef: &PipelineRef{ - Name: "pipeline", - }, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Params: []Param{{ - Name: "p1", - Value: *v1beta1.NewArrayOrString("baz"), - }}, - Resources: []PipelineResourceBinding{{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }}, - }, - Status: PipelineRunStatus{ - PipelineRunStatusFields: PipelineRunStatusFields{ - StartTime: &metav1.Time{Time: time.Now().Add(-4 * time.Minute)}, - CompletionTime: &metav1.Time{Time: time.Now().Add(-1 * time.Minute)}, - TaskRuns: map[string]*PipelineRunTaskRunStatus{ - "foo-run": { - PipelineTaskName: "foo", - }, - }, - }, - }, - }, - }, { - name: "simple conversion pipelinespec", - in: &PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: PipelineRunSpec{ - PipelineSpec: &PipelineSpec{ - Tasks: []PipelineTask{{ - Name: "task1", - TaskRef: &TaskRef{ - Name: "taskref", - }, - }, { - Name: "task2", - TaskSpec: &TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - }}, - RunAfter: []string{"task1"}, - }}, - }, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Params: []Param{{ - Name: "p1", - Value: *v1beta1.NewArrayOrString("baz"), - }}, - Resources: []PipelineResourceBinding{{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }}, - }, - Status: PipelineRunStatus{ - PipelineRunStatusFields: PipelineRunStatusFields{ - StartTime: &metav1.Time{Time: time.Now().Add(-4 * time.Minute)}, - CompletionTime: &metav1.Time{Time: time.Now().Add(-1 * time.Minute)}, - TaskRuns: map[string]*PipelineRunTaskRunStatus{ - "foo-run": { - PipelineTaskName: "foo", - }, - }, - }, - }, - }, - }} - - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - if !test.wantErr { - t.Errorf("ConvertTo() = %v", err) - } - return - } - t.Logf("ConvertTo() = %#v", ver) - got := &PipelineRun{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.in, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} - -// TestBetaPipelineRunRoundTripDown tests PipelineRun converting downwards from -// v1beta1 to v1alpha1 and back again and to try and detect if information has -// been lost in the transitions. -func TestBetaPipelineRunRoundTripDown(t *testing.T) { - for _, test := range []struct { - name string - in *v1beta1.PipelineRun - }{{ - name: "nested pipelinespec with finally", - in: &v1beta1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: v1beta1.PipelineRunSpec{ - PipelineSpec: &v1beta1.PipelineSpec{ - Tasks: []v1beta1.PipelineTask{{ - Name: "task1", - TaskRef: &TaskRef{ - Name: "taskref", - }, - }}, - Finally: []v1beta1.PipelineTask{{ - Name: "finally1", - TaskRef: &TaskRef{ - Name: "finallytaskref", - }, - }}, - }, - }, - Status: PipelineRunStatus{ - PipelineRunStatusFields: PipelineRunStatusFields{ - StartTime: &metav1.Time{Time: time.Now().Add(-4 * time.Minute)}, - CompletionTime: &metav1.Time{Time: time.Now().Add(-1 * time.Minute)}, - TaskRuns: map[string]*PipelineRunTaskRunStatus{ - "foo-run": { - PipelineTaskName: "foo", - }, - }, - }, - }, - }, - }} { - t.Run(test.name, func(t *testing.T) { - alpha := &PipelineRun{} - beta := &v1beta1.PipelineRun{} - if err := alpha.ConvertFrom(context.Background(), test.in); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - if err := alpha.ConvertTo(context.Background(), beta); err != nil { - t.Errorf("ConvertTo() = %v", err) - } - if d := cmp.Diff(test.in, beta); d != "" { - t.Errorf("v1beta1 roundtrip %s", diff.PrintWantGot(d)) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_defaults.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_defaults.go deleted file mode 100644 index ce1f35ad08b..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_defaults.go +++ /dev/null @@ -1,55 +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 v1alpha1 - -import ( - "context" - "time" - - "github.com/tektoncd/pipeline/pkg/apis/config" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -var _ apis.Defaultable = (*PipelineRun)(nil) - -// SetDefaults implements apis.Defaultable -func (pr *PipelineRun) SetDefaults(ctx context.Context) { - pr.Spec.SetDefaults(ctx) -} - -// SetDefaults implements apis.Defaultable -func (prs *PipelineRunSpec) SetDefaults(ctx context.Context) { - cfg := config.FromContextOrDefaults(ctx) - if prs.Timeout == nil { - prs.Timeout = &metav1.Duration{Duration: time.Duration(cfg.Defaults.DefaultTimeoutMinutes) * time.Minute} - } - - defaultSA := cfg.Defaults.DefaultServiceAccount - if prs.ServiceAccountName == "" && defaultSA != "" { - prs.ServiceAccountName = defaultSA - } - - defaultPodTemplate := cfg.Defaults.DefaultPodTemplate - if prs.PodTemplate == nil { - prs.PodTemplate = defaultPodTemplate - } - - if prs.PipelineSpec != nil { - prs.PipelineSpec.SetDefaults(ctx) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_defaults_test.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_defaults_test.go deleted file mode 100644 index 7d22c4b6592..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_defaults_test.go +++ /dev/null @@ -1,257 +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 v1alpha1_test - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - logtesting "knative.dev/pkg/logging/testing" -) - -var ( - ignoreUnexportedResources = cmpopts.IgnoreUnexported() -) - -func TestPipelineRunSpec_SetDefaults(t *testing.T) { - cases := []struct { - desc string - prs *v1alpha1.PipelineRunSpec - want *v1alpha1.PipelineRunSpec - }{ - { - desc: "timeout is nil", - prs: &v1alpha1.PipelineRunSpec{}, - want: &v1alpha1.PipelineRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, - { - desc: "timeout is not nil", - prs: &v1alpha1.PipelineRunSpec{ - Timeout: &metav1.Duration{Duration: 500 * time.Millisecond}, - }, - want: &v1alpha1.PipelineRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 500 * time.Millisecond}, - }, - }, - { - desc: "pod template is nil", - prs: &v1alpha1.PipelineRunSpec{}, - want: &v1alpha1.PipelineRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, - { - desc: "pod template is not nil", - prs: &v1alpha1.PipelineRunSpec{ - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label": "value", - }, - }, - }, - want: &v1alpha1.PipelineRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label": "value", - }, - }, - }, - }, - } - for _, tc := range cases { - t.Run(tc.desc, func(t *testing.T) { - ctx := context.Background() - tc.prs.SetDefaults(ctx) - - if d := cmp.Diff(tc.want, tc.prs); d != "" { - t.Errorf("Mismatch of PipelineRunSpec %s", diff.PrintWantGot(d)) - } - }) - } - -} - -func TestPipelineRunDefaulting(t *testing.T) { - tests := []struct { - name string - in *v1alpha1.PipelineRun - want *v1alpha1.PipelineRun - wc func(context.Context) context.Context - }{{ - name: "empty no context", - in: &v1alpha1.PipelineRun{}, - want: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, - }, { - name: "PipelineRef default config context", - in: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - }, - }, - want: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "PipelineRef default config context with sa", - in: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - }, - }, - want: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - ServiceAccountName: "tekton", - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-service-account": "tekton", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "PipelineRef pod template is coming from default config pod template", - in: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - }, - }, - want: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - ServiceAccountName: "tekton", - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label": "value", - }, - }, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-service-account": "tekton", - "default-pod-template": "nodeSelector: { 'label': 'value' }", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "PipelineRef pod template takes precedence over default config pod template", - in: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label2": "value2", - }, - }, - }, - }, - want: &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "foo"}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - ServiceAccountName: "tekton", - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label2": "value2", - }, - }, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-service-account": "tekton", - "default-pod-template": "nodeSelector: { 'label': 'value' }", - }, - }) - return s.ToContext(ctx) - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - got := tc.in - ctx := context.Background() - if tc.wc != nil { - ctx = tc.wc(ctx) - } - got.SetDefaults(ctx) - if !cmp.Equal(got, tc.want, ignoreUnexportedResources) { - d := cmp.Diff(got, tc.want, ignoreUnexportedResources) - t.Errorf("SetDefaults %s", diff.PrintWantGot(d)) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_types.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_types.go deleted file mode 100644 index 2a3682b2da8..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_types.go +++ /dev/null @@ -1,205 +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 v1alpha1 - -import ( - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/clock" - "knative.dev/pkg/apis" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// PipelineRun represents a single execution of a Pipeline. PipelineRuns are how -// the graph of Tasks declared in a Pipeline are executed; they specify inputs -// to Pipelines such as parameter values and capture operational aspects of the -// Tasks execution such as service account and tolerations. Creating a -// PipelineRun creates TaskRuns for Tasks in the referenced Pipeline. -// -// +k8s:openapi-gen=true -type PipelineRun struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // +optional - Spec PipelineRunSpec `json:"spec,omitempty"` - // +optional - Status PipelineRunStatus `json:"status,omitempty"` -} - -// GetName returns the PipelineRun's name -func (pr *PipelineRun) GetName() string { - return pr.ObjectMeta.GetName() -} - -// PipelineRunSpec defines the desired state of PipelineRun -type PipelineRunSpec struct { - // +optional - PipelineRef *PipelineRef `json:"pipelineRef,omitempty"` - // +optional - PipelineSpec *PipelineSpec `json:"pipelineSpec,omitempty"` - // Resources is a list of bindings specifying which actual instances of - // PipelineResources to use for the resources the Pipeline has declared - // it needs. - Resources []PipelineResourceBinding `json:"resources,omitempty"` - // Params is a list of parameter names and values. - Params []Param `json:"params,omitempty"` - // +optional - ServiceAccountName string `json:"serviceAccountName,omitempty"` - // Used for cancelling a pipelinerun (and maybe more later on) - // +optional - Status PipelineRunSpecStatus `json:"status,omitempty"` - // Time after which the Pipeline times out. Defaults to never. - // Refer to Go's ParseDuration documentation for expected format: https://golang.org/pkg/time/#ParseDuration - // +optional - Timeout *metav1.Duration `json:"timeout,omitempty"` - // PodTemplate holds pod specific configuration - PodTemplate *PodTemplate `json:"podTemplate,omitempty"` - // Workspaces holds a set of workspace bindings that must match names - // with those declared in the pipeline. - // +optional - Workspaces []WorkspaceBinding `json:"workspaces,omitempty"` - // TaskRunSpecs holds a set of task specific specs - // +optional - TaskRunSpecs []PipelineTaskRunSpec `json:"taskRunSpecs,omitempty"` -} - -// PipelineRunSpecStatus defines the pipelinerun spec status the user can provide -type PipelineRunSpecStatus = v1beta1.PipelineRunSpecStatus - -const ( - // PipelineRunSpecStatusCancelled indicates that the user wants to cancel the task, - // if not already cancelled or terminated - PipelineRunSpecStatusCancelled = v1beta1.PipelineRunSpecStatusCancelledDeprecated -) - -// PipelineResourceRef can be used to refer to a specific instance of a Resource -type PipelineResourceRef = v1beta1.PipelineResourceRef - -// PipelineRef can be used to refer to a specific instance of a Pipeline. -// Copied from CrossVersionObjectReference: https://github.com/kubernetes/kubernetes/blob/169df7434155cbbc22f1532cba8e0a9588e29ad8/pkg/apis/autoscaling/types.go#L64 -type PipelineRef = v1beta1.PipelineRef - -// PipelineRunStatus defines the observed state of PipelineRun -type PipelineRunStatus = v1beta1.PipelineRunStatus - -// PipelineRunStatusFields holds the fields of PipelineRunStatus' status. -// This is defined separately and inlined so that other types can readily -// consume these fields via duck typing. -type PipelineRunStatusFields = v1beta1.PipelineRunStatusFields - -// PipelineRunTaskRunStatus contains the name of the PipelineTask for this TaskRun and the TaskRun's Status -type PipelineRunTaskRunStatus = v1beta1.PipelineRunTaskRunStatus - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// PipelineRunList contains a list of PipelineRun -type PipelineRunList struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - Items []PipelineRun `json:"items,omitempty"` -} - -// PipelineTaskRun reports the results of running a step in the Task. Each -// task has the potential to succeed or fail (based on the exit code) -// and produces logs. -type PipelineTaskRun = v1beta1.PipelineTaskRun - -// GetGroupVersionKind implements kmeta.OwnerRefable. -func (*PipelineRun) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind(pipeline.PipelineRunControllerName) -} - -// IsDone returns true if the PipelineRun's status indicates that it is done. -func (pr *PipelineRun) IsDone() bool { - return !pr.Status.GetCondition(apis.ConditionSucceeded).IsUnknown() -} - -// HasStarted function check whether pipelinerun has valid start time set in its status -func (pr *PipelineRun) HasStarted() bool { - return pr.Status.StartTime != nil && !pr.Status.StartTime.IsZero() -} - -// IsCancelled returns true if the PipelineRun's spec status is set to Cancelled state -func (pr *PipelineRun) IsCancelled() bool { - return pr.Spec.Status == PipelineRunSpecStatusCancelled -} - -// GetRunKey return the pipelinerun key for timeout handler map -func (pr *PipelineRun) GetRunKey() string { - // The address of the pointer is a threadsafe unique identifier for the pipelinerun - return fmt.Sprintf("%s/%p", pipeline.PipelineRunControllerName, pr) -} - -// IsTimedOut returns true if a pipelinerun has exceeded its spec.Timeout based on its status.Timeout -func (pr *PipelineRun) IsTimedOut(c clock.PassiveClock) bool { - pipelineTimeout := pr.Spec.Timeout - startTime := pr.Status.StartTime - - if !startTime.IsZero() && pipelineTimeout != nil { - timeout := pipelineTimeout.Duration - if timeout == config.NoTimeoutDuration { - return false - } - runtime := c.Since(startTime.Time) - if runtime > timeout { - return true - } - } - return false -} - -// HasVolumeClaimTemplate returns true if PipelineRun contains volumeClaimTemplates that is -// used for creating PersistentVolumeClaims with an OwnerReference for each run -func (pr *PipelineRun) HasVolumeClaimTemplate() bool { - for _, ws := range pr.Spec.Workspaces { - if ws.VolumeClaimTemplate != nil { - return true - } - } - return false -} - -// PipelineTaskRunSpec holds task specific specs -type PipelineTaskRunSpec struct { - PipelineTaskName string `json:"pipelineTaskName,omitempty"` - TaskServiceAccountName string `json:"taskServiceAccountName,omitempty"` - TaskPodTemplate *PodTemplate `json:"taskPodTemplate,omitempty"` -} - -// GetTaskRunSpecs returns the task specific spec for a given -// PipelineTask if configured, otherwise it returns the PipelineRun's default. -func (pr *PipelineRun) GetTaskRunSpecs(pipelineTaskName string) (string, *PodTemplate) { - serviceAccountName := pr.Spec.ServiceAccountName - taskPodTemplate := pr.Spec.PodTemplate - for _, task := range pr.Spec.TaskRunSpecs { - if task.PipelineTaskName == pipelineTaskName { - taskPodTemplate = task.TaskPodTemplate - serviceAccountName = task.TaskServiceAccountName - } - } - return serviceAccountName, taskPodTemplate -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_types_test.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_types_test.go deleted file mode 100644 index 98c7cb87771..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_types_test.go +++ /dev/null @@ -1,342 +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 v1alpha1_test - -import ( - "fmt" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/clock" - "knative.dev/pkg/apis" -) - -var now = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC) -var testClock = clock.NewFakePassiveClock(now) - -func TestPipelineRunStatusConditions(t *testing.T) { - p := &v1alpha1.PipelineRun{} - foo := &apis.Condition{ - Type: "Foo", - Status: "True", - } - bar := &apis.Condition{ - Type: "Bar", - Status: "True", - } - - var ignoreVolatileTime = cmp.Comparer(func(_, _ apis.VolatileTime) bool { - return true - }) - - // Add a new condition. - p.Status.SetCondition(foo) - - fooStatus := p.Status.GetCondition(foo.Type) - if d := cmp.Diff(fooStatus, foo, ignoreVolatileTime); d != "" { - t.Errorf("Unexpected pipeline run condition type; diff %s", diff.PrintWantGot(d)) - } - - // Add a second condition. - p.Status.SetCondition(bar) - - barStatus := p.Status.GetCondition(bar.Type) - - if d := cmp.Diff(barStatus, bar, ignoreVolatileTime); d != "" { - t.Fatalf("Unexpected pipeline run condition type; diff %s", diff.PrintWantGot(d)) - } -} - -func TestInitializeConditions(t *testing.T) { - p := &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-name", - Namespace: "test-ns", - }, - } - p.Status.InitializeConditions(testClock) - - if p.Status.TaskRuns == nil { - t.Fatalf("PipelineRun status not initialized correctly") - } - - if p.Status.StartTime.IsZero() { - t.Fatalf("PipelineRun StartTime not initialized correctly") - } - - p.Status.TaskRuns["fooTask"] = &v1alpha1.PipelineRunTaskRunStatus{} - - p.Status.InitializeConditions(testClock) - if len(p.Status.TaskRuns) != 1 { - t.Fatalf("PipelineRun status getting reset") - } -} - -func TestPipelineRunIsDone(t *testing.T) { - pr := &v1alpha1.PipelineRun{} - foo := &apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionFalse, - } - pr.Status.SetCondition(foo) - if !pr.IsDone() { - t.Fatal("Expected pipelinerun status to be done") - } -} - -func TestPipelineRunIsCancelled(t *testing.T) { - pr := &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - Status: v1alpha1.PipelineRunSpecStatusCancelled, - }, - } - if !pr.IsCancelled() { - t.Fatal("Expected pipelinerun status to be cancelled") - } -} - -func TestPipelineRunHasVolumeClaimTemplate(t *testing.T) { - pr := &v1alpha1.PipelineRun{ - Spec: v1alpha1.PipelineRunSpec{ - Workspaces: []v1alpha1.WorkspaceBinding{{ - Name: "my-workspace", - VolumeClaimTemplate: &corev1.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pvc", - }, - Spec: corev1.PersistentVolumeClaimSpec{}, - }, - }}, - }, - } - if !pr.HasVolumeClaimTemplate() { - t.Fatal("Expected pipelinerun to have a volumeClaimTemplate workspace") - } -} - -func TestPipelineRunKey(t *testing.T) { - pr := &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "prunname", - }, - } - expectedKey := fmt.Sprintf("PipelineRun/%p", pr) - if pr.GetRunKey() != expectedKey { - t.Fatalf("Expected taskrun key to be %s but got %s", expectedKey, pr.GetRunKey()) - } -} - -func TestPipelineRunHasStarted(t *testing.T) { - params := []struct { - name string - prStatus v1alpha1.PipelineRunStatus - expectedValue bool - }{{ - name: "prWithNoStartTime", - prStatus: v1alpha1.PipelineRunStatus{}, - expectedValue: false, - }, { - name: "prWithStartTime", - prStatus: v1alpha1.PipelineRunStatus{ - PipelineRunStatusFields: v1alpha1.PipelineRunStatusFields{ - StartTime: &metav1.Time{Time: now}, - }, - }, - expectedValue: true, - }, { - name: "prWithZeroStartTime", - prStatus: v1alpha1.PipelineRunStatus{ - PipelineRunStatusFields: v1alpha1.PipelineRunStatusFields{ - StartTime: &metav1.Time{}, - }, - }, - expectedValue: false, - }} - for _, tc := range params { - t.Run(tc.name, func(t *testing.T) { - pr := &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "prunname", - Namespace: "testns", - }, - Status: tc.prStatus, - } - if pr.HasStarted() != tc.expectedValue { - t.Fatalf("Expected pipelinerun HasStarted() to return %t but got %t", tc.expectedValue, pr.HasStarted()) - } - }) - } -} - -func TestPipelineRunHasTimedOut(t *testing.T) { - tcs := []struct { - name string - timeout time.Duration - starttime time.Time - expected bool - }{{ - name: "timedout", - timeout: 1 * time.Second, - starttime: now.AddDate(0, 0, -1), - expected: true, - }, { - name: "nottimedout", - timeout: 25 * time.Hour, - starttime: now.AddDate(0, 0, -1), - expected: false, - }, { - name: "notimeoutspecified", - timeout: 0 * time.Second, - starttime: now.AddDate(0, 0, -1), - expected: false, - }, - } - - for _, tc := range tcs { - t.Run(t.Name(), func(t *testing.T) { - pr := &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pr", - }, - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{ - Name: "test-pipeline", - }, - Timeout: &metav1.Duration{Duration: tc.timeout}, - }, - Status: v1alpha1.PipelineRunStatus{ - PipelineRunStatusFields: v1alpha1.PipelineRunStatusFields{ - StartTime: &metav1.Time{Time: tc.starttime}, - }, - }, - } - - if pr.IsTimedOut(testClock) != tc.expected { - t.Fatalf("Expected isTimedOut to be %t", tc.expected) - } - }) - } -} - -func TestPipelineRunGetPodSpecSABackcompatibility(t *testing.T) { - for _, tt := range []struct { - name string - pr *v1alpha1.PipelineRun - expectedSAs map[string]string - }{ - { - name: "test backward compatibility", - pr: &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{Name: "pr"}, - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "prs"}, - ServiceAccountName: "defaultSA", - TaskRunSpecs: []v1alpha1.PipelineTaskRunSpec{{ - PipelineTaskName: "taskName", - TaskServiceAccountName: "newTaskSA", - }}, - }, - }, - expectedSAs: map[string]string{ - "unknown": "defaultSA", - "taskName": "newTaskSA", - }, - }, - { - name: "mixed default SA backward compatibility", - pr: &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{Name: "pr"}, - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{Name: "prs"}, - ServiceAccountName: "defaultSA", - TaskRunSpecs: []v1alpha1.PipelineTaskRunSpec{{ - PipelineTaskName: "taskNameOne", - TaskServiceAccountName: "TaskSAOne", - }, { - PipelineTaskName: "taskNameTwo", - TaskServiceAccountName: "newTaskTwo", - }}, - }, - }, - expectedSAs: map[string]string{ - "unknown": "defaultSA", - "taskNameOne": "TaskSAOne", - "taskNameTwo": "newTaskTwo", - }, - }, - } { - for taskName, expected := range tt.expectedSAs { - t.Run(tt.name, func(t *testing.T) { - sa, _ := tt.pr.GetTaskRunSpecs(taskName) - if expected != sa { - t.Errorf("%s: wrong service account: got: %v, want: %v", tt.name, sa, expected) - } - }) - } - } -} - -func TestPipelineRunGetPodSpec(t *testing.T) { - for _, tt := range []struct { - name string - pr *v1alpha1.PipelineRun - expectedPodTemplates map[string][]string - }{ - { - name: "mix default and none default", - pr: &v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{Name: "pr"}, - Spec: v1alpha1.PipelineRunSpec{ - PodTemplate: &v1alpha1.PodTemplate{SchedulerName: "scheduleTest"}, - PipelineRef: &v1alpha1.PipelineRef{Name: "prs"}, - ServiceAccountName: "defaultSA", - TaskRunSpecs: []v1alpha1.PipelineTaskRunSpec{{ - PipelineTaskName: "taskNameOne", - TaskServiceAccountName: "TaskSAOne", - TaskPodTemplate: &v1alpha1.PodTemplate{SchedulerName: "scheduleTestOne"}, - }, { - PipelineTaskName: "taskNameTwo", - TaskServiceAccountName: "newTaskTwo", - TaskPodTemplate: &v1alpha1.PodTemplate{SchedulerName: "scheduleTestTwo"}, - }}, - }, - }, - expectedPodTemplates: map[string][]string{ - "unknown": {"scheduleTest", "defaultSA"}, - "taskNameOne": {"scheduleTestOne", "TaskSAOne"}, - "taskNameTwo": {"scheduleTestTwo", "newTaskTwo"}, - }, - }, - } { - for taskName, values := range tt.expectedPodTemplates { - t.Run(tt.name, func(t *testing.T) { - sa, taskPodTemplate := tt.pr.GetTaskRunSpecs(taskName) - if values[0] != taskPodTemplate.SchedulerName { - t.Errorf("%s: wrong task podtemplate scheduler name: got: %v, want: %v", tt.name, taskPodTemplate.SchedulerName, values[0]) - } - if values[1] != sa { - t.Errorf("%s: wrong service account: got: %v, want: %v", tt.name, sa, values[1]) - } - }) - } - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_validation.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_validation.go deleted file mode 100644 index f6396cb4337..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_validation.go +++ /dev/null @@ -1,85 +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 v1alpha1 - -import ( - "context" - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/validate" - "k8s.io/apimachinery/pkg/api/equality" - "knative.dev/pkg/apis" -) - -var _ apis.Validatable = (*PipelineRun)(nil) - -// Validate pipelinerun -func (pr *PipelineRun) Validate(ctx context.Context) *apis.FieldError { - if err := validate.ObjectMetadata(pr.GetObjectMeta()).ViaField("metadata"); err != nil { - return err - } - if apis.IsInDelete(ctx) { - return nil - } - return pr.Spec.Validate(ctx) -} - -// Validate pipelinerun spec -func (ps *PipelineRunSpec) Validate(ctx context.Context) *apis.FieldError { - if equality.Semantic.DeepEqual(ps, &PipelineRunSpec{}) { - return apis.ErrMissingField("spec") - } - - // can't have both pipelineRef and pipelineSpec at the same time - if (ps.PipelineRef != nil && ps.PipelineRef.Name != "") && ps.PipelineSpec != nil { - return apis.ErrDisallowedFields("spec.pipelineref", "spec.pipelinespec") - } - - // Check that one of PipelineRef and PipelineSpec is present - if (ps.PipelineRef == nil || (ps.PipelineRef != nil && ps.PipelineRef.Name == "")) && ps.PipelineSpec == nil { - return apis.ErrMissingField("spec.pipelineref.name", "spec.pipelinespec") - } - - // Validate PipelineSpec if it's present - if ps.PipelineSpec != nil { - if err := ps.PipelineSpec.Validate(ctx); err != nil { - return err - } - } - - if ps.Timeout != nil { - // timeout should be a valid duration of at least 0. - if ps.Timeout.Duration < 0 { - return apis.ErrInvalidValue(fmt.Sprintf("%s should be >= 0", ps.Timeout.Duration.String()), "spec.timeout") - } - } - - if ps.Workspaces != nil { - wsNames := make(map[string]int) - for idx, ws := range ps.Workspaces { - if prevIdx, alreadyExists := wsNames[ws.Name]; alreadyExists { - return &apis.FieldError{ - Message: fmt.Sprintf("workspace %q provided by pipelinerun more than once, at index %d and %d", ws.Name, prevIdx, idx), - Paths: []string{"spec.workspaces"}, - } - } - wsNames[ws.Name] = idx - } - } - - return nil -} diff --git a/pkg/apis/pipeline/v1alpha1/pipelinerun_validation_test.go b/pkg/apis/pipeline/v1alpha1/pipelinerun_validation_test.go deleted file mode 100644 index 643e3daab91..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pipelinerun_validation_test.go +++ /dev/null @@ -1,221 +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 v1alpha1_test - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestPipelineRun_Invalidate(t *testing.T) { - tests := []struct { - name string - pr v1alpha1.PipelineRun - want *apis.FieldError - }{ - { - name: "invalid pipelinerun", - pr: v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "prmetaname", - }, - }, - want: apis.ErrMissingField("spec"), - }, - { - name: "invalid pipelinerun metadata", - pr: v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pipelinerun,name", - }, - }, - want: &apis.FieldError{ - Message: `invalid resource name "pipelinerun,name": must be a valid DNS label`, - Paths: []string{"metadata.name"}, - }, - }, { - name: "no pipeline reference", - pr: v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pipelinelinename", - }, - Spec: v1alpha1.PipelineRunSpec{ - ServiceAccountName: "foo", - }, - }, - want: apis.ErrMissingField("spec.pipelineref.name, spec.pipelinespec"), - }, { - name: "negative pipeline timeout", - pr: v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pipelinelinename", - }, - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{ - Name: "prname", - }, - Timeout: &metav1.Duration{Duration: -48 * time.Hour}, - }, - }, - want: apis.ErrInvalidValue("-48h0m0s should be >= 0", "spec.timeout"), - }, - } - - for _, ps := range tests { - t.Run(ps.name, func(t *testing.T) { - err := ps.pr.Validate(context.Background()) - if d := cmp.Diff(err.Error(), ps.want.Error()); d != "" { - t.Errorf("PipelineRun.Validate/%s %s", ps.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestPipelineRun_Validate(t *testing.T) { - tests := []struct { - name string - pr v1alpha1.PipelineRun - }{ - { - name: "normal case", - pr: v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pipelinelinename", - }, - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{ - Name: "prname", - }, - }, - }, - }, { - name: "no timeout", - pr: v1alpha1.PipelineRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pipelinelinename", - }, - Spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{ - Name: "prname", - }, - Timeout: &metav1.Duration{Duration: 0}, - }, - }, - }, - } - - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - if err := ts.pr.Validate(context.Background()); err != nil { - t.Errorf("Unexpected PipelineRun.Validate() error = %v", err) - } - }) - } -} - -func TestPipelineRunSpec_Invalidate(t *testing.T) { - tests := []struct { - name string - spec v1alpha1.PipelineRunSpec - wantErr *apis.FieldError - }{{ - name: "Empty pipelineSpec", - spec: v1alpha1.PipelineRunSpec{}, - wantErr: apis.ErrMissingField("spec"), - }, { - name: "pipelineRef without Pipeline Name", - spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{}, - }, - wantErr: apis.ErrMissingField("spec.pipelineref.name", "spec.pipelinespec"), - }, { - name: "pipelineRef and pipelineSpec together", - spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{ - Name: "pipelinerefname", - }, - PipelineSpec: &v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "mytask", - TaskRef: &v1alpha1.TaskRef{ - Name: "mytask", - }, - }}}, - }, - wantErr: apis.ErrDisallowedFields("spec.pipelinespec", "spec.pipelineref"), - }, { - name: "workspaces may only appear once", - spec: v1alpha1.PipelineRunSpec{ - PipelineRef: &v1alpha1.PipelineRef{ - Name: "pipelinerefname", - }, - Workspaces: []v1alpha1.WorkspaceBinding{{ - Name: "ws", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, { - Name: "ws", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - }, - wantErr: &apis.FieldError{ - Message: `workspace "ws" provided by pipelinerun more than once, at index 0 and 1`, - Paths: []string{"spec.workspaces"}, - }, - }} - for _, ps := range tests { - t.Run(ps.name, func(t *testing.T) { - err := ps.spec.Validate(context.Background()) - if d := cmp.Diff(ps.wantErr.Error(), err.Error()); d != "" { - t.Errorf("PipelineRunSpec.Validate/%s %s", ps.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestPipelineRunSpec_Validate(t *testing.T) { - tests := []struct { - name string - spec v1alpha1.PipelineRunSpec - }{{ - name: "PipelineRun without pipelineRef", - spec: v1alpha1.PipelineRunSpec{ - PipelineSpec: &v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "mytask", - TaskRef: &v1alpha1.TaskRef{ - Name: "mytask", - }, - }}, - }, - }, - }} - for _, ps := range tests { - t.Run(ps.name, func(t *testing.T) { - if err := ps.spec.Validate(context.Background()); err != nil { - t.Errorf("PipelineRunSpec.Validate/%s %v", ps.name, err) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/pod.go b/pkg/apis/pipeline/v1alpha1/pod.go deleted file mode 100644 index 156c66b2d50..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pod.go +++ /dev/null @@ -1,8 +0,0 @@ -package v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/apis/pipeline/pod" -) - -// PodTemplate holds pod specific configuration -type PodTemplate = pod.Template diff --git a/pkg/apis/pipeline/v1alpha1/pod_test.go b/pkg/apis/pipeline/v1alpha1/pod_test.go deleted file mode 100644 index 7bcc4bdd58b..00000000000 --- a/pkg/apis/pipeline/v1alpha1/pod_test.go +++ /dev/null @@ -1,17 +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 v1alpha1_test diff --git a/pkg/apis/pipeline/v1alpha1/register.go b/pkg/apis/pipeline/v1alpha1/register.go index ca83ff92047..42b5e4b18ec 100644 --- a/pkg/apis/pipeline/v1alpha1/register.go +++ b/pkg/apis/pipeline/v1alpha1/register.go @@ -46,18 +46,6 @@ var ( // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, - &Task{}, - &TaskList{}, - &ClusterTask{}, - &ClusterTaskList{}, - &TaskRun{}, - &TaskRunList{}, - &Pipeline{}, - &PipelineList{}, - &PipelineRun{}, - &PipelineRunList{}, - &PipelineResource{}, - &PipelineResourceList{}, &Run{}, &RunList{}, ) diff --git a/pkg/apis/pipeline/v1alpha1/resource_paths.go b/pkg/apis/pipeline/v1alpha1/resource_paths.go deleted file mode 100644 index 6aa94913b0f..00000000000 --- a/pkg/apis/pipeline/v1alpha1/resource_paths.go +++ /dev/null @@ -1,40 +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 v1alpha1 - -import "path/filepath" - -// InputResourcePath returns the path where the given input resource -// will get mounted in a Pod -func InputResourcePath(r ResourceDeclaration) string { - return path("/workspace", r) -} - -// OutputResourcePath returns the path to the output resource in a Pod -func OutputResourcePath(r ResourceDeclaration) string { - return path("/workspace/output", r) -} - -func path(root string, r ResourceDeclaration) string { - if r.TargetPath != "" { - if filepath.IsAbs(r.TargetPath) { - return r.TargetPath - } - return filepath.Join("/workspace", r.TargetPath) - } - return filepath.Join(root, r.Name) -} diff --git a/pkg/apis/pipeline/v1alpha1/resource_paths_test.go b/pkg/apis/pipeline/v1alpha1/resource_paths_test.go deleted file mode 100644 index 0fa0a0112a4..00000000000 --- a/pkg/apis/pipeline/v1alpha1/resource_paths_test.go +++ /dev/null @@ -1,81 +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 v1alpha1_test - -import ( - "testing" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" -) - -func TestInputResourcePath(t *testing.T) { - tcs := []struct { - name string - resource v1alpha1.ResourceDeclaration - expected string - }{{ - name: "default_path", - resource: v1alpha1.ResourceDeclaration{ - Name: "foo", - }, - expected: "/workspace/foo", - }, { - name: "with target path", - resource: v1alpha1.ResourceDeclaration{ - Name: "foo", - TargetPath: "bar", - }, - expected: "/workspace/bar", - }} - - for _, tc := range tcs { - t.Run(tc.name, func(t *testing.T) { - if actual := v1alpha1.InputResourcePath(tc.resource); actual != tc.expected { - t.Errorf("Unexpected input resource path: %s", actual) - } - }) - } -} - -func TestOutputResourcePath(t *testing.T) { - tcs := []struct { - name string - resource v1alpha1.ResourceDeclaration - expected string - }{{ - name: "default_path", - resource: v1alpha1.ResourceDeclaration{ - Name: "foo", - }, - expected: "/workspace/output/foo", - }, { - name: "with target path", - resource: v1alpha1.ResourceDeclaration{ - Name: "foo", - TargetPath: "bar", - }, - expected: "/workspace/bar", - }} - - for _, tc := range tcs { - t.Run(tc.name, func(t *testing.T) { - if actual := v1alpha1.OutputResourcePath(tc.resource); actual != tc.expected { - t.Errorf("Unexpected output resource path: %s", actual) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/resource_types.go b/pkg/apis/pipeline/v1alpha1/resource_types.go deleted file mode 100644 index d987494e173..00000000000 --- a/pkg/apis/pipeline/v1alpha1/resource_types.go +++ /dev/null @@ -1,109 +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 v1alpha1 - -import ( - "fmt" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" -) - -// PipelineResourceInterface interface to be implemented by different PipelineResource types -type PipelineResourceInterface interface { - // GetName returns the name of this PipelineResource instance. - GetName() string - // GetType returns the type of this PipelineResource (often a super type, e.g. in the case of storage). - GetType() PipelineResourceType - // Replacements returns all the attributes that this PipelineResource has that - // can be used for variable replacement. - Replacements() map[string]string - // GetOutputTaskModifier returns the TaskModifier instance that should be used on a Task - // in order to add this kind of resource when it is being used as an output. - GetOutputTaskModifier(ts *TaskSpec, path string) (TaskModifier, error) - // GetInputTaskModifier returns the TaskModifier instance that should be used on a Task - // in order to add this kind of resource when it is being used as an input. - GetInputTaskModifier(ts *TaskSpec, path string) (TaskModifier, error) -} - -// TaskModifier is an interface to be implemented by different PipelineResources -type TaskModifier = v1beta1.TaskModifier - -// InternalTaskModifier implements TaskModifier for resources that are built-in to Tekton Pipelines. -type InternalTaskModifier = v1beta1.InternalTaskModifier - -func checkStepNotAlreadyAdded(s Step, steps []Step) error { - for _, step := range steps { - if s.Name == step.Name { - return fmt.Errorf("Step %s cannot be added again", step.Name) - } - } - return nil -} - -// ApplyTaskModifier applies a modifier to the task by appending and prepending steps and volumes. -// If steps with the same name exist in ts an error will be returned. If identical Volumes have -// been added, they will not be added again. If Volumes with the same name but different contents -// have been added, an error will be returned. -// FIXME(vdemeester) de-duplicate this -func ApplyTaskModifier(ts *TaskSpec, tm TaskModifier) error { - steps := tm.GetStepsToPrepend() - for _, step := range steps { - if err := checkStepNotAlreadyAdded(step, ts.Steps); err != nil { - return err - } - } - ts.Steps = append(steps, ts.Steps...) - - steps = tm.GetStepsToAppend() - for _, step := range steps { - if err := checkStepNotAlreadyAdded(step, ts.Steps); err != nil { - return err - } - } - ts.Steps = append(ts.Steps, steps...) - - volumes := tm.GetVolumes() - for _, volume := range volumes { - var alreadyAdded bool - for _, v := range ts.Volumes { - if volume.Name == v.Name { - // If a Volume with the same name but different contents has already been added, we can't add both - if d := cmp.Diff(volume, v); d != "" { - return fmt.Errorf("tried to add volume %s already added but with different contents", volume.Name) - } - // If an identical Volume has already been added, don't add it again - alreadyAdded = true - } - } - if !alreadyAdded { - ts.Volumes = append(ts.Volumes, volume) - } - } - - return nil -} - -// PipelineResourceBinding connects a reference to an instance of a PipelineResource -// with a PipelineResource dependency that the Pipeline has declared -type PipelineResourceBinding = v1beta1.PipelineResourceBinding - -// PipelineResourceResult used to export the image name and digest as json -type PipelineResourceResult = v1beta1.PipelineResourceResult - -// ResultType used to find out whether a PipelineResourceResult is from a task result or not -type ResultType = v1beta1.ResultType diff --git a/pkg/apis/pipeline/v1alpha1/resource_types_test.go b/pkg/apis/pipeline/v1alpha1/resource_types_test.go deleted file mode 100644 index 3ccb8a0864f..00000000000 --- a/pkg/apis/pipeline/v1alpha1/resource_types_test.go +++ /dev/null @@ -1,138 +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 v1alpha1_test - -import ( - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" -) - -var ( - prependStep = v1alpha1.Step{ - Name: "prepend-step", - Image: "dummy", - Command: []string{"doit"}, - Args: []string{"stuff", "things"}, - } - appendStep = v1alpha1.Step{ - Name: "append-step", - Image: "dummy", - Command: []string{"doit"}, - Args: []string{"other stuff", "other things"}, - } - volume = corev1.Volume{ - Name: "magic-volume", - VolumeSource: corev1.VolumeSource{ - PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: "some-claim"}, - }, - } -) - -type TestTaskModifier struct{} - -func (tm *TestTaskModifier) GetStepsToPrepend() []v1alpha1.Step { - return []v1alpha1.Step{prependStep} -} - -func (tm *TestTaskModifier) GetStepsToAppend() []v1alpha1.Step { - return []v1alpha1.Step{appendStep} -} - -func (tm *TestTaskModifier) GetVolumes() []corev1.Volume { - return []corev1.Volume{volume} -} - -func TestApplyTaskModifier(t *testing.T) { - testcases := []struct { - name string - ts v1alpha1.TaskSpec - }{{ - name: "success", - ts: v1alpha1.TaskSpec{}, - }, { - name: "identical volume already added", - ts: v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - // Trying to add the same Volume that has already been added shouldn't be an error - // and it should not be added twice - Volumes: []corev1.Volume{volume}, - }}, - }} - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - if err := v1alpha1.ApplyTaskModifier(&tc.ts, &TestTaskModifier{}); err != nil { - t.Fatalf("Did not expect error modifying TaskSpec but got %v", err) - } - - expectedTaskSpec := v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{prependStep, appendStep}, - Volumes: []corev1.Volume{ - volume, - }, - }} - - if d := cmp.Diff(expectedTaskSpec, tc.ts); d != "" { - t.Errorf("TaskSpec was not modified as expected %s", diff.PrintWantGot(d)) - } - }) - } -} - -func TestApplyTaskModifier_AlreadyAdded(t *testing.T) { - testcases := []struct { - name string - ts v1alpha1.TaskSpec - }{{ - name: "prepend already added", - ts: v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{prependStep}, - }}, - }, { - name: "append already added", - ts: v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{appendStep}, - }}, - }, { - name: "both steps already added", - ts: v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{prependStep, appendStep}, - }}, - }, { - name: "both steps already added reverse order", - ts: v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{appendStep, prependStep}, - }}, - }, { - name: "volume with same name but diff content already added", - ts: v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Volumes: []corev1.Volume{{ - Name: "magic-volume", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }}, - }}, - }} - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - if err := v1alpha1.ApplyTaskModifier(&tc.ts, &TestTaskModifier{}); err == nil { - t.Errorf("Expected error when applying values already added but got none") - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/run_types.go b/pkg/apis/pipeline/v1alpha1/run_types.go index 4d7e1a94c27..7889cfa8b8f 100644 --- a/pkg/apis/pipeline/v1alpha1/run_types.go +++ b/pkg/apis/pipeline/v1alpha1/run_types.go @@ -47,7 +47,7 @@ type EmbeddedRunSpec struct { // RunSpec defines the desired state of Run type RunSpec struct { // +optional - Ref *TaskRef `json:"ref,omitempty"` + Ref *v1beta1.TaskRef `json:"ref,omitempty"` // Spec is a specification of a custom task // +optional @@ -69,7 +69,7 @@ type RunSpec struct { // PodTemplate holds pod specific configuration // +optional - PodTemplate *PodTemplate `json:"podTemplate,omitempty"` + PodTemplate *v1beta1.PodTemplate `json:"podTemplate,omitempty"` // Time after which the custom-task times out. // Refer Go's ParseDuration documentation for expected format: https://golang.org/pkg/time/#ParseDuration diff --git a/pkg/apis/pipeline/v1alpha1/run_types_test.go b/pkg/apis/pipeline/v1alpha1/run_types_test.go index 6c1f8bfe3bc..50bfea694be 100644 --- a/pkg/apis/pipeline/v1alpha1/run_types_test.go +++ b/pkg/apis/pipeline/v1alpha1/run_types_test.go @@ -29,10 +29,14 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/clock" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" ) +var now = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC) +var testClock = clock.NewFakePassiveClock(now) + func TestGetParams(t *testing.T) { for _, c := range []struct { desc string @@ -209,7 +213,7 @@ status: }, Spec: v1alpha1.RunSpec{ Retries: 3, - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "example.dev/v0", Kind: "Example", }, diff --git a/pkg/apis/pipeline/v1alpha1/run_validation.go b/pkg/apis/pipeline/v1alpha1/run_validation.go index 483c918de66..59bcb43c9ad 100644 --- a/pkg/apis/pipeline/v1alpha1/run_validation.go +++ b/pkg/apis/pipeline/v1alpha1/run_validation.go @@ -19,6 +19,7 @@ package v1alpha1 import ( "context" + "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "github.com/tektoncd/pipeline/pkg/apis/validate" "k8s.io/apimachinery/pkg/api/equality" "knative.dev/pkg/apis" @@ -66,9 +67,9 @@ func (rs *RunSpec) Validate(ctx context.Context) *apis.FieldError { return apis.ErrMissingField("spec.spec.kind") } } - if err := validateParameters("spec.params", rs.Params); err != nil { + if err := v1beta1.ValidateParameters(ctx, rs.Params).ViaField("spec.params"); err != nil { return err } - return validateWorkspaceBindings(ctx, rs.Workspaces) + return v1beta1.ValidateWorkspaceBindings(ctx, rs.Workspaces).ViaField("spec.workspaces") } diff --git a/pkg/apis/pipeline/v1alpha1/run_validation_test.go b/pkg/apis/pipeline/v1alpha1/run_validation_test.go index b174004d637..53c26734081 100644 --- a/pkg/apis/pipeline/v1alpha1/run_validation_test.go +++ b/pkg/apis/pipeline/v1alpha1/run_validation_test.go @@ -72,7 +72,7 @@ func TestRun_Invalid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "apiVersion", Kind: "kind", }, @@ -92,7 +92,7 @@ func TestRun_Invalid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "", }, }, @@ -105,7 +105,7 @@ func TestRun_Invalid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "", }, @@ -150,7 +150,7 @@ func TestRun_Invalid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", }, @@ -163,7 +163,7 @@ func TestRun_Invalid(t *testing.T) { }}, }, }, - want: apis.ErrMultipleOneOf("spec.params"), + want: apis.ErrMultipleOneOf("spec.params[foo].name"), }} { t.Run(c.name, func(t *testing.T) { err := c.run.Validate(context.Background()) @@ -185,7 +185,7 @@ func TestRun_Valid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", Name: "blah", @@ -199,7 +199,7 @@ func TestRun_Valid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", }, @@ -227,7 +227,7 @@ func TestRun_Valid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", }, @@ -247,7 +247,7 @@ func TestRun_Valid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", }, @@ -278,7 +278,7 @@ func TestRun_Workspaces_Invalid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", }, @@ -290,7 +290,7 @@ func TestRun_Workspaces_Invalid(t *testing.T) { }}, }, }, - wantErr: apis.ErrMissingField("workspace.persistentvolumeclaim.claimname"), + wantErr: apis.ErrMissingField("spec.workspaces[0].persistentvolumeclaim.claimname"), }, { name: "bind same workspace twice", run: &v1alpha1.Run{ @@ -298,7 +298,7 @@ func TestRun_Workspaces_Invalid(t *testing.T) { Name: "temp", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "blah", Kind: "blah", }, @@ -311,7 +311,7 @@ func TestRun_Workspaces_Invalid(t *testing.T) { }}, }, }, - wantErr: apis.ErrMultipleOneOf("spec.workspaces.name"), + wantErr: apis.ErrMultipleOneOf("spec.workspaces[1].name"), }} for _, ts := range tests { t.Run(ts.name, func(t *testing.T) { diff --git a/pkg/apis/pipeline/v1alpha1/step_replacements.go b/pkg/apis/pipeline/v1alpha1/step_replacements.go deleted file mode 100644 index 15f9b9ade20..00000000000 --- a/pkg/apis/pipeline/v1alpha1/step_replacements.go +++ /dev/null @@ -1,27 +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 v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/substitution" -) - -// ApplyStepReplacements applies variable interpolation on a Step. -func ApplyStepReplacements(step *Step, stringReplacements map[string]string, arrayReplacements map[string][]string) { - step.Script = substitution.ApplyReplacements(step.Script, stringReplacements) - ApplyContainerReplacements(step, stringReplacements, arrayReplacements) -} diff --git a/pkg/apis/pipeline/v1alpha1/step_replacements_test.go b/pkg/apis/pipeline/v1alpha1/step_replacements_test.go deleted file mode 100644 index 633c09a0db5..00000000000 --- a/pkg/apis/pipeline/v1alpha1/step_replacements_test.go +++ /dev/null @@ -1,128 +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 v1alpha1_test - -import ( - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" -) - -func TestApplyStepReplacements(t *testing.T) { - replacements := map[string]string{ - "replace.me": "replaced!", - } - - arrayReplacements := map[string][]string{ - "array.replace.me": {"val1", "val2"}, - } - - s := v1alpha1.Step{ - Script: "$(replace.me)", - Name: "$(replace.me)", - Image: "$(replace.me)", - Command: []string{"$(array.replace.me)"}, - Args: []string{"$(array.replace.me)"}, - WorkingDir: "$(replace.me)", - EnvFrom: []corev1.EnvFromSource{{ - ConfigMapRef: &corev1.ConfigMapEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - }, - SecretRef: &corev1.SecretEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - }, - }}, - Env: []corev1.EnvVar{{ - Name: "not_me", - Value: "$(replace.me)", - ValueFrom: &corev1.EnvVarSource{ - ConfigMapKeyRef: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - Key: "$(replace.me)", - }, - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "$(replace.me)", - }, - Key: "$(replace.me)", - }, - }, - }}, - VolumeMounts: []corev1.VolumeMount{{ - Name: "$(replace.me)", - MountPath: "$(replace.me)", - SubPath: "$(replace.me)", - }}, - } - - expected := v1alpha1.Step{ - Script: "replaced!", - Name: "replaced!", - Image: "replaced!", - Command: []string{"val1", "val2"}, - Args: []string{"val1", "val2"}, - WorkingDir: "replaced!", - EnvFrom: []corev1.EnvFromSource{{ - ConfigMapRef: &corev1.ConfigMapEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - }, - SecretRef: &corev1.SecretEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - }, - }}, - Env: []corev1.EnvVar{{ - Name: "not_me", - Value: "replaced!", - ValueFrom: &corev1.EnvVarSource{ - ConfigMapKeyRef: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - Key: "replaced!", - }, - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "replaced!", - }, - Key: "replaced!", - }, - }, - }}, - VolumeMounts: []corev1.VolumeMount{{ - Name: "replaced!", - MountPath: "replaced!", - SubPath: "replaced!", - }}, - } - v1alpha1.ApplyStepReplacements(&s, replacements, arrayReplacements) - if d := cmp.Diff(s, expected); d != "" { - t.Errorf("Container replacements failed: %s", diff.PrintWantGot(d)) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/storage_resource.go b/pkg/apis/pipeline/v1alpha1/storage_resource.go deleted file mode 100644 index 6f636bfb71c..00000000000 --- a/pkg/apis/pipeline/v1alpha1/storage_resource.go +++ /dev/null @@ -1,24 +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 v1alpha1 - -import ( - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" -) - -// PipelineResourceTypeGCS is the subtype for the GCSResources, which is backed by a GCS blob/directory. -const PipelineResourceTypeGCS PipelineResourceType = resource.PipelineResourceTypeGCS diff --git a/pkg/apis/pipeline/v1alpha1/task_conversion.go b/pkg/apis/pipeline/v1alpha1/task_conversion.go deleted file mode 100644 index 027d1493a5c..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_conversion.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "knative.dev/pkg/apis" -) - -var _ apis.Convertible = (*Task)(nil) - -// ConvertTo implements api.Convertible -func (t *Task) ConvertTo(ctx context.Context, obj apis.Convertible) error { - switch sink := obj.(type) { - case *v1beta1.Task: - sink.ObjectMeta = t.ObjectMeta - return t.Spec.ConvertTo(ctx, &sink.Spec) - default: - return fmt.Errorf("unknown version, got: %T", sink) - } -} - -// ConvertTo implements api.Convertible -func (ts *TaskSpec) ConvertTo(ctx context.Context, sink *v1beta1.TaskSpec) error { - sink.Steps = ts.Steps - sink.Volumes = ts.Volumes - sink.StepTemplate = ts.StepTemplate - sink.Sidecars = ts.Sidecars - sink.Workspaces = ts.Workspaces - sink.Results = ts.Results - sink.Resources = ts.Resources - sink.Params = ts.Params - sink.Description = ts.Description - if ts.Inputs != nil { - if len(ts.Inputs.Params) > 0 && len(ts.Params) > 0 { - // This shouldn't happen as it shouldn't pass validation - return apis.ErrMultipleOneOf("inputs.params", "params") - } - if len(ts.Inputs.Params) > 0 { - sink.Params = make([]v1beta1.ParamSpec, len(ts.Inputs.Params)) - for i, param := range ts.Inputs.Params { - sink.Params[i] = *param.DeepCopy() - } - } - if len(ts.Inputs.Resources) > 0 { - if sink.Resources == nil { - sink.Resources = &v1beta1.TaskResources{} - } - if len(ts.Inputs.Resources) > 0 && ts.Resources != nil && len(ts.Resources.Inputs) > 0 { - // This shouldn't happen as it shouldn't pass validation but just in case - return apis.ErrMultipleOneOf("inputs.resources", "resources.inputs") - } - sink.Resources.Inputs = make([]v1beta1.TaskResource, len(ts.Inputs.Resources)) - for i, resource := range ts.Inputs.Resources { - sink.Resources.Inputs[i] = v1beta1.TaskResource{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: resource.Name, - Type: resource.Type, - Description: resource.Description, - TargetPath: resource.TargetPath, - Optional: resource.Optional, - }} - } - } - } - if ts.Outputs != nil && len(ts.Outputs.Resources) > 0 { - if sink.Resources == nil { - sink.Resources = &v1beta1.TaskResources{} - } - if len(ts.Outputs.Resources) > 0 && ts.Resources != nil && len(ts.Resources.Outputs) > 0 { - // This shouldn't happen as it shouldn't pass validation but just in case - return apis.ErrMultipleOneOf("outputs.resources", "resources.outputs") - } - sink.Resources.Outputs = make([]v1beta1.TaskResource, len(ts.Outputs.Resources)) - for i, resource := range ts.Outputs.Resources { - sink.Resources.Outputs[i] = v1beta1.TaskResource{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: resource.Name, - Type: resource.Type, - Description: resource.Description, - TargetPath: resource.TargetPath, - Optional: resource.Optional, - }} - } - } - return nil -} - -// ConvertFrom implements api.Convertible -func (t *Task) ConvertFrom(ctx context.Context, obj apis.Convertible) error { - switch source := obj.(type) { - case *v1beta1.Task: - t.ObjectMeta = source.ObjectMeta - return t.Spec.ConvertFrom(ctx, &source.Spec) - default: - return fmt.Errorf("unknown version, got: %T", t) - } -} - -// ConvertFrom implements api.Convertible -func (ts *TaskSpec) ConvertFrom(ctx context.Context, source *v1beta1.TaskSpec) error { - ts.Steps = source.Steps - ts.Volumes = source.Volumes - ts.StepTemplate = source.StepTemplate - ts.Sidecars = source.Sidecars - ts.Workspaces = source.Workspaces - ts.Results = source.Results - ts.Params = source.Params - ts.Resources = source.Resources - ts.Description = source.Description - return nil -} diff --git a/pkg/apis/pipeline/v1alpha1/task_conversion_test.go b/pkg/apis/pipeline/v1alpha1/task_conversion_test.go deleted file mode 100644 index d20edf4118a..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_conversion_test.go +++ /dev/null @@ -1,316 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - resource "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestTaskConversionBadType(t *testing.T) { - good, bad := &Task{}, &Pipeline{} - - if err := good.ConvertTo(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } - - if err := good.ConvertFrom(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } -} - -func TestTaskConversion(t *testing.T) { - versions := []apis.Convertible{&v1beta1.Task{}} - - tests := []struct { - name string - in *Task - wantErr bool - }{{ - name: "simple conversion", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Description: "test", - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - Volumes: []corev1.Volume{{}}, - Params: []v1beta1.ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - }, - }, { - name: "deprecated and non deprecated inputs", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - Inputs: &Inputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - wantErr: true, - }, { - name: "deprecated and non deprecated params", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Params: []v1beta1.ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - Inputs: &Inputs{ - Params: []ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - }, - }, - wantErr: true, - }, { - name: "deprecated and non deprecated outputs", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - Outputs: &Outputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - wantErr: true, - }} - - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - if !test.wantErr { - t.Errorf("ConvertTo() = %v", err) - } - return - } - t.Logf("ConvertTo() = %#v", ver) - got := &Task{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.in, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} - -func TestTaskConversionFromDeprecated(t *testing.T) { - versions := []apis.Convertible{&v1beta1.Task{}} - tests := []struct { - name string - in *Task - want *Task - }{{ - name: "inputs params", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - Inputs: &Inputs{ - Params: []ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - }, - }, - want: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Params: []v1beta1.ParamSpec{{ - Name: "param-1", - Type: v1beta1.ParamTypeString, - Description: "My first param", - }}, - }, - }, - }, - }, { - name: "inputs resource", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - Inputs: &Inputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - want: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - }, - }, { - name: "outputs resource", - in: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - Outputs: &Outputs{ - Resources: []TaskResource{{ResourceDeclaration: ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - want: &Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Resources: &v1beta1.TaskResources{ - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - }, - }, - }} - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - t.Errorf("ConvertTo() = %v", err) - } - t.Logf("ConvertTo() = %#v", ver) - got := &Task{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.want, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} diff --git a/pkg/apis/pipeline/v1alpha1/task_defaults.go b/pkg/apis/pipeline/v1alpha1/task_defaults.go deleted file mode 100644 index d61bc7b7cfc..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_defaults.go +++ /dev/null @@ -1,47 +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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -var _ apis.Defaultable = (*Task)(nil) - -// SetDefaults implements apis.Defaultable -func (t *Task) SetDefaults(ctx context.Context) { - t.Spec.SetDefaults(ctx) -} - -// SetDefaults set any defaults for the task spec -func (ts *TaskSpec) SetDefaults(ctx context.Context) { - for i := range ts.Params { - ts.Params[i].SetDefaults(ctx) - } - if ts.Inputs != nil { - ts.Inputs.SetDefaults(ctx) - } -} - -// SetDefaults implements apis.Defaultable -func (inputs *Inputs) SetDefaults(ctx context.Context) { - for i := range inputs.Params { - inputs.Params[i].SetDefaults(ctx) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/task_interface.go b/pkg/apis/pipeline/v1alpha1/task_interface.go deleted file mode 100644 index d545dddd31b..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_interface.go +++ /dev/null @@ -1,26 +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 v1alpha1 - -import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - -// TaskObject is implemented by Task and ClusterTask -type TaskObject interface { - TaskMetadata() metav1.ObjectMeta - TaskSpec() TaskSpec - Copy() TaskObject -} diff --git a/pkg/apis/pipeline/v1alpha1/task_types.go b/pkg/apis/pipeline/v1alpha1/task_types.go deleted file mode 100644 index 2c4180b5796..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_types.go +++ /dev/null @@ -1,146 +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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" -) - -const ( - // TaskRunResultType default task run result value - TaskRunResultType ResultType = v1beta1.TaskRunResultType - // PipelineResourceResultType default pipeline result value - PipelineResourceResultType ResultType = v1beta1.PipelineResourceResultType - // UnknownResultType default unknown result type value - UnknownResultType ResultType = v1beta1.UnknownResultType -) - -// TaskSpec returns the task's spec -func (t *Task) TaskSpec() TaskSpec { - return t.Spec -} - -// TaskMetadata returns the task's ObjectMeta -func (t *Task) TaskMetadata() metav1.ObjectMeta { - return t.ObjectMeta -} - -// Copy returns a deep copy of the task -func (t *Task) Copy() TaskObject { - return t.DeepCopy() -} - -// TaskSpec defines the desired state of Task. -type TaskSpec struct { - v1beta1.TaskSpec `json:",inline"` - - // Inputs is an optional set of parameters and resources which must be - // supplied by the user when a Task is executed by a TaskRun. - // +optional - Inputs *Inputs `json:"inputs,omitempty"` - // Outputs is an optional set of resources and results produced when this - // Task is run. - // +optional - Outputs *Outputs `json:"outputs,omitempty"` -} - -// TaskResult used to describe the results of a task -type TaskResult = v1beta1.TaskResult - -// Step embeds the Container type, which allows it to include fields not -// provided by Container. -type Step = v1beta1.Step - -// Sidecar has nearly the same data structure as Step, consisting of a Container and an optional Script, but does not have the ability to timeout. -type Sidecar = v1beta1.Sidecar - -// StepTemplate is a template for a Step -type StepTemplate = v1beta1.StepTemplate - -// +genclient -// +genclient:noStatus -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Task represents a collection of sequential steps that are run as part of a -// Pipeline using a set of inputs and producing a set of outputs. Tasks execute -// when TaskRuns are created that provide the input parameters and resources and -// output resources the Task requires. -// -// +k8s:openapi-gen=true -type Task struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata"` - - // Spec holds the desired state of the Task from the client - // +optional - Spec TaskSpec `json:"spec"` -} - -// Inputs are the requirements that a task needs to run a Build. -type Inputs struct { - // Resources is a list of the input resources required to run the task. - // Resources are represented in TaskRuns as bindings to instances of - // PipelineResources. - // +optional - Resources []TaskResource `json:"resources,omitempty"` - // Params is a list of input parameters required to run the task. Params - // must be supplied as inputs in TaskRuns unless they declare a default - // value. - // +optional - Params []ParamSpec `json:"params,omitempty"` -} - -// TaskResource defines an input or output Resource declared as a requirement -// by a Task. The Name field will be used to refer to these Resources within -// the Task definition, and when provided as an Input, the Name will be the -// path to the volume mounted containing this Resource as an input (e.g. -// an input Resource named `workspace` will be mounted at `/workspace`). -type TaskResource = v1beta1.TaskResource - -// Outputs allow a task to declare what data the Build/Task will be producing, -// i.e. results such as logs and artifacts such as images. -type Outputs struct { - // +optional - Results []TestResult `json:"results,omitempty"` - // +optional - Resources []TaskResource `json:"resources,omitempty"` -} - -// TestResult allows a task to specify the location where test logs -// can be found and what format they will be in. -type TestResult struct { - // Name declares the name by which a result is referenced in the Task's - // definition. Results may be referenced by name in the definition of a - // Task's steps. - Name string `json:"name"` - // TODO: maybe this is an enum with types like "go test", "junit", etc. - Format string `json:"format"` - Path string `json:"path"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// TaskList contains a list of Task -type TaskList struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - Items []Task `json:"items"` -} diff --git a/pkg/apis/pipeline/v1alpha1/task_validation.go b/pkg/apis/pipeline/v1alpha1/task_validation.go deleted file mode 100644 index a80b5658f6e..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_validation.go +++ /dev/null @@ -1,437 +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 v1alpha1 - -import ( - "context" - "fmt" - "path/filepath" - "strings" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/pkg/apis/validate" - "github.com/tektoncd/pipeline/pkg/substitution" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/validation" - "knative.dev/pkg/apis" -) - -var _ apis.Validatable = (*Task)(nil) - -// Validate implements apis.Validatable -func (t *Task) Validate(ctx context.Context) *apis.FieldError { - if err := validate.ObjectMetadata(t.GetObjectMeta()); err != nil { - return err.ViaField("metadata") - } - if apis.IsInDelete(ctx) { - return nil - } - return t.Spec.Validate(ctx) -} - -// Validate implements apis.Validatable -func (ts *TaskSpec) Validate(ctx context.Context) *apis.FieldError { - - if len(ts.Steps) == 0 { - return apis.ErrMissingField("steps") - } - if err := ValidateVolumes(ts.Volumes).ViaField("volumes"); err != nil { - return err - } - if err := validateDeclaredWorkspaces(ts.Workspaces, ts.Steps, ts.StepTemplate); err != nil { - return err - } - mergedSteps, err := v1beta1.MergeStepsWithStepTemplate(ts.StepTemplate, ts.Steps) - if err != nil { - return &apis.FieldError{ - Message: fmt.Sprintf("error merging step template and steps: %s", err), - Paths: []string{"stepTemplate"}, - } - } - - if err := validateSteps(mergedSteps).ViaField("steps"); err != nil { - return err - } - - if ts.Inputs != nil { - if len(ts.Inputs.Params) > 0 && len(ts.Params) > 0 { - return apis.ErrMultipleOneOf("inputs.params", "params") - } - if ts.Resources != nil && len(ts.Resources.Inputs) > 0 && len(ts.Inputs.Resources) > 0 { - return apis.ErrMultipleOneOf("inputs.resources", "resources.inputs") - } - } - if ts.Outputs != nil { - if ts.Resources != nil && len(ts.Resources.Outputs) > 0 && len(ts.Outputs.Resources) > 0 { - return apis.ErrMultipleOneOf("outputs.resources", "resources.outputs") - } - } - - // Validate Resources declaration - if err := ts.Resources.Validate(ctx); err != nil { - return err - } - // Validate that the parameters type are correct - if err := v1beta1.ValidateParameterTypes(ctx, ts.Params); err != nil { - return err - } - - // A task doesn't have to have inputs or outputs, but if it does they must be valid. - // A task can't duplicate input or output names. - // Deprecated - if ts.Inputs != nil { - for _, resource := range ts.Inputs.Resources { - if err := validateResourceType(resource, fmt.Sprintf("taskspec.Inputs.Resources.%s.Type", resource.Name)); err != nil { - return err - } - } - if err := checkForDuplicates(ts.Inputs.Resources, "taskspec.Inputs.Resources.Name"); err != nil { - return err - } - if err := validateInputParameterTypes(ts.Inputs); err != nil { - return err - } - } - // Deprecated - if ts.Outputs != nil { - for _, resource := range ts.Outputs.Resources { - if err := validateResourceType(resource, fmt.Sprintf("taskspec.Outputs.Resources.%s.Type", resource.Name)); err != nil { - return err - } - } - if err := checkForDuplicates(ts.Outputs.Resources, "taskspec.Outputs.Resources.Name"); err != nil { - return err - } - } - - // Validate task step names - for _, step := range ts.Steps { - if errs := validation.IsDNS1123Label(step.Name); step.Name != "" && len(errs) > 0 { - return &apis.FieldError{ - Message: fmt.Sprintf("invalid value %q", step.Name), - Paths: []string{"taskspec.steps.name"}, - Details: "Task step name must be a valid DNS Label, For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - } - } - } - - if err := v1beta1.ValidateParameterVariables(ctx, ts.Steps, ts.Params); err != nil { - return err - } - // Deprecated - if err := validateInputParameterVariables(ts.Steps, ts.Inputs, ts.Params); err != nil { - return err - } - - if err := v1beta1.ValidateResourcesVariables(ctx, ts.Steps, ts.Resources); err != nil { - return err - } - // Deprecated - return validateResourceVariables(ts.Steps, ts.Inputs, ts.Outputs, ts.Resources) -} - -// validateDeclaredWorkspaces will make sure that the declared workspaces do not try to use -// a mount path which conflicts with any other declared workspaces, with the explicitly -// declared volume mounts, or with the stepTemplate. The names must also be unique. -func validateDeclaredWorkspaces(workspaces []WorkspaceDeclaration, steps []Step, stepTemplate *StepTemplate) *apis.FieldError { - mountPaths := sets.NewString() - for _, step := range steps { - for _, vm := range step.VolumeMounts { - mountPaths.Insert(filepath.Clean(vm.MountPath)) - } - } - if stepTemplate != nil { - for _, vm := range stepTemplate.VolumeMounts { - mountPaths.Insert(filepath.Clean(vm.MountPath)) - } - } - - wsNames := sets.NewString() - for _, w := range workspaces { - // Workspace names must be unique - if wsNames.Has(w.Name) { - return &apis.FieldError{ - Message: fmt.Sprintf("workspace name %q must be unique", w.Name), - Paths: []string{"workspaces.name"}, - } - } - wsNames.Insert(w.Name) - // Workspaces must not try to use mount paths that are already used - mountPath := filepath.Clean(w.GetMountPath()) - if mountPaths.Has(mountPath) { - return &apis.FieldError{ - Message: fmt.Sprintf("workspace mount path %q must be unique", mountPath), - Paths: []string{"workspaces.mountpath"}, - } - } - mountPaths.Insert(mountPath) - } - return nil -} - -// ValidateVolumes validates a slice of volumes to make sure there are no duplicate names -func ValidateVolumes(volumes []corev1.Volume) *apis.FieldError { - // Task must not have duplicate volume names. - vols := sets.NewString() - for _, v := range volumes { - if vols.Has(v.Name) { - return &apis.FieldError{ - Message: fmt.Sprintf("multiple volumes with same name %q", v.Name), - Paths: []string{"name"}, - } - } - vols.Insert(v.Name) - } - return nil -} - -func validateSteps(steps []Step) *apis.FieldError { - // Task must not have duplicate step names. - names := sets.NewString() - for idx, s := range steps { - if s.Image == "" { - return apis.ErrMissingField("Image") - } - - if s.Script != "" { - if len(s.Command) > 0 { - return &apis.FieldError{ - Message: fmt.Sprintf("step %d script cannot be used with command", idx), - Paths: []string{"script"}, - } - } - } - - if s.Name != "" { - if names.Has(s.Name) { - return apis.ErrInvalidValue(s.Name, "name") - } - names.Insert(s.Name) - } - - for _, vm := range s.VolumeMounts { - if strings.HasPrefix(vm.MountPath, "/tekton/") && - !strings.HasPrefix(vm.MountPath, "/tekton/home") { - return &apis.FieldError{ - Message: fmt.Sprintf("step %d volumeMount cannot be mounted under /tekton/ (volumeMount %q mounted at %q)", idx, vm.Name, vm.MountPath), - Paths: []string{"volumeMounts.mountPath"}, - } - } - if strings.HasPrefix(vm.Name, "tekton-internal-") { - return &apis.FieldError{ - Message: fmt.Sprintf(`step %d volumeMount name %q cannot start with "tekton-internal-"`, idx, vm.Name), - Paths: []string{"volumeMounts.name"}, - } - } - } - } - return nil -} - -func validateInputParameterTypes(inputs *Inputs) *apis.FieldError { - for _, p := range inputs.Params { - // Ensure param has a valid type. - validType := false - for _, allowedType := range AllParamTypes { - if p.Type == allowedType { - validType = true - } - } - if !validType { - return apis.ErrInvalidValue(p.Type, fmt.Sprintf("taskspec.inputs.params.%s.type", p.Name)) - } - - // If a default value is provided, ensure its type matches param's declared type. - if (p.Default != nil) && (p.Default.Type != p.Type) { - return &apis.FieldError{ - Message: fmt.Sprintf( - "\"%v\" type does not match default value's type: \"%v\"", p.Type, p.Default.Type), - Paths: []string{ - fmt.Sprintf("taskspec.inputs.params.%s.type", p.Name), - fmt.Sprintf("taskspec.inputs.params.%s.default.type", p.Name), - }, - } - } - } - return nil -} - -func validateInputParameterVariables(steps []Step, inputs *Inputs, params []v1beta1.ParamSpec) *apis.FieldError { - parameterNames := sets.NewString() - arrayParameterNames := sets.NewString() - - for _, p := range params { - parameterNames.Insert(p.Name) - if p.Type == ParamTypeArray { - arrayParameterNames.Insert(p.Name) - } - } - // Deprecated - if inputs != nil { - for _, p := range inputs.Params { - parameterNames.Insert(p.Name) - if p.Type == ParamTypeArray { - arrayParameterNames.Insert(p.Name) - } - } - } - - if err := validateVariables(steps, "params", parameterNames); err != nil { - return err - } - return validateArrayUsage(steps, "params", arrayParameterNames) -} - -func validateResourceVariables(steps []Step, inputs *Inputs, outputs *Outputs, resources *v1beta1.TaskResources) *apis.FieldError { - resourceNames := sets.NewString() - if resources != nil { - for _, r := range resources.Inputs { - resourceNames.Insert(r.Name) - } - for _, r := range resources.Outputs { - resourceNames.Insert(r.Name) - } - } - // Deprecated - if inputs != nil { - for _, r := range inputs.Resources { - resourceNames.Insert(r.Name) - } - } - // Deprecated - if outputs != nil { - for _, r := range outputs.Resources { - resourceNames.Insert(r.Name) - } - } - return validateVariables(steps, "resources", resourceNames) -} - -func validateArrayUsage(steps []Step, prefix string, vars sets.String) *apis.FieldError { - for _, step := range steps { - if err := validateTaskNoArrayReferenced("name", step.Name, prefix, vars); err != nil { - return err - } - if err := validateTaskNoArrayReferenced("image", step.Image, prefix, vars); err != nil { - return err - } - if err := validateTaskNoArrayReferenced("workingDir", step.WorkingDir, prefix, vars); err != nil { - return err - } - for i, cmd := range step.Command { - if err := validateTaskArraysIsolated(fmt.Sprintf("command[%d]", i), cmd, prefix, vars); err != nil { - return err - } - } - for i, arg := range step.Args { - if err := validateTaskArraysIsolated(fmt.Sprintf("arg[%d]", i), arg, prefix, vars); err != nil { - return err - } - } - for _, env := range step.Env { - if err := validateTaskNoArrayReferenced(fmt.Sprintf("env[%s]", env.Name), env.Value, prefix, vars); err != nil { - return err - } - } - for i, v := range step.VolumeMounts { - if err := validateTaskNoArrayReferenced(fmt.Sprintf("volumeMount[%d].Name", i), v.Name, prefix, vars); err != nil { - return err - } - if err := validateTaskNoArrayReferenced(fmt.Sprintf("volumeMount[%d].MountPath", i), v.MountPath, prefix, vars); err != nil { - return err - } - if err := validateTaskNoArrayReferenced(fmt.Sprintf("volumeMount[%d].SubPath", i), v.SubPath, prefix, vars); err != nil { - return err - } - } - } - return nil -} - -func validateVariables(steps []Step, prefix string, vars sets.String) *apis.FieldError { - for _, step := range steps { - if err := validateTaskVariable("name", step.Name, prefix, vars); err != nil { - return err - } - if err := validateTaskVariable("image", step.Image, prefix, vars); err != nil { - return err - } - if err := validateTaskVariable("workingDir", step.WorkingDir, prefix, vars); err != nil { - return err - } - for i, cmd := range step.Command { - if err := validateTaskVariable(fmt.Sprintf("command[%d]", i), cmd, prefix, vars); err != nil { - return err - } - } - for i, arg := range step.Args { - if err := validateTaskVariable(fmt.Sprintf("arg[%d]", i), arg, prefix, vars); err != nil { - return err - } - } - for _, env := range step.Env { - if err := validateTaskVariable(fmt.Sprintf("env[%s]", env.Name), env.Value, prefix, vars); err != nil { - return err - } - } - for i, v := range step.VolumeMounts { - if err := validateTaskVariable(fmt.Sprintf("volumeMount[%d].Name", i), v.Name, prefix, vars); err != nil { - return err - } - if err := validateTaskVariable(fmt.Sprintf("volumeMount[%d].MountPath", i), v.MountPath, prefix, vars); err != nil { - return err - } - if err := validateTaskVariable(fmt.Sprintf("volumeMount[%d].SubPath", i), v.SubPath, prefix, vars); err != nil { - return err - } - } - } - return nil -} - -func validateTaskVariable(name, value, prefix string, vars sets.String) *apis.FieldError { - return substitution.ValidateVariable(name, value, "(?:inputs|outputs)."+prefix, "step", "taskspec.steps", vars) -} - -func validateTaskNoArrayReferenced(name, value, prefix string, arrayNames sets.String) *apis.FieldError { - return substitution.ValidateVariableProhibited(name, value, "(?:inputs|outputs)."+prefix, "step", "taskspec.steps", arrayNames) -} - -func validateTaskArraysIsolated(name, value, prefix string, arrayNames sets.String) *apis.FieldError { - return substitution.ValidateVariableIsolated(name, value, "(?:inputs|outputs)."+prefix, "step", "taskspec.steps", arrayNames) -} - -func checkForDuplicates(resources []TaskResource, path string) *apis.FieldError { - encountered := sets.NewString() - for _, r := range resources { - if encountered.Has(strings.ToLower(r.Name)) { - return apis.ErrMultipleOneOf(path) - } - encountered.Insert(strings.ToLower(r.Name)) - } - return nil -} - -func validateResourceType(r TaskResource, path string) *apis.FieldError { - for _, allowed := range AllResourceTypes { - if r.Type == allowed { - return nil - } - } - return apis.ErrInvalidValue(r.Type, path) -} diff --git a/pkg/apis/pipeline/v1alpha1/task_validation_test.go b/pkg/apis/pipeline/v1alpha1/task_validation_test.go deleted file mode 100644 index febb2de3343..00000000000 --- a/pkg/apis/pipeline/v1alpha1/task_validation_test.go +++ /dev/null @@ -1,1029 +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 v1alpha1_test - -import ( - "context" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "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/test/diff" - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" -) - -var validResource = v1alpha1.TaskResource{ - ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "source", - Type: "git", - }, -} - -var validImageResource = v1alpha1.TaskResource{ - ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "source", - Type: "image", - }, -} - -var invalidResource = v1alpha1.TaskResource{ - ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "source", - Type: "what", - }, -} - -var optionalResource = v1alpha1.TaskResource{ - ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "source", - Type: "git", - Optional: true, - }, -} - -var requiredResource = v1alpha1.TaskResource{ - ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "source", - Type: "git", - Optional: false, - }, -} - -var validSteps = []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", -}} - -var invalidSteps = []v1alpha1.Step{{ - Name: "replaceImage", - Image: "myimage", -}} - -func TestTaskSpecValidate(t *testing.T) { - type fields struct { - Inputs *v1alpha1.Inputs - Outputs *v1alpha1.Outputs - Steps []v1alpha1.Step - StepTemplate *v1alpha1.StepTemplate - Workspaces []v1alpha1.WorkspaceDeclaration - } - tests := []struct { - name string - fields fields - }{{ - name: "unnamed steps", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - }, { - Image: "myotherimage", - }}, - }, - }, { - name: "valid inputs (type implied)", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "task", - Description: "param", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "default", - }, - }}, - }, - Steps: validSteps, - }, - }, { - name: "valid inputs type explicit", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "task", - Type: v1alpha1.ParamTypeString, - Description: "param", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "default", - }, - }}, - }, - Steps: validSteps, - }, - }, { - name: "valid inputs (required)", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{requiredResource}, - }, - Steps: validSteps, - }, - }, { - name: "valid inputs (optional)", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{optionalResource}, - }, - Steps: validSteps, - }, - }, { - name: "valid outputs", - fields: fields{ - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: validSteps, - }, - }, { - name: "both valid", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: validSteps, - }, - }, { - name: "output image resoure", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - }, - Steps: validSteps, - }, - }, { - name: "valid outputs (required)", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{requiredResource}, - }, - Steps: validSteps, - }, - }, { - name: "valid outputs (optional)", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{optionalResource}, - }, - Steps: validSteps, - }, - }, { - name: "valid template variable", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - }, { - Name: "foo-is-baz", - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "$(inputs.resources.source.url)", - Args: []string{"--flag=$(inputs.params.baz) && $(input.params.foo-is-baz)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - }, { - name: "valid array template variable", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "$(inputs.resources.source.url)", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"$(inputs.params.baz)", "middle string", "$(input.params.foo-is-baz)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - }, { - name: "valid star array template variable", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "$(inputs.resources.source.url)", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"$(inputs.params.baz[*])", "middle string", "$(input.params.foo-is-baz[*])"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - }, { - name: "valid legacy credential helper (creds-init) path variable", - fields: fields{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "echo", - Args: []string{"$(credentials.path)"}, - }}, - }, - }, { - name: "step template included in validation", - fields: fields{ - Steps: []v1alpha1.Step{{ - Name: "astep", - Command: []string{"echo"}, - Args: []string{"hello"}, - }}, - StepTemplate: &v1alpha1.StepTemplate{ - Image: "some-image", - }, - }, - }, { - name: "valid step with script", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "my-image", - Script: ` - #!/usr/bin/env bash - hello world`, - }}, - }, - }, { - name: "valid step with script and args", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "my-image", - Args: []string{"arg"}, - Script: ` - #!/usr/bin/env bash - hello $1`, - }}, - }, - }, { - name: "valid step with volumeMount under /tekton/home", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - VolumeMounts: []corev1.VolumeMount{{ - Name: "foo", - MountPath: "/tekton/home", - }}, - }}, - }, - }, { - name: "valid workspace", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "my-image", - Args: []string{"arg"}, - }}, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "foo-workspace", - Description: "my great workspace", - MountPath: "some/path", - }}, - }, - }} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ts := &v1alpha1.TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Steps: tt.fields.Steps, - StepTemplate: tt.fields.StepTemplate, - Workspaces: tt.fields.Workspaces, - }, - Inputs: tt.fields.Inputs, - Outputs: tt.fields.Outputs, - } - ctx := context.Background() - ts.SetDefaults(ctx) - if err := ts.Validate(ctx); err != nil { - t.Errorf("TaskSpec.Validate() = %v", err) - } - }) - } -} - -func TestTaskSpecValidateError(t *testing.T) { - type fields struct { - Inputs *v1alpha1.Inputs - Outputs *v1alpha1.Outputs - Steps []v1alpha1.Step - Volumes []corev1.Volume - StepTemplate *v1alpha1.StepTemplate - Workspaces []v1alpha1.WorkspaceDeclaration - // v1beta1 - Params []v1beta1.ParamSpec - Resources *v1beta1.TaskResources - } - tests := []struct { - name string - fields fields - expectedError apis.FieldError - }{{ - name: "empty spec", - expectedError: apis.FieldError{ - Message: `missing field(s)`, - Paths: []string{"steps"}, - }, - }, { - name: "no build", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - }, - expectedError: apis.FieldError{ - Message: `missing field(s)`, - Paths: []string{"steps"}, - }, - }, { - name: "one invalid input", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{ - invalidResource, - validResource, - }, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{ - validResource, - }, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: `invalid value: what`, - Paths: []string{"taskspec.Inputs.Resources.source.Type"}, - }, - }, { - name: "invalid input type", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "validparam", - Type: v1alpha1.ParamTypeString, - Description: "parameter", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "default", - }, - }, { - Name: "param-with-invalid-type", - Type: "invalidtype", - Description: "invalidtypedesc", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "default", - }, - }}, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: `invalid value: invalidtype`, - Paths: []string{"taskspec.inputs.params.param-with-invalid-type.type"}, - }, - }, { - name: "input mismatching default/type 1", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "task", - Type: v1alpha1.ParamTypeArray, - Description: "param", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "default", - }, - }}, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: `"array" type does not match default value's type: "string"`, - Paths: []string{"taskspec.inputs.params.task.type", "taskspec.inputs.params.task.default.type"}, - }, - }, { - name: "input mismatching default/type 2", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "task", - Type: v1alpha1.ParamTypeString, - Description: "param", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"default", "array"}, - }, - }}, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: `"string" type does not match default value's type: "array"`, - Paths: []string{"taskspec.inputs.params.task.type", "taskspec.inputs.params.task.default.type"}, - }, - }, { - name: "one invalid output", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{ - validResource, - }, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{ - invalidResource, - validResource, - }, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: `invalid value: what`, - Paths: []string{"taskspec.Outputs.Resources.source.Type"}, - }, - }, { - name: "duplicated inputs", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{ - validResource, - validResource, - }, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{ - validResource, - }, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: "expected exactly one, got both", - Paths: []string{"taskspec.Inputs.Resources.Name"}, - }, - }, { - name: "duplicated outputs", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{ - validResource, - }, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{ - validResource, - validResource, - }, - }, - Steps: validSteps, - }, - expectedError: apis.FieldError{ - Message: "expected exactly one, got both", - Paths: []string{"taskspec.Outputs.Resources.Name"}, - }, - }, { - name: "invalid build", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{}, - }, - expectedError: apis.FieldError{ - Message: "missing field(s)", - Paths: []string{"steps"}, - }, - }, { - name: "invalid build step name", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: invalidSteps, - }, - expectedError: apis.FieldError{ - Message: `invalid value "replaceImage"`, - Paths: []string{"taskspec.steps.name"}, - Details: "Task step name must be a valid DNS Label, For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - }, - }, { - name: "inexistent input param variable", - fields: fields{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - Args: []string{"--flag=$(inputs.params.inexistent)"}, - }}, - }, - expectedError: apis.FieldError{ - Message: `non-existent variable in "--flag=$(inputs.params.inexistent)" for step arg[0]`, - Paths: []string{"taskspec.steps.arg[0]"}, - }, - }, { - name: "array used in unaccepted field", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "$(inputs.params.baz)", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"$(inputs.params.baz)", "middle string", "$(input.resources.foo.url)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - expectedError: apis.FieldError{ - Message: `variable type invalid in "$(inputs.params.baz)" for step image`, - Paths: []string{"taskspec.steps.image"}, - }, - }, { - name: "star array used in unaccepted field", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "$(inputs.params.baz[*])", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"$(inputs.params.baz)", "middle string", "$(input.resources.foo.url)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - expectedError: apis.FieldError{ - Message: `variable type invalid in "$(inputs.params.baz[*])" for step image`, - Paths: []string{"taskspec.steps.image"}, - }, - }, { - name: "array not properly isolated", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "someimage", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"not isolated: $(inputs.params.baz)", "middle string", "$(input.resources.foo.url)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - expectedError: apis.FieldError{ - Message: `variable is not properly isolated in "not isolated: $(inputs.params.baz)" for step arg[0]`, - Paths: []string{"taskspec.steps.arg[0]"}, - }, - }, { - name: "star array not properly isolated", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Type: v1alpha1.ParamTypeArray, - }, { - Name: "foo-is-baz", - Type: v1alpha1.ParamTypeArray, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "someimage", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"not isolated: $(inputs.params.baz[*])", "middle string", "$(input.resources.foo.url)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - expectedError: apis.FieldError{ - Message: `variable is not properly isolated in "not isolated: $(inputs.params.baz[*])" for step arg[0]`, - Paths: []string{"taskspec.steps.arg[0]"}, - }, - }, { - name: "inexistent input resource variable", - fields: fields{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage:$(inputs.resources.inputs)", - }}, - }, - expectedError: apis.FieldError{ - Message: `non-existent variable in "myimage:$(inputs.resources.inputs)" for step image`, - Paths: []string{"taskspec.steps.image"}, - }, - }, { - name: "inferred array not properly isolated", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{validImageResource}, - Params: []v1alpha1.ParamSpec{{ - Name: "baz", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"implied", "array", "type"}, - }, - }, { - Name: "foo-is-baz", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeArray, - ArrayVal: []string{"implied", "array", "type"}, - }, - }}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{validResource}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "someimage", - Command: []string{"$(inputs.params.foo-is-baz)"}, - Args: []string{"not isolated: $(inputs.params.baz)", "middle string", "$(input.resources.foo.url)"}, - WorkingDir: "/foo/bar/$(outputs.resources.source)", - }}, - }, - expectedError: apis.FieldError{ - Message: `variable is not properly isolated in "not isolated: $(inputs.params.baz)" for step arg[0]`, - Paths: []string{"taskspec.steps.arg[0]"}, - }, - }, { - name: "inexistent input resource variable", - fields: fields{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage:$(inputs.resources.inputs)", - }}, - }, - expectedError: apis.FieldError{ - Message: `non-existent variable in "myimage:$(inputs.resources.inputs)" for step image`, - Paths: []string{"taskspec.steps.image"}, - }, - }, { - name: "inexistent output param variable", - fields: fields{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - WorkingDir: "/foo/bar/$(outputs.resources.inexistent)", - }}, - }, - expectedError: apis.FieldError{ - Message: `non-existent variable in "/foo/bar/$(outputs.resources.inexistent)" for step workingDir`, - Paths: []string{"taskspec.steps.workingDir"}, - }, - }, { - name: "Inexistent param variable with existing", - fields: fields{ - Inputs: &v1alpha1.Inputs{ - Params: []v1alpha1.ParamSpec{{ - Name: "foo", - Description: "param", - Default: &v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "default", - }, - }}, - }, - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - Args: []string{"$(inputs.params.foo) && $(inputs.params.inexistent)"}, - }}, - }, - expectedError: apis.FieldError{ - Message: `non-existent variable in "$(inputs.params.foo) && $(inputs.params.inexistent)" for step arg[0]`, - Paths: []string{"taskspec.steps.arg[0]"}, - }, - }, { - name: "Multiple volumes with same name", - fields: fields{ - Steps: validSteps, - Volumes: []corev1.Volume{{ - Name: "workspace", - }, { - Name: "workspace", - }}, - }, - expectedError: apis.FieldError{ - Message: `multiple volumes with same name "workspace"`, - Paths: []string{"volumes.name"}, - }, - }, { - name: "step with script and command", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - Command: []string{"command"}, - Script: "script", - }}, - }, - expectedError: apis.FieldError{ - Message: "step 0 script cannot be used with command", - Paths: []string{"steps.script"}, - }, - }, { - name: "step volume mounts under /tekton/", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - VolumeMounts: []corev1.VolumeMount{{ - Name: "foo", - MountPath: "/tekton/foo", - }}, - }}, - }, - expectedError: apis.FieldError{ - Message: `step 0 volumeMount cannot be mounted under /tekton/ (volumeMount "foo" mounted at "/tekton/foo")`, - Paths: []string{"steps.volumeMounts.mountPath"}, - }, - }, { - name: "step volume mount name starts with tekton-internal-", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - VolumeMounts: []corev1.VolumeMount{{ - Name: "tekton-internal-foo", - MountPath: "/this/is/fine", - }}, - }}, - }, - expectedError: apis.FieldError{ - Message: `step 0 volumeMount name "tekton-internal-foo" cannot start with "tekton-internal-"`, - Paths: []string{"steps.volumeMounts.name"}, - }, - }, { - name: "declared workspaces names are not unique", - fields: fields{ - Steps: validSteps, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "same-workspace", - }, { - Name: "same-workspace", - }}, - }, - expectedError: apis.FieldError{ - Message: "workspace name \"same-workspace\" must be unique", - Paths: []string{"workspaces.name"}, - }, - }, { - name: "declared workspaces clash with each other", - fields: fields{ - Steps: validSteps, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "some-workspace", - MountPath: "/foo", - }, { - Name: "another-workspace", - MountPath: "/foo", - }}, - }, - expectedError: apis.FieldError{ - Message: "workspace mount path \"/foo\" must be unique", - Paths: []string{"workspaces.mountpath"}, - }, - }, { - name: "workspace mount path already in volumeMounts", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - Command: []string{"command"}, - VolumeMounts: []corev1.VolumeMount{{ - Name: "my-mount", - MountPath: "/foo", - }}, - }}, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "some-workspace", - MountPath: "/foo", - }}, - }, - expectedError: apis.FieldError{ - Message: "workspace mount path \"/foo\" must be unique", - Paths: []string{"workspaces.mountpath"}, - }, - }, { - name: "workspace default mount path already in volumeMounts", - fields: fields{ - Steps: []v1alpha1.Step{{ - Image: "myimage", - Command: []string{"command"}, - VolumeMounts: []corev1.VolumeMount{{ - Name: "my-mount", - MountPath: "/workspace/some-workspace/", - }}, - }}, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "some-workspace", - }}, - }, - expectedError: apis.FieldError{ - Message: "workspace mount path \"/workspace/some-workspace\" must be unique", - Paths: []string{"workspaces.mountpath"}, - }, - }, { - name: "workspace mount path already in stepTemplate", - fields: fields{ - StepTemplate: &v1alpha1.StepTemplate{ - VolumeMounts: []corev1.VolumeMount{{ - Name: "my-mount", - MountPath: "/foo", - }}, - }, - Steps: validSteps, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "some-workspace", - MountPath: "/foo", - }}, - }, - expectedError: apis.FieldError{ - Message: "workspace mount path \"/foo\" must be unique", - Paths: []string{"workspaces.mountpath"}, - }, - }, { - name: "workspace default mount path already in stepTemplate", - fields: fields{ - StepTemplate: &v1alpha1.StepTemplate{ - VolumeMounts: []corev1.VolumeMount{{ - Name: "my-mount", - MountPath: "/workspace/some-workspace", - }}, - }, - Steps: validSteps, - Workspaces: []v1alpha1.WorkspaceDeclaration{{ - Name: "some-workspace", - }}, - }, - expectedError: apis.FieldError{ - Message: "workspace mount path \"/workspace/some-workspace\" must be unique", - Paths: []string{"workspaces.mountpath"}, - }, - }, { - name: "v1beta1: params and deprecated inputs.params", - fields: fields{ - Steps: validSteps, - Params: []v1beta1.ParamSpec{{ - Name: "param1", - Type: v1beta1.ParamTypeString, - }}, - Inputs: &v1alpha1.Inputs{ - Params: []v1alpha1.ParamSpec{{ - Name: "param1", - Type: v1beta1.ParamTypeString, - }}, - }, - }, - expectedError: apis.FieldError{ - Message: "expected exactly one, got both", - Paths: []string{"inputs.params", "params"}, - }, - }, { - name: "v1beta1: resources.inputs and deprecated inputs.resource", - fields: fields{ - Steps: validSteps, - Resources: &v1beta1.TaskResources{ - Inputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - Inputs: &v1alpha1.Inputs{ - Resources: []v1alpha1.TaskResource{{ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "input-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - expectedError: apis.FieldError{ - Message: "expected exactly one, got both", - Paths: []string{"inputs.resources", "resources.inputs"}, - }, - }, { - name: "v1beta1: resources.outputs and deprecated outputs.resource", - fields: fields{ - Steps: validSteps, - Resources: &v1beta1.TaskResources{ - Outputs: []v1beta1.TaskResource{{ResourceDeclaration: v1beta1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - Outputs: &v1alpha1.Outputs{ - Resources: []v1alpha1.TaskResource{{ResourceDeclaration: v1alpha1.ResourceDeclaration{ - Name: "output-1", - Type: resource.PipelineResourceTypeGit, - }}}, - }, - }, - expectedError: apis.FieldError{ - Message: "expected exactly one, got both", - Paths: []string{"outputs.resources", "resources.outputs"}, - }, - }} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ts := &v1alpha1.TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Steps: tt.fields.Steps, - Volumes: tt.fields.Volumes, - StepTemplate: tt.fields.StepTemplate, - Workspaces: tt.fields.Workspaces, - Params: tt.fields.Params, - Resources: tt.fields.Resources, - }, - Inputs: tt.fields.Inputs, - Outputs: tt.fields.Outputs, - } - ctx := context.Background() - ts.SetDefaults(ctx) - err := ts.Validate(context.Background()) - if err == nil { - t.Fatalf("Expected an error, got nothing for %v", ts) - } - if d := cmp.Diff(tt.expectedError, *err, cmpopts.IgnoreUnexported(apis.FieldError{})); d != "" { - t.Errorf("TaskSpec.Validate() errors diff %s", diff.PrintWantGot(d)) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_conversion.go b/pkg/apis/pipeline/v1alpha1/taskrun_conversion.go deleted file mode 100644 index e41b49ae1e1..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_conversion.go +++ /dev/null @@ -1,149 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "fmt" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "knative.dev/pkg/apis" -) - -var _ apis.Convertible = (*TaskRun)(nil) - -// ConvertTo implements api.Convertible -func (tr *TaskRun) ConvertTo(ctx context.Context, obj apis.Convertible) error { - switch sink := obj.(type) { - case *v1beta1.TaskRun: - sink.ObjectMeta = tr.ObjectMeta - if err := tr.Spec.ConvertTo(ctx, &sink.Spec); err != nil { - return err - } - sink.Status = tr.Status - return nil - default: - return fmt.Errorf("unknown version, got: %T", sink) - } -} - -// ConvertTo implements api.Convertible -func (trs *TaskRunSpec) ConvertTo(ctx context.Context, sink *v1beta1.TaskRunSpec) error { - sink.ServiceAccountName = trs.ServiceAccountName - sink.TaskRef = trs.TaskRef - if trs.TaskSpec != nil { - sink.TaskSpec = &v1beta1.TaskSpec{} - if err := trs.TaskSpec.ConvertTo(ctx, sink.TaskSpec); err != nil { - return err - } - } - sink.Status = trs.Status - sink.Timeout = trs.Timeout - sink.PodTemplate = trs.PodTemplate - sink.Workspaces = trs.Workspaces - sink.Params = trs.Params - sink.Resources = trs.Resources - // Deprecated fields - if trs.Inputs != nil { - if len(trs.Inputs.Params) > 0 && len(trs.Params) > 0 { - // This shouldn't happen as it shouldn't pass validation - return apis.ErrMultipleOneOf("inputs.params", "params") - } - if len(trs.Inputs.Params) > 0 { - sink.Params = make([]v1beta1.Param, len(trs.Inputs.Params)) - for i, param := range trs.Inputs.Params { - sink.Params[i] = *param.DeepCopy() - } - } - if len(trs.Inputs.Resources) > 0 { - if sink.Resources == nil { - sink.Resources = &v1beta1.TaskRunResources{} - } - if len(trs.Inputs.Resources) > 0 && trs.Resources != nil && len(trs.Resources.Inputs) > 0 { - // This shouldn't happen as it shouldn't pass validation but just in case - return apis.ErrMultipleOneOf("inputs.resources", "resources.inputs") - } - sink.Resources.Inputs = make([]v1beta1.TaskResourceBinding, len(trs.Inputs.Resources)) - for i, resource := range trs.Inputs.Resources { - sink.Resources.Inputs[i] = v1beta1.TaskResourceBinding{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: resource.Name, - ResourceRef: resource.ResourceRef, - ResourceSpec: resource.ResourceSpec, - }, - Paths: resource.Paths, - } - } - } - } - - if trs.Outputs != nil && len(trs.Outputs.Resources) > 0 { - if sink.Resources == nil { - sink.Resources = &v1beta1.TaskRunResources{} - } - if len(trs.Outputs.Resources) > 0 && trs.Resources != nil && len(trs.Resources.Outputs) > 0 { - // This shouldn't happen as it shouldn't pass validation but just in case - return apis.ErrMultipleOneOf("outputs.resources", "resources.outputs") - } - sink.Resources.Outputs = make([]v1beta1.TaskResourceBinding, len(trs.Outputs.Resources)) - for i, resource := range trs.Outputs.Resources { - sink.Resources.Outputs[i] = v1beta1.TaskResourceBinding{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: resource.Name, - ResourceRef: resource.ResourceRef, - ResourceSpec: resource.ResourceSpec, - }, - Paths: resource.Paths, - } - } - } - return nil -} - -// ConvertFrom implements api.Convertible -func (tr *TaskRun) ConvertFrom(ctx context.Context, obj apis.Convertible) error { - switch source := obj.(type) { - case *v1beta1.TaskRun: - tr.ObjectMeta = source.ObjectMeta - if err := tr.Spec.ConvertFrom(ctx, &source.Spec); err != nil { - return err - } - tr.Status = source.Status - return nil - default: - return fmt.Errorf("unknown version, got: %T", tr) - } -} - -// ConvertFrom implements api.Convertible -func (trs *TaskRunSpec) ConvertFrom(ctx context.Context, source *v1beta1.TaskRunSpec) error { - trs.ServiceAccountName = source.ServiceAccountName - trs.TaskRef = source.TaskRef - if source.TaskSpec != nil { - trs.TaskSpec = &TaskSpec{} - if err := trs.TaskSpec.ConvertFrom(ctx, source.TaskSpec); err != nil { - return err - } - } - trs.Status = source.Status - trs.Timeout = source.Timeout - trs.PodTemplate = source.PodTemplate - trs.Workspaces = source.Workspaces - trs.Params = source.Params - trs.Resources = source.Resources - return nil -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_conversion_test.go b/pkg/apis/pipeline/v1alpha1/taskrun_conversion_test.go deleted file mode 100644 index 9e0397940be..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_conversion_test.go +++ /dev/null @@ -1,434 +0,0 @@ -/* -Copyright 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 v1alpha1 - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestTaskRunConversionBadType(t *testing.T) { - good, bad := &TaskRun{}, &Task{} - - if err := good.ConvertTo(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } - - if err := good.ConvertFrom(context.Background(), bad); err == nil { - t.Errorf("ConvertTo() = %#v, wanted error", bad) - } -} - -func TestTaskRunConversion(t *testing.T) { - versions := []apis.Convertible{&v1beta1.TaskRun{}} - - tests := []struct { - name string - in *TaskRun - wantErr bool - }{{ - name: "simple conversion taskref", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - TaskRef: &TaskRef{ - Name: "task", - }, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Params: []Param{{ - Name: "p1", - Value: *v1beta1.NewArrayOrString("baz"), - }}, - Resources: &v1beta1.TaskRunResources{ - Inputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - Outputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "o1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r2"}, - }, - }}, - }, - }, - Status: TaskRunStatus{ - TaskRunStatusFields: TaskRunStatusFields{ - PodName: "foo", - StartTime: &metav1.Time{Time: time.Now().Add(-4 * time.Minute)}, - CompletionTime: &metav1.Time{Time: time.Now().Add(-1 * time.Minute)}, - Steps: []StepState{{ - Name: "s1", - }}, - }, - }, - }, - }, { - name: "simple conversion taskspec", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - TaskSpec: &TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - }}, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Params: []Param{{ - Name: "p1", - Value: *v1beta1.NewArrayOrString("baz"), - }}, - Resources: &v1beta1.TaskRunResources{ - Inputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - Outputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "o1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r2"}, - }, - }}, - }, - }, - }, - }, { - name: "deprecated and non deprecated params", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - TaskSpec: &TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - }}, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Params: []Param{{ - Name: "p1", - Value: *v1beta1.NewArrayOrString("baz"), - }}, - Inputs: &TaskRunInputs{ - Params: []Param{{ - Name: "p2", - Value: *v1beta1.NewArrayOrString("bar"), - }}, - }, - }, - }, - wantErr: true, - }, { - name: "deprecated and non deprecated inputs", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - TaskSpec: &TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - }}, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Resources: &v1beta1.TaskRunResources{ - Inputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - Inputs: &TaskRunInputs{ - Resources: []TaskResourceBinding{{ - PipelineResourceBinding: PipelineResourceBinding{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - }, - }, - wantErr: true, - }, { - name: "deprecated and non deprecated outputs", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - TaskSpec: &TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "foo", - }}, - }}, - ServiceAccountName: "sa", - Timeout: &metav1.Duration{Duration: 1 * time.Minute}, - PodTemplate: &PodTemplate{ - NodeSelector: map[string]string{"foo": "bar"}, - }, - Workspaces: []WorkspaceBinding{{ - Name: "w1", - SubPath: "foo", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }}, - Resources: &v1beta1.TaskRunResources{ - Outputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "o1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - Outputs: &TaskRunOutputs{ - Resources: []TaskResourceBinding{{ - PipelineResourceBinding: PipelineResourceBinding{ - Name: "o1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - }, - }, - wantErr: true, - }} - - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - if !test.wantErr { - t.Errorf("ConvertTo() = %v", err) - } - return - } - t.Logf("ConvertTo() = %#v", ver) - got := &TaskRun{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.in, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} - -func TestTaskRunConversionFromDeprecated(t *testing.T) { - versions := []apis.Convertible{&v1beta1.TaskRun{}} - tests := []struct { - name string - in *TaskRun - want *TaskRun - }{{ - name: "inputs params", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - Inputs: &TaskRunInputs{ - Params: []Param{{ - Name: "p2", - Value: *v1beta1.NewArrayOrString("bar"), - }}, - }, - }, - }, - want: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - Params: []Param{{ - Name: "p2", - Value: *v1beta1.NewArrayOrString("bar"), - }}, - }, - }, - }, { - name: "inputs resource", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - Inputs: &TaskRunInputs{ - Resources: []TaskResourceBinding{{ - PipelineResourceBinding: PipelineResourceBinding{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - }, - }, - want: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - Resources: &v1beta1.TaskRunResources{ - Inputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "i1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - }, - }, - }, { - name: "outputs resource", - in: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - Outputs: &TaskRunOutputs{ - Resources: []TaskResourceBinding{{ - PipelineResourceBinding: PipelineResourceBinding{ - Name: "o1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - }, - }, - want: &TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Generation: 1, - }, - Spec: TaskRunSpec{ - Resources: &v1beta1.TaskRunResources{ - Outputs: []v1beta1.TaskResourceBinding{{ - PipelineResourceBinding: v1beta1.PipelineResourceBinding{ - Name: "o1", - ResourceRef: &v1beta1.PipelineResourceRef{Name: "r1"}, - }, - Paths: []string{"foo", "bar"}, - }}, - }, - }, - }, - }} - for _, test := range tests { - for _, version := range versions { - t.Run(test.name, func(t *testing.T) { - ver := version - if err := test.in.ConvertTo(context.Background(), ver); err != nil { - t.Errorf("ConvertTo() = %v", err) - } - t.Logf("ConvertTo() = %#v", ver) - got := &TaskRun{} - if err := got.ConvertFrom(context.Background(), ver); err != nil { - t.Errorf("ConvertFrom() = %v", err) - } - t.Logf("ConvertFrom() = %#v", got) - if d := cmp.Diff(test.want, got); d != "" { - t.Errorf("roundtrip %s", diff.PrintWantGot(d)) - } - }) - } - } -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_defaults.go b/pkg/apis/pipeline/v1alpha1/taskrun_defaults.go deleted file mode 100644 index 871703ca841..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_defaults.go +++ /dev/null @@ -1,74 +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 v1alpha1 - -import ( - "context" - "time" - - "github.com/tektoncd/pipeline/pkg/apis/config" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -var _ apis.Defaultable = (*TaskRun)(nil) - -// ManagedByLabelKey is the label key used to mark what is managing this resource -const ManagedByLabelKey = "app.kubernetes.io/managed-by" - -// SetDefaults implements apis.Defaultable -func (tr *TaskRun) SetDefaults(ctx context.Context) { - ctx = apis.WithinParent(ctx, tr.ObjectMeta) - tr.Spec.SetDefaults(apis.WithinSpec(ctx)) - - // If the TaskRun doesn't have a managed-by label, apply the default - // specified in the config. - cfg := config.FromContextOrDefaults(ctx) - if tr.ObjectMeta.Labels == nil { - tr.ObjectMeta.Labels = map[string]string{} - } - if _, found := tr.ObjectMeta.Labels[ManagedByLabelKey]; !found { - tr.ObjectMeta.Labels[ManagedByLabelKey] = cfg.Defaults.DefaultManagedByLabelValue - } -} - -// SetDefaults implements apis.Defaultable -func (trs *TaskRunSpec) SetDefaults(ctx context.Context) { - cfg := config.FromContextOrDefaults(ctx) - if trs.TaskRef != nil && trs.TaskRef.Kind == "" { - trs.TaskRef.Kind = NamespacedTaskKind - } - - if trs.Timeout == nil { - trs.Timeout = &metav1.Duration{Duration: time.Duration(cfg.Defaults.DefaultTimeoutMinutes) * time.Minute} - } - - defaultSA := cfg.Defaults.DefaultServiceAccount - if trs.ServiceAccountName == "" && defaultSA != "" { - trs.ServiceAccountName = defaultSA - } - - defaultPodTemplate := cfg.Defaults.DefaultPodTemplate - if trs.PodTemplate == nil { - trs.PodTemplate = defaultPodTemplate - } - - // If this taskrun has an embedded task, apply the usual task defaults - if trs.TaskSpec != nil { - trs.TaskSpec.SetDefaults(ctx) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_defaults_test.go b/pkg/apis/pipeline/v1alpha1/taskrun_defaults_test.go deleted file mode 100644 index 86fcee74827..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_defaults_test.go +++ /dev/null @@ -1,379 +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 v1alpha1_test - -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/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - logtesting "knative.dev/pkg/logging/testing" -) - -func TestTaskRunSpec_SetDefaults(t *testing.T) { - cases := []struct { - desc string - trs *v1alpha1.TaskRunSpec - want *v1alpha1.TaskRunSpec - }{{ - desc: "taskref is nil", - trs: &v1alpha1.TaskRunSpec{ - TaskRef: nil, - Timeout: &metav1.Duration{Duration: 500 * time.Millisecond}, - }, - want: &v1alpha1.TaskRunSpec{ - TaskRef: nil, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 500 * time.Millisecond}, - }, - }, { - desc: "taskref kind is empty", - trs: &v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{}, - Timeout: &metav1.Duration{Duration: 500 * time.Millisecond}, - }, - want: &v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Kind: v1alpha1.NamespacedTaskKind}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 500 * time.Millisecond}, - }, - }, { - desc: "timeout is nil", - trs: &v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Kind: v1alpha1.ClusterTaskKind}, - }, - want: &v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Kind: v1alpha1.ClusterTaskKind}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, { - desc: "pod template is nil", - trs: &v1alpha1.TaskRunSpec{}, - want: &v1alpha1.TaskRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, { - desc: "pod template is not nil", - trs: &v1alpha1.TaskRunSpec{ - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label": "value", - }, - }, - }, - want: &v1alpha1.TaskRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label": "value", - }, - }, - }, - }, { - desc: "embedded taskSpec", - trs: &v1alpha1.TaskRunSpec{ - TaskSpec: &v1alpha1.TaskSpec{ - Inputs: &v1alpha1.Inputs{ - Params: []v1alpha1.ParamSpec{{ - Name: "param-name", - }}, - }, - }, - }, - want: &v1alpha1.TaskRunSpec{ - TaskSpec: &v1alpha1.TaskSpec{ - Inputs: &v1alpha1.Inputs{ - Params: []v1alpha1.ParamSpec{{ - Name: "param-name", - Type: v1alpha1.ParamTypeString, - }}, - }, - }, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }} - for _, tc := range cases { - t.Run(tc.desc, func(t *testing.T) { - ctx := context.Background() - tc.trs.SetDefaults(ctx) - - if d := cmp.Diff(tc.want, tc.trs); d != "" { - t.Errorf("Mismatch of TaskRunSpec %s", diff.PrintWantGot(d)) - } - }) - } -} - -func TestTaskRunDefaulting(t *testing.T) { - tests := []struct { - name string - in *v1alpha1.TaskRun - want *v1alpha1.TaskRun - wc func(context.Context) context.Context - }{{ - name: "empty no context", - in: &v1alpha1.TaskRun{}, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "tekton-pipelines"}, - }, - Spec: v1alpha1.TaskRunSpec{ - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, - }, { - name: "TaskRef default to namespace kind", - in: &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "tekton-pipelines"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: config.DefaultTimeoutMinutes * time.Minute}, - }, - }, - }, { - name: "TaskRef default config context", - in: &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "tekton-pipelines"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "TaskRef default config context with SA", - in: &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "tekton-pipelines"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - ServiceAccountName: "tekton", - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-service-account": "tekton", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "TaskRun managed-by set in config", - in: &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "something-else"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-managed-by-label-value": "something-else", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "TaskRun managed-by set in request and config (request wins)", - in: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "user-specified"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "user-specified"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - ServiceAccountName: config.DefaultServiceAccountValue, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-managed-by-label-value": "something-else", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "TaskRef pod template is coming from default config pod template", - in: &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "tekton-pipelines"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - ServiceAccountName: "tekton", - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label": "value", - }, - }, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-service-account": "tekton", - "default-pod-template": "nodeSelector: { 'label': 'value' }", - }, - }) - return s.ToContext(ctx) - }, - }, { - name: "TaskRef pod template takes precedence over default config pod template", - in: &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo"}, - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label2": "value2", - }, - }, - }, - }, - want: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app.kubernetes.io/managed-by": "tekton-pipelines"}, - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{Name: "foo", Kind: v1alpha1.NamespacedTaskKind}, - Timeout: &metav1.Duration{Duration: 5 * time.Minute}, - ServiceAccountName: "tekton", - PodTemplate: &v1alpha1.PodTemplate{ - NodeSelector: map[string]string{ - "label2": "value2", - }, - }, - }, - }, - wc: func(ctx context.Context) context.Context { - s := config.NewStore(logtesting.TestLogger(t)) - s.OnConfigChanged(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: config.GetDefaultsConfigName(), - }, - Data: map[string]string{ - "default-timeout-minutes": "5", - "default-service-account": "tekton", - "default-pod-template": "nodeSelector: { 'label': 'value' }", - }, - }) - return s.ToContext(ctx) - }, - }} - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - got := tc.in - ctx := context.Background() - if tc.wc != nil { - ctx = tc.wc(ctx) - } - got.SetDefaults(ctx) - if d := cmp.Diff(tc.want, got, ignoreUnexportedResources); d != "" { - t.Errorf("SetDefaults %s", diff.PrintWantGot(d)) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_types.go b/pkg/apis/pipeline/v1alpha1/taskrun_types.go deleted file mode 100644 index 6f6af8cb471..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_types.go +++ /dev/null @@ -1,266 +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 v1alpha1 - -import ( - "fmt" - "time" - - apisconfig "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/clock" - "knative.dev/pkg/apis" -) - -// TaskRunSpec defines the desired state of TaskRun -type TaskRunSpec struct { - // +optional - ServiceAccountName string `json:"serviceAccountName"` - // no more than one of the TaskRef and TaskSpec may be specified. - // +optional - TaskRef *TaskRef `json:"taskRef,omitempty"` - // +optional - TaskSpec *TaskSpec `json:"taskSpec,omitempty"` - // Used for cancelling a taskrun (and maybe more later on) - // +optional - Status TaskRunSpecStatus `json:"status,omitempty"` - // Time after which the build times out. Defaults to 10 minutes. - // Specified build timeout should be less than 24h. - // Refer Go's ParseDuration documentation for expected format: https://golang.org/pkg/time/#ParseDuration - // +optional - Timeout *metav1.Duration `json:"timeout,omitempty"` - // PodTemplate holds pod specific configuration - // +optional - PodTemplate *PodTemplate `json:"podTemplate,omitempty"` - // Workspaces is a list of WorkspaceBindings from volumes to workspaces. - // +optional - Workspaces []WorkspaceBinding `json:"workspaces,omitempty"` - // From v1beta1 - // +optional - Params []Param `json:"params,omitempty"` - // +optional - Resources *v1beta1.TaskRunResources `json:"resources,omitempty"` - // Deprecated - // +optional - Inputs *TaskRunInputs `json:"inputs,omitempty"` - // +optional - Outputs *TaskRunOutputs `json:"outputs,omitempty"` -} - -// TaskRunSpecStatus defines the taskrun spec status the user can provide -type TaskRunSpecStatus = v1beta1.TaskRunSpecStatus - -const ( - // TaskRunSpecStatusCancelled indicates that the user wants to cancel the task, - // if not already cancelled or terminated - TaskRunSpecStatusCancelled = v1beta1.TaskRunSpecStatusCancelled - - // TaskRunReasonCancelled indicates that the TaskRun has been cancelled - // because it was requested so by the user - TaskRunReasonCancelled = v1beta1.TaskRunSpecStatusCancelled -) - -// TaskRunInputs holds the input values that this task was invoked with. -type TaskRunInputs struct { - // +optional - Resources []TaskResourceBinding `json:"resources,omitempty"` - // +optional - Params []Param `json:"params,omitempty"` -} - -// TaskResourceBinding points to the PipelineResource that -// will be used for the Task input or output called Name. -type TaskResourceBinding = v1beta1.TaskResourceBinding - -// TaskRunOutputs holds the output values that this task was invoked with. -type TaskRunOutputs struct { - // +optional - Resources []TaskResourceBinding `json:"resources,omitempty"` -} - -// TaskRunStatus defines the observed state of TaskRun -type TaskRunStatus = v1beta1.TaskRunStatus - -// TaskRunStatusFields holds the fields of TaskRun's status. This is defined -// separately and inlined so that other types can readily consume these fields -// via duck typing. -type TaskRunStatusFields = v1beta1.TaskRunStatusFields - -// TaskRunResult used to describe the results of a task -type TaskRunResult = v1beta1.TaskRunResult - -// StepState reports the results of running a step in the Task. -type StepState = v1beta1.StepState - -// SidecarState reports the results of sidecar in the Task. -type SidecarState = v1beta1.SidecarState - -// CloudEventDelivery is the target of a cloud event along with the state of -// delivery. -type CloudEventDelivery = v1beta1.CloudEventDelivery - -// CloudEventCondition is a string that represents the condition of the event. -type CloudEventCondition = v1beta1.CloudEventCondition - -const ( - // CloudEventConditionUnknown means that the condition for the event to be - // triggered was not met yet, or we don't know the state yet. - CloudEventConditionUnknown CloudEventCondition = v1beta1.CloudEventConditionUnknown - // CloudEventConditionSent means that the event was sent successfully - CloudEventConditionSent CloudEventCondition = v1beta1.CloudEventConditionSent - // CloudEventConditionFailed means that there was one or more attempts to - // send the event, and none was successful so far. - CloudEventConditionFailed CloudEventCondition = v1beta1.CloudEventConditionFailed -) - -// CloudEventDeliveryState reports the state of a cloud event to be sent. -type CloudEventDeliveryState = v1beta1.CloudEventDeliveryState - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// TaskRun represents a single execution of a Task. TaskRuns are how the steps -// specified in a Task are executed; they specify the parameters and resources -// used to run the steps in a Task. -// -// +k8s:openapi-gen=true -type TaskRun struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // +optional - Spec TaskRunSpec `json:"spec,omitempty"` - // +optional - Status TaskRunStatus `json:"status,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// TaskRunList contains a list of TaskRun -type TaskRunList struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ListMeta `json:"metadata,omitempty"` - Items []TaskRun `json:"items"` -} - -// GetGroupVersionKind implements kmeta.OwnerRefable. -func (*TaskRun) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind(pipeline.TaskRunControllerName) -} - -// GetPipelineRunPVCName for taskrun gets pipelinerun -func (tr *TaskRun) GetPipelineRunPVCName() string { - if tr == nil { - return "" - } - for _, ref := range tr.GetOwnerReferences() { - if ref.Kind == pipeline.PipelineRunControllerName { - return fmt.Sprintf("%s-pvc", ref.Name) - } - } - return "" -} - -// HasPipelineRunOwnerReference returns true of TaskRun has -// owner reference of type PipelineRun -func (tr *TaskRun) HasPipelineRunOwnerReference() bool { - for _, ref := range tr.GetOwnerReferences() { - if ref.Kind == pipeline.PipelineRunControllerName { - return true - } - } - return false -} - -// IsDone returns true if the TaskRun's status indicates that it is done. -func (tr *TaskRun) IsDone() bool { - return !tr.Status.GetCondition(apis.ConditionSucceeded).IsUnknown() -} - -// HasStarted function check whether taskrun has valid start time set in its status -func (tr *TaskRun) HasStarted() bool { - return tr.Status.StartTime != nil && !tr.Status.StartTime.IsZero() -} - -// IsSuccessful returns true if the TaskRun's status indicates that it is done. -func (tr *TaskRun) IsSuccessful() bool { - return tr.Status.GetCondition(apis.ConditionSucceeded).IsTrue() -} - -// IsCancelled returns true if the TaskRun's spec status is set to Cancelled state -func (tr *TaskRun) IsCancelled() bool { - return tr.Spec.Status == TaskRunSpecStatusCancelled -} - -// HasTimedOut returns true if the TaskRun runtime is beyond the allowed timeout -func (tr *TaskRun) HasTimedOut(c clock.PassiveClock) bool { - if tr.Status.StartTime.IsZero() { - return false - } - timeout := tr.GetTimeout() - // If timeout is set to 0 or defaulted to 0, there is no timeout. - if timeout == apisconfig.NoTimeoutDuration { - return false - } - runtime := c.Since(tr.Status.StartTime.Time) - return runtime > timeout -} - -// GetTimeout returns the timeout for the TaskRun, or the default if not specified -func (tr *TaskRun) GetTimeout() time.Duration { - // Use the platform default is no timeout is set - if tr.Spec.Timeout == nil { - return apisconfig.DefaultTimeoutMinutes * time.Minute - } - return tr.Spec.Timeout.Duration -} - -// GetRunKey return the taskrun key for timeout handler map -func (tr *TaskRun) GetRunKey() string { - // The address of the pointer is a threadsafe unique identifier for the taskrun - return fmt.Sprintf("%s/%p", "TaskRun", tr) -} - -// IsPartOfPipeline return true if TaskRun is a part of a Pipeline. -// It also return the name of Pipeline and PipelineRun -func (tr *TaskRun) IsPartOfPipeline() (bool, string, string) { - if tr == nil || len(tr.Labels) == 0 { - return false, "", "" - } - - if pl, ok := tr.Labels[pipeline.PipelineLabelKey]; ok { - return true, pl, tr.Labels[pipeline.PipelineRunLabelKey] - } - - return false, "", "" -} - -// HasVolumeClaimTemplate returns true if TaskRun contains volumeClaimTemplates that is -// used for creating PersistentVolumeClaims with an OwnerReference for each run -func (tr *TaskRun) HasVolumeClaimTemplate() bool { - for _, ws := range tr.Spec.Workspaces { - if ws.VolumeClaimTemplate != nil { - return true - } - } - return false -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_types_test.go b/pkg/apis/pipeline/v1alpha1/taskrun_types_test.go deleted file mode 100644 index d9d074254aa..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_types_test.go +++ /dev/null @@ -1,354 +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 v1alpha1_test - -import ( - "fmt" - "testing" - "time" - - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestTaskRun_GetPipelineRunPVCName(t *testing.T) { - tests := []struct { - name string - tr *v1alpha1.TaskRun - expectedPVCName string - }{{ - name: "invalid owner reference", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - OwnerReferences: []metav1.OwnerReference{{ - Kind: "SomeOtherOwner", - Name: "testpr", - }}, - }, - }, - expectedPVCName: "", - }, { - name: "valid pipelinerun owner", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - OwnerReferences: []metav1.OwnerReference{{ - Kind: "PipelineRun", - Name: "testpr", - }}, - }, - }, - expectedPVCName: "testpr-pvc", - }, { - name: "nil taskrun", - expectedPVCName: "", - }} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if tt.tr.GetPipelineRunPVCName() != tt.expectedPVCName { - t.Fatalf("taskrun pipeline run pvc name mismatch: got %s ; expected %s", tt.tr.GetPipelineRunPVCName(), tt.expectedPVCName) - } - }) - } -} - -func TestTaskRun_HasPipelineRun(t *testing.T) { - tests := []struct { - name string - tr *v1alpha1.TaskRun - want bool - }{{ - name: "invalid owner reference", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - OwnerReferences: []metav1.OwnerReference{{ - Kind: "SomeOtherOwner", - Name: "testpr", - }}, - }, - }, - want: false, - }, { - name: "valid pipelinerun owner", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - OwnerReferences: []metav1.OwnerReference{{ - Kind: "PipelineRun", - Name: "testpr", - }}, - }, - }, - want: true, - }} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if tt.tr.HasPipelineRunOwnerReference() != tt.want { - t.Fatalf("taskrun pipeline run pvc name mismatch: got %s ; expected %t", tt.tr.GetPipelineRunPVCName(), tt.want) - } - }) - } -} - -func TestTaskRunIsDone(t *testing.T) { - tr := &v1alpha1.TaskRun{ - Status: v1alpha1.TaskRunStatus{ - Status: duckv1beta1.Status{ - Conditions: duckv1beta1.Conditions{ - apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionFalse, - }, - }, - }, - }, - } - if !tr.IsDone() { - t.Fatal("Expected pipelinerun status to be done") - } -} - -func TestTaskRunIsCancelled(t *testing.T) { - tr := &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - Status: v1alpha1.TaskRunSpecStatusCancelled, - }, - } - if !tr.IsCancelled() { - t.Fatal("Expected pipelinerun status to be cancelled") - } -} - -func TestTaskRunHasVolumeClaimTemplate(t *testing.T) { - tr := &v1alpha1.TaskRun{ - Spec: v1alpha1.TaskRunSpec{ - Workspaces: []v1alpha1.WorkspaceBinding{{ - Name: "my-workspace", - VolumeClaimTemplate: &corev1.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pvc", - }, - Spec: corev1.PersistentVolumeClaimSpec{}, - }, - }}, - }, - } - if !tr.HasVolumeClaimTemplate() { - t.Fatal("Expected taskrun to have a volumeClaimTemplate workspace") - } -} - -func TestTaskRunKey(t *testing.T) { - tr := &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - }, - } - expectedKey := fmt.Sprintf("TaskRun/%p", tr) - if tr.GetRunKey() != expectedKey { - t.Fatalf("Expected taskrun key to be %s but got %s", expectedKey, tr.GetRunKey()) - } -} - -func TestTaskRunHasStarted(t *testing.T) { - params := []struct { - name string - trStatus v1alpha1.TaskRunStatus - expectedValue bool - }{{ - name: "trWithNoStartTime", - trStatus: v1alpha1.TaskRunStatus{}, - expectedValue: false, - }, { - name: "trWithStartTime", - trStatus: v1alpha1.TaskRunStatus{ - TaskRunStatusFields: v1alpha1.TaskRunStatusFields{ - StartTime: &metav1.Time{Time: now}, - }, - }, - expectedValue: true, - }, { - name: "trWithZeroStartTime", - trStatus: v1alpha1.TaskRunStatus{ - TaskRunStatusFields: v1alpha1.TaskRunStatusFields{ - StartTime: &metav1.Time{}, - }, - }, - expectedValue: false, - }} - for _, tc := range params { - t.Run(tc.name, func(t *testing.T) { - tr := &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - }, - } - tr.Status = tc.trStatus - if tr.HasStarted() != tc.expectedValue { - t.Fatalf("Expected taskrun HasStarted() to return %t but got %t", tc.expectedValue, tr.HasStarted()) - } - }) - } -} - -func TestTaskRunIsOfPipelinerun(t *testing.T) { - tests := []struct { - name string - tr *v1alpha1.TaskRun - expectedValue bool - expetectedPipeline string - expetectedPipelineRun string - }{{ - name: "yes", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - Labels: map[string]string{ - pipeline.PipelineLabelKey: "pipeline", - pipeline.PipelineRunLabelKey: "pipelinerun", - }, - }, - }, - expectedValue: true, - expetectedPipeline: "pipeline", - expetectedPipelineRun: "pipelinerun", - }, { - name: "no", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskrunname", - }, - }, - expectedValue: false, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - value, pipeline, pipelineRun := test.tr.IsPartOfPipeline() - if value != test.expectedValue { - t.Fatalf("Expecting %v got %v", test.expectedValue, value) - } - - if pipeline != test.expetectedPipeline { - t.Fatalf("Mismatch in pipeline: got %s expected %s", pipeline, test.expetectedPipeline) - } - - if pipelineRun != test.expetectedPipelineRun { - t.Fatalf("Mismatch in pipelinerun: got %s expected %s", pipelineRun, test.expetectedPipelineRun) - } - }) - } -} - -func TestHasTimedOut(t *testing.T) { - // IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC - zeroTime := time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC) - testCases := []struct { - name string - taskRun *v1alpha1.TaskRun - expectedStatus bool - }{{ - name: "TaskRun not started", - taskRun: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-not-started", - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "task-name", - }, - }, - Status: v1alpha1.TaskRunStatus{ - Status: duckv1beta1.Status{ - Conditions: duckv1beta1.Conditions{ - apis.Condition{}, - }, - }, - TaskRunStatusFields: v1alpha1.TaskRunStatusFields{ - StartTime: &metav1.Time{Time: zeroTime}, - }, - }, - }, - expectedStatus: false, - }, { - name: "TaskRun no timeout", - taskRun: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-no-timeout", - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "task-name", - }, - Timeout: &metav1.Duration{Duration: 0}, - }, - Status: v1alpha1.TaskRunStatus{ - Status: duckv1beta1.Status{ - Conditions: duckv1beta1.Conditions{ - apis.Condition{}, - }, - }, - TaskRunStatusFields: v1alpha1.TaskRunStatusFields{ - StartTime: &metav1.Time{Time: now.Add(-15 * time.Hour)}, - }, - }, - }, - expectedStatus: false, - }, { - name: "TaskRun timed out", - taskRun: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-taskrun-timeout", - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "task-name", - }, - Timeout: &metav1.Duration{Duration: 10 * time.Second}, - }, - Status: v1alpha1.TaskRunStatus{ - Status: duckv1beta1.Status{ - Conditions: duckv1beta1.Conditions{ - apis.Condition{}, - }, - }, - TaskRunStatusFields: v1alpha1.TaskRunStatusFields{ - StartTime: &metav1.Time{Time: now.Add(-15 * time.Second)}, - }, - }, - }, - expectedStatus: true, - }} - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - result := tc.taskRun.HasTimedOut(testClock) - if d := cmp.Diff(result, tc.expectedStatus); d != "" { - t.Fatalf(diff.PrintWantGot(d)) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_validation.go b/pkg/apis/pipeline/v1alpha1/taskrun_validation.go deleted file mode 100644 index a898c21d6d5..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_validation.go +++ /dev/null @@ -1,174 +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 v1alpha1 - -import ( - "context" - "fmt" - "strings" - - "github.com/tektoncd/pipeline/pkg/apis/validate" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/util/sets" - "knative.dev/pkg/apis" -) - -var _ apis.Validatable = (*TaskRun)(nil) - -// Validate taskrun -func (tr *TaskRun) Validate(ctx context.Context) *apis.FieldError { - if err := validate.ObjectMetadata(tr.GetObjectMeta()).ViaField("metadata"); err != nil { - return err - } - if apis.IsInDelete(ctx) { - return nil - } - return tr.Spec.Validate(ctx) -} - -// Validate taskrun spec -func (ts *TaskRunSpec) Validate(ctx context.Context) *apis.FieldError { - if equality.Semantic.DeepEqual(ts, &TaskRunSpec{}) { - return apis.ErrMissingField("spec") - } - - // can't have both taskRef and taskSpec at the same time - if (ts.TaskRef != nil && ts.TaskRef.Name != "") && ts.TaskSpec != nil { - return apis.ErrDisallowedFields("spec.taskref", "spec.taskspec") - } - - // Check that one of TaskRef and TaskSpec is present - if (ts.TaskRef == nil || (ts.TaskRef != nil && ts.TaskRef.Name == "")) && ts.TaskSpec == nil { - return apis.ErrMissingField("spec.taskref.name", "spec.taskspec") - } - - // Validate TaskSpec if it's present - if ts.TaskSpec != nil { - if err := ts.TaskSpec.Validate(ctx); err != nil { - return err - } - } - - // Deprecated - // check for input resources - if ts.Inputs != nil { - if err := ts.Inputs.Validate(ctx, "spec.Inputs"); err != nil { - return err - } - } - - // Deprecated - // check for output resources - if ts.Outputs != nil { - if err := ts.Outputs.Validate(ctx, "spec.Outputs"); err != nil { - return err - } - } - - // Validate Resources - if err := ts.Resources.Validate(ctx); err != nil { - return err - } - - if err := validateWorkspaceBindings(ctx, ts.Workspaces); err != nil { - return err - } - if err := validateParameters("spec.inputs.params", ts.Params); err != nil { - return err - } - - if ts.Timeout != nil { - // timeout should be a valid duration of at least 0. - if ts.Timeout.Duration < 0 { - return apis.ErrInvalidValue(fmt.Sprintf("%s should be >= 0", ts.Timeout.Duration.String()), "spec.timeout") - } - } - - return nil -} - -// Validate implements apis.Validatable -func (i TaskRunInputs) Validate(ctx context.Context, path string) *apis.FieldError { - if err := validatePipelineResources(ctx, i.Resources, fmt.Sprintf("%s.Resources.Name", path)); err != nil { - return err - } - return validateParameters("spec.inputs.params", i.Params) -} - -// Validate implements apis.Validatable -func (o TaskRunOutputs) Validate(ctx context.Context, path string) *apis.FieldError { - return validatePipelineResources(ctx, o.Resources, fmt.Sprintf("%s.Resources.Name", path)) -} - -// validateWorkspaceBindings makes sure the volumes provided for the Task's declared workspaces make sense. -func validateWorkspaceBindings(ctx context.Context, wb []WorkspaceBinding) *apis.FieldError { - seen := sets.NewString() - for _, w := range wb { - if seen.Has(w.Name) { - return apis.ErrMultipleOneOf("spec.workspaces.name") - } - seen.Insert(w.Name) - - if err := w.Validate(ctx).ViaField("workspace"); err != nil { - return err - } - } - - return nil -} - -// validatePipelineResources validates that -// 1. resource is not declared more than once -// 2. if both resource reference and resource spec is defined at the same time -// 3. at least resource ref or resource spec is defined -func validatePipelineResources(ctx context.Context, resources []TaskResourceBinding, path string) *apis.FieldError { - encountered := sets.NewString() - for _, r := range resources { - // We should provide only one binding for each resource required by the Task. - name := strings.ToLower(r.Name) - if encountered.Has(strings.ToLower(name)) { - return apis.ErrMultipleOneOf(path) - } - encountered.Insert(name) - // Check that both resource ref and resource Spec are not present - if r.ResourceRef != nil && r.ResourceSpec != nil { - return apis.ErrDisallowedFields(fmt.Sprintf("%s.ResourceRef", path), fmt.Sprintf("%s.ResourceSpec", path)) - } - // Check that one of resource ref and resource Spec is present - if (r.ResourceRef == nil || r.ResourceRef.Name == "") && r.ResourceSpec == nil { - return apis.ErrMissingField(fmt.Sprintf("%s.ResourceRef", path), fmt.Sprintf("%s.ResourceSpec", path)) - } - if r.ResourceSpec != nil && r.ResourceSpec.Validate(ctx) != nil { - return r.ResourceSpec.Validate(ctx) - } - } - - return nil -} - -// TODO(jasonhall): Share this with v1beta1/taskrun_validation.go -func validateParameters(path string, params []Param) *apis.FieldError { - // Template must not duplicate parameter names. - seen := sets.NewString() - for _, p := range params { - if seen.Has(strings.ToLower(p.Name)) { - return apis.ErrMultipleOneOf(path) - } - seen.Insert(p.Name) - } - return nil -} diff --git a/pkg/apis/pipeline/v1alpha1/taskrun_validation_test.go b/pkg/apis/pipeline/v1alpha1/taskrun_validation_test.go deleted file mode 100644 index 86404ae7b5e..00000000000 --- a/pkg/apis/pipeline/v1alpha1/taskrun_validation_test.go +++ /dev/null @@ -1,438 +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 v1alpha1_test - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "github.com/tektoncd/pipeline/test/diff" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func TestTaskRun_Invalid(t *testing.T) { - tests := []struct { - name string - task *v1alpha1.TaskRun - want *apis.FieldError - }{{ - name: "invalid taskspec", - task: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskmetaname", - }, - }, - want: apis.ErrMissingField("spec"), - }, { - name: "invalid taskrun metadata", - task: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "task,name", - }, - }, - want: &apis.FieldError{ - Message: `invalid resource name "task,name": must be a valid DNS label`, - Paths: []string{"metadata.name"}, - }, - }} - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - err := ts.task.Validate(context.Background()) - if d := cmp.Diff(err.Error(), ts.want.Error()); d != "" { - t.Errorf("TaskRun.Validate/%s %s", ts.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestTaskRun_Validate(t *testing.T) { - tr := &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskname", - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "taskrefname", - }, - }, - } - if err := tr.Validate(context.Background()); err != nil { - t.Errorf("TaskRun.Validate() error = %v", err) - } -} - -func TestTaskRun_Workspaces_Invalid(t *testing.T) { - tests := []struct { - name string - tr *v1alpha1.TaskRun - wantErr *apis.FieldError - }{{ - name: "make sure WorkspaceBinding validation invoked", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskname", - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "task", - }, - Workspaces: []v1alpha1.WorkspaceBinding{{ - Name: "workspace", - PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ - ClaimName: "", - }, - }}, - }, - }, - wantErr: apis.ErrMissingField("workspace.persistentvolumeclaim.claimname"), - }, { - name: "bind same workspace twice", - tr: &v1alpha1.TaskRun{ - ObjectMeta: metav1.ObjectMeta{ - Name: "taskname", - }, - Spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "task", - }, - Workspaces: []v1alpha1.WorkspaceBinding{ - { - Name: "workspace", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - { - Name: "workspace", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }, - }, - }, - wantErr: apis.ErrMultipleOneOf("spec.workspaces.name"), - }} - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - err := ts.tr.Validate(context.Background()) - if err == nil { - t.Errorf("Expected error for invalid TaskRun but got none") - } - if d := cmp.Diff(ts.wantErr.Error(), err.Error()); d != "" { - t.Errorf("TaskRunSpec.Validate/%s %s", ts.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestTaskRunSpec_Invalid(t *testing.T) { - tests := []struct { - name string - spec v1alpha1.TaskRunSpec - wantErr *apis.FieldError - }{{ - name: "invalid taskspec", - spec: v1alpha1.TaskRunSpec{}, - wantErr: apis.ErrMissingField("spec"), - }, { - name: "invalid taskref name", - spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{}, - }, - wantErr: apis.ErrMissingField("spec.taskref.name, spec.taskspec"), - }, { - name: "invalid taskref and taskspec together", - spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "taskrefname", - }, - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - }}, - }}, - }, - wantErr: apis.ErrDisallowedFields("spec.taskspec", "spec.taskref"), - }, { - name: "negative pipeline timeout", - spec: v1alpha1.TaskRunSpec{ - TaskRef: &v1alpha1.TaskRef{ - Name: "taskrefname", - }, - Timeout: &metav1.Duration{Duration: -48 * time.Hour}, - }, - wantErr: apis.ErrInvalidValue("-48h0m0s should be >= 0", "spec.timeout"), - }, { - name: "invalid taskspec", - spec: v1alpha1.TaskRunSpec{ - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "invalid-name-with-$weird-char*/%", - Image: "myimage", - }}, - }}, - }, - wantErr: &apis.FieldError{ - Message: `invalid value "invalid-name-with-$weird-char*/%"`, - Paths: []string{"taskspec.steps.name"}, - Details: "Task step name must be a valid DNS Label, For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - }, - }} - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - err := ts.spec.Validate(context.Background()) - if d := cmp.Diff(ts.wantErr.Error(), err.Error()); d != "" { - t.Errorf("TaskRunSpec.Validate/%s %s", ts.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestTaskRunSpec_Validate(t *testing.T) { - tests := []struct { - name string - spec v1alpha1.TaskRunSpec - }{{ - name: "taskspec without a taskRef", - spec: v1alpha1.TaskRunSpec{ - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - }}, - }}, - }, - }, { - name: "no timeout", - spec: v1alpha1.TaskRunSpec{ - Timeout: &metav1.Duration{Duration: 0}, - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - }}, - }}, - }, - }, { - name: "task spec with credentials.path variable", - spec: v1alpha1.TaskRunSpec{ - TaskSpec: &v1alpha1.TaskSpec{TaskSpec: v1beta1.TaskSpec{ - Steps: []v1alpha1.Step{{ - Name: "mystep", - Image: "myimage", - Script: `echo "creds-init writes to $(credentials.path)"`, - }}, - }}, - }, - }} - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - if err := ts.spec.Validate(context.Background()); err != nil { - t.Errorf("TaskRunSpec.Validate()/%s error = %v", ts.name, err) - } - }) - } -} - -func TestInput_Validate(t *testing.T) { - i := v1alpha1.TaskRunInputs{ - Params: []v1alpha1.Param{{ - Name: "name", - Value: v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "value", - }, - }}, - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource", - }, - Name: "workspace", - }, - }}, - } - if err := i.Validate(context.Background(), "spec.inputs"); err != nil { - t.Errorf("TaskRunInputs.Validate() error = %v", err) - } -} - -func TestInput_Invalid(t *testing.T) { - tests := []struct { - name string - inputs v1alpha1.TaskRunInputs - wantErr *apis.FieldError - }{{ - name: "duplicate task inputs", - inputs: v1alpha1.TaskRunInputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource1", - }, - Name: "workspace", - }, - }, { - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource2", - }, - Name: "workspace", - }, - }}, - }, - wantErr: apis.ErrMultipleOneOf("spec.Inputs.Resources.Name"), - }, { - name: "invalid task input params", - inputs: v1alpha1.TaskRunInputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource", - }, - Name: "resource", - }, - }}, - Params: []v1alpha1.Param{{ - Name: "name", - Value: v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "value", - }, - }, { - Name: "name", - Value: v1alpha1.ArrayOrString{ - Type: v1alpha1.ParamTypeString, - StringVal: "value", - }, - }}, - }, - wantErr: apis.ErrMultipleOneOf("spec.inputs.params"), - }, { - name: "duplicate resource ref and resource spec", - inputs: v1alpha1.TaskRunInputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource", - }, - ResourceSpec: &v1alpha1.PipelineResourceSpec{ - Type: v1alpha1.PipelineResourceTypeGit, - }, - Name: "resource-dup", - }, - }}, - }, - wantErr: apis.ErrDisallowedFields("spec.Inputs.Resources.Name.ResourceRef", "spec.Inputs.Resources.Name.ResourceSpec"), - }, { - name: "invalid resource spec", - inputs: v1alpha1.TaskRunInputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceSpec: &v1alpha1.PipelineResourceSpec{ - Type: "non-existent", - }, - Name: "resource-inv", - }, - }}, - }, - wantErr: apis.ErrInvalidValue("spec.type", "non-existent"), - }, { - name: "no resource ref and resource spec", - inputs: v1alpha1.TaskRunInputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - Name: "resource", - }, - }}, - }, - wantErr: apis.ErrMissingField("spec.Inputs.Resources.Name.ResourceRef", "spec.Inputs.Resources.Name.ResourceSpec"), - }} - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - err := ts.inputs.Validate(context.Background(), "spec.Inputs") - if d := cmp.Diff(err.Error(), ts.wantErr.Error()); d != "" { - t.Errorf("TaskRunInputs.Validate/%s %s", ts.name, diff.PrintWantGot(d)) - } - }) - } -} - -func TestOutput_Validate(t *testing.T) { - i := v1alpha1.TaskRunOutputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource", - }, - Name: "someimage", - }, - }}, - } - if err := i.Validate(context.Background(), "spec.outputs"); err != nil { - t.Errorf("TaskRunOutputs.Validate() error = %v", err) - } -} -func TestOutput_Invalid(t *testing.T) { - tests := []struct { - name string - outputs v1alpha1.TaskRunOutputs - wantErr *apis.FieldError - }{{ - name: "duplicated task outputs", - outputs: v1alpha1.TaskRunOutputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource1", - }, - Name: "workspace", - }, - }, { - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - ResourceRef: &v1alpha1.PipelineResourceRef{ - Name: "testresource2", - }, - Name: "workspace", - }, - }}, - }, - wantErr: apis.ErrMultipleOneOf("spec.Outputs.Resources.Name"), - }, { - name: "no output resource with resource spec nor resource ref", - outputs: v1alpha1.TaskRunOutputs{ - Resources: []v1alpha1.TaskResourceBinding{{ - PipelineResourceBinding: v1alpha1.PipelineResourceBinding{ - Name: "workspace", - }, - }}, - }, - wantErr: apis.ErrMissingField("spec.Outputs.Resources.Name.ResourceSpec", "spec.Outputs.Resources.Name.ResourceRef"), - }} - for _, ts := range tests { - t.Run(ts.name, func(t *testing.T) { - err := ts.outputs.Validate(context.Background(), "spec.Outputs") - if d := cmp.Diff(err.Error(), ts.wantErr.Error()); d != "" { - t.Errorf("TaskRunOutputs.Validate/%s %s", ts.name, diff.PrintWantGot(d)) - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/types_test.go b/pkg/apis/pipeline/v1alpha1/types_test.go deleted file mode 100644 index 47693c13d28..00000000000 --- a/pkg/apis/pipeline/v1alpha1/types_test.go +++ /dev/null @@ -1,33 +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 v1alpha1_test - -import ( - "testing" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "knative.dev/pkg/webhook/resourcesemantics" -) - -func TestTypes(t *testing.T) { - // Assert that types satisfy webhook interface. - var _ resourcesemantics.GenericCRD = (*v1alpha1.ClusterTask)(nil) - var _ resourcesemantics.GenericCRD = (*v1alpha1.TaskRun)(nil) - var _ resourcesemantics.GenericCRD = (*v1alpha1.PipelineResource)(nil) - var _ resourcesemantics.GenericCRD = (*v1alpha1.Task)(nil) - var _ resourcesemantics.GenericCRD = (*v1alpha1.TaskRun)(nil) -} diff --git a/pkg/apis/pipeline/v1alpha1/workspace_types.go b/pkg/apis/pipeline/v1alpha1/workspace_types.go deleted file mode 100644 index 4dfd2c5a67b..00000000000 --- a/pkg/apis/pipeline/v1alpha1/workspace_types.go +++ /dev/null @@ -1,35 +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 v1alpha1 - -import ( - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" -) - -// WorkspaceDeclaration is a declaration of a volume that a Task requires. -type WorkspaceDeclaration = v1beta1.WorkspaceDeclaration - -// WorkspaceBinding maps a Task's declared workspace to a Volume. -type WorkspaceBinding = v1beta1.WorkspaceBinding - -// PipelineWorkspaceDeclaration creates a named slot in a Pipeline that a PipelineRun -// is expected to populate with a workspace binding. -type PipelineWorkspaceDeclaration = v1beta1.PipelineWorkspaceDeclaration - -// WorkspacePipelineTaskBinding describes how a workspace passed into the pipeline should be -// mapped to a task's declared workspace. -type WorkspacePipelineTaskBinding = v1beta1.WorkspacePipelineTaskBinding diff --git a/pkg/apis/pipeline/v1alpha1/workspace_validation.go b/pkg/apis/pipeline/v1alpha1/workspace_validation.go deleted file mode 100644 index 7536360d31d..00000000000 --- a/pkg/apis/pipeline/v1alpha1/workspace_validation.go +++ /dev/null @@ -1,17 +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 v1alpha1 diff --git a/pkg/apis/pipeline/v1alpha1/workspace_validation_test.go b/pkg/apis/pipeline/v1alpha1/workspace_validation_test.go deleted file mode 100644 index 02fed2bbe1a..00000000000 --- a/pkg/apis/pipeline/v1alpha1/workspace_validation_test.go +++ /dev/null @@ -1,142 +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 v1alpha1 - -import ( - "context" - "testing" - - corev1 "k8s.io/api/core/v1" -) - -func TestWorkspaceBindingValidateValid(t *testing.T) { - for _, tc := range []struct { - name string - binding *WorkspaceBinding - }{{ - name: "Valid PVC", - binding: &WorkspaceBinding{ - Name: "beth", - PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ - ClaimName: "pool-party", - }, - }, - }, { - name: "Valid emptyDir", - binding: &WorkspaceBinding{ - Name: "beth", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }, { - name: "Valid configMap", - binding: &WorkspaceBinding{ - Name: "beth", - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "a-configmap-name", - }, - }, - }, - }, { - name: "Valid secret", - binding: &WorkspaceBinding{ - Name: "beth", - Secret: &corev1.SecretVolumeSource{ - SecretName: "my-secret", - }, - }, - }} { - t.Run(tc.name, func(t *testing.T) { - if err := tc.binding.Validate(context.Background()); err != nil { - t.Errorf("didnt expect error for valid binding but got: %v", err) - } - }) - } - -} - -func TestWorkspaceBindingValidateInvalid(t *testing.T) { - for _, tc := range []struct { - name string - binding *WorkspaceBinding - }{{ - name: "no binding provided", - binding: nil, - }, { - name: "Provided both pvc and emptydir", - binding: &WorkspaceBinding{ - Name: "beth", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ - ClaimName: "pool-party", - }, - }, - }, { - name: "Provided both emptydir and configmap", - binding: &WorkspaceBinding{ - Name: "beth", - EmptyDir: &corev1.EmptyDirVolumeSource{}, - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "foo-configmap", - }, - }, - }, - }, { - name: "Provided both configmap and secret", - binding: &WorkspaceBinding{ - Name: "beth", - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "my-configmap", - }, - }, - Secret: &corev1.SecretVolumeSource{ - SecretName: "my-secret", - }, - }, - }, { - name: "Provided neither pvc nor emptydir", - binding: &WorkspaceBinding{ - Name: "beth", - }, - }, { - name: "Provided pvc without claim name", - binding: &WorkspaceBinding{ - Name: "beth", - PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{}, - }, - }, { - name: "Provide configmap without a name", - binding: &WorkspaceBinding{ - Name: "beth", - ConfigMap: &corev1.ConfigMapVolumeSource{}, - }, - }, { - name: "Provide secret without a secretName", - binding: &WorkspaceBinding{ - Name: "beth", - Secret: &corev1.SecretVolumeSource{}, - }, - }} { - t.Run(tc.name, func(t *testing.T) { - if err := tc.binding.Validate(context.Background()); err == nil { - t.Errorf("expected error for invalid binding but didn't get any!") - } - }) - } -} diff --git a/pkg/apis/pipeline/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/pipeline/v1alpha1/zz_generated.deepcopy.go index 77c31346c88..47123e63dd9 100644 --- a/pkg/apis/pipeline/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/pipeline/v1alpha1/zz_generated.deepcopy.go @@ -29,481 +29,20 @@ import ( ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterTask) DeepCopyInto(out *ClusterTask) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTask. -func (in *ClusterTask) DeepCopy() *ClusterTask { - if in == nil { - return nil - } - out := new(ClusterTask) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterTask) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterTaskList) DeepCopyInto(out *ClusterTaskList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterTask, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterTaskList. -func (in *ClusterTaskList) DeepCopy() *ClusterTaskList { - if in == nil { - return nil - } - out := new(ClusterTaskList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterTaskList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EmbeddedRunSpec) DeepCopyInto(out *EmbeddedRunSpec) { - *out = *in - out.TypeMeta = in.TypeMeta - in.Metadata.DeepCopyInto(&out.Metadata) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EmbeddedRunSpec. -func (in *EmbeddedRunSpec) DeepCopy() *EmbeddedRunSpec { - if in == nil { - return nil - } - out := new(EmbeddedRunSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Inputs) DeepCopyInto(out *Inputs) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]v1beta1.TaskResource, len(*in)) - copy(*out, *in) - } - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]v1beta1.ParamSpec, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Inputs. -func (in *Inputs) DeepCopy() *Inputs { - if in == nil { - return nil - } - out := new(Inputs) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Outputs) DeepCopyInto(out *Outputs) { - *out = *in - if in.Results != nil { - in, out := &in.Results, &out.Results - *out = make([]TestResult, len(*in)) - copy(*out, *in) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]v1beta1.TaskResource, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Outputs. -func (in *Outputs) DeepCopy() *Outputs { - if in == nil { - return nil - } - out := new(Outputs) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Pipeline) DeepCopyInto(out *Pipeline) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - if in.Status != nil { - in, out := &in.Status, &out.Status - *out = new(PipelineStatus) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Pipeline. -func (in *Pipeline) DeepCopy() *Pipeline { - if in == nil { - return nil - } - out := new(Pipeline) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Pipeline) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineList) DeepCopyInto(out *PipelineList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Pipeline, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineList. -func (in *PipelineList) DeepCopy() *PipelineList { - if in == nil { - return nil - } - out := new(PipelineList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PipelineList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineRun) DeepCopyInto(out *PipelineRun) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineRun. -func (in *PipelineRun) DeepCopy() *PipelineRun { - if in == nil { - return nil - } - out := new(PipelineRun) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PipelineRun) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineRunList) DeepCopyInto(out *PipelineRunList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]PipelineRun, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineRunList. -func (in *PipelineRunList) DeepCopy() *PipelineRunList { - if in == nil { - return nil - } - out := new(PipelineRunList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PipelineRunList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineRunSpec) DeepCopyInto(out *PipelineRunSpec) { - *out = *in - if in.PipelineRef != nil { - in, out := &in.PipelineRef, &out.PipelineRef - *out = new(v1beta1.PipelineRef) - (*in).DeepCopyInto(*out) - } - if in.PipelineSpec != nil { - in, out := &in.PipelineSpec, &out.PipelineSpec - *out = new(PipelineSpec) - (*in).DeepCopyInto(*out) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]v1beta1.PipelineResourceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]v1beta1.Param, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Timeout != nil { - in, out := &in.Timeout, &out.Timeout - *out = new(v1.Duration) - **out = **in - } - if in.PodTemplate != nil { - in, out := &in.PodTemplate, &out.PodTemplate - *out = new(pod.Template) - (*in).DeepCopyInto(*out) - } - if in.Workspaces != nil { - in, out := &in.Workspaces, &out.Workspaces - *out = make([]v1beta1.WorkspaceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.TaskRunSpecs != nil { - in, out := &in.TaskRunSpecs, &out.TaskRunSpecs - *out = make([]PipelineTaskRunSpec, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineRunSpec. -func (in *PipelineRunSpec) DeepCopy() *PipelineRunSpec { - if in == nil { - return nil - } - out := new(PipelineRunSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineSpec) DeepCopyInto(out *PipelineSpec) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]v1beta1.PipelineDeclaredResource, len(*in)) - copy(*out, *in) - } - if in.Tasks != nil { - in, out := &in.Tasks, &out.Tasks - *out = make([]PipelineTask, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]v1beta1.ParamSpec, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Workspaces != nil { - in, out := &in.Workspaces, &out.Workspaces - *out = make([]v1beta1.PipelineWorkspaceDeclaration, len(*in)) - copy(*out, *in) - } - if in.Results != nil { - in, out := &in.Results, &out.Results - *out = make([]v1beta1.PipelineResult, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineSpec. -func (in *PipelineSpec) DeepCopy() *PipelineSpec { - if in == nil { - return nil - } - out := new(PipelineSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineStatus) DeepCopyInto(out *PipelineStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineStatus. -func (in *PipelineStatus) DeepCopy() *PipelineStatus { - if in == nil { - return nil - } - out := new(PipelineStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineTask) DeepCopyInto(out *PipelineTask) { - *out = *in - if in.TaskRef != nil { - in, out := &in.TaskRef, &out.TaskRef - *out = new(v1beta1.TaskRef) - (*in).DeepCopyInto(*out) - } - if in.TaskSpec != nil { - in, out := &in.TaskSpec, &out.TaskSpec - *out = new(TaskSpec) - (*in).DeepCopyInto(*out) - } - if in.RunAfter != nil { - in, out := &in.RunAfter, &out.RunAfter - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = new(v1beta1.PipelineTaskResources) - (*in).DeepCopyInto(*out) - } - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]v1beta1.Param, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Workspaces != nil { - in, out := &in.Workspaces, &out.Workspaces - *out = make([]v1beta1.WorkspacePipelineTaskBinding, len(*in)) - copy(*out, *in) - } - if in.Timeout != nil { - in, out := &in.Timeout, &out.Timeout - *out = new(v1.Duration) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineTask. -func (in *PipelineTask) DeepCopy() *PipelineTask { - if in == nil { - return nil - } - out := new(PipelineTask) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in PipelineTaskList) DeepCopyInto(out *PipelineTaskList) { - { - in := &in - *out = make(PipelineTaskList, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - return - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineTaskList. -func (in PipelineTaskList) DeepCopy() PipelineTaskList { - if in == nil { - return nil - } - out := new(PipelineTaskList) - in.DeepCopyInto(out) - return *out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PipelineTaskRunSpec) DeepCopyInto(out *PipelineTaskRunSpec) { +func (in *EmbeddedRunSpec) DeepCopyInto(out *EmbeddedRunSpec) { *out = *in - if in.TaskPodTemplate != nil { - in, out := &in.TaskPodTemplate, &out.TaskPodTemplate - *out = new(pod.Template) - (*in).DeepCopyInto(*out) - } + out.TypeMeta = in.TypeMeta + in.Metadata.DeepCopyInto(&out.Metadata) + in.Spec.DeepCopyInto(&out.Spec) return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineTaskRunSpec. -func (in *PipelineTaskRunSpec) DeepCopy() *PipelineTaskRunSpec { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EmbeddedRunSpec. +func (in *EmbeddedRunSpec) DeepCopy() *EmbeddedRunSpec { if in == nil { return nil } - out := new(PipelineTaskRunSpec) + out := new(EmbeddedRunSpec) in.DeepCopyInto(out) return out } @@ -618,285 +157,3 @@ func (in *RunSpec) DeepCopy() *RunSpec { in.DeepCopyInto(out) return out } - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Task) DeepCopyInto(out *Task) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Task. -func (in *Task) DeepCopy() *Task { - if in == nil { - return nil - } - out := new(Task) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Task) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskList) DeepCopyInto(out *TaskList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Task, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskList. -func (in *TaskList) DeepCopy() *TaskList { - if in == nil { - return nil - } - out := new(TaskList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *TaskList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskRun) DeepCopyInto(out *TaskRun) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskRun. -func (in *TaskRun) DeepCopy() *TaskRun { - if in == nil { - return nil - } - out := new(TaskRun) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *TaskRun) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskRunInputs) DeepCopyInto(out *TaskRunInputs) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]v1beta1.TaskResourceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]v1beta1.Param, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskRunInputs. -func (in *TaskRunInputs) DeepCopy() *TaskRunInputs { - if in == nil { - return nil - } - out := new(TaskRunInputs) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskRunList) DeepCopyInto(out *TaskRunList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]TaskRun, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskRunList. -func (in *TaskRunList) DeepCopy() *TaskRunList { - if in == nil { - return nil - } - out := new(TaskRunList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *TaskRunList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskRunOutputs) DeepCopyInto(out *TaskRunOutputs) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]v1beta1.TaskResourceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskRunOutputs. -func (in *TaskRunOutputs) DeepCopy() *TaskRunOutputs { - if in == nil { - return nil - } - out := new(TaskRunOutputs) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskRunSpec) DeepCopyInto(out *TaskRunSpec) { - *out = *in - if in.TaskRef != nil { - in, out := &in.TaskRef, &out.TaskRef - *out = new(v1beta1.TaskRef) - (*in).DeepCopyInto(*out) - } - if in.TaskSpec != nil { - in, out := &in.TaskSpec, &out.TaskSpec - *out = new(TaskSpec) - (*in).DeepCopyInto(*out) - } - if in.Timeout != nil { - in, out := &in.Timeout, &out.Timeout - *out = new(v1.Duration) - **out = **in - } - if in.PodTemplate != nil { - in, out := &in.PodTemplate, &out.PodTemplate - *out = new(pod.Template) - (*in).DeepCopyInto(*out) - } - if in.Workspaces != nil { - in, out := &in.Workspaces, &out.Workspaces - *out = make([]v1beta1.WorkspaceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]v1beta1.Param, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = new(v1beta1.TaskRunResources) - (*in).DeepCopyInto(*out) - } - if in.Inputs != nil { - in, out := &in.Inputs, &out.Inputs - *out = new(TaskRunInputs) - (*in).DeepCopyInto(*out) - } - if in.Outputs != nil { - in, out := &in.Outputs, &out.Outputs - *out = new(TaskRunOutputs) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskRunSpec. -func (in *TaskRunSpec) DeepCopy() *TaskRunSpec { - if in == nil { - return nil - } - out := new(TaskRunSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TaskSpec) DeepCopyInto(out *TaskSpec) { - *out = *in - in.TaskSpec.DeepCopyInto(&out.TaskSpec) - if in.Inputs != nil { - in, out := &in.Inputs, &out.Inputs - *out = new(Inputs) - (*in).DeepCopyInto(*out) - } - if in.Outputs != nil { - in, out := &in.Outputs, &out.Outputs - *out = new(Outputs) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TaskSpec. -func (in *TaskSpec) DeepCopy() *TaskSpec { - if in == nil { - return nil - } - out := new(TaskSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TestResult) DeepCopyInto(out *TestResult) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TestResult. -func (in *TestResult) DeepCopy() *TestResult { - if in == nil { - return nil - } - out := new(TestResult) - in.DeepCopyInto(out) - return out -} diff --git a/pkg/apis/pipeline/v1beta1/taskrun_validation.go b/pkg/apis/pipeline/v1beta1/taskrun_validation.go index e4fa03228e7..b802e933017 100644 --- a/pkg/apis/pipeline/v1beta1/taskrun_validation.go +++ b/pkg/apis/pipeline/v1beta1/taskrun_validation.go @@ -56,8 +56,8 @@ func (ts *TaskRunSpec) Validate(ctx context.Context) (errs *apis.FieldError) { errs = errs.Also(ts.TaskSpec.Validate(ctx).ViaField("taskSpec")) } - errs = errs.Also(validateParameters(ctx, ts.Params).ViaField("params")) - errs = errs.Also(validateWorkspaceBindings(ctx, ts.Workspaces).ViaField("workspaces")) + errs = errs.Also(ValidateParameters(ctx, ts.Params).ViaField("params")) + errs = errs.Also(ValidateWorkspaceBindings(ctx, ts.Workspaces).ViaField("workspaces")) errs = errs.Also(ts.Resources.Validate(ctx).ViaField("resources")) if ts.Debug != nil { errs = errs.Also(ValidateEnabledAPIFields(ctx, "debug", config.AlphaAPIFields).ViaField("debug")) @@ -101,8 +101,8 @@ func validateDebug(db *TaskRunDebug) (errs *apis.FieldError) { return errs } -// validateWorkspaceBindings makes sure the volumes provided for the Task's declared workspaces make sense. -func validateWorkspaceBindings(ctx context.Context, wb []WorkspaceBinding) (errs *apis.FieldError) { +// ValidateWorkspaceBindings makes sure the volumes provided for the Task's declared workspaces make sense. +func ValidateWorkspaceBindings(ctx context.Context, wb []WorkspaceBinding) (errs *apis.FieldError) { var names []string for idx, w := range wb { names = append(names, w.Name) @@ -112,7 +112,8 @@ func validateWorkspaceBindings(ctx context.Context, wb []WorkspaceBinding) (errs return errs } -func validateParameters(ctx context.Context, params []Param) (errs *apis.FieldError) { +// ValidateParameters makes sure the params for the Task are valid. +func ValidateParameters(ctx context.Context, params []Param) (errs *apis.FieldError) { var names []string for _, p := range params { if p.Value.Type == ParamTypeObject { diff --git a/pkg/apis/resource/v1alpha1/git/git_resource_test.go b/pkg/apis/resource/v1alpha1/git/git_resource_test.go index 3d0847727d1..7a56205271a 100644 --- a/pkg/apis/resource/v1alpha1/git/git_resource_test.go +++ b/pkg/apis/resource/v1alpha1/git/git_resource_test.go @@ -19,17 +19,16 @@ package git_test import ( "testing" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/ptr" - "github.com/google/go-cmp/cmp" - pipeline "github.com/tektoncd/pipeline/pkg/apis/pipeline" - resourcev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + "github.com/tektoncd/pipeline/pkg/apis/pipeline" "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/git" "github.com/tektoncd/pipeline/test/diff" "github.com/tektoncd/pipeline/test/names" corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/pkg/ptr" ) func TestNewGitResource_Invalid(t *testing.T) { diff --git a/pkg/apis/resource/v1alpha1/storage/artifact_bucket_test.go b/pkg/apis/resource/v1alpha1/storage/artifact_bucket_test.go index ffeb8e51cb4..bad8640d838 100644 --- a/pkg/apis/resource/v1alpha1/storage/artifact_bucket_test.go +++ b/pkg/apis/resource/v1alpha1/storage/artifact_bucket_test.go @@ -21,7 +21,8 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "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/apis/resource/v1alpha1/storage" "github.com/tektoncd/pipeline/test/diff" "github.com/tektoncd/pipeline/test/names" @@ -37,7 +38,7 @@ var ( bucket = storage.ArtifactBucket{ Location: "gs://fake-bucket", - Secrets: []v1alpha1.SecretParam{{ + Secrets: []resourcev1alpha1.SecretParam{{ FieldName: "GOOGLE_APPLICATION_CREDENTIALS", SecretName: secretName, SecretKey: "serviceaccount", @@ -50,7 +51,7 @@ var ( func TestBucketGetCopyFromContainerSpec(t *testing.T) { names.TestingSeed() - want := []v1alpha1.Step{{ + want := []v1beta1.Step{{ Name: "artifact-dest-mkdir-workspace-9l9zj", Image: "busybox", Command: []string{"mkdir", "-p", "/workspace/destination"}, @@ -71,7 +72,7 @@ func TestBucketGetCopyFromContainerSpec(t *testing.T) { func TestBucketGetCopyToContainerSpec(t *testing.T) { names.TestingSeed() - want := []v1alpha1.Step{{ + want := []v1beta1.Step{{ Name: "artifact-copy-to-workspace-9l9zj", Image: "gcr.io/google.com/cloudsdktool/cloud-sdk", Command: []string{"gsutil"}, diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/clustertask.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/clustertask.go deleted file mode 100644 index 570202483b3..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/clustertask.go +++ /dev/null @@ -1,168 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ClusterTasksGetter has a method to return a ClusterTaskInterface. -// A group's client should implement this interface. -type ClusterTasksGetter interface { - ClusterTasks() ClusterTaskInterface -} - -// ClusterTaskInterface has methods to work with ClusterTask resources. -type ClusterTaskInterface interface { - Create(ctx context.Context, clusterTask *v1alpha1.ClusterTask, opts v1.CreateOptions) (*v1alpha1.ClusterTask, error) - Update(ctx context.Context, clusterTask *v1alpha1.ClusterTask, opts v1.UpdateOptions) (*v1alpha1.ClusterTask, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.ClusterTask, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.ClusterTaskList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTask, err error) - ClusterTaskExpansion -} - -// clusterTasks implements ClusterTaskInterface -type clusterTasks struct { - client rest.Interface -} - -// newClusterTasks returns a ClusterTasks -func newClusterTasks(c *TektonV1alpha1Client) *clusterTasks { - return &clusterTasks{ - client: c.RESTClient(), - } -} - -// Get takes name of the clusterTask, and returns the corresponding clusterTask object, and an error if there is any. -func (c *clusterTasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterTask, err error) { - result = &v1alpha1.ClusterTask{} - err = c.client.Get(). - Resource("clustertasks"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ClusterTasks that match those selectors. -func (c *clusterTasks) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterTaskList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.ClusterTaskList{} - err = c.client.Get(). - Resource("clustertasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested clusterTasks. -func (c *clusterTasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Resource("clustertasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a clusterTask and creates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *clusterTasks) Create(ctx context.Context, clusterTask *v1alpha1.ClusterTask, opts v1.CreateOptions) (result *v1alpha1.ClusterTask, err error) { - result = &v1alpha1.ClusterTask{} - err = c.client.Post(). - Resource("clustertasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(clusterTask). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a clusterTask and updates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *clusterTasks) Update(ctx context.Context, clusterTask *v1alpha1.ClusterTask, opts v1.UpdateOptions) (result *v1alpha1.ClusterTask, err error) { - result = &v1alpha1.ClusterTask{} - err = c.client.Put(). - Resource("clustertasks"). - Name(clusterTask.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(clusterTask). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the clusterTask and deletes it. Returns an error if one occurs. -func (c *clusterTasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Resource("clustertasks"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *clusterTasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Resource("clustertasks"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched clusterTask. -func (c *clusterTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTask, err error) { - result = &v1alpha1.ClusterTask{} - err = c.client.Patch(pt). - Resource("clustertasks"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_clustertask.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_clustertask.go deleted file mode 100644 index 65275200cb7..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_clustertask.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeClusterTasks implements ClusterTaskInterface -type FakeClusterTasks struct { - Fake *FakeTektonV1alpha1 -} - -var clustertasksResource = schema.GroupVersionResource{Group: "tekton.dev", Version: "v1alpha1", Resource: "clustertasks"} - -var clustertasksKind = schema.GroupVersionKind{Group: "tekton.dev", Version: "v1alpha1", Kind: "ClusterTask"} - -// Get takes name of the clusterTask, and returns the corresponding clusterTask object, and an error if there is any. -func (c *FakeClusterTasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(clustertasksResource, name), &v1alpha1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterTask), err -} - -// List takes label and field selectors, and returns the list of ClusterTasks that match those selectors. -func (c *FakeClusterTasks) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterTaskList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(clustertasksResource, clustertasksKind, opts), &v1alpha1.ClusterTaskList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ClusterTaskList{ListMeta: obj.(*v1alpha1.ClusterTaskList).ListMeta} - for _, item := range obj.(*v1alpha1.ClusterTaskList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested clusterTasks. -func (c *FakeClusterTasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(clustertasksResource, opts)) -} - -// Create takes the representation of a clusterTask and creates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *FakeClusterTasks) Create(ctx context.Context, clusterTask *v1alpha1.ClusterTask, opts v1.CreateOptions) (result *v1alpha1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(clustertasksResource, clusterTask), &v1alpha1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterTask), err -} - -// Update takes the representation of a clusterTask and updates it. Returns the server's representation of the clusterTask, and an error, if there is any. -func (c *FakeClusterTasks) Update(ctx context.Context, clusterTask *v1alpha1.ClusterTask, opts v1.UpdateOptions) (result *v1alpha1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(clustertasksResource, clusterTask), &v1alpha1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterTask), err -} - -// Delete takes name of the clusterTask and deletes it. Returns an error if one occurs. -func (c *FakeClusterTasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteActionWithOptions(clustertasksResource, name, opts), &v1alpha1.ClusterTask{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeClusterTasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(clustertasksResource, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.ClusterTaskList{}) - return err -} - -// Patch applies the patch and returns the patched clusterTask. -func (c *FakeClusterTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTask, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(clustertasksResource, name, pt, data, subresources...), &v1alpha1.ClusterTask{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterTask), err -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline.go deleted file mode 100644 index d79e7903285..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline.go +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakePipelines implements PipelineInterface -type FakePipelines struct { - Fake *FakeTektonV1alpha1 - ns string -} - -var pipelinesResource = schema.GroupVersionResource{Group: "tekton.dev", Version: "v1alpha1", Resource: "pipelines"} - -var pipelinesKind = schema.GroupVersionKind{Group: "tekton.dev", Version: "v1alpha1", Kind: "Pipeline"} - -// Get takes name of the pipeline, and returns the corresponding pipeline object, and an error if there is any. -func (c *FakePipelines) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(pipelinesResource, c.ns, name), &v1alpha1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Pipeline), err -} - -// List takes label and field selectors, and returns the list of Pipelines that match those selectors. -func (c *FakePipelines) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PipelineList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(pipelinesResource, pipelinesKind, c.ns, opts), &v1alpha1.PipelineList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.PipelineList{ListMeta: obj.(*v1alpha1.PipelineList).ListMeta} - for _, item := range obj.(*v1alpha1.PipelineList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested pipelines. -func (c *FakePipelines) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(pipelinesResource, c.ns, opts)) - -} - -// Create takes the representation of a pipeline and creates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *FakePipelines) Create(ctx context.Context, pipeline *v1alpha1.Pipeline, opts v1.CreateOptions) (result *v1alpha1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(pipelinesResource, c.ns, pipeline), &v1alpha1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Pipeline), err -} - -// Update takes the representation of a pipeline and updates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *FakePipelines) Update(ctx context.Context, pipeline *v1alpha1.Pipeline, opts v1.UpdateOptions) (result *v1alpha1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(pipelinesResource, c.ns, pipeline), &v1alpha1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Pipeline), err -} - -// Delete takes name of the pipeline and deletes it. Returns an error if one occurs. -func (c *FakePipelines) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(pipelinesResource, c.ns, name, opts), &v1alpha1.Pipeline{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakePipelines) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(pipelinesResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.PipelineList{}) - return err -} - -// Patch applies the patch and returns the patched pipeline. -func (c *FakePipelines) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Pipeline, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(pipelinesResource, c.ns, name, pt, data, subresources...), &v1alpha1.Pipeline{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Pipeline), err -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go index 72bad222bd1..7ef7a75e92b 100644 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go +++ b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipeline_client.go @@ -28,30 +28,10 @@ type FakeTektonV1alpha1 struct { *testing.Fake } -func (c *FakeTektonV1alpha1) ClusterTasks() v1alpha1.ClusterTaskInterface { - return &FakeClusterTasks{c} -} - -func (c *FakeTektonV1alpha1) Pipelines(namespace string) v1alpha1.PipelineInterface { - return &FakePipelines{c, namespace} -} - -func (c *FakeTektonV1alpha1) PipelineRuns(namespace string) v1alpha1.PipelineRunInterface { - return &FakePipelineRuns{c, namespace} -} - func (c *FakeTektonV1alpha1) Runs(namespace string) v1alpha1.RunInterface { return &FakeRuns{c, namespace} } -func (c *FakeTektonV1alpha1) Tasks(namespace string) v1alpha1.TaskInterface { - return &FakeTasks{c, namespace} -} - -func (c *FakeTektonV1alpha1) TaskRuns(namespace string) v1alpha1.TaskRunInterface { - return &FakeTaskRuns{c, namespace} -} - // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *FakeTektonV1alpha1) RESTClient() rest.Interface { diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipelinerun.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipelinerun.go deleted file mode 100644 index 6573a028bbf..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_pipelinerun.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakePipelineRuns implements PipelineRunInterface -type FakePipelineRuns struct { - Fake *FakeTektonV1alpha1 - ns string -} - -var pipelinerunsResource = schema.GroupVersionResource{Group: "tekton.dev", Version: "v1alpha1", Resource: "pipelineruns"} - -var pipelinerunsKind = schema.GroupVersionKind{Group: "tekton.dev", Version: "v1alpha1", Kind: "PipelineRun"} - -// Get takes name of the pipelineRun, and returns the corresponding pipelineRun object, and an error if there is any. -func (c *FakePipelineRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(pipelinerunsResource, c.ns, name), &v1alpha1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.PipelineRun), err -} - -// List takes label and field selectors, and returns the list of PipelineRuns that match those selectors. -func (c *FakePipelineRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PipelineRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(pipelinerunsResource, pipelinerunsKind, c.ns, opts), &v1alpha1.PipelineRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.PipelineRunList{ListMeta: obj.(*v1alpha1.PipelineRunList).ListMeta} - for _, item := range obj.(*v1alpha1.PipelineRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested pipelineRuns. -func (c *FakePipelineRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(pipelinerunsResource, c.ns, opts)) - -} - -// Create takes the representation of a pipelineRun and creates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *FakePipelineRuns) Create(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.CreateOptions) (result *v1alpha1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(pipelinerunsResource, c.ns, pipelineRun), &v1alpha1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.PipelineRun), err -} - -// Update takes the representation of a pipelineRun and updates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *FakePipelineRuns) Update(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.UpdateOptions) (result *v1alpha1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(pipelinerunsResource, c.ns, pipelineRun), &v1alpha1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.PipelineRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakePipelineRuns) UpdateStatus(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.UpdateOptions) (*v1alpha1.PipelineRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(pipelinerunsResource, "status", c.ns, pipelineRun), &v1alpha1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.PipelineRun), err -} - -// Delete takes name of the pipelineRun and deletes it. Returns an error if one occurs. -func (c *FakePipelineRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(pipelinerunsResource, c.ns, name, opts), &v1alpha1.PipelineRun{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakePipelineRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(pipelinerunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.PipelineRunList{}) - return err -} - -// Patch applies the patch and returns the patched pipelineRun. -func (c *FakePipelineRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PipelineRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(pipelinerunsResource, c.ns, name, pt, data, subresources...), &v1alpha1.PipelineRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.PipelineRun), err -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_task.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_task.go deleted file mode 100644 index f3dea1b1f5b..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_task.go +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeTasks implements TaskInterface -type FakeTasks struct { - Fake *FakeTektonV1alpha1 - ns string -} - -var tasksResource = schema.GroupVersionResource{Group: "tekton.dev", Version: "v1alpha1", Resource: "tasks"} - -var tasksKind = schema.GroupVersionKind{Group: "tekton.dev", Version: "v1alpha1", Kind: "Task"} - -// Get takes name of the task, and returns the corresponding task object, and an error if there is any. -func (c *FakeTasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(tasksResource, c.ns, name), &v1alpha1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Task), err -} - -// List takes label and field selectors, and returns the list of Tasks that match those selectors. -func (c *FakeTasks) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.TaskList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(tasksResource, tasksKind, c.ns, opts), &v1alpha1.TaskList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.TaskList{ListMeta: obj.(*v1alpha1.TaskList).ListMeta} - for _, item := range obj.(*v1alpha1.TaskList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested tasks. -func (c *FakeTasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(tasksResource, c.ns, opts)) - -} - -// Create takes the representation of a task and creates it. Returns the server's representation of the task, and an error, if there is any. -func (c *FakeTasks) Create(ctx context.Context, task *v1alpha1.Task, opts v1.CreateOptions) (result *v1alpha1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(tasksResource, c.ns, task), &v1alpha1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Task), err -} - -// Update takes the representation of a task and updates it. Returns the server's representation of the task, and an error, if there is any. -func (c *FakeTasks) Update(ctx context.Context, task *v1alpha1.Task, opts v1.UpdateOptions) (result *v1alpha1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(tasksResource, c.ns, task), &v1alpha1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Task), err -} - -// Delete takes name of the task and deletes it. Returns an error if one occurs. -func (c *FakeTasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(tasksResource, c.ns, name, opts), &v1alpha1.Task{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeTasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(tasksResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.TaskList{}) - return err -} - -// Patch applies the patch and returns the patched task. -func (c *FakeTasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Task, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(tasksResource, c.ns, name, pt, data, subresources...), &v1alpha1.Task{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Task), err -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_taskrun.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_taskrun.go deleted file mode 100644 index 72082b26685..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/fake/fake_taskrun.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - "context" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeTaskRuns implements TaskRunInterface -type FakeTaskRuns struct { - Fake *FakeTektonV1alpha1 - ns string -} - -var taskrunsResource = schema.GroupVersionResource{Group: "tekton.dev", Version: "v1alpha1", Resource: "taskruns"} - -var taskrunsKind = schema.GroupVersionKind{Group: "tekton.dev", Version: "v1alpha1", Kind: "TaskRun"} - -// Get takes name of the taskRun, and returns the corresponding taskRun object, and an error if there is any. -func (c *FakeTaskRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(taskrunsResource, c.ns, name), &v1alpha1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.TaskRun), err -} - -// List takes label and field selectors, and returns the list of TaskRuns that match those selectors. -func (c *FakeTaskRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.TaskRunList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(taskrunsResource, taskrunsKind, c.ns, opts), &v1alpha1.TaskRunList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.TaskRunList{ListMeta: obj.(*v1alpha1.TaskRunList).ListMeta} - for _, item := range obj.(*v1alpha1.TaskRunList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested taskRuns. -func (c *FakeTaskRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(taskrunsResource, c.ns, opts)) - -} - -// Create takes the representation of a taskRun and creates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *FakeTaskRuns) Create(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.CreateOptions) (result *v1alpha1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(taskrunsResource, c.ns, taskRun), &v1alpha1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.TaskRun), err -} - -// Update takes the representation of a taskRun and updates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *FakeTaskRuns) Update(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.UpdateOptions) (result *v1alpha1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(taskrunsResource, c.ns, taskRun), &v1alpha1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.TaskRun), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeTaskRuns) UpdateStatus(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.UpdateOptions) (*v1alpha1.TaskRun, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(taskrunsResource, "status", c.ns, taskRun), &v1alpha1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.TaskRun), err -} - -// Delete takes name of the taskRun and deletes it. Returns an error if one occurs. -func (c *FakeTaskRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteActionWithOptions(taskrunsResource, c.ns, name, opts), &v1alpha1.TaskRun{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeTaskRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(taskrunsResource, c.ns, listOpts) - - _, err := c.Fake.Invokes(action, &v1alpha1.TaskRunList{}) - return err -} - -// Patch applies the patch and returns the patched taskRun. -func (c *FakeTaskRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.TaskRun, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(taskrunsResource, c.ns, name, pt, data, subresources...), &v1alpha1.TaskRun{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.TaskRun), err -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/generated_expansion.go index 58b8994efd7..40814697cff 100644 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/generated_expansion.go @@ -18,14 +18,4 @@ limitations under the License. package v1alpha1 -type ClusterTaskExpansion interface{} - -type PipelineExpansion interface{} - -type PipelineRunExpansion interface{} - type RunExpansion interface{} - -type TaskExpansion interface{} - -type TaskRunExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline.go deleted file mode 100644 index cc0a370f770..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline.go +++ /dev/null @@ -1,178 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// PipelinesGetter has a method to return a PipelineInterface. -// A group's client should implement this interface. -type PipelinesGetter interface { - Pipelines(namespace string) PipelineInterface -} - -// PipelineInterface has methods to work with Pipeline resources. -type PipelineInterface interface { - Create(ctx context.Context, pipeline *v1alpha1.Pipeline, opts v1.CreateOptions) (*v1alpha1.Pipeline, error) - Update(ctx context.Context, pipeline *v1alpha1.Pipeline, opts v1.UpdateOptions) (*v1alpha1.Pipeline, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Pipeline, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PipelineList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Pipeline, err error) - PipelineExpansion -} - -// pipelines implements PipelineInterface -type pipelines struct { - client rest.Interface - ns string -} - -// newPipelines returns a Pipelines -func newPipelines(c *TektonV1alpha1Client, namespace string) *pipelines { - return &pipelines{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the pipeline, and returns the corresponding pipeline object, and an error if there is any. -func (c *pipelines) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Pipeline, err error) { - result = &v1alpha1.Pipeline{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Pipelines that match those selectors. -func (c *pipelines) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PipelineList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.PipelineList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested pipelines. -func (c *pipelines) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a pipeline and creates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *pipelines) Create(ctx context.Context, pipeline *v1alpha1.Pipeline, opts v1.CreateOptions) (result *v1alpha1.Pipeline, err error) { - result = &v1alpha1.Pipeline{} - err = c.client.Post(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipeline). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a pipeline and updates it. Returns the server's representation of the pipeline, and an error, if there is any. -func (c *pipelines) Update(ctx context.Context, pipeline *v1alpha1.Pipeline, opts v1.UpdateOptions) (result *v1alpha1.Pipeline, err error) { - result = &v1alpha1.Pipeline{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelines"). - Name(pipeline.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipeline). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the pipeline and deletes it. Returns an error if one occurs. -func (c *pipelines) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *pipelines) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelines"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched pipeline. -func (c *pipelines) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Pipeline, err error) { - result = &v1alpha1.Pipeline{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("pipelines"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go index 3392e3a95db..28d39482a6f 100644 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go +++ b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipeline_client.go @@ -28,12 +28,7 @@ import ( type TektonV1alpha1Interface interface { RESTClient() rest.Interface - ClusterTasksGetter - PipelinesGetter - PipelineRunsGetter RunsGetter - TasksGetter - TaskRunsGetter } // TektonV1alpha1Client is used to interact with features provided by the tekton.dev group. @@ -41,30 +36,10 @@ type TektonV1alpha1Client struct { restClient rest.Interface } -func (c *TektonV1alpha1Client) ClusterTasks() ClusterTaskInterface { - return newClusterTasks(c) -} - -func (c *TektonV1alpha1Client) Pipelines(namespace string) PipelineInterface { - return newPipelines(c, namespace) -} - -func (c *TektonV1alpha1Client) PipelineRuns(namespace string) PipelineRunInterface { - return newPipelineRuns(c, namespace) -} - func (c *TektonV1alpha1Client) Runs(namespace string) RunInterface { return newRuns(c, namespace) } -func (c *TektonV1alpha1Client) Tasks(namespace string) TaskInterface { - return newTasks(c, namespace) -} - -func (c *TektonV1alpha1Client) TaskRuns(namespace string) TaskRunInterface { - return newTaskRuns(c, namespace) -} - // NewForConfig creates a new TektonV1alpha1Client for the given config. // NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), // where httpClient was generated with rest.HTTPClientFor(c). diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipelinerun.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipelinerun.go deleted file mode 100644 index cdf2a1e3671..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/pipelinerun.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// PipelineRunsGetter has a method to return a PipelineRunInterface. -// A group's client should implement this interface. -type PipelineRunsGetter interface { - PipelineRuns(namespace string) PipelineRunInterface -} - -// PipelineRunInterface has methods to work with PipelineRun resources. -type PipelineRunInterface interface { - Create(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.CreateOptions) (*v1alpha1.PipelineRun, error) - Update(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.UpdateOptions) (*v1alpha1.PipelineRun, error) - UpdateStatus(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.UpdateOptions) (*v1alpha1.PipelineRun, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.PipelineRun, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PipelineRunList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PipelineRun, err error) - PipelineRunExpansion -} - -// pipelineRuns implements PipelineRunInterface -type pipelineRuns struct { - client rest.Interface - ns string -} - -// newPipelineRuns returns a PipelineRuns -func newPipelineRuns(c *TektonV1alpha1Client, namespace string) *pipelineRuns { - return &pipelineRuns{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the pipelineRun, and returns the corresponding pipelineRun object, and an error if there is any. -func (c *pipelineRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PipelineRun, err error) { - result = &v1alpha1.PipelineRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of PipelineRuns that match those selectors. -func (c *pipelineRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PipelineRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.PipelineRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested pipelineRuns. -func (c *pipelineRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a pipelineRun and creates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *pipelineRuns) Create(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.CreateOptions) (result *v1alpha1.PipelineRun, err error) { - result = &v1alpha1.PipelineRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a pipelineRun and updates it. Returns the server's representation of the pipelineRun, and an error, if there is any. -func (c *pipelineRuns) Update(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.UpdateOptions) (result *v1alpha1.PipelineRun, err error) { - result = &v1alpha1.PipelineRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(pipelineRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *pipelineRuns) UpdateStatus(ctx context.Context, pipelineRun *v1alpha1.PipelineRun, opts v1.UpdateOptions) (result *v1alpha1.PipelineRun, err error) { - result = &v1alpha1.PipelineRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(pipelineRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(pipelineRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the pipelineRun and deletes it. Returns an error if one occurs. -func (c *pipelineRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *pipelineRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("pipelineruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched pipelineRun. -func (c *pipelineRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PipelineRun, err error) { - result = &v1alpha1.PipelineRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("pipelineruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/task.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/task.go deleted file mode 100644 index ba5b46d27db..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/task.go +++ /dev/null @@ -1,178 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// TasksGetter has a method to return a TaskInterface. -// A group's client should implement this interface. -type TasksGetter interface { - Tasks(namespace string) TaskInterface -} - -// TaskInterface has methods to work with Task resources. -type TaskInterface interface { - Create(ctx context.Context, task *v1alpha1.Task, opts v1.CreateOptions) (*v1alpha1.Task, error) - Update(ctx context.Context, task *v1alpha1.Task, opts v1.UpdateOptions) (*v1alpha1.Task, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Task, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.TaskList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Task, err error) - TaskExpansion -} - -// tasks implements TaskInterface -type tasks struct { - client rest.Interface - ns string -} - -// newTasks returns a Tasks -func newTasks(c *TektonV1alpha1Client, namespace string) *tasks { - return &tasks{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the task, and returns the corresponding task object, and an error if there is any. -func (c *tasks) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Task, err error) { - result = &v1alpha1.Task{} - err = c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Tasks that match those selectors. -func (c *tasks) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.TaskList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.TaskList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested tasks. -func (c *tasks) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a task and creates it. Returns the server's representation of the task, and an error, if there is any. -func (c *tasks) Create(ctx context.Context, task *v1alpha1.Task, opts v1.CreateOptions) (result *v1alpha1.Task, err error) { - result = &v1alpha1.Task{} - err = c.client.Post(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(task). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a task and updates it. Returns the server's representation of the task, and an error, if there is any. -func (c *tasks) Update(ctx context.Context, task *v1alpha1.Task, opts v1.UpdateOptions) (result *v1alpha1.Task, err error) { - result = &v1alpha1.Task{} - err = c.client.Put(). - Namespace(c.ns). - Resource("tasks"). - Name(task.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(task). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the task and deletes it. Returns an error if one occurs. -func (c *tasks) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("tasks"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *tasks) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("tasks"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched task. -func (c *tasks) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Task, err error) { - result = &v1alpha1.Task{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("tasks"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/taskrun.go b/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/taskrun.go deleted file mode 100644 index d3e7f1b7045..00000000000 --- a/pkg/client/clientset/versioned/typed/pipeline/v1alpha1/taskrun.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - scheme "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// TaskRunsGetter has a method to return a TaskRunInterface. -// A group's client should implement this interface. -type TaskRunsGetter interface { - TaskRuns(namespace string) TaskRunInterface -} - -// TaskRunInterface has methods to work with TaskRun resources. -type TaskRunInterface interface { - Create(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.CreateOptions) (*v1alpha1.TaskRun, error) - Update(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.UpdateOptions) (*v1alpha1.TaskRun, error) - UpdateStatus(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.UpdateOptions) (*v1alpha1.TaskRun, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.TaskRun, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.TaskRunList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.TaskRun, err error) - TaskRunExpansion -} - -// taskRuns implements TaskRunInterface -type taskRuns struct { - client rest.Interface - ns string -} - -// newTaskRuns returns a TaskRuns -func newTaskRuns(c *TektonV1alpha1Client, namespace string) *taskRuns { - return &taskRuns{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the taskRun, and returns the corresponding taskRun object, and an error if there is any. -func (c *taskRuns) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.TaskRun, err error) { - result = &v1alpha1.TaskRun{} - err = c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of TaskRuns that match those selectors. -func (c *taskRuns) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.TaskRunList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.TaskRunList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested taskRuns. -func (c *taskRuns) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a taskRun and creates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *taskRuns) Create(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.CreateOptions) (result *v1alpha1.TaskRun, err error) { - result = &v1alpha1.TaskRun{} - err = c.client.Post(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a taskRun and updates it. Returns the server's representation of the taskRun, and an error, if there is any. -func (c *taskRuns) Update(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.UpdateOptions) (result *v1alpha1.TaskRun, err error) { - result = &v1alpha1.TaskRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("taskruns"). - Name(taskRun.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *taskRuns) UpdateStatus(ctx context.Context, taskRun *v1alpha1.TaskRun, opts v1.UpdateOptions) (result *v1alpha1.TaskRun, err error) { - result = &v1alpha1.TaskRun{} - err = c.client.Put(). - Namespace(c.ns). - Resource("taskruns"). - Name(taskRun.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(taskRun). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the taskRun and deletes it. Returns an error if one occurs. -func (c *taskRuns) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *taskRuns) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("taskruns"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched taskRun. -func (c *taskRuns) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.TaskRun, err error) { - result = &v1alpha1.TaskRun{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("taskruns"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index a5efe0759fc..868960f0c9c 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -54,18 +54,8 @@ func (f *genericInformer) Lister() cache.GenericLister { func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { // Group=tekton.dev, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("clustertasks"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().ClusterTasks().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("pipelines"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().Pipelines().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("pipelineruns"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().PipelineRuns().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("runs"): return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().Runs().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("tasks"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().Tasks().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("taskruns"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Tekton().V1alpha1().TaskRuns().Informer()}, nil // Group=tekton.dev, Version=v1beta1 case v1beta1.SchemeGroupVersion.WithResource("clustertasks"): diff --git a/pkg/client/informers/externalversions/pipeline/v1alpha1/clustertask.go b/pkg/client/informers/externalversions/pipeline/v1alpha1/clustertask.go deleted file mode 100644 index 3cdc89018af..00000000000 --- a/pkg/client/informers/externalversions/pipeline/v1alpha1/clustertask.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterTaskInformer provides access to a shared informer and lister for -// ClusterTasks. -type ClusterTaskInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ClusterTaskLister -} - -type clusterTaskInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewClusterTaskInformer constructs a new informer for ClusterTask type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterTaskInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterTaskInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterTaskInformer constructs a new informer for ClusterTask type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterTaskInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().ClusterTasks().List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().ClusterTasks().Watch(context.TODO(), options) - }, - }, - &pipelinev1alpha1.ClusterTask{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterTaskInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterTaskInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterTaskInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.ClusterTask{}, f.defaultInformer) -} - -func (f *clusterTaskInformer) Lister() v1alpha1.ClusterTaskLister { - return v1alpha1.NewClusterTaskLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/pipeline/v1alpha1/interface.go b/pkg/client/informers/externalversions/pipeline/v1alpha1/interface.go index 4fdb40457e8..25a56f81347 100644 --- a/pkg/client/informers/externalversions/pipeline/v1alpha1/interface.go +++ b/pkg/client/informers/externalversions/pipeline/v1alpha1/interface.go @@ -24,18 +24,8 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { - // ClusterTasks returns a ClusterTaskInformer. - ClusterTasks() ClusterTaskInformer - // Pipelines returns a PipelineInformer. - Pipelines() PipelineInformer - // PipelineRuns returns a PipelineRunInformer. - PipelineRuns() PipelineRunInformer // Runs returns a RunInformer. Runs() RunInformer - // Tasks returns a TaskInformer. - Tasks() TaskInformer - // TaskRuns returns a TaskRunInformer. - TaskRuns() TaskRunInformer } type version struct { @@ -49,32 +39,7 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// ClusterTasks returns a ClusterTaskInformer. -func (v *version) ClusterTasks() ClusterTaskInformer { - return &clusterTaskInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// Pipelines returns a PipelineInformer. -func (v *version) Pipelines() PipelineInformer { - return &pipelineInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// PipelineRuns returns a PipelineRunInformer. -func (v *version) PipelineRuns() PipelineRunInformer { - return &pipelineRunInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - // Runs returns a RunInformer. func (v *version) Runs() RunInformer { return &runInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } - -// Tasks returns a TaskInformer. -func (v *version) Tasks() TaskInformer { - return &taskInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// TaskRuns returns a TaskRunInformer. -func (v *version) TaskRuns() TaskRunInformer { - return &taskRunInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/client/informers/externalversions/pipeline/v1alpha1/pipeline.go b/pkg/client/informers/externalversions/pipeline/v1alpha1/pipeline.go deleted file mode 100644 index 848ec0e548f..00000000000 --- a/pkg/client/informers/externalversions/pipeline/v1alpha1/pipeline.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// PipelineInformer provides access to a shared informer and lister for -// Pipelines. -type PipelineInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.PipelineLister -} - -type pipelineInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewPipelineInformer constructs a new informer for Pipeline type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewPipelineInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredPipelineInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredPipelineInformer constructs a new informer for Pipeline type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredPipelineInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().Pipelines(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().Pipelines(namespace).Watch(context.TODO(), options) - }, - }, - &pipelinev1alpha1.Pipeline{}, - resyncPeriod, - indexers, - ) -} - -func (f *pipelineInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredPipelineInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *pipelineInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.Pipeline{}, f.defaultInformer) -} - -func (f *pipelineInformer) Lister() v1alpha1.PipelineLister { - return v1alpha1.NewPipelineLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/pipeline/v1alpha1/pipelinerun.go b/pkg/client/informers/externalversions/pipeline/v1alpha1/pipelinerun.go deleted file mode 100644 index a8d50138069..00000000000 --- a/pkg/client/informers/externalversions/pipeline/v1alpha1/pipelinerun.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// PipelineRunInformer provides access to a shared informer and lister for -// PipelineRuns. -type PipelineRunInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.PipelineRunLister -} - -type pipelineRunInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewPipelineRunInformer constructs a new informer for PipelineRun type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewPipelineRunInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredPipelineRunInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredPipelineRunInformer constructs a new informer for PipelineRun type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredPipelineRunInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().PipelineRuns(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().PipelineRuns(namespace).Watch(context.TODO(), options) - }, - }, - &pipelinev1alpha1.PipelineRun{}, - resyncPeriod, - indexers, - ) -} - -func (f *pipelineRunInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredPipelineRunInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *pipelineRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.PipelineRun{}, f.defaultInformer) -} - -func (f *pipelineRunInformer) Lister() v1alpha1.PipelineRunLister { - return v1alpha1.NewPipelineRunLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/pipeline/v1alpha1/task.go b/pkg/client/informers/externalversions/pipeline/v1alpha1/task.go deleted file mode 100644 index 4e5320f5686..00000000000 --- a/pkg/client/informers/externalversions/pipeline/v1alpha1/task.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// TaskInformer provides access to a shared informer and lister for -// Tasks. -type TaskInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.TaskLister -} - -type taskInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewTaskInformer constructs a new informer for Task type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewTaskInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredTaskInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredTaskInformer constructs a new informer for Task type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredTaskInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().Tasks(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().Tasks(namespace).Watch(context.TODO(), options) - }, - }, - &pipelinev1alpha1.Task{}, - resyncPeriod, - indexers, - ) -} - -func (f *taskInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredTaskInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *taskInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.Task{}, f.defaultInformer) -} - -func (f *taskInformer) Lister() v1alpha1.TaskLister { - return v1alpha1.NewTaskLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/pipeline/v1alpha1/taskrun.go b/pkg/client/informers/externalversions/pipeline/v1alpha1/taskrun.go deleted file mode 100644 index 41c3ae610ee..00000000000 --- a/pkg/client/informers/externalversions/pipeline/v1alpha1/taskrun.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - time "time" - - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// TaskRunInformer provides access to a shared informer and lister for -// TaskRuns. -type TaskRunInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.TaskRunLister -} - -type taskRunInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewTaskRunInformer constructs a new informer for TaskRun type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewTaskRunInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredTaskRunInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredTaskRunInformer constructs a new informer for TaskRun type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredTaskRunInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().TaskRuns(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.TektonV1alpha1().TaskRuns(namespace).Watch(context.TODO(), options) - }, - }, - &pipelinev1alpha1.TaskRun{}, - resyncPeriod, - indexers, - ) -} - -func (f *taskRunInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredTaskRunInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *taskRunInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&pipelinev1alpha1.TaskRun{}, f.defaultInformer) -} - -func (f *taskRunInformer) Lister() v1alpha1.TaskRunLister { - return v1alpha1.NewTaskRunLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/injection/client/client.go b/pkg/client/injection/client/client.go index 949065abe3f..f496980248e 100644 --- a/pkg/client/injection/client/client.go +++ b/pkg/client/injection/client/client.go @@ -113,395 +113,6 @@ func (w *wrapTektonV1alpha1) RESTClient() rest.Interface { panic("RESTClient called on dynamic client!") } -func (w *wrapTektonV1alpha1) ClusterTasks() typedtektonv1alpha1.ClusterTaskInterface { - return &wrapTektonV1alpha1ClusterTaskImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "tekton.dev", - Version: "v1alpha1", - Resource: "clustertasks", - }), - } -} - -type wrapTektonV1alpha1ClusterTaskImpl struct { - dyn dynamic.NamespaceableResourceInterface -} - -var _ typedtektonv1alpha1.ClusterTaskInterface = (*wrapTektonV1alpha1ClusterTaskImpl)(nil) - -func (w *wrapTektonV1alpha1ClusterTaskImpl) Create(ctx context.Context, in *v1alpha1.ClusterTask, opts v1.CreateOptions) (*v1alpha1.ClusterTask, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "ClusterTask", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.ClusterTask{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Delete(ctx, name, opts) -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.ClusterTask, error) { - uo, err := w.dyn.Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.ClusterTask{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.ClusterTaskList, error) { - uo, err := w.dyn.List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.ClusterTaskList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTask, err error) { - uo, err := w.dyn.Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.ClusterTask{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) Update(ctx context.Context, in *v1alpha1.ClusterTask, opts v1.UpdateOptions) (*v1alpha1.ClusterTask, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "ClusterTask", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.ClusterTask{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) UpdateStatus(ctx context.Context, in *v1alpha1.ClusterTask, opts v1.UpdateOptions) (*v1alpha1.ClusterTask, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "ClusterTask", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.ClusterTask{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1ClusterTaskImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} - -func (w *wrapTektonV1alpha1) Pipelines(namespace string) typedtektonv1alpha1.PipelineInterface { - return &wrapTektonV1alpha1PipelineImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "tekton.dev", - Version: "v1alpha1", - Resource: "pipelines", - }), - - namespace: namespace, - } -} - -type wrapTektonV1alpha1PipelineImpl struct { - dyn dynamic.NamespaceableResourceInterface - - namespace string -} - -var _ typedtektonv1alpha1.PipelineInterface = (*wrapTektonV1alpha1PipelineImpl)(nil) - -func (w *wrapTektonV1alpha1PipelineImpl) Create(ctx context.Context, in *v1alpha1.Pipeline, opts v1.CreateOptions) (*v1alpha1.Pipeline, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "Pipeline", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Pipeline{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) -} - -func (w *wrapTektonV1alpha1PipelineImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapTektonV1alpha1PipelineImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Pipeline, error) { - uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Pipeline{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PipelineList, error) { - uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Pipeline, err error) { - uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Pipeline{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineImpl) Update(ctx context.Context, in *v1alpha1.Pipeline, opts v1.UpdateOptions) (*v1alpha1.Pipeline, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "Pipeline", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Pipeline{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineImpl) UpdateStatus(ctx context.Context, in *v1alpha1.Pipeline, opts v1.UpdateOptions) (*v1alpha1.Pipeline, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "Pipeline", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Pipeline{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} - -func (w *wrapTektonV1alpha1) PipelineRuns(namespace string) typedtektonv1alpha1.PipelineRunInterface { - return &wrapTektonV1alpha1PipelineRunImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "tekton.dev", - Version: "v1alpha1", - Resource: "pipelineruns", - }), - - namespace: namespace, - } -} - -type wrapTektonV1alpha1PipelineRunImpl struct { - dyn dynamic.NamespaceableResourceInterface - - namespace string -} - -var _ typedtektonv1alpha1.PipelineRunInterface = (*wrapTektonV1alpha1PipelineRunImpl)(nil) - -func (w *wrapTektonV1alpha1PipelineRunImpl) Create(ctx context.Context, in *v1alpha1.PipelineRun, opts v1.CreateOptions) (*v1alpha1.PipelineRun, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "PipelineRun", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.PipelineRun, error) { - uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.PipelineRunList, error) { - uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineRunList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PipelineRun, err error) { - uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) Update(ctx context.Context, in *v1alpha1.PipelineRun, opts v1.UpdateOptions) (*v1alpha1.PipelineRun, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "PipelineRun", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) UpdateStatus(ctx context.Context, in *v1alpha1.PipelineRun, opts v1.UpdateOptions) (*v1alpha1.PipelineRun, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "PipelineRun", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.PipelineRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1PipelineRunImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} - func (w *wrapTektonV1alpha1) Runs(namespace string) typedtektonv1alpha1.RunInterface { return &wrapTektonV1alpha1RunImpl{ dyn: w.dyn.Resource(schema.GroupVersionResource{ @@ -633,268 +244,6 @@ func (w *wrapTektonV1alpha1RunImpl) Watch(ctx context.Context, opts v1.ListOptio return nil, errors.New("NYI: Watch") } -func (w *wrapTektonV1alpha1) Tasks(namespace string) typedtektonv1alpha1.TaskInterface { - return &wrapTektonV1alpha1TaskImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "tekton.dev", - Version: "v1alpha1", - Resource: "tasks", - }), - - namespace: namespace, - } -} - -type wrapTektonV1alpha1TaskImpl struct { - dyn dynamic.NamespaceableResourceInterface - - namespace string -} - -var _ typedtektonv1alpha1.TaskInterface = (*wrapTektonV1alpha1TaskImpl)(nil) - -func (w *wrapTektonV1alpha1TaskImpl) Create(ctx context.Context, in *v1alpha1.Task, opts v1.CreateOptions) (*v1alpha1.Task, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "Task", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Task{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) -} - -func (w *wrapTektonV1alpha1TaskImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapTektonV1alpha1TaskImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Task, error) { - uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Task{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.TaskList, error) { - uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Task, err error) { - uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Task{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskImpl) Update(ctx context.Context, in *v1alpha1.Task, opts v1.UpdateOptions) (*v1alpha1.Task, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "Task", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Task{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskImpl) UpdateStatus(ctx context.Context, in *v1alpha1.Task, opts v1.UpdateOptions) (*v1alpha1.Task, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "Task", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.Task{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} - -func (w *wrapTektonV1alpha1) TaskRuns(namespace string) typedtektonv1alpha1.TaskRunInterface { - return &wrapTektonV1alpha1TaskRunImpl{ - dyn: w.dyn.Resource(schema.GroupVersionResource{ - Group: "tekton.dev", - Version: "v1alpha1", - Resource: "taskruns", - }), - - namespace: namespace, - } -} - -type wrapTektonV1alpha1TaskRunImpl struct { - dyn dynamic.NamespaceableResourceInterface - - namespace string -} - -var _ typedtektonv1alpha1.TaskRunInterface = (*wrapTektonV1alpha1TaskRunImpl)(nil) - -func (w *wrapTektonV1alpha1TaskRunImpl) Create(ctx context.Context, in *v1alpha1.TaskRun, opts v1.CreateOptions) (*v1alpha1.TaskRun, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "TaskRun", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskRunImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { - return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) -} - -func (w *wrapTektonV1alpha1TaskRunImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { - return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) -} - -func (w *wrapTektonV1alpha1TaskRunImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.TaskRun, error) { - uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskRunImpl) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.TaskRunList, error) { - uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskRunList{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskRunImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.TaskRun, err error) { - uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskRunImpl) Update(ctx context.Context, in *v1alpha1.TaskRun, opts v1.UpdateOptions) (*v1alpha1.TaskRun, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "TaskRun", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskRunImpl) UpdateStatus(ctx context.Context, in *v1alpha1.TaskRun, opts v1.UpdateOptions) (*v1alpha1.TaskRun, error) { - in.SetGroupVersionKind(schema.GroupVersionKind{ - Group: "tekton.dev", - Version: "v1alpha1", - Kind: "TaskRun", - }) - uo := &unstructured.Unstructured{} - if err := convert(in, uo); err != nil { - return nil, err - } - uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) - if err != nil { - return nil, err - } - out := &v1alpha1.TaskRun{} - if err := convert(uo, out); err != nil { - return nil, err - } - return out, nil -} - -func (w *wrapTektonV1alpha1TaskRunImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { - return nil, errors.New("NYI: Watch") -} - // TektonV1beta1 retrieves the TektonV1beta1Client func (w *wrapClient) TektonV1beta1() typedtektonv1beta1.TektonV1beta1Interface { return &wrapTektonV1beta1{ diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/clustertask.go b/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/clustertask.go deleted file mode 100644 index 409a8854201..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/clustertask.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package clustertask - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - factory "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Tekton().V1alpha1().ClusterTasks() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.ClusterTaskInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.ClusterTaskInformer from context.") - } - return untyped.(v1alpha1.ClusterTaskInformer) -} - -type wrapper struct { - client versioned.Interface - - resourceVersion string -} - -var _ v1alpha1.ClusterTaskInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.ClusterTaskLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.ClusterTask{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.ClusterTaskLister { - return w -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.ClusterTask, err error) { - lo, err := w.client.TektonV1alpha1().ClusterTasks().List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.ClusterTask, error) { - return w.client.TektonV1alpha1().ClusterTasks().Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/fake/fake.go deleted file mode 100644 index f0e19fda7a0..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake" - clustertask "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/clustertask" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = clustertask.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Tekton().V1alpha1().ClusterTasks() - return context.WithValue(ctx, clustertask.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered/clustertask.go b/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered/clustertask.go deleted file mode 100644 index 5d9bd6be83b..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered/clustertask.go +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().ClusterTasks() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.ClusterTaskInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.ClusterTaskInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.ClusterTaskInformer) -} - -type wrapper struct { - client versioned.Interface - - selector string -} - -var _ v1alpha1.ClusterTaskInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.ClusterTaskLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.ClusterTask{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.ClusterTaskLister { - return w -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.ClusterTask, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.TektonV1alpha1().ClusterTasks().List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.ClusterTask, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.TektonV1alpha1().ClusterTasks().Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered/fake/fake.go deleted file mode 100644 index 28ccd64c23b..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - factoryfiltered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().ClusterTasks() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/fake/fake.go deleted file mode 100644 index f42d2caca7d..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake" - pipeline "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/pipeline" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = pipeline.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Tekton().V1alpha1().Pipelines() - return context.WithValue(ctx, pipeline.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered/fake/fake.go deleted file mode 100644 index 78ad0a8ff46..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - factoryfiltered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().Pipelines() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered/pipeline.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered/pipeline.go deleted file mode 100644 index c841aedc3d5..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/filtered/pipeline.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().Pipelines() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.PipelineInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.PipelineInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.PipelineInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - selector string -} - -var _ v1alpha1.PipelineInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.PipelineLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.Pipeline{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.PipelineLister { - return w -} - -func (w *wrapper) Pipelines(namespace string) pipelinev1alpha1.PipelineNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, selector: w.selector} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.Pipeline, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.TektonV1alpha1().Pipelines(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.Pipeline, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.TektonV1alpha1().Pipelines(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/pipeline.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/pipeline.go deleted file mode 100644 index 59f2d0b36b5..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/pipeline.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package pipeline - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - factory "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Tekton().V1alpha1().Pipelines() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.PipelineInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.PipelineInformer from context.") - } - return untyped.(v1alpha1.PipelineInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - resourceVersion string -} - -var _ v1alpha1.PipelineInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.PipelineLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.Pipeline{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.PipelineLister { - return w -} - -func (w *wrapper) Pipelines(namespace string) pipelinev1alpha1.PipelineNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.Pipeline, err error) { - lo, err := w.client.TektonV1alpha1().Pipelines(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.Pipeline, error) { - return w.client.TektonV1alpha1().Pipelines(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/fake/fake.go deleted file mode 100644 index 27e660f3253..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake" - pipelinerun "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = pipelinerun.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Tekton().V1alpha1().PipelineRuns() - return context.WithValue(ctx, pipelinerun.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered/fake/fake.go deleted file mode 100644 index ab5effc9de8..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - factoryfiltered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().PipelineRuns() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered/pipelinerun.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered/pipelinerun.go deleted file mode 100644 index 328e85bd098..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/filtered/pipelinerun.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().PipelineRuns() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.PipelineRunInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.PipelineRunInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.PipelineRunInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - selector string -} - -var _ v1alpha1.PipelineRunInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.PipelineRunLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.PipelineRun{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.PipelineRunLister { - return w -} - -func (w *wrapper) PipelineRuns(namespace string) pipelinev1alpha1.PipelineRunNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, selector: w.selector} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.PipelineRun, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.TektonV1alpha1().PipelineRuns(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.PipelineRun, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.TektonV1alpha1().PipelineRuns(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/pipelinerun.go b/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/pipelinerun.go deleted file mode 100644 index 8bcab6ba131..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/pipelinerun.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package pipelinerun - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - factory "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Tekton().V1alpha1().PipelineRuns() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.PipelineRunInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.PipelineRunInformer from context.") - } - return untyped.(v1alpha1.PipelineRunInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - resourceVersion string -} - -var _ v1alpha1.PipelineRunInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.PipelineRunLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.PipelineRun{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.PipelineRunLister { - return w -} - -func (w *wrapper) PipelineRuns(namespace string) pipelinev1alpha1.PipelineRunNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.PipelineRun, err error) { - lo, err := w.client.TektonV1alpha1().PipelineRuns(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.PipelineRun, error) { - return w.client.TektonV1alpha1().PipelineRuns(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/task/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/task/fake/fake.go deleted file mode 100644 index 10f3e63a9a8..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/task/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake" - task "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/task" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = task.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Tekton().V1alpha1().Tasks() - return context.WithValue(ctx, task.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered/fake/fake.go deleted file mode 100644 index 6c2536e24be..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - factoryfiltered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().Tasks() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered/task.go b/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered/task.go deleted file mode 100644 index c4f84e14a2f..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/task/filtered/task.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().Tasks() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.TaskInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.TaskInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.TaskInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - selector string -} - -var _ v1alpha1.TaskInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.TaskLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.Task{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.TaskLister { - return w -} - -func (w *wrapper) Tasks(namespace string) pipelinev1alpha1.TaskNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, selector: w.selector} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.Task, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.TektonV1alpha1().Tasks(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.Task, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.TektonV1alpha1().Tasks(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/task/task.go b/pkg/client/injection/informers/pipeline/v1alpha1/task/task.go deleted file mode 100644 index 87c1ef2354e..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/task/task.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package task - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - factory "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Tekton().V1alpha1().Tasks() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.TaskInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.TaskInformer from context.") - } - return untyped.(v1alpha1.TaskInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - resourceVersion string -} - -var _ v1alpha1.TaskInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.TaskLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.Task{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.TaskLister { - return w -} - -func (w *wrapper) Tasks(namespace string) pipelinev1alpha1.TaskNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.Task, err error) { - lo, err := w.client.TektonV1alpha1().Tasks(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.Task, error) { - return w.client.TektonV1alpha1().Tasks(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/fake/fake.go deleted file mode 100644 index 0fb73a76fa6..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake" - taskrun "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/taskrun" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = taskrun.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Tekton().V1alpha1().TaskRuns() - return context.WithValue(ctx, taskrun.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered/fake/fake.go b/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered/fake/fake.go deleted file mode 100644 index 6da8ee4e9c2..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - factoryfiltered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().TaskRuns() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered/taskrun.go b/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered/taskrun.go deleted file mode 100644 index 999ca18d464..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/filtered/taskrun.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - filtered "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/filtered" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Tekton().V1alpha1().TaskRuns() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -func withDynamicInformer(ctx context.Context) context.Context { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - for _, selector := range labelSelectors { - inf := &wrapper{client: client.Get(ctx), selector: selector} - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - } - return ctx -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.TaskRunInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.TaskRunInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.TaskRunInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - selector string -} - -var _ v1alpha1.TaskRunInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.TaskRunLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.TaskRun{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.TaskRunLister { - return w -} - -func (w *wrapper) TaskRuns(namespace string) pipelinev1alpha1.TaskRunNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, selector: w.selector} -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.TaskRun, err error) { - reqs, err := labels.ParseToRequirements(w.selector) - if err != nil { - return nil, err - } - selector = selector.Add(reqs...) - lo, err := w.client.TektonV1alpha1().TaskRuns(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.TaskRun, error) { - // TODO(mattmoor): Check that the fetched object matches the selector. - return w.client.TektonV1alpha1().TaskRuns(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. - }) -} diff --git a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/taskrun.go b/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/taskrun.go deleted file mode 100644 index d56952cc978..00000000000 --- a/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/taskrun.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package taskrun - -import ( - context "context" - - apispipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - versioned "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - v1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - client "github.com/tektoncd/pipeline/pkg/client/injection/client" - factory "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory" - pipelinev1alpha1 "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - cache "k8s.io/client-go/tools/cache" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) - injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Tekton().V1alpha1().TaskRuns() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -func withDynamicInformer(ctx context.Context) context.Context { - inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} - return context.WithValue(ctx, Key{}, inf) -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.TaskRunInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1.TaskRunInformer from context.") - } - return untyped.(v1alpha1.TaskRunInformer) -} - -type wrapper struct { - client versioned.Interface - - namespace string - - resourceVersion string -} - -var _ v1alpha1.TaskRunInformer = (*wrapper)(nil) -var _ pipelinev1alpha1.TaskRunLister = (*wrapper)(nil) - -func (w *wrapper) Informer() cache.SharedIndexInformer { - return cache.NewSharedIndexInformer(nil, &apispipelinev1alpha1.TaskRun{}, 0, nil) -} - -func (w *wrapper) Lister() pipelinev1alpha1.TaskRunLister { - return w -} - -func (w *wrapper) TaskRuns(namespace string) pipelinev1alpha1.TaskRunNamespaceLister { - return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} -} - -// SetResourceVersion allows consumers to adjust the minimum resourceVersion -// used by the underlying client. It is not accessible via the standard -// lister interface, but can be accessed through a user-defined interface and -// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) -func (w *wrapper) SetResourceVersion(resourceVersion string) { - w.resourceVersion = resourceVersion -} - -func (w *wrapper) List(selector labels.Selector) (ret []*apispipelinev1alpha1.TaskRun, err error) { - lo, err := w.client.TektonV1alpha1().TaskRuns(w.namespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: selector.String(), - ResourceVersion: w.resourceVersion, - }) - if err != nil { - return nil, err - } - for idx := range lo.Items { - ret = append(ret, &lo.Items[idx]) - } - return ret, nil -} - -func (w *wrapper) Get(name string) (*apispipelinev1alpha1.TaskRun, error) { - return w.client.TektonV1alpha1().TaskRuns(w.namespace).Get(context.TODO(), name, v1.GetOptions{ - ResourceVersion: w.resourceVersion, - }) -} diff --git a/pkg/client/listers/pipeline/v1alpha1/clustertask.go b/pkg/client/listers/pipeline/v1alpha1/clustertask.go deleted file mode 100644 index 7344d81a74b..00000000000 --- a/pkg/client/listers/pipeline/v1alpha1/clustertask.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ClusterTaskLister helps list ClusterTasks. -// All objects returned here must be treated as read-only. -type ClusterTaskLister interface { - // List lists all ClusterTasks in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.ClusterTask, err error) - // Get retrieves the ClusterTask from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.ClusterTask, error) - ClusterTaskListerExpansion -} - -// clusterTaskLister implements the ClusterTaskLister interface. -type clusterTaskLister struct { - indexer cache.Indexer -} - -// NewClusterTaskLister returns a new ClusterTaskLister. -func NewClusterTaskLister(indexer cache.Indexer) ClusterTaskLister { - return &clusterTaskLister{indexer: indexer} -} - -// List lists all ClusterTasks in the indexer. -func (s *clusterTaskLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterTask, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ClusterTask)) - }) - return ret, err -} - -// Get retrieves the ClusterTask from the index for a given name. -func (s *clusterTaskLister) Get(name string) (*v1alpha1.ClusterTask, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("clustertask"), name) - } - return obj.(*v1alpha1.ClusterTask), nil -} diff --git a/pkg/client/listers/pipeline/v1alpha1/expansion_generated.go b/pkg/client/listers/pipeline/v1alpha1/expansion_generated.go index 6f4c92c04af..ef742ea3490 100644 --- a/pkg/client/listers/pipeline/v1alpha1/expansion_generated.go +++ b/pkg/client/listers/pipeline/v1alpha1/expansion_generated.go @@ -18,26 +18,6 @@ limitations under the License. package v1alpha1 -// ClusterTaskListerExpansion allows custom methods to be added to -// ClusterTaskLister. -type ClusterTaskListerExpansion interface{} - -// PipelineListerExpansion allows custom methods to be added to -// PipelineLister. -type PipelineListerExpansion interface{} - -// PipelineNamespaceListerExpansion allows custom methods to be added to -// PipelineNamespaceLister. -type PipelineNamespaceListerExpansion interface{} - -// PipelineRunListerExpansion allows custom methods to be added to -// PipelineRunLister. -type PipelineRunListerExpansion interface{} - -// PipelineRunNamespaceListerExpansion allows custom methods to be added to -// PipelineRunNamespaceLister. -type PipelineRunNamespaceListerExpansion interface{} - // RunListerExpansion allows custom methods to be added to // RunLister. type RunListerExpansion interface{} @@ -45,19 +25,3 @@ type RunListerExpansion interface{} // RunNamespaceListerExpansion allows custom methods to be added to // RunNamespaceLister. type RunNamespaceListerExpansion interface{} - -// TaskListerExpansion allows custom methods to be added to -// TaskLister. -type TaskListerExpansion interface{} - -// TaskNamespaceListerExpansion allows custom methods to be added to -// TaskNamespaceLister. -type TaskNamespaceListerExpansion interface{} - -// TaskRunListerExpansion allows custom methods to be added to -// TaskRunLister. -type TaskRunListerExpansion interface{} - -// TaskRunNamespaceListerExpansion allows custom methods to be added to -// TaskRunNamespaceLister. -type TaskRunNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/pipeline/v1alpha1/pipeline.go b/pkg/client/listers/pipeline/v1alpha1/pipeline.go deleted file mode 100644 index 80c75c9981b..00000000000 --- a/pkg/client/listers/pipeline/v1alpha1/pipeline.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// PipelineLister helps list Pipelines. -// All objects returned here must be treated as read-only. -type PipelineLister interface { - // List lists all Pipelines in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Pipeline, err error) - // Pipelines returns an object that can list and get Pipelines. - Pipelines(namespace string) PipelineNamespaceLister - PipelineListerExpansion -} - -// pipelineLister implements the PipelineLister interface. -type pipelineLister struct { - indexer cache.Indexer -} - -// NewPipelineLister returns a new PipelineLister. -func NewPipelineLister(indexer cache.Indexer) PipelineLister { - return &pipelineLister{indexer: indexer} -} - -// List lists all Pipelines in the indexer. -func (s *pipelineLister) List(selector labels.Selector) (ret []*v1alpha1.Pipeline, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Pipeline)) - }) - return ret, err -} - -// Pipelines returns an object that can list and get Pipelines. -func (s *pipelineLister) Pipelines(namespace string) PipelineNamespaceLister { - return pipelineNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// PipelineNamespaceLister helps list and get Pipelines. -// All objects returned here must be treated as read-only. -type PipelineNamespaceLister interface { - // List lists all Pipelines in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Pipeline, err error) - // Get retrieves the Pipeline from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.Pipeline, error) - PipelineNamespaceListerExpansion -} - -// pipelineNamespaceLister implements the PipelineNamespaceLister -// interface. -type pipelineNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Pipelines in the indexer for a given namespace. -func (s pipelineNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Pipeline, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Pipeline)) - }) - return ret, err -} - -// Get retrieves the Pipeline from the indexer for a given namespace and name. -func (s pipelineNamespaceLister) Get(name string) (*v1alpha1.Pipeline, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("pipeline"), name) - } - return obj.(*v1alpha1.Pipeline), nil -} diff --git a/pkg/client/listers/pipeline/v1alpha1/pipelinerun.go b/pkg/client/listers/pipeline/v1alpha1/pipelinerun.go deleted file mode 100644 index 105871d9701..00000000000 --- a/pkg/client/listers/pipeline/v1alpha1/pipelinerun.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// PipelineRunLister helps list PipelineRuns. -// All objects returned here must be treated as read-only. -type PipelineRunLister interface { - // List lists all PipelineRuns in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.PipelineRun, err error) - // PipelineRuns returns an object that can list and get PipelineRuns. - PipelineRuns(namespace string) PipelineRunNamespaceLister - PipelineRunListerExpansion -} - -// pipelineRunLister implements the PipelineRunLister interface. -type pipelineRunLister struct { - indexer cache.Indexer -} - -// NewPipelineRunLister returns a new PipelineRunLister. -func NewPipelineRunLister(indexer cache.Indexer) PipelineRunLister { - return &pipelineRunLister{indexer: indexer} -} - -// List lists all PipelineRuns in the indexer. -func (s *pipelineRunLister) List(selector labels.Selector) (ret []*v1alpha1.PipelineRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.PipelineRun)) - }) - return ret, err -} - -// PipelineRuns returns an object that can list and get PipelineRuns. -func (s *pipelineRunLister) PipelineRuns(namespace string) PipelineRunNamespaceLister { - return pipelineRunNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// PipelineRunNamespaceLister helps list and get PipelineRuns. -// All objects returned here must be treated as read-only. -type PipelineRunNamespaceLister interface { - // List lists all PipelineRuns in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.PipelineRun, err error) - // Get retrieves the PipelineRun from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.PipelineRun, error) - PipelineRunNamespaceListerExpansion -} - -// pipelineRunNamespaceLister implements the PipelineRunNamespaceLister -// interface. -type pipelineRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all PipelineRuns in the indexer for a given namespace. -func (s pipelineRunNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.PipelineRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.PipelineRun)) - }) - return ret, err -} - -// Get retrieves the PipelineRun from the indexer for a given namespace and name. -func (s pipelineRunNamespaceLister) Get(name string) (*v1alpha1.PipelineRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("pipelinerun"), name) - } - return obj.(*v1alpha1.PipelineRun), nil -} diff --git a/pkg/client/listers/pipeline/v1alpha1/task.go b/pkg/client/listers/pipeline/v1alpha1/task.go deleted file mode 100644 index 2c60610afe1..00000000000 --- a/pkg/client/listers/pipeline/v1alpha1/task.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// TaskLister helps list Tasks. -// All objects returned here must be treated as read-only. -type TaskLister interface { - // List lists all Tasks in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Task, err error) - // Tasks returns an object that can list and get Tasks. - Tasks(namespace string) TaskNamespaceLister - TaskListerExpansion -} - -// taskLister implements the TaskLister interface. -type taskLister struct { - indexer cache.Indexer -} - -// NewTaskLister returns a new TaskLister. -func NewTaskLister(indexer cache.Indexer) TaskLister { - return &taskLister{indexer: indexer} -} - -// List lists all Tasks in the indexer. -func (s *taskLister) List(selector labels.Selector) (ret []*v1alpha1.Task, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Task)) - }) - return ret, err -} - -// Tasks returns an object that can list and get Tasks. -func (s *taskLister) Tasks(namespace string) TaskNamespaceLister { - return taskNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// TaskNamespaceLister helps list and get Tasks. -// All objects returned here must be treated as read-only. -type TaskNamespaceLister interface { - // List lists all Tasks in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.Task, err error) - // Get retrieves the Task from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.Task, error) - TaskNamespaceListerExpansion -} - -// taskNamespaceLister implements the TaskNamespaceLister -// interface. -type taskNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Tasks in the indexer for a given namespace. -func (s taskNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Task, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Task)) - }) - return ret, err -} - -// Get retrieves the Task from the indexer for a given namespace and name. -func (s taskNamespaceLister) Get(name string) (*v1alpha1.Task, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("task"), name) - } - return obj.(*v1alpha1.Task), nil -} diff --git a/pkg/client/listers/pipeline/v1alpha1/taskrun.go b/pkg/client/listers/pipeline/v1alpha1/taskrun.go deleted file mode 100644 index 933cc942865..00000000000 --- a/pkg/client/listers/pipeline/v1alpha1/taskrun.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// TaskRunLister helps list TaskRuns. -// All objects returned here must be treated as read-only. -type TaskRunLister interface { - // List lists all TaskRuns in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.TaskRun, err error) - // TaskRuns returns an object that can list and get TaskRuns. - TaskRuns(namespace string) TaskRunNamespaceLister - TaskRunListerExpansion -} - -// taskRunLister implements the TaskRunLister interface. -type taskRunLister struct { - indexer cache.Indexer -} - -// NewTaskRunLister returns a new TaskRunLister. -func NewTaskRunLister(indexer cache.Indexer) TaskRunLister { - return &taskRunLister{indexer: indexer} -} - -// List lists all TaskRuns in the indexer. -func (s *taskRunLister) List(selector labels.Selector) (ret []*v1alpha1.TaskRun, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.TaskRun)) - }) - return ret, err -} - -// TaskRuns returns an object that can list and get TaskRuns. -func (s *taskRunLister) TaskRuns(namespace string) TaskRunNamespaceLister { - return taskRunNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// TaskRunNamespaceLister helps list and get TaskRuns. -// All objects returned here must be treated as read-only. -type TaskRunNamespaceLister interface { - // List lists all TaskRuns in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1alpha1.TaskRun, err error) - // Get retrieves the TaskRun from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1alpha1.TaskRun, error) - TaskRunNamespaceListerExpansion -} - -// taskRunNamespaceLister implements the TaskRunNamespaceLister -// interface. -type taskRunNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all TaskRuns in the indexer for a given namespace. -func (s taskRunNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.TaskRun, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.TaskRun)) - }) - return ret, err -} - -// Get retrieves the TaskRun from the indexer for a given namespace and name. -func (s taskRunNamespaceLister) Get(name string) (*v1alpha1.TaskRun, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("taskrun"), name) - } - return obj.(*v1alpha1.TaskRun), nil -} diff --git a/pkg/controller/filter.go b/pkg/controller/filter.go index 092b937c073..92ac30fe6fa 100644 --- a/pkg/controller/filter.go +++ b/pkg/controller/filter.go @@ -21,6 +21,7 @@ package controller import ( "github.com/tektoncd/pipeline/pkg/apis/pipeline" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" + "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" listersalpha "github.com/tektoncd/pipeline/pkg/client/listers/pipeline/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -51,7 +52,7 @@ func FilterRunRef(apiVersion, kind string) func(interface{}) bool { } result := false if r.Spec.Ref != nil { - result = r.Spec.Ref.APIVersion == apiVersion && r.Spec.Ref.Kind == v1alpha1.TaskKind(kind) + result = r.Spec.Ref.APIVersion == apiVersion && r.Spec.Ref.Kind == v1beta1.TaskKind(kind) } else if r.Spec.Spec != nil { result = r.Spec.Spec.APIVersion == apiVersion && r.Spec.Spec.Kind == kind } @@ -97,7 +98,7 @@ func FilterOwnerRunRef(runLister listersalpha.RunLister, apiVersion, kind string } result := false if run.Spec.Ref != nil { - result = run.Spec.Ref.APIVersion == apiVersion && run.Spec.Ref.Kind == v1alpha1.TaskKind(kind) + result = run.Spec.Ref.APIVersion == apiVersion && run.Spec.Ref.Kind == v1beta1.TaskKind(kind) } else if run.Spec.Spec != nil { result = run.Spec.Spec.APIVersion == apiVersion && run.Spec.Spec.Kind == kind } diff --git a/pkg/controller/filter_test.go b/pkg/controller/filter_test.go index 53e7d63acfa..062abecea82 100644 --- a/pkg/controller/filter_test.go +++ b/pkg/controller/filter_test.go @@ -64,7 +64,7 @@ func TestFilterRunRef(t *testing.T) { desc: "both ref and spec", in: &v1alpha1.Run{ Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "not-matching", Kind: kind, }, @@ -81,7 +81,7 @@ func TestFilterRunRef(t *testing.T) { desc: "Run without matching apiVersion in taskRef", in: &v1alpha1.Run{ Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: "not-matching", Kind: kind, }, @@ -92,7 +92,7 @@ func TestFilterRunRef(t *testing.T) { desc: "Run without matching kind in taskRef", in: &v1alpha1.Run{ Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion, Kind: "not-matching", }, @@ -103,7 +103,7 @@ func TestFilterRunRef(t *testing.T) { desc: "Run with matching apiVersion and kind in taskRef", in: &v1alpha1.Run{ Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion, Kind: kind, }, @@ -153,7 +153,7 @@ func TestFilterRunRef(t *testing.T) { desc: "Run with matching apiVersion and kind and name for taskRef", in: &v1alpha1.Run{ Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion, Kind: kind, Name: "some-name", @@ -201,7 +201,7 @@ func TestFilterOwnerRunRef(t *testing.T) { Namespace: "default", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion, Kind: kind, }, @@ -265,7 +265,7 @@ func TestFilterOwnerRunRef(t *testing.T) { Namespace: "default", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion2, // different apiversion Kind: kind, }, @@ -329,7 +329,7 @@ func TestFilterOwnerRunRef(t *testing.T) { Namespace: "default", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion, Kind: kind2, // different kind }, @@ -419,7 +419,7 @@ func TestFilterOwnerRunRef(t *testing.T) { Namespace: "default", }, Spec: v1alpha1.RunSpec{ - Ref: &v1alpha1.TaskRef{ + Ref: &v1beta1.TaskRef{ APIVersion: apiVersion, Kind: kind, }, diff --git a/pkg/entrypoint/entrypointer_test.go b/pkg/entrypoint/entrypointer_test.go index 2cc06095d22..cb9abe44979 100644 --- a/pkg/entrypoint/entrypointer_test.go +++ b/pkg/entrypoint/entrypointer_test.go @@ -30,7 +30,6 @@ import ( "time" "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "github.com/tektoncd/pipeline/pkg/termination" "github.com/tektoncd/pipeline/test/diff" @@ -229,7 +228,7 @@ func TestEntrypointer(t *testing.T) { } fileContents, err := ioutil.ReadFile(terminationPath) if err == nil { - var entries []v1alpha1.PipelineResourceResult + var entries []v1beta1.PipelineResourceResult if err := json.Unmarshal(fileContents, &entries); err == nil { var found = false for _, result := range entries { diff --git a/pkg/reconciler/pipelinerun/pipelinerun.go b/pkg/reconciler/pipelinerun/pipelinerun.go index 9780fcdcd80..fe5892f5747 100644 --- a/pkg/reconciler/pipelinerun/pipelinerun.go +++ b/pkg/reconciler/pipelinerun/pipelinerun.go @@ -33,6 +33,7 @@ import ( "github.com/tektoncd/pipeline/pkg/apis/pipeline" "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/artifacts" clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" pipelinerunreconciler "github.com/tektoncd/pipeline/pkg/client/injection/reconciler/pipeline/v1beta1/pipelinerun" @@ -285,7 +286,7 @@ func (c *Reconciler) resolvePipelineState( tasks []v1beta1.PipelineTask, pipelineMeta *metav1.ObjectMeta, pr *v1beta1.PipelineRun, - providedResources map[string]*v1alpha1.PipelineResource) (resources.PipelineRunState, error) { + providedResources map[string]*resourcev1alpha1.PipelineResource) (resources.PipelineRunState, error) { pst := resources.PipelineRunState{} // Resolve each task individually because they each could have a different reference context (remote or local). for _, task := range tasks { diff --git a/pkg/reconciler/pipelinerun/resources/pipelineref.go b/pkg/reconciler/pipelinerun/resources/pipelineref.go index 9b70a8f05c0..ee4ba31745a 100644 --- a/pkg/reconciler/pipelinerun/resources/pipelineref.go +++ b/pkg/reconciler/pipelinerun/resources/pipelineref.go @@ -23,7 +23,6 @@ import ( "github.com/google/go-containerregistry/pkg/authn/k8schain" "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" "github.com/tektoncd/pipeline/pkg/remote" @@ -132,12 +131,5 @@ func readRuntimeObjectAsPipeline(ctx context.Context, obj runtime.Object) (v1bet return pipeline, nil } - if pipeline, ok := obj.(*v1alpha1.Pipeline); ok { - betaPipeline := &v1beta1.Pipeline{} - err := pipeline.ConvertTo(ctx, betaPipeline) - betaPipeline.SetDefaults(ctx) - return betaPipeline, err - } - return nil, errors.New("resource is not a pipeline") } diff --git a/pkg/reconciler/pipelinerun/resources/pipelineref_test.go b/pkg/reconciler/pipelinerun/resources/pipelineref_test.go index 7829e23c50a..6e296b10d11 100644 --- a/pkg/reconciler/pipelinerun/resources/pipelineref_test.go +++ b/pkg/reconciler/pipelinerun/resources/pipelineref_test.go @@ -26,7 +26,6 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-containerregistry/pkg/registry" "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake" "github.com/tektoncd/pipeline/pkg/reconciler/pipelinerun/resources" @@ -167,37 +166,6 @@ func TestGetPipelineFunc(t *testing.T) { Bundle: u.Host + "/remote-pipeline-without-defaults", }, expected: simplePipelineWithSpecParamAndKind(v1beta1.ParamTypeString, v1beta1.NamespacedTaskKind), - }, { - name: "remote-v1alpha1-pipeline-without-defaults", - localPipelines: []runtime.Object{simplePipeline()}, - remotePipelines: []runtime.Object{ - &v1alpha1.Pipeline{ - ObjectMeta: metav1.ObjectMeta{ - Name: "simple", - Namespace: "default", - }, - TypeMeta: metav1.TypeMeta{ - Kind: "Pipeline", - APIVersion: "tekton.dev/v1alpha1", - }, - Spec: v1alpha1.PipelineSpec{ - Tasks: []v1alpha1.PipelineTask{{ - Name: "something", - TaskRef: &v1alpha1.TaskRef{ - Name: "something", - }, - }}, - Params: []v1alpha1.ParamSpec{{ - Name: "foo", - }}, - }, - }, - }, - ref: &v1alpha1.PipelineRef{ - Name: "simple", - Bundle: u.Host + "/remote-v1alpha1-pipeline-without-defaults", - }, - expected: simplePipelineWithSpecParamKindNoType(v1beta1.ParamTypeString, v1beta1.NamespacedTaskKind), }} for _, tc := range testcases { @@ -383,7 +351,7 @@ func simplePipelineWithBaseSpec() *v1beta1.Pipeline { return p } -func simplePipelineWithSpecAndParam(pt v1alpha1.ParamType) *v1beta1.Pipeline { +func simplePipelineWithSpecAndParam(pt v1beta1.ParamType) *v1beta1.Pipeline { p := simplePipelineWithBaseSpec() p.Spec.Params = []v1beta1.ParamSpec{{ Name: "foo", @@ -404,12 +372,6 @@ func simplePipelineWithSpecParamAndKind(pt v1beta1.ParamType, tk v1beta1.TaskKin return p } -func simplePipelineWithSpecParamKindNoType(pt v1beta1.ParamType, tk v1beta1.TaskKind) *v1beta1.Pipeline { - p := simplePipelineWithSpecParamAndKind(pt, tk) - p.TypeMeta = metav1.TypeMeta{} - return p -} - // This is missing the kind and apiVersion because those are added by // the MustParse helpers from the test package. var pipelineYAMLString = ` diff --git a/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go b/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go index 8437dd06775..7c36f51adc2 100644 --- a/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go +++ b/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go @@ -3100,8 +3100,8 @@ func TestResolvePipelineRunTask_WithMatrix(t *testing.T) { TaskSpec: &v1beta1.TaskSpec{Steps: []v1beta1.Step{{ Name: "step1", }}}, - Inputs: map[string]*v1alpha1.PipelineResource{}, - Outputs: map[string]*v1alpha1.PipelineResource{}, + Inputs: map[string]*resourcev1alpha1.PipelineResource{}, + Outputs: map[string]*resourcev1alpha1.PipelineResource{}, } getTask := func(ctx context.Context, name string) (v1beta1.TaskObject, error) { return task, nil } diff --git a/pkg/reconciler/taskrun/resources/taskref.go b/pkg/reconciler/taskrun/resources/taskref.go index a6f8d6af987..35c1f6612d6 100644 --- a/pkg/reconciler/taskrun/resources/taskref.go +++ b/pkg/reconciler/taskrun/resources/taskref.go @@ -24,7 +24,6 @@ import ( "github.com/google/go-containerregistry/pkg/authn/k8schain" "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" "github.com/tektoncd/pipeline/pkg/remote" @@ -45,7 +44,7 @@ var errEtcdLeaderChange = "etcdserver: leader changed" // GetTaskKind returns the referenced Task kind (Task, ClusterTask, ...) if the TaskRun is using TaskRef. func GetTaskKind(taskrun *v1beta1.TaskRun) v1beta1.TaskKind { - kind := v1alpha1.NamespacedTaskKind + kind := v1beta1.NamespacedTaskKind if taskrun.Spec.TaskRef != nil && taskrun.Spec.TaskRef.Kind != "" { kind = taskrun.Spec.TaskRef.Kind } @@ -79,7 +78,7 @@ func GetTaskFuncFromTaskRun(ctx context.Context, k8s kubernetes.Interface, tekto func GetTaskFunc(ctx context.Context, k8s kubernetes.Interface, tekton clientset.Interface, requester remoteresource.Requester, owner kmeta.OwnerRefable, tr *v1beta1.TaskRef, trName string, namespace, saName string) (GetTask, error) { cfg := config.FromContextOrDefaults(ctx) - kind := v1alpha1.NamespacedTaskKind + kind := v1beta1.NamespacedTaskKind if tr != nil && tr.Kind != "" { kind = tr.Kind } @@ -154,21 +153,6 @@ func readRuntimeObjectAsTask(ctx context.Context, obj runtime.Object) (v1beta1.T return task, nil } - // If this object is not already a v1beta1 object, figure out what type it is actually and try to coerce it - // into a v1beta1.TaskInterface compatible object. - switch tt := obj.(type) { - case *v1alpha1.Task: - betaTask := &v1beta1.Task{} - err := tt.ConvertTo(ctx, betaTask) - betaTask.SetDefaults(ctx) - return betaTask, err - case *v1alpha1.ClusterTask: - betaTask := &v1beta1.ClusterTask{} - err := tt.ConvertTo(ctx, betaTask) - betaTask.SetDefaults(ctx) - return betaTask, err - } - return nil, errors.New("resource is not a task") } diff --git a/pkg/reconciler/taskrun/resources/taskref_test.go b/pkg/reconciler/taskrun/resources/taskref_test.go index 124da526ebe..c4b779c3125 100644 --- a/pkg/reconciler/taskrun/resources/taskref_test.go +++ b/pkg/reconciler/taskrun/resources/taskref_test.go @@ -26,7 +26,6 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-containerregistry/pkg/registry" "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake" "github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources" @@ -73,6 +72,52 @@ var ( } ) +func TestGetTaskKind(t *testing.T) { + testCases := []struct { + name string + tr *v1beta1.TaskRun + expected v1beta1.TaskKind + }{ + { + name: "no task ref", + tr: &v1beta1.TaskRun{ + Spec: v1beta1.TaskRunSpec{ + TaskSpec: &v1beta1.TaskSpec{}, + }, + }, + expected: v1beta1.NamespacedTaskKind, + }, { + name: "no kind on task ref", + tr: &v1beta1.TaskRun{ + Spec: v1beta1.TaskRunSpec{ + TaskRef: &v1beta1.TaskRef{Name: "whatever"}, + }, + }, + expected: v1beta1.NamespacedTaskKind, + }, { + name: "kind on task ref", + tr: &v1beta1.TaskRun{ + Spec: v1beta1.TaskRunSpec{ + TaskRef: &v1beta1.TaskRef{ + Name: "whatever", + Kind: "something-else", + }, + }, + }, + expected: v1beta1.TaskKind("something-else"), + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + tk := resources.GetTaskKind(tc.tr) + if tk != tc.expected { + t.Errorf("expected kind %s, but got %s", tc.expected, tk) + } + }) + } +} + func TestLocalTaskRef(t *testing.T) { testcases := []struct { name string @@ -282,51 +327,6 @@ func TestGetTaskFunc(t *testing.T) { }, }, expectedKind: v1beta1.NamespacedTaskKind, - }, { - name: "remote-v1alpha1-task-without-defaults", - localTasks: []runtime.Object{}, - remoteTasks: []runtime.Object{ - &v1alpha1.Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "simple", - Namespace: "default", - }, - TypeMeta: metav1.TypeMeta{ - APIVersion: "tekton.dev/v1alpha1", - Kind: "Task", - }, - Spec: v1alpha1.TaskSpec{ - TaskSpec: v1beta1.TaskSpec{ - Params: []v1alpha1.ParamSpec{{ - Name: "foo", - }}, - Steps: []v1alpha1.Step{{ - Image: "something", - }}, - }, - }, - }, - }, - ref: &v1alpha1.TaskRef{ - Name: "simple", - Bundle: u.Host + "/remote-v1alpha1-task-without-defaults", - }, - expected: &v1beta1.Task{ - ObjectMeta: metav1.ObjectMeta{ - Name: "simple", - Namespace: "default", - }, - Spec: v1beta1.TaskSpec{ - Steps: []v1beta1.Step{{ - Image: "something", - }}, - Params: []v1beta1.ParamSpec{{ - Name: "foo", - Type: v1beta1.ParamTypeString, - }}, - }, - }, - expectedKind: v1beta1.NamespacedTaskKind, }, { name: "local-task", localTasks: []runtime.Object{simpleNamespacedTask}, @@ -359,27 +359,34 @@ func TestGetTaskFunc(t *testing.T) { name: "remote-cluster-task", localTasks: []runtime.Object{ &v1beta1.ClusterTask{ - TypeMeta: metav1.TypeMeta{APIVersion: "v1alpha1", Kind: "ClusterTask"}, + TypeMeta: metav1.TypeMeta{APIVersion: "v1beta1", Kind: "ClusterTask"}, ObjectMeta: metav1.ObjectMeta{Name: "simple"}, Spec: v1beta1.TaskSpec{Params: []v1beta1.ParamSpec{{Name: "foo"}}}, }, }, remoteTasks: []runtime.Object{ &v1beta1.ClusterTask{ - TypeMeta: metav1.TypeMeta{APIVersion: "tekton.dev/v1alpha1", Kind: "ClusterTask"}, + TypeMeta: metav1.TypeMeta{APIVersion: "tekton.dev/v1beta1", Kind: "ClusterTask"}, ObjectMeta: metav1.ObjectMeta{Name: "simple"}, }, &v1beta1.ClusterTask{ - TypeMeta: metav1.TypeMeta{APIVersion: "tekton.dev/v1alpha1", Kind: "ClusterTask"}, + TypeMeta: metav1.TypeMeta{APIVersion: "tekton.dev/v1beta1", Kind: "ClusterTask"}, ObjectMeta: metav1.ObjectMeta{Name: "dummy"}, }, }, ref: &v1beta1.TaskRef{ - Name: "simple", - Kind: v1alpha1.ClusterTaskKind, - Bundle: u.Host + "/remote-cluster-task", + Name: "simple", + APIVersion: "tekton.dev/v1beta1", + Kind: v1beta1.ClusterTaskKind, + Bundle: u.Host + "/remote-cluster-task", + }, + expected: &v1beta1.ClusterTask{ + ObjectMeta: metav1.ObjectMeta{Name: "simple"}, + TypeMeta: metav1.TypeMeta{ + APIVersion: "tekton.dev/v1beta1", + Kind: "ClusterTask", + }, }, - expected: &v1beta1.ClusterTask{ObjectMeta: metav1.ObjectMeta{Name: "simple"}}, expectedKind: v1beta1.ClusterTaskKind, }, { name: "local-cluster-task", @@ -394,9 +401,9 @@ func TestGetTaskFunc(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: "dummy"}, }, }, - ref: &v1alpha1.TaskRef{ + ref: &v1beta1.TaskRef{ Name: "simple", - Kind: v1alpha1.ClusterTaskKind, + Kind: v1beta1.ClusterTaskKind, }, expected: simpleClusterTask, expectedKind: v1beta1.ClusterTaskKind, diff --git a/pkg/reconciler/taskrun/taskrun_test.go b/pkg/reconciler/taskrun/taskrun_test.go index 773db5570db..f661f455131 100644 --- a/pkg/reconciler/taskrun/taskrun_test.go +++ b/pkg/reconciler/taskrun/taskrun_test.go @@ -36,8 +36,8 @@ import ( "github.com/tektoncd/pipeline/pkg/apis/config" "github.com/tektoncd/pipeline/pkg/apis/pipeline" "github.com/tektoncd/pipeline/pkg/apis/pipeline/pod" - resourcev1alpha1 "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" podconvert "github.com/tektoncd/pipeline/pkg/pod" "github.com/tektoncd/pipeline/pkg/reconciler/events/cloudevent" "github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources" diff --git a/pkg/reconciler/taskrun/validate_resources_test.go b/pkg/reconciler/taskrun/validate_resources_test.go index 6feae3f9044..75649862575 100644 --- a/pkg/reconciler/taskrun/validate_resources_test.go +++ b/pkg/reconciler/taskrun/validate_resources_test.go @@ -20,12 +20,11 @@ import ( "context" "testing" - "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/tektoncd/pipeline/pkg/apis/config" - resourcev1alpha1 "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/taskrun/resources" ) @@ -81,7 +80,7 @@ func TestValidateResolvedTaskResources_ValidResources(t *testing.T) { Inputs: map[string]*resourcev1alpha1.PipelineResource{ "resource-to-build": { ObjectMeta: metav1.ObjectMeta{Name: "example-resource"}, - Spec: v1alpha1.PipelineResourceSpec{ + Spec: resourcev1alpha1.PipelineResourceSpec{ Type: resourcev1alpha1.PipelineResourceTypeGit, Params: []v1beta1.ResourceParam{{ Name: "foo", @@ -91,7 +90,7 @@ func TestValidateResolvedTaskResources_ValidResources(t *testing.T) { }, "optional-resource-to-build": { ObjectMeta: metav1.ObjectMeta{Name: "example-resource"}, - Spec: v1alpha1.PipelineResourceSpec{ + Spec: resourcev1alpha1.PipelineResourceSpec{ Type: resourcev1alpha1.PipelineResourceTypeGit, Params: []v1beta1.ResourceParam{{ Name: "foo", @@ -103,13 +102,13 @@ func TestValidateResolvedTaskResources_ValidResources(t *testing.T) { Outputs: map[string]*resourcev1alpha1.PipelineResource{ "resource-to-provide": { ObjectMeta: metav1.ObjectMeta{Name: "example-image"}, - Spec: v1alpha1.PipelineResourceSpec{ + Spec: resourcev1alpha1.PipelineResourceSpec{ Type: resourcev1alpha1.PipelineResourceTypeImage, }, }, "optional-resource-to-provide": { ObjectMeta: metav1.ObjectMeta{Name: "example-image"}, - Spec: v1alpha1.PipelineResourceSpec{ + Spec: resourcev1alpha1.PipelineResourceSpec{ Type: resourcev1alpha1.PipelineResourceTypeImage, }, }, diff --git a/pkg/workspace/validate_test.go b/pkg/workspace/validate_test.go index 31f0e534fcc..cd4894d0b8a 100644 --- a/pkg/workspace/validate_test.go +++ b/pkg/workspace/validate_test.go @@ -20,7 +20,6 @@ import ( "errors" "testing" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" corev1 "k8s.io/api/core/v1" ) @@ -28,22 +27,22 @@ import ( func TestValidateBindingsValid(t *testing.T) { for _, tc := range []struct { name string - declarations []v1alpha1.WorkspaceDeclaration - bindings []v1alpha1.WorkspaceBinding + declarations []v1beta1.WorkspaceDeclaration + bindings []v1beta1.WorkspaceBinding }{{ name: "no bindings provided or required", declarations: nil, bindings: nil, }, { name: "empty list of bindings provided and required", - declarations: []v1alpha1.WorkspaceDeclaration{}, - bindings: []v1alpha1.WorkspaceBinding{}, + declarations: []v1beta1.WorkspaceDeclaration{}, + bindings: []v1beta1.WorkspaceBinding{}, }, { name: "Successfully bound with PVC", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ ClaimName: "pool-party", @@ -51,30 +50,30 @@ func TestValidateBindingsValid(t *testing.T) { }}, }, { name: "Successfully bound with emptyDir", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", EmptyDir: &corev1.EmptyDirVolumeSource{}, }}, }, { name: "Included optional workspace", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", Optional: true, }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", EmptyDir: &corev1.EmptyDirVolumeSource{}, }}, }, { name: "Omitted optional workspace", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", Optional: true, }}, - bindings: []v1alpha1.WorkspaceBinding{}, + bindings: []v1beta1.WorkspaceBinding{}, }} { t.Run(tc.name, func(t *testing.T) { if err := ValidateBindings(tc.declarations, tc.bindings); err != nil { @@ -88,14 +87,14 @@ func TestValidateBindingsValid(t *testing.T) { func TestValidateBindingsInvalid(t *testing.T) { for _, tc := range []struct { name string - declarations []v1alpha1.WorkspaceDeclaration - bindings []v1alpha1.WorkspaceBinding + declarations []v1beta1.WorkspaceDeclaration + bindings []v1beta1.WorkspaceBinding }{{ name: "Didn't provide binding matching declared workspace", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "kate", EmptyDir: &corev1.EmptyDirVolumeSource{}, }, { @@ -104,21 +103,21 @@ func TestValidateBindingsInvalid(t *testing.T) { }}, }, { name: "Provided a binding that wasn't needed", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "randall", }, { Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", EmptyDir: &corev1.EmptyDirVolumeSource{}, }}, }, { name: "Provided both pvc and emptydir", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", EmptyDir: &corev1.EmptyDirVolumeSource{}, PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ @@ -127,18 +126,18 @@ func TestValidateBindingsInvalid(t *testing.T) { }}, }, { name: "Provided neither pvc nor emptydir", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", }}, }, { name: "Provided pvc without claim name", - declarations: []v1alpha1.WorkspaceDeclaration{{ + declarations: []v1beta1.WorkspaceDeclaration{{ Name: "beth", }}, - bindings: []v1alpha1.WorkspaceBinding{{ + bindings: []v1beta1.WorkspaceBinding{{ Name: "beth", PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{}, }}, diff --git a/test/controller.go b/test/controller.go index 9844d3f12d1..5c996054b52 100644 --- a/test/controller.go +++ b/test/controller.go @@ -25,6 +25,7 @@ import ( // Link in the fakes so they get injected into injection.Fake "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" fakepipelineclientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake" informersv1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" informersv1beta1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1beta1" @@ -71,7 +72,7 @@ type Data struct { TaskRuns []*v1beta1.TaskRun Tasks []*v1beta1.Task ClusterTasks []*v1beta1.ClusterTask - PipelineResources []*v1alpha1.PipelineResource + PipelineResources []*resourcev1alpha1.PipelineResource Runs []*v1alpha1.Run Pods []*corev1.Pod Namespaces []*corev1.Namespace diff --git a/test/git_checkout_test.go b/test/git_checkout_test.go index 986a9c5db72..3fd5eb38cad 100644 --- a/test/git_checkout_test.go +++ b/test/git_checkout_test.go @@ -25,9 +25,8 @@ import ( "strings" "testing" + "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" knativetest "knative.dev/pkg/test" diff --git a/test/helm_task_test.go b/test/helm_task_test.go index bb6bf0e12e8..577247a9350 100644 --- a/test/helm_task_test.go +++ b/test/helm_task_test.go @@ -26,8 +26,8 @@ import ( "github.com/tektoncd/pipeline/test/parse" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" "github.com/tektoncd/pipeline/pkg/names" rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/test/kaniko_task_test.go b/test/kaniko_task_test.go index caecbba91ad..4062e88eb9f 100644 --- a/test/kaniko_task_test.go +++ b/test/kaniko_task_test.go @@ -25,11 +25,10 @@ import ( "strings" "testing" - "github.com/tektoncd/pipeline/test/parse" - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" + "github.com/tektoncd/pipeline/test/parse" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" knativetest "knative.dev/pkg/test" diff --git a/test/parse/yaml.go b/test/parse/yaml.go index 065a9c4dde7..e283307f9f0 100644 --- a/test/parse/yaml.go +++ b/test/parse/yaml.go @@ -34,16 +34,6 @@ kind: TaskRun return &tr } -// MustParseAlphaTaskRun takes YAML and parses it into a *v1alpha1.TaskRun -func MustParseAlphaTaskRun(t *testing.T, yaml string) *v1alpha1.TaskRun { - var tr v1alpha1.TaskRun - yaml = `apiVersion: tekton.dev/v1alpha1 -kind: TaskRun -` + yaml - mustParseYAML(t, yaml, &tr) - return &tr -} - // MustParseRun takes YAML and parses it into a *v1alpha1.Run func MustParseRun(t *testing.T, yaml string) *v1alpha1.Run { var r v1alpha1.Run @@ -74,16 +64,6 @@ kind: ClusterTask return &clusterTask } -// MustParseAlphaTask takes YAML and parses it into a *v1alpha1.Task -func MustParseAlphaTask(t *testing.T, yaml string) *v1alpha1.Task { - var task v1alpha1.Task - yaml = `apiVersion: tekton.dev/v1alpha1 -kind: Task -` + yaml - mustParseYAML(t, yaml, &task) - return &task -} - // MustParsePipelineRun takes YAML and parses it into a *v1beta1.PipelineRun func MustParsePipelineRun(t *testing.T, yaml string) *v1beta1.PipelineRun { var pr v1beta1.PipelineRun @@ -94,16 +74,6 @@ kind: PipelineRun return &pr } -// MustParseAlphaPipelineRun takes YAML and parses it into a *v1alpha1.PipelineRun -func MustParseAlphaPipelineRun(t *testing.T, yaml string) *v1alpha1.PipelineRun { - var pr v1alpha1.PipelineRun - yaml = `apiVersion: tekton.dev/v1alpha1 -kind: PipelineRun -` + yaml - mustParseYAML(t, yaml, &pr) - return &pr -} - // MustParsePipeline takes YAML and parses it into a *v1beta1.Pipeline func MustParsePipeline(t *testing.T, yaml string) *v1beta1.Pipeline { var pipeline v1beta1.Pipeline @@ -114,16 +84,6 @@ kind: Pipeline return &pipeline } -// MustParseAlphaPipeline takes YAML and parses it into a *v1alpha1.Pipeline -func MustParseAlphaPipeline(t *testing.T, yaml string) *v1alpha1.Pipeline { - var pipeline v1alpha1.Pipeline - yaml = `apiVersion: tekton.dev/v1alpha1 -kind: Pipeline -` + yaml - mustParseYAML(t, yaml, &pipeline) - return &pipeline -} - // MustParsePipelineResource takes YAML and parses it into a *resourcev1alpha1.PipelineResource func MustParsePipelineResource(t *testing.T, yaml string) *resourcev1alpha1.PipelineResource { var resource resourcev1alpha1.PipelineResource diff --git a/test/pipelinerun_test.go b/test/pipelinerun_test.go index 20f797e7780..6f11fd59413 100644 --- a/test/pipelinerun_test.go +++ b/test/pipelinerun_test.go @@ -27,12 +27,11 @@ import ( "testing" "time" - "github.com/tektoncd/pipeline/test/parse" - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" + "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" "github.com/tektoncd/pipeline/pkg/artifacts" + "github.com/tektoncd/pipeline/test/parse" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" k8sres "k8s.io/apimachinery/pkg/api/resource" diff --git a/test/v1alpha1/artifact_bucket_test.go b/test/v1alpha1/artifact_bucket_test.go deleted file mode 100644 index 4996d306e5d..00000000000 --- a/test/v1alpha1/artifact_bucket_test.go +++ /dev/null @@ -1,339 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/config" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -const ( - systemNamespace = "tekton-pipelines" - bucketSecretName = "bucket-secret" - bucketSecretKey = "bucket-secret-key" -) - -// TestStorageBucketPipelineRun is an integration test that will verify a pipeline -// can use a bucket for temporary storage of artifacts shared between tasks -func TestStorageBucketPipelineRun(t *testing.T) { - var ( - helloworldResourceName = helpers.ObjectNameForTest(t) - addFileTaskName = helpers.ObjectNameForTest(t) - runFileTaskName = helpers.ObjectNameForTest(t) - bucketTestPipelineName = helpers.ObjectNameForTest(t) - bucketTestPipelineRunName = helpers.ObjectNameForTest(t) - ) - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - configFilePath := os.Getenv("GCP_SERVICE_ACCOUNT_KEY_PATH") - if configFilePath == "" { - t.Skip("GCP_SERVICE_ACCOUNT_KEY_PATH variable is not set.") - } - c, namespace := setup(ctx, t) - // Bucket tests can't run in parallel without causing issues with other tests. - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - bucketName := fmt.Sprintf("build-pipeline-test-%s-%d", namespace, time.Now().Unix()) - - t.Logf("Creating Secret %s", bucketSecretName) - if _, err := c.KubeClient.CoreV1().Secrets(namespace).Create(ctx, getBucketSecret(t, configFilePath, namespace), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Secret %q: %v", bucketSecretName, err) - } - defer deleteBucketSecret(ctx, c, t, namespace) - - t.Logf("Creating GCS bucket %s", bucketName) - createbuckettask := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: createbuckettask -spec: - steps: - - name: step1 - image: gcr.io/google.com/cloudsdktool/cloud-sdk:alpine - command: ['/bin/bash'] - args: ['-c', 'gcloud auth activate-service-account --key-file /var/secret/bucket-secret/bucket-secret-key && gsutil mb gs://%s'] - volumeMounts: - - name: bucket-secret-volume - mountPath: /var/secret/%s - env: - - name: CREDENTIALS - value: /var/secret/%s/%s - volumes: - - name: bucket-secret-volume - secret: - secretName: %s -`, bucketName, bucketSecretName, bucketSecretName, bucketSecretKey, bucketSecretName)) - - t.Logf("Creating Task %s", "createbuckettask") - if _, err := c.TaskClient.Create(ctx, createbuckettask, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", "createbuckettask", err) - } - - createbuckettaskrun := parse.MustParseAlphaTaskRun(t, ` -metadata: - name: createbuckettaskrun -spec: - taskRef: - name: createbuckettask -`) - - t.Logf("Creating TaskRun %s", "createbuckettaskrun") - if _, err := c.TaskRunClient.Create(ctx, createbuckettaskrun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun `%s`: %s", "createbuckettaskrun", err) - } - - if err := WaitForTaskRunState(ctx, c, "createbuckettaskrun", TaskRunSucceed("createbuckettaskrun"), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun %s to finish: %s", "createbuckettaskrun", err) - } - - defer runTaskToDeleteBucket(ctx, c, t, namespace, bucketName, bucketSecretName, bucketSecretKey) - - originalConfigMap, err := c.KubeClient.CoreV1().ConfigMaps(systemNamespace).Get(ctx, config.GetArtifactBucketConfigName(), metav1.GetOptions{}) - if err != nil { - t.Fatalf("Failed to get ConfigMap `%s`: %s", config.GetArtifactBucketConfigName(), err) - } - originalConfigMapData := originalConfigMap.Data - - t.Logf("Creating ConfigMap %s", config.GetArtifactBucketConfigName()) - configMapData := map[string]string{ - config.BucketLocationKey: fmt.Sprintf("gs://%s", bucketName), - config.BucketServiceAccountSecretNameKey: bucketSecretName, - config.BucketServiceAccountSecretKeyKey: bucketSecretKey, - } - if err := updateConfigMap(ctx, c.KubeClient, systemNamespace, config.GetArtifactBucketConfigName(), configMapData); err != nil { - t.Fatal(err) - } - defer resetConfigMap(ctx, t, c, systemNamespace, config.GetArtifactBucketConfigName(), originalConfigMapData) - - t.Logf("Creating Git PipelineResource %s", helloworldResourceName) - helloworldResource := parse.MustParsePipelineResource(t, fmt.Sprintf(` -metadata: - name: %s -spec: - params: - - name: Url - value: https://github.com/pivotal-nader-ziada/gohelloworld - - name: Revision - value: master - type: git -`, helloworldResourceName)) - if _, err := c.PipelineResourceClient.Create(ctx, helloworldResource, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline Resource `%s`: %s", helloworldResourceName, err) - } - - t.Logf("Creating Task %s", addFileTaskName) - addFileTask := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - inputs: - resources: - - name: %s - type: git - outputs: - resources: - - name: %s - type: git - steps: - - image: ubuntu - name: addfile - script: |- - echo '#!/bin/bash - echo hello' > /workspace/helloworldgit/newfile - - image: ubuntu - name: make-executable - script: chmod +x /workspace/helloworldgit/newfile -`, addFileTaskName, helloworldResourceName, helloworldResourceName)) - if _, err := c.TaskClient.Create(ctx, addFileTask, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", addFileTaskName, err) - } - - t.Logf("Creating Task %s", runFileTaskName) - readFileTask := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - inputs: - - name: %s - type: git - steps: - - command: ['/workspace/hellowrld/newfile'] - image: ubuntu - name: runfile -`, runFileTaskName, helloworldResourceName)) - if _, err := c.TaskClient.Create(ctx, readFileTask, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", runFileTaskName, err) - } - - t.Logf("Creating Pipeline %s", bucketTestPipelineName) - bucketTestPipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - - name: source-repo - type: git - tasks: - - name: addfile - resources: - inputs: - - name: helloworldgit - resource: source-repo - outputs: - - name: helloworldgit - resource: source-repo - taskRef: - name: %s - - name: runfile - resources: - inputs: - - name: helloworldgit - resource: source-repo - from: - - addfile - taskRef: - name: %s -`, bucketTestPipelineName, addFileTaskName, runFileTaskName)) - if _, err := c.PipelineClient.Create(ctx, bucketTestPipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", bucketTestPipelineName, err) - } - - t.Logf("Creating PipelineRun %s", bucketTestPipelineRunName) - bucketTestPipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s - resources: - - name: source-repo - resourceRef: - name: %s -`, bucketTestPipelineRunName, bucketTestPipelineName, helloworldResourceName)) - if _, err := c.PipelineRunClient.Create(ctx, bucketTestPipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", bucketTestPipelineRunName, err) - } - - // Verify status of PipelineRun (wait for it) - if err := WaitForPipelineRunState(ctx, c, bucketTestPipelineRunName, timeout, PipelineRunSucceed(bucketTestPipelineRunName), "PipelineRunCompleted"); err != nil { - t.Errorf("Error waiting for PipelineRun %s to finish: %s", bucketTestPipelineRunName, err) - t.Fatalf("PipelineRun execution failed") - } -} - -// updateConfigMap updates the config map for specified @name with values. We can't use the one from knativetest because -// it assumes that Data is already a non-nil map, and by default, it isn't! -func updateConfigMap(ctx context.Context, client kubernetes.Interface, name string, configName string, values map[string]string) error { - configMap, err := client.CoreV1().ConfigMaps(name).Get(ctx, configName, metav1.GetOptions{}) - if err != nil { - return err - } - - if configMap.Data == nil { - configMap.Data = make(map[string]string) - } - - for key, value := range values { - configMap.Data[key] = value - } - - _, err = client.CoreV1().ConfigMaps(name).Update(ctx, configMap, metav1.UpdateOptions{}) - return err -} - -func getBucketSecret(t *testing.T, configFilePath, namespace string) *corev1.Secret { - t.Helper() - f, err := ioutil.ReadFile(configFilePath) - if err != nil { - t.Fatalf("Failed to read json key file %s at path %s", err, configFilePath) - } - return &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: namespace, - Name: bucketSecretName, - }, - StringData: map[string]string{ - bucketSecretKey: string(f), - }, - } -} - -func deleteBucketSecret(ctx context.Context, c *clients, t *testing.T, namespace string) { - if err := c.KubeClient.CoreV1().Secrets(namespace).Delete(ctx, bucketSecretName, metav1.DeleteOptions{}); err != nil { - t.Fatalf("Failed to delete Secret `%s`: %s", bucketSecretName, err) - } -} - -func resetConfigMap(ctx context.Context, t *testing.T, c *clients, namespace, configName string, values map[string]string) { - if err := updateConfigMap(ctx, c.KubeClient, namespace, configName, values); err != nil { - t.Log(err) - } -} - -func runTaskToDeleteBucket(ctx context.Context, c *clients, t *testing.T, namespace, bucketName, bucketSecretName, bucketSecretKey string) { - deletelbuckettask := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - volumes: - - name: bucket-secret-volume - secret: - secretName: %s -`, helpers.ObjectNameForTest(t), bucketSecretName)) - - t.Logf("Creating Task %s", deletelbuckettask.Name) - if _, err := c.TaskClient.Create(ctx, deletelbuckettask, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", deletelbuckettask.Name, err) - } - - deletelbuckettaskrun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), deletelbuckettask.Name)) - - t.Logf("Creating TaskRun %s", deletelbuckettaskrun.Name) - if _, err := c.TaskRunClient.Create(ctx, deletelbuckettaskrun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun `%s`: %s", deletelbuckettaskrun.Name, err) - } - - if err := WaitForTaskRunState(ctx, c, deletelbuckettaskrun.Name, TaskRunSucceed(deletelbuckettaskrun.Name), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun %s to finish: %s", deletelbuckettaskrun.Name, err) - } -} diff --git a/test/v1alpha1/build_logs.go b/test/v1alpha1/build_logs.go deleted file mode 100644 index 74b19054096..00000000000 --- a/test/v1alpha1/build_logs.go +++ /dev/null @@ -1,74 +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 test - -import ( - "context" - "fmt" - "io/ioutil" - "strings" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "knative.dev/pkg/test/logging" -) - -// CollectPodLogs will get the logs for all containers in a Pod -func CollectPodLogs(ctx context.Context, c *clients, podName, namespace string, logf logging.FormatLogger) { - logs, err := getContainersLogsFromPod(ctx, c.KubeClient, podName, namespace) - if err != nil { - logf("Could not get logs for pod %s: %s", podName, err) - } - logf("build logs %s", logs) -} - -func getContainersLogsFromPod(ctx context.Context, c kubernetes.Interface, pod, namespace string) (string, error) { - p, err := c.CoreV1().Pods(namespace).Get(ctx, pod, metav1.GetOptions{}) - if err != nil { - return "", err - } - - sb := strings.Builder{} - for _, container := range p.Spec.Containers { - sb.WriteString(fmt.Sprintf("\n>>> Container %s:\n", container.Name)) - logs, err := getContainerLogsFromPod(ctx, c, pod, container.Name, namespace) - if err != nil { - return "", err - } - sb.WriteString(logs) - } - return sb.String(), nil -} - -func getContainerLogsFromPod(ctx context.Context, c kubernetes.Interface, pod, container, namespace string) (string, error) { - sb := strings.Builder{} - // Do not follow, which will block until the Pod terminates, and potentially deadlock the test. - // If done in the wrong order, this could actually block things and prevent the Pod from being - // deleted at all. - req := c.CoreV1().Pods(namespace).GetLogs(pod, &corev1.PodLogOptions{Follow: false, Container: container}) - rc, err := req.Stream(ctx) - if err != nil { - return "", err - } - bs, err := ioutil.ReadAll(rc) - if err != nil { - return "", err - } - sb.Write(bs) - return sb.String(), nil -} diff --git a/test/v1alpha1/cancel_test.go b/test/v1alpha1/cancel_test.go deleted file mode 100644 index 89d405fd3e7..00000000000 --- a/test/v1alpha1/cancel_test.go +++ /dev/null @@ -1,177 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "encoding/json" - "fmt" - "strings" - "sync" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - "gomodules.xyz/jsonpatch/v2" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestTaskRunPipelineRunCancel cancels a PipelineRun and verifies TaskRun statuses and Pod deletions. -func TestTaskRunPipelineRunCancel(t *testing.T) { - // We run the test twice, once with a PipelineTask configured to retry - // on failure, to ensure that cancelling the PipelineRun doesn't cause - // the retrying TaskRun to retry. - for _, numRetries := range []int{0, 1} { - numRetries := numRetries // capture range variable - t.Run(fmt.Sprintf("retries=%d", numRetries), func(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - pipelineRunName := helpers.ObjectNameForTest(t) - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineSpec: - tasks: - - name: task - retries: %d - taskSpec: - steps: - - image: busybox - script: 'sleep 5000' -`, pipelineRunName, numRetries)) - - t.Logf("Creating PipelineRun in namespace %s", namespace) - if _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", pipelineRunName, err) - } - - t.Logf("Waiting for Pipelinerun %s in namespace %s to be started", pipelineRunName, namespace) - if err := WaitForPipelineRunState(ctx, c, pipelineRunName, pipelineRunTimeout, Running(pipelineRunName), "PipelineRunRunning"); err != nil { - t.Fatalf("Error waiting for PipelineRun %s to be running: %s", pipelineRunName, err) - } - - taskrunList, err := c.TaskRunClient.List(ctx, metav1.ListOptions{LabelSelector: "tekton.dev/pipelineRun=" + pipelineRunName}) - if err != nil { - t.Fatalf("Error listing TaskRuns for PipelineRun %s: %s", pipelineRunName, err) - } - - var wg sync.WaitGroup - t.Logf("Waiting for TaskRuns from PipelineRun %s in namespace %s to be running", pipelineRunName, namespace) - for _, taskrunItem := range taskrunList.Items { - wg.Add(1) - go func(name string) { - defer wg.Done() - err := WaitForTaskRunState(ctx, c, name, Running(name), "TaskRunRunning") - if err != nil { - t.Errorf("Error waiting for TaskRun %s to be running: %v", name, err) - } - }(taskrunItem.Name) - } - wg.Wait() - - pr, err := c.PipelineRunClient.Get(ctx, pipelineRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Failed to get PipelineRun `%s`: %s", pipelineRunName, err) - } - - patches := []jsonpatch.JsonPatchOperation{{ - Operation: "add", - Path: "/spec/status", - Value: v1beta1.PipelineRunSpecStatusCancelled, - }} - patchBytes, err := json.Marshal(patches) - if err != nil { - t.Fatalf("failed to marshal patch bytes in order to cancel") - } - if _, err := c.PipelineRunClient.Patch(ctx, pr.Name, types.JSONPatchType, patchBytes, metav1.PatchOptions{}, ""); err != nil { - t.Fatalf("Failed to patch PipelineRun `%s` with cancellation: %s", pipelineRunName, err) - } - - t.Logf("Waiting for PipelineRun %s in namespace %s to be cancelled", pipelineRunName, namespace) - if err := WaitForPipelineRunState(ctx, c, pipelineRunName, pipelineRunTimeout, FailedWithReason("Cancelled", pipelineRunName), "Cancelled"); err != nil { - t.Errorf("Error waiting for PipelineRun %q to finished: %s", pipelineRunName, err) - } - - t.Logf("Waiting for TaskRuns in PipelineRun %s in namespace %s to be cancelled", pipelineRunName, namespace) - for _, taskrunItem := range taskrunList.Items { - wg.Add(1) - go func(name string) { - defer wg.Done() - err := WaitForTaskRunState(ctx, c, name, FailedWithReason("TaskRunCancelled", name), "TaskRunCancelled") - if err != nil { - t.Errorf("Error waiting for TaskRun %s to be finished: %v", name, err) - } - }(taskrunItem.Name) - } - wg.Wait() - - var trName []string - taskrunList, err = c.TaskRunClient.List(ctx, metav1.ListOptions{LabelSelector: "tekton.dev/pipelineRun=" + pipelineRunName}) - if err != nil { - t.Fatalf("Error listing TaskRuns for PipelineRun %s: %s", pipelineRunName, err) - } - for _, taskrunItem := range taskrunList.Items { - trName = append(trName, taskrunItem.Name) - } - matchKinds := map[string][]string{"PipelineRun": {pipelineRunName}} - // Expected failure events: 1 for the pipelinerun cancel - expectedNumberOfEvents := 1 - t.Logf("Making sure %d events were created from pipelinerun with kinds %v", expectedNumberOfEvents, matchKinds) - events, err := collectMatchingEvents(ctx, c.KubeClient, namespace, matchKinds, "Failed") - if err != nil { - t.Fatalf("Failed to collect matching events: %q", err) - } - if len(events) < expectedNumberOfEvents { - collectedEvents := make([]string, 0, len(events)) - for _, event := range events { - collectedEvents = append(collectedEvents, fmt.Sprintf("%#v", event)) - } - t.Fatalf("Expected %d number of failed events from pipelinerun but got %d; list of received events : %s", expectedNumberOfEvents, len(events), strings.Join(collectedEvents, ", ")) - } - matchKinds = map[string][]string{"TaskRun": trName} - // Expected failure events: 1 for each TaskRun - expectedNumberOfEvents = len(trName) - t.Logf("Making sure %d events were created from taskruns with kinds %v", expectedNumberOfEvents, matchKinds) - events, err = collectMatchingEvents(ctx, c.KubeClient, namespace, matchKinds, "Failed") - if err != nil { - t.Fatalf("Failed to collect matching events: %q", err) - } - if len(events) < expectedNumberOfEvents { - collectedEvents := make([]string, 0, len(events)) - for _, event := range events { - collectedEvents = append(collectedEvents, fmt.Sprintf("%#v", event)) - } - t.Fatalf("Expected %d number of failed events from taskrun but got %d; list of received events : %s", expectedNumberOfEvents, len(events), strings.Join(collectedEvents, ", ")) - } - }) - } -} diff --git a/test/v1alpha1/clients.go b/test/v1alpha1/clients.go deleted file mode 100644 index f359aa10a18..00000000000 --- a/test/v1alpha1/clients.go +++ /dev/null @@ -1,97 +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. -*/ - -/* -Get access to client objects - -To initialize client objects you can use the setup function. It returns a clients struct -that contains initialized clients for accessing: - - - Kubernetes objects - - Pipelines (https://github.com/tektoncd/pipeline#pipeline) - -For example, to create a Pipeline - - _, err = clients.PipelineClient.Pipelines.Create(test.Pipeline(namespaceName, pipelineName)) - -And you can use the client to clean up resources created by your test - - func tearDown(clients *test.Clients) { - if clients != nil { - clients.Delete([]string{routeName}, []string{configName}) - } - } - -*/ - -package test - -import ( - "testing" - - "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" - resourceversioned "github.com/tektoncd/pipeline/pkg/client/resource/clientset/versioned" - resourcev1alpha1 "github.com/tektoncd/pipeline/pkg/client/resource/clientset/versioned/typed/resource/v1alpha1" - "k8s.io/client-go/kubernetes" - knativetest "knative.dev/pkg/test" -) - -// clients holds instances of interfaces for making requests to the Pipeline controllers. -type clients struct { - KubeClient kubernetes.Interface - - PipelineClient v1alpha1.PipelineInterface - TaskClient v1alpha1.TaskInterface - TaskRunClient v1alpha1.TaskRunInterface - PipelineRunClient v1alpha1.PipelineRunInterface - PipelineResourceClient resourcev1alpha1.PipelineResourceInterface -} - -// newClients instantiates and returns several clientsets required for making requests to the -// Pipeline cluster specified by the combination of clusterName and configPath. Clients can -// make requests within namespace. -func newClients(t *testing.T, configPath, clusterName, namespace string) *clients { - t.Helper() - var err error - c := &clients{} - - cfg, err := knativetest.BuildClientConfig(configPath, clusterName) - if err != nil { - t.Fatalf("failed to create configuration obj from %s for cluster %s: %s", configPath, clusterName, err) - } - - kubeClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - t.Fatalf("failed to create kubeclient from config file at %s: %s", configPath, err) - } - c.KubeClient = kubeClient - - cs, err := versioned.NewForConfig(cfg) - if err != nil { - t.Fatalf("failed to create pipeline clientset from config file at %s: %s", configPath, err) - } - rcs, err := resourceversioned.NewForConfig(cfg) - if err != nil { - t.Fatalf("failed to create pipeline clientset from config file at %s: %s", configPath, err) - } - c.PipelineClient = cs.TektonV1alpha1().Pipelines(namespace) - c.TaskClient = cs.TektonV1alpha1().Tasks(namespace) - c.TaskRunClient = cs.TektonV1alpha1().TaskRuns(namespace) - c.PipelineRunClient = cs.TektonV1alpha1().PipelineRuns(namespace) - c.PipelineResourceClient = rcs.TektonV1alpha1().PipelineResources(namespace) - return c -} diff --git a/test/v1alpha1/cluster_resource_test.go b/test/v1alpha1/cluster_resource_test.go deleted file mode 100644 index ec25537cbb5..00000000000 --- a/test/v1alpha1/cluster_resource_test.go +++ /dev/null @@ -1,202 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "testing" - - resourcev1alpha1 "github.com/tektoncd/pipeline/pkg/apis/resource/v1alpha1" - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -func TestClusterResource(t *testing.T) { - secretName := "hw-secret" - configName := "hw-config" - resourceName := helpers.ObjectNameForTest(t) - taskName := helpers.ObjectNameForTest(t) - taskRunName := helpers.ObjectNameForTest(t) - - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - t.Logf("Creating secret %s", secretName) - if _, err := c.KubeClient.CoreV1().Secrets(namespace).Create(ctx, getClusterResourceTaskSecret(namespace, secretName), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Secret `%s`: %s", secretName, err) - } - - t.Logf("Creating configMap %s", configName) - if _, err := c.KubeClient.CoreV1().ConfigMaps(namespace).Create(ctx, getClusterConfigMap(namespace, configName), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create configMap `%s`: %s", configName, err) - } - - t.Logf("Creating cluster PipelineResource %s", resourceName) - if _, err := c.PipelineResourceClient.Create(ctx, getClusterResource(t, namespace, resourceName, secretName), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create cluster Pipeline Resource `%s`: %s", resourceName, err) - } - - t.Logf("Creating Task %s", taskName) - if _, err := c.TaskClient.Create(ctx, getClusterResourceTask(t, taskName, configName), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", taskName, err) - } - - t.Logf("Creating TaskRun %s", taskRunName) - if _, err := c.TaskRunClient.Create(ctx, getClusterResourceTaskRun(t, namespace, taskRunName, taskName, resourceName), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Taskrun `%s`: %s", taskRunName, err) - } - - // Verify status of TaskRun (wait for it) - if err := WaitForTaskRunState(ctx, c, taskRunName, TaskRunSucceed(taskRunName), "TaskRunCompleted"); err != nil { - t.Errorf("Error waiting for TaskRun %s to finish: %s", taskRunName, err) - } -} - -func getClusterResource(t *testing.T, namespace, name, sname string) *resourcev1alpha1.PipelineResource { - return parse.MustParsePipelineResource(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - type: cluster - params: - - name: Name - value: helloworld-cluster - - name: Url - value: https://1.1.1.1 - - name: username - value: test-user - - name: password - value: test-password - secrets: - - fieldName: cadata - secretKey: cadatakey - secretName: %s - - fieldName: token - secretKey: tokenkey - secretName: %s -`, name, namespace, sname, sname)) -} - -func getClusterResourceTaskSecret(namespace, name string) *corev1.Secret { - return &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Data: map[string][]byte{ - "cadatakey": []byte("Y2EtY2VydAo="), // ca-cert - "tokenkey": []byte("dG9rZW4K"), // token - }, - } -} - -func getClusterResourceTask(t *testing.T, name, configName string) *v1alpha1.Task { - return parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - inputs: - resources: - - name: target-cluster - type: cluster - volumes: - - name: config-vol - configMap: - name: %s - steps: - - name: check-file-existence - image: ubuntu - command: ['cat'] - args: ['/workspace/target-cluster/kubeconfig'] - - name: check-config-data - image: ubuntu - command: ['cat'] - args: ['/config/test.data'] - volumeMounts: - - name: config-vol - mountPath: /config - - name: check-contents - image: ubuntu - command: ['bash'] - args: ['-c', 'cmp -b /workspace/target-cluster/kubeconfig /config/test.data'] - volumeMounts: - - name: config-vol - mountPath: /config -`, name, configName)) -} - -func getClusterResourceTaskRun(t *testing.T, namespace, name, taskName, resName string) *v1alpha1.TaskRun { - return parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - taskRef: - name: %s - inputs: - resources: - - name: target-cluster - resourceRef: - name: %s -`, name, namespace, taskName, resName)) -} - -func getClusterConfigMap(namespace, name string) *corev1.ConfigMap { - return &corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: namespace, - Name: name, - }, - Data: map[string]string{ - "test.data": `apiVersion: v1 -clusters: -- cluster: - certificate-authority-data: WTJFdFkyVnlkQW89 - server: https://1.1.1.1 - name: target-cluster -contexts: -- context: - cluster: target-cluster - user: test-user - name: target-cluster -current-context: target-cluster -kind: Config -preferences: {} -users: -- name: test-user - user: - token: dG9rZW4K -`, - }, - } -} diff --git a/test/v1alpha1/controller.go b/test/v1alpha1/controller.go deleted file mode 100644 index f9644510bce..00000000000 --- a/test/v1alpha1/controller.go +++ /dev/null @@ -1,167 +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 test - -import ( - "context" - "testing" - - // Link in the fakes so they get injected into injection.Fake - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - fakepipelineclientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/fake" - informersv1alpha1 "github.com/tektoncd/pipeline/pkg/client/informers/externalversions/pipeline/v1alpha1" - fakepipelineclient "github.com/tektoncd/pipeline/pkg/client/injection/client/fake" - fakeclustertaskinformer "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/clustertask/fake" - fakepipelineinformer "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/pipeline/fake" - fakepipelineruninformer "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/pipelinerun/fake" - faketaskinformer "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/task/fake" - faketaskruninformer "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1alpha1/taskrun/fake" - fakeresourceclientset "github.com/tektoncd/pipeline/pkg/client/resource/clientset/versioned/fake" - resourceinformersv1alpha1 "github.com/tektoncd/pipeline/pkg/client/resource/informers/externalversions/resource/v1alpha1" - fakeresourceclient "github.com/tektoncd/pipeline/pkg/client/resource/injection/client/fake" - fakeresourceinformer "github.com/tektoncd/pipeline/pkg/client/resource/injection/informers/resource/v1alpha1/pipelineresource/fake" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - coreinformers "k8s.io/client-go/informers/core/v1" - fakekubeclientset "k8s.io/client-go/kubernetes/fake" - fakekubeclient "knative.dev/pkg/client/injection/kube/client/fake" - fakefilteredpodinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/pod/filtered/fake" - "knative.dev/pkg/controller" -) - -// Data represents the desired state of the system (i.e. existing resources) to seed controllers -// with. -type Data struct { - PipelineRuns []*v1alpha1.PipelineRun - Pipelines []*v1alpha1.Pipeline - TaskRuns []*v1alpha1.TaskRun - Tasks []*v1alpha1.Task - ClusterTasks []*v1alpha1.ClusterTask - PipelineResources []*v1alpha1.PipelineResource - Pods []*corev1.Pod - Namespaces []*corev1.Namespace -} - -// Clients holds references to clients which are useful for reconciler tests. -type Clients struct { - Pipeline *fakepipelineclientset.Clientset - Resource *fakeresourceclientset.Clientset - Kube *fakekubeclientset.Clientset -} - -// Informers holds references to informers which are useful for reconciler tests. -type Informers struct { - PipelineRun informersv1alpha1.PipelineRunInformer - Pipeline informersv1alpha1.PipelineInformer - TaskRun informersv1alpha1.TaskRunInformer - Task informersv1alpha1.TaskInformer - ClusterTask informersv1alpha1.ClusterTaskInformer - PipelineResource resourceinformersv1alpha1.PipelineResourceInformer - Pod coreinformers.PodInformer -} - -// Assets holds references to the controller, logs, clients, and informers. -type Assets struct { - Controller *controller.Impl - Clients Clients -} - -// SeedTestData returns Clients and Informers populated with the -// given Data. -// nolint: revive -func SeedTestData(t *testing.T, ctx context.Context, d Data) (Clients, Informers) { - c := Clients{ - Kube: fakekubeclient.Get(ctx), - Pipeline: fakepipelineclient.Get(ctx), - Resource: fakeresourceclient.Get(ctx), - } - - i := Informers{ - PipelineRun: fakepipelineruninformer.Get(ctx), - Pipeline: fakepipelineinformer.Get(ctx), - TaskRun: faketaskruninformer.Get(ctx), - Task: faketaskinformer.Get(ctx), - ClusterTask: fakeclustertaskinformer.Get(ctx), - PipelineResource: fakeresourceinformer.Get(ctx), - Pod: fakefilteredpodinformer.Get(ctx, v1alpha1.ManagedByLabelKey), - } - - for _, pr := range d.PipelineRuns { - if err := i.PipelineRun.Informer().GetIndexer().Add(pr); err != nil { - t.Fatal(err) - } - if _, err := c.Pipeline.TektonV1alpha1().PipelineRuns(pr.Namespace).Create(ctx, pr, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, p := range d.Pipelines { - if err := i.Pipeline.Informer().GetIndexer().Add(p); err != nil { - t.Fatal(err) - } - if _, err := c.Pipeline.TektonV1alpha1().Pipelines(p.Namespace).Create(ctx, p, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, tr := range d.TaskRuns { - if err := i.TaskRun.Informer().GetIndexer().Add(tr); err != nil { - t.Fatal(err) - } - if _, err := c.Pipeline.TektonV1alpha1().TaskRuns(tr.Namespace).Create(ctx, tr, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, ta := range d.Tasks { - if err := i.Task.Informer().GetIndexer().Add(ta); err != nil { - t.Fatal(err) - } - if _, err := c.Pipeline.TektonV1alpha1().Tasks(ta.Namespace).Create(ctx, ta, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, ct := range d.ClusterTasks { - if err := i.ClusterTask.Informer().GetIndexer().Add(ct); err != nil { - t.Fatal(err) - } - if _, err := c.Pipeline.TektonV1alpha1().ClusterTasks().Create(ctx, ct, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, r := range d.PipelineResources { - if err := i.PipelineResource.Informer().GetIndexer().Add(r); err != nil { - t.Fatal(err) - } - if _, err := c.Resource.TektonV1alpha1().PipelineResources(r.Namespace).Create(ctx, r, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, p := range d.Pods { - if err := i.Pod.Informer().GetIndexer().Add(p); err != nil { - t.Fatal(err) - } - if _, err := c.Kube.CoreV1().Pods(p.Namespace).Create(ctx, p, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - for _, n := range d.Namespaces { - if _, err := c.Kube.CoreV1().Namespaces().Create(ctx, n, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } - c.Pipeline.ClearActions() - c.Kube.ClearActions() - return c, i -} diff --git a/test/v1alpha1/dag_test.go b/test/v1alpha1/dag_test.go deleted file mode 100644 index de79b7b6cfd..00000000000 --- a/test/v1alpha1/dag_test.go +++ /dev/null @@ -1,258 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "math" - "sort" - "strings" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -const sleepDuration = 15 * time.Second - -// TestDAGPipelineRun creates a graph of arbitrary Tasks, then looks at the corresponding -// TaskRun start times to ensure they were run in the order intended, which is: -// | -// pipeline-task-1 -// / \ -// pipeline-task-2-parallel-1 pipeline-task-2-parallel-2 -// \ / -// pipeline-task-3 -// | -// pipeline-task-4 -func TestDAGPipelineRun(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - // Create the Task that echoes text - echoTask := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - resources: - inputs: - - name: repo - type: git - outputs: - - name: repo - type: git - params: - - name: text - type: string - description: 'The text that should be echoed' - steps: - - image: busybox - script: 'echo $(params["text"])' - - image: busybox - # Sleep for N seconds so that we can check that tasks that - # should be run in parallel have overlap. - script: 'sleep %d' - - image: busybox - script: 'ln -s $(resources.inputs.repo.path) $(resources.outputs.repo.path)' -`, helpers.ObjectNameForTest(t), namespace, int(sleepDuration.Seconds()))) - if _, err := c.TaskClient.Create(ctx, echoTask, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create echo Task: %s", err) - } - - // Create the repo PipelineResource (doesn't really matter which repo we use) - repoResource := parse.MustParsePipelineResource(t, fmt.Sprintf(` -metadata: - name: %s -spec: - type: git - params: - - name: Url - value: https://github.com/githubtraining/example-basic -`, helpers.ObjectNameForTest(t))) - if _, err := c.PipelineResourceClient.Create(ctx, repoResource, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create simple repo PipelineResource: %s", err) - } - - // Intentionally declaring Tasks in a mixed up order to ensure the order - // of execution isn't at all dependent on the order they are declared in - pipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - resources: - - name: repo - type: git - tasks: - - name: pipeline-task-3 - params: - - name: text - value: wow - resources: - inputs: - - from: - - pipeline-task-2-parallel-1 - - pipeline-task-2-parallel-2 - name: repo - resource: repo - outputs: - - name: repo - resource: repo - taskRef: - name: %s - - name: pipeline-task-2-parallel-2 - params: - - name: text - value: such parallel - resources: - inputs: - - from: - - pipeline-task-1 - name: repo - resource: repo - outputs: - - name: repo - resource: repo - taskRef: - name: %s - - name: pipeline-task-4 - params: - - name: text - value: very cloud native - resources: - inputs: - - name: repo - resource: repo - outputs: - - name: repo - resource: repo - runAfter: - - pipeline-task-3 - taskRef: - name: %s - - name: pipeline-task-2-parallel-1 - params: - - name: text - value: much graph - resources: - inputs: - - from: - - pipeline-task-1 - name: repo - resource: repo - outputs: - - name: repo - resource: repo - taskRef: - name: %s - - name: pipeline-task-1 - params: - - name: text - value: how to ci/cd? - resources: - inputs: - - name: repo - resource: repo - outputs: - - name: repo - resource: repo - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), namespace, echoTask.Name, echoTask.Name, echoTask.Name, echoTask.Name, echoTask.Name)) - if _, err := c.PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create dag-pipeline: %s", err) - } - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - pipelineRef: - name: %s - resources: - - name: repo - resourceRef: - name: %s -`, helpers.ObjectNameForTest(t), namespace, pipeline.Name, repoResource.Name)) - if _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create dag-pipeline-run PipelineRun: %s", err) - } - t.Logf("Waiting for DAG pipeline to complete") - if err := WaitForPipelineRunState(ctx, c, pipelineRun.Name, pipelineRunTimeout, PipelineRunSucceed(pipelineRun.Name), "PipelineRunSuccess"); err != nil { - t.Fatalf("Error waiting for PipelineRun to finish: %s", err) - } - - verifyExpectedOrder(ctx, t, c.TaskRunClient, pipelineRun.Name) -} - -func verifyExpectedOrder(ctx context.Context, t *testing.T, c clientset.TaskRunInterface, prName string) { - t.Logf("Verifying order of execution") - - taskRunsResp, err := c.List(ctx, metav1.ListOptions{}) - if err != nil { - t.Fatalf("Couldn't get TaskRuns (so that we could check when they executed): %v", err) - } - taskRuns := taskRunsResp.Items - if len(taskRuns) != 5 { - t.Fatalf("Expected 5 TaskRuns to have executed but only got start times for %d TaskRuns", len(taskRuns)) - } - - sort.Slice(taskRuns, func(i, j int) bool { - it := taskRuns[i].Status.StartTime.Time - jt := taskRuns[j].Status.StartTime.Time - return it.Before(jt) - }) - - wantPrefixes := []string{ - prName + "-pipeline-task-1", - // Could be task-2-parallel-1 or task-2-parallel-2 - prName + "-pipeline-task-2-parallel", - prName + "-pipeline-task-2-parallel", - prName + "-pipeline-task-3", - prName + "-pipeline-task-4", - } - for i, wp := range wantPrefixes { - if !strings.HasPrefix(taskRuns[i].Name, wp) { - t.Errorf("Expected task %q to execute first, but %q was first", wp, taskRuns[0].Name) - } - } - - // Check that the two tasks that can run in parallel did - s1 := taskRuns[1].Status.StartTime.Time - s2 := taskRuns[2].Status.StartTime.Time - absDiff := time.Duration(math.Abs(float64(s2.Sub(s1)))) - if absDiff > sleepDuration { - t.Errorf("Expected parallel tasks to execute more or less at the same time, but they were %v apart", absDiff) - } -} diff --git a/test/v1alpha1/doc.go b/test/v1alpha1/doc.go deleted file mode 100644 index 6498ae4b4aa..00000000000 --- a/test/v1alpha1/doc.go +++ /dev/null @@ -1,18 +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 test holds the project's end-to-end tests (e2e). -package test diff --git a/test/v1alpha1/duplicate_test.go b/test/v1alpha1/duplicate_test.go deleted file mode 100644 index c55d434e608..00000000000 --- a/test/v1alpha1/duplicate_test.go +++ /dev/null @@ -1,91 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "sync" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestDuplicatePodTaskRun creates multiple builds and checks that each of them has only one build pod. -func TestDuplicatePodTaskRun(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - c, namespace := setup(ctx, t) - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - var wg sync.WaitGroup - // The number of builds generated has a direct impact on test - // runtime and is traded off against proving the taskrun - // reconciler's efficacy at not duplicating pods. - for i := 0; i < 5; i++ { - wg.Add(1) - taskrunName := helpers.ObjectNameForTest(t) - t.Logf("Creating taskrun %q.", taskrunName) - - taskrun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskSpec: - steps: - - image: busybox - command: ['/bin/echo'] - args: ['simple'] -`, taskrunName)) - if _, err := c.TaskRunClient.Create(ctx, taskrun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Error creating taskrun: %v", err) - } - go func(t *testing.T) { - defer wg.Done() - - if err := WaitForTaskRunState(ctx, c, taskrunName, TaskRunSucceed(taskrunName), "TaskRunDuplicatePodTaskRunFailed"); err != nil { - t.Errorf("Error waiting for TaskRun to finish: %s", err) - return - } - - pods, err := c.KubeClient.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{ - LabelSelector: fmt.Sprintf("%s=%s", pipeline.TaskRunLabelKey, taskrunName), - }) - if err != nil { - t.Errorf("Error getting TaskRun pod list: %v", err) - return - } - if n := len(pods.Items); n != 1 { - t.Errorf("Error matching the number of build pods: expecting 1 pod, got %d", n) - return - } - }(t) - } - wg.Wait() -} diff --git a/test/v1alpha1/embed_test.go b/test/v1alpha1/embed_test.go deleted file mode 100644 index 84d55cc71ae..00000000000 --- a/test/v1alpha1/embed_test.go +++ /dev/null @@ -1,111 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -const ( - // TODO(#127) Currently not reliable to retrieve this output - taskOutput = "do you want to build a snowman" -) - -// TestTaskRun_EmbeddedResource is an integration test that will verify a very simple "hello world" TaskRun can be -// executed with an embedded resource spec. -func TestTaskRun_EmbeddedResource(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - task := getEmbeddedTask(t, []string{"/bin/sh", "-c", fmt.Sprintf("echo %s", taskOutput)}) - t.Logf("Creating Task and TaskRun in namespace %s", namespace) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task.Name, err) - } - taskRun := getEmbeddedTaskRun(t, namespace, task.Name) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun `%s`: %s", taskRun.Name, err) - } - - t.Logf("Waiting for TaskRun %s in namespace %s to complete", taskRun.Name, namespace) - if err := WaitForTaskRunState(ctx, c, taskRun.Name, TaskRunSucceed(taskRun.Name), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun %s to finish: %s", taskRun.Name, err) - } - - // TODO(#127) Currently we have no reliable access to logs from the TaskRun so we'll assume successful - // completion of the TaskRun means the TaskRun did what it was intended. -} - -func getEmbeddedTask(t *testing.T, args []string) *v1alpha1.Task { - var argsForYaml []string - for _, s := range args { - argsForYaml = append(argsForYaml, fmt.Sprintf("'%s'", s)) - } - return parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - inputs: - resources: - - name: docs - type: git - steps: - - image: ubuntu - command: ['/bin/bash'] - args: ['-c', 'cat /workspace/docs/LICENSE'] - - image: busybox - command: %s -`, helpers.ObjectNameForTest(t), fmt.Sprintf("[%s]", strings.Join(argsForYaml, ", ")))) -} - -func getEmbeddedTaskRun(t *testing.T, namespace, taskName string) *v1alpha1.TaskRun { - return parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - inputs: - resources: - - name: docs - resourceSpec: - type: git - params: - - name: URL - value: https://github.com/knative/docs - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), namespace, taskName)) -} diff --git a/test/v1alpha1/entrypoint_test.go b/test/v1alpha1/entrypoint_test.go deleted file mode 100644 index bbb93c7747f..00000000000 --- a/test/v1alpha1/entrypoint_test.go +++ /dev/null @@ -1,72 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestEntrypointRunningStepsInOrder is an integration test that will -// verify attempt to the get the entrypoint of a container image -// that doesn't have a cmd defined. In addition to making sure the steps -// are executed in the order specified -func TestEntrypointRunningStepsInOrder(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - epTaskRunName := helpers.ObjectNameForTest(t) - t.Logf("Creating TaskRun in namespace %s", namespace) - if _, err := c.TaskRunClient.Create(ctx, parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - taskSpec: - steps: - - image: busybox - workingDir: /workspace - script: 'sleep 3 && touch foo' - - image: ubuntu - workingDir: /workspace - script: 'ls foo' -`, epTaskRunName, namespace)), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to finish successfully", namespace) - if err := WaitForTaskRunState(ctx, c, epTaskRunName, TaskRunSucceed(epTaskRunName), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun to finish successfully: %s", err) - } - -} diff --git a/test/v1alpha1/git_checkout_test.go b/test/v1alpha1/git_checkout_test.go deleted file mode 100644 index 441cac75364..00000000000 --- a/test/v1alpha1/git_checkout_test.go +++ /dev/null @@ -1,278 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestGitPipelineRun is an integration test that will verify the source code -// is either fetched or pulled successfully under different resource -// parameters. -func TestGitPipelineRun(t *testing.T) { - for _, tc := range []struct { - name string - repo string - revision string - refspec string - sslVerify string - }{{ - name: "tekton @ main", - repo: "https://github.com/tektoncd/pipeline", - revision: "main", - }, { - name: "tekton @ commit", - repo: "https://github.com/tektoncd/pipeline", - revision: "c15aced0e5aaee6456fbe6f7a7e95e0b5b3b2b2f", - }, { - name: "tekton @ release", - repo: "https://github.com/tektoncd/pipeline", - revision: "release-0.1", - }, { - name: "tekton @ tag", - repo: "https://github.com/tektoncd/pipeline", - revision: "v0.1.0", - }, { - name: "tekton @ PR ref", - repo: "https://github.com/tektoncd/pipeline", - revision: "refs/pull/347/head", - }, { - name: "tekton @ main with refspec", - repo: "https://github.com/tektoncd/pipeline", - revision: "main", - refspec: "refs/tags/v0.1.0:refs/tags/v0.1.0 refs/heads/main:refs/heads/main", - }, { - name: "tekton @ commit with PR refspec", - repo: "https://github.com/tektoncd/pipeline", - revision: "968d5d37a61bfb85426c885dc1090c1cc4b33436", - refspec: "refs/pull/1009/head", - }, { - name: "tekton @ main with PR refspec", - repo: "https://github.com/tektoncd/pipeline", - revision: "main", - refspec: "refs/pull/1009/head:refs/heads/main", - }, { - name: "tekton @ main with sslverify=false", - repo: "https://github.com/tektoncd/pipeline", - revision: "main", - sslVerify: "false", - }, { - name: "non-master repo with default revision", - repo: "https://github.com/tektoncd/results", - revision: "", - }, { - name: "non-master repo with main revision", - repo: "https://github.com/tektoncd/results", - revision: "main", - }} { - tc := tc // capture range variable - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - gitSourceResourceName := helpers.ObjectNameForTest(t) - gitTestPipelineRunName := helpers.ObjectNameForTest(t) - - t.Logf("Creating Git PipelineResource %s", gitSourceResourceName) - // Still using the struct here rather than YAML because we'd have to conditionally determine which fields to set in the YAML. - if _, err := c.PipelineResourceClient.Create(ctx, &v1alpha1.PipelineResource{ - ObjectMeta: metav1.ObjectMeta{Name: gitSourceResourceName}, - Spec: v1alpha1.PipelineResourceSpec{ - Type: v1alpha1.PipelineResourceTypeGit, - Params: []v1alpha1.ResourceParam{ - {Name: "Url", Value: tc.repo}, - {Name: "Revision", Value: tc.revision}, - {Name: "Refspec", Value: tc.refspec}, - {Name: "sslVerify", Value: tc.sslVerify}, - }, - }, - }, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline Resource `%s`: %s", gitSourceResourceName, err) - } - - t.Logf("Creating PipelineRun %s", gitTestPipelineRunName) - if _, err := c.PipelineRunClient.Create(ctx, parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineSpec: - resources: - - name: git-repo - type: git - tasks: - - name: git-check - resources: - inputs: - - name: gitsource - resource: git-repo - taskSpec: - resources: - inputs: - - name: gitsource - type: git - steps: - - args: ['--git-dir=/workspace/gitsource/.git', 'show'] - image: alpine/git - resources: - - name: git-repo - resourceRef: - name: %s -`, gitTestPipelineRunName, gitSourceResourceName)), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun %q: %s", gitTestPipelineRunName, err) - } - - if err := WaitForPipelineRunState(ctx, c, gitTestPipelineRunName, timeout, PipelineRunSucceed(gitTestPipelineRunName), "PipelineRunCompleted"); err != nil { - t.Errorf("Error waiting for PipelineRun %s to finish: %s", gitTestPipelineRunName, err) - t.Fatalf("PipelineRun execution failed") - } - }) - } -} - -// TestGitPipelineRunFail is a test to ensure that the code extraction from -// github fails as expected when an invalid revision or https proxy is passed -// on the pipelineresource. -func TestGitPipelineRunFail(t *testing.T) { - for _, tc := range []struct { - name string - revision string - httpsproxy string - }{{ - name: "invalid revision", - revision: "Idontexistrabbitmonkeydonkey", - }, { - name: "invalid httpsproxy", - httpsproxy: "invalid.https.proxy.example.com", - }} { - tc := tc // capture range variable - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - gitSourceResourceName := helpers.ObjectNameForTest(t) - gitTestPipelineRunName := helpers.ObjectNameForTest(t) - - t.Logf("Creating Git PipelineResource %s", gitSourceResourceName) - // Still using the struct here rather than YAML because we'd have to conditionally determine which fields to set in the YAML. - if _, err := c.PipelineResourceClient.Create(ctx, &v1alpha1.PipelineResource{ - ObjectMeta: metav1.ObjectMeta{Name: gitSourceResourceName}, - Spec: v1alpha1.PipelineResourceSpec{ - Type: v1alpha1.PipelineResourceTypeGit, - Params: []v1alpha1.ResourceParam{ - {Name: "Url", Value: "https://github.com/tektoncd/pipeline"}, - {Name: "Revision", Value: tc.revision}, - {Name: "httpsProxy", Value: tc.httpsproxy}, - }, - }, - }, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline Resource `%s`: %s", gitSourceResourceName, err) - } - - t.Logf("Creating PipelineRun %s", gitTestPipelineRunName) - if _, err := c.PipelineRunClient.Create(ctx, parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineSpec: - resources: - - name: git-repo - type: git - tasks: - - name: git-check - resources: - inputs: - - name: gitsource - resource: git-repo - taskSpec: - resources: - inputs: - - name: gitsource - type: git - steps: - - args: ['--git-dir=/workspace/gitsource/.git', 'show'] - image: alpine/git - resources: - - name: git-repo - resourceRef: - name: %s -`, gitTestPipelineRunName, gitSourceResourceName)), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun %q: %s", gitTestPipelineRunName, err) - } - - if err := WaitForPipelineRunState(ctx, c, gitTestPipelineRunName, timeout, PipelineRunSucceed(gitTestPipelineRunName), "PipelineRunCompleted"); err != nil { - taskruns, err := c.TaskRunClient.List(ctx, metav1.ListOptions{}) - if err != nil { - t.Errorf("Error getting TaskRun list for PipelineRun %s %s", gitTestPipelineRunName, err) - } - for _, tr := range taskruns.Items { - if tr.Status.PodName != "" { - p, err := c.KubeClient.CoreV1().Pods(namespace).Get(ctx, tr.Status.PodName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Error getting pod `%s` in namespace `%s`", tr.Status.PodName, namespace) - } - - for _, stat := range p.Status.ContainerStatuses { - if strings.HasPrefix(stat.Name, "step-git-source-"+gitSourceResourceName) { - if stat.State.Terminated != nil { - req := c.KubeClient.CoreV1().Pods(namespace).GetLogs(p.Name, &corev1.PodLogOptions{Container: stat.Name}) - logContent, err := req.Do(ctx).Raw() - if err != nil { - t.Fatalf("Error getting pod logs for pod `%s` and container `%s` in namespace `%s`", tr.Status.PodName, stat.Name, namespace) - } - // Check for failure messages from fetch and pull in the log file - if strings.Contains(strings.ToLower(string(logContent)), "couldn't find remote ref idontexistrabbitmonkeydonkey") { - t.Logf("Found exepected errors when retrieving non-existent git revision") - } else { - t.Logf("Container `%s` log File: %s", stat.Name, logContent) - t.Fatalf("The git code extraction did not fail as expected. Expected errors not found in log file.") - } - } - } - } - } - } - - } else { - t.Fatalf("PipelineRun succeeded when should have failed") - } - }) - } -} diff --git a/test/v1alpha1/init_test.go b/test/v1alpha1/init_test.go deleted file mode 100644 index 0747bcc5a28..00000000000 --- a/test/v1alpha1/init_test.go +++ /dev/null @@ -1,231 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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. -*/ - -// This file contains initialization logic for the tests, such as special magical global state that needs to be initialized. - -package test - -import ( - "context" - "flag" - "fmt" - "os" - "strings" - "sync" - "testing" - - "github.com/tektoncd/pipeline/pkg/names" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/logging" - "knative.dev/pkg/test/logstream" - "sigs.k8s.io/yaml" - - // Mysteriously by k8s libs, or they fail to create `KubeClient`s from config. Apparently just importing it is enough. @_@ side effects @_@. https://github.com/kubernetes/client-go/issues/242 - _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - // Mysteriously by k8s libs, or they fail to create `KubeClient`s when using oidc authentication. Apparently just importing it is enough. @_@ side effects @_@. https://github.com/kubernetes/client-go/issues/345 - _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" -) - -var initMetrics sync.Once -var skipRootUserTests = false - -func init() { - flag.BoolVar(&skipRootUserTests, "skipRootUserTests", false, "Skip tests that require root user") -} - -func setup(ctx context.Context, t *testing.T, fn ...func(context.Context, *testing.T, *clients, string)) (*clients, string) { - t.Helper() - namespace := names.SimpleNameGenerator.RestrictLengthWithRandomSuffix("arendelle") - - initializeLogsAndMetrics(t) - - // Inline controller logs from SYSTEM_NAMESPACE into the t.Log output. - cancel := logstream.Start(t) - t.Cleanup(cancel) - - c := newClients(t, knativetest.Flags.Kubeconfig, knativetest.Flags.Cluster, namespace) - createNamespace(ctx, t, namespace, c.KubeClient) - verifyServiceAccountExistence(ctx, t, namespace, c.KubeClient) - - for _, f := range fn { - f(ctx, t, c, namespace) - } - - return c, namespace -} - -func header(logf logging.FormatLogger, text string) { - left := "### " - right := " ###" - txt := left + text + right - bar := strings.Repeat("#", len(txt)) - logf(bar) - logf(txt) - logf(bar) -} - -func tearDown(ctx context.Context, t *testing.T, cs *clients, namespace string) { - t.Helper() - if cs.KubeClient == nil { - return - } - if t.Failed() { - header(t.Logf, fmt.Sprintf("Dumping objects from %s", namespace)) - bs, err := getCRDYaml(ctx, cs, namespace) - if err != nil { - t.Error(err) - } else { - t.Log(string(bs)) - } - header(t.Logf, fmt.Sprintf("Dumping logs from Pods in the %s", namespace)) - taskruns, err := cs.TaskRunClient.List(ctx, metav1.ListOptions{}) - if err != nil { - t.Errorf("Error getting TaskRun list %s", err) - } - for _, tr := range taskruns.Items { - if tr.Status.PodName != "" { - CollectPodLogs(ctx, cs, tr.Status.PodName, namespace, t.Logf) - } - } - } - - if os.Getenv("TEST_KEEP_NAMESPACES") == "" { - t.Logf("Deleting namespace %s", namespace) - if err := cs.KubeClient.CoreV1().Namespaces().Delete(ctx, namespace, metav1.DeleteOptions{}); err != nil { - t.Errorf("Failed to delete namespace %s: %s", namespace, err) - } - } -} - -func initializeLogsAndMetrics(t *testing.T) { - initMetrics.Do(func() { - flag.Parse() - flag.Set("alsologtostderr", "true") - logging.InitializeLogger() - - // if knativetest.Flags.EmitMetrics { - logging.InitializeMetricExporter(t.Name()) - //} - }) -} - -func createNamespace(ctx context.Context, t *testing.T, namespace string, kubeClient kubernetes.Interface) { - t.Logf("Create namespace %s to deploy to", namespace) - labels := map[string]string{ - "tekton.dev/test-e2e": "true", - } - if _, err := kubeClient.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: namespace, - Labels: labels, - }, - }, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create namespace %s for tests: %s", namespace, err) - } -} - -func verifyServiceAccountExistence(ctx context.Context, t *testing.T, namespace string, kubeClient kubernetes.Interface) { - defaultSA := "default" - t.Logf("Verify SA %q is created in namespace %q", defaultSA, namespace) - - if err := wait.PollImmediate(interval, timeout, func() (bool, error) { - _, err := kubeClient.CoreV1().ServiceAccounts(namespace).Get(ctx, defaultSA, metav1.GetOptions{}) - if err != nil && errors.IsNotFound(err) { - return false, nil - } - return true, err - }); err != nil { - t.Fatalf("Failed to get SA %q in namespace %q for tests: %s", defaultSA, namespace, err) - } -} - -// TestMain initializes anything global needed by the tests. Right now this is just log and metric -// setup since the log and metric libs we're using use global state :( -func TestMain(m *testing.M) { - flag.Parse() - c := m.Run() - fmt.Fprintf(os.Stderr, "Using kubeconfig at `%s` with cluster `%s`\n", knativetest.Flags.Kubeconfig, knativetest.Flags.Cluster) - os.Exit(c) -} - -func getCRDYaml(ctx context.Context, cs *clients, ns string) ([]byte, error) { - var output []byte - printOrAdd := func(i interface{}) { - bs, err := yaml.Marshal(i) - if err != nil { - return - } - output = append(output, []byte("\n---\n")...) - output = append(output, bs...) - } - - ps, err := cs.PipelineClient.List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, fmt.Errorf("could not get pipeline: %w", err) - } - for _, i := range ps.Items { - printOrAdd(i) - } - - prs, err := cs.PipelineResourceClient.List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, fmt.Errorf("could not get pipelinerun resource: %w", err) - } - for _, i := range prs.Items { - printOrAdd(i) - } - - prrs, err := cs.PipelineRunClient.List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, fmt.Errorf("could not get pipelinerun: %w", err) - } - for _, i := range prrs.Items { - printOrAdd(i) - } - - ts, err := cs.TaskClient.List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, fmt.Errorf("could not get tasks: %w", err) - } - for _, i := range ts.Items { - printOrAdd(i) - } - trs, err := cs.TaskRunClient.List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, fmt.Errorf("could not get taskrun: %w", err) - } - for _, i := range trs.Items { - printOrAdd(i) - } - - pods, err := cs.KubeClient.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{}) - if err != nil { - return nil, fmt.Errorf("could not get pods: %w", err) - } - for _, i := range pods.Items { - printOrAdd(i) - } - - return output, nil -} diff --git a/test/v1alpha1/kaniko_task_test.go b/test/v1alpha1/kaniko_task_test.go deleted file mode 100644 index b483b716440..00000000000 --- a/test/v1alpha1/kaniko_task_test.go +++ /dev/null @@ -1,245 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/test/parse" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -const ( - // This is a random revision chosen on 2020/10/09 - revision = "a310cc6d1cd449f95cedd23393de766fdc649651" -) - -// TestTaskRun is an integration test that will verify a TaskRun using kaniko -func TestKanikoTaskRun(t *testing.T) { - if skipRootUserTests { - t.Skip("Skip test as skipRootUserTests set to true") - } - - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t, withRegistry) - t.Parallel() - - repo := fmt.Sprintf("registry.%s:5000/kanikotasktest", namespace) - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - git := getGitResource(t) - t.Logf("Creating Git PipelineResource %s", git.Name) - if _, err := c.PipelineResourceClient.Create(ctx, git, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline Resource `%s`: %s", git.Name, err) - } - - image := getImageResource(t, repo) - t.Logf("Creating Image PipelineResource %s", repo) - if _, err := c.PipelineResourceClient.Create(ctx, image, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline Resource `%s`: %s", git.Name, err) - } - - task := getTask(t, repo, namespace) - t.Logf("Creating Task %s", task.Name) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task.Name, err) - } - - tr := getTaskRun(t, namespace, task.Name, git.Name, image.Name) - t.Logf("Creating TaskRun %s", tr.Name) - if _, err := c.TaskRunClient.Create(ctx, tr, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun `%s`: %s", tr.Name, err) - } - - // Verify status of TaskRun (wait for it) - - if err := WaitForTaskRunState(ctx, c, tr.Name, Succeed(tr.Name), "TaskRunCompleted"); err != nil { - t.Errorf("Error waiting for TaskRun %s to finish: %s", tr.Name, err) - } - - tr, err := c.TaskRunClient.Get(ctx, tr.Name, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error retrieving taskrun: %s", err) - } - digest := "" - commit := "" - url := "" - for _, rr := range tr.Status.ResourcesResult { - switch rr.Key { - case "digest": - digest = rr.Value - case "commit": - commit = rr.Value - case "url": - url = rr.Value - } - } - if digest == "" { - t.Errorf("Digest not found in TaskRun.Status: %v", tr.Status) - } - if commit == "" { - t.Errorf("Commit not found in TaskRun.Status: %v", tr.Status) - } - - if url == "" { - t.Errorf("URL not found in TaskRun.Status: %v", tr.Status) - } - - if revision != commit { - t.Fatalf("Expected remote commit to match local revision: %s, %s", commit, revision) - } - - // match the local digest, which is first capture group against the remote image - remoteDigest, err := getRemoteDigest(ctx, t, c, namespace, repo) - if err != nil { - t.Fatalf("Expected to get digest for remote image %s: %v", repo, err) - } - if d := cmp.Diff(digest, remoteDigest); d != "" { - t.Fatalf("Expected local digest %s to match remote digest %s: %s", digest, remoteDigest, d) - } -} - -func getGitResource(t *testing.T) *v1alpha1.PipelineResource { - return parse.MustParsePipelineResource(t, fmt.Sprintf(` -metadata: - name: %s -spec: - type: git - params: - - name: Url - value: https://github.com/GoogleContainerTools/kaniko - - name: Revision - value: %s -`, helpers.ObjectNameForTest(t), revision)) -} - -func getImageResource(t *testing.T, repo string) *v1alpha1.PipelineResource { - return parse.MustParsePipelineResource(t, fmt.Sprintf(` -metadata: - name: %s -spec: - type: image - params: - - name: url - value: %s -`, helpers.ObjectNameForTest(t), repo)) -} - -func getTask(t *testing.T, repo, namespace string) *v1alpha1.Task { - return parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - inputs: - resources: - - name: gitsource - type: git - outputs: - resources: - - name: builtImage - type: image - steps: - - name: kaniko - image: gcr.io/kaniko-project/executor:v1.3.0 - args: ['--dockerfile=/workspace/gitsource/integration/dockerfiles/Dockerfile_test_label', - '--destination=%s', - '--context=/workspace/gitsource', - '--oci-layout-path=/workspace/output/builtImage', - '--insecure', - '--insecure-pull', - '--insecure-registry=registry.%s:5000/'] - securityContext: - runAsUser: 0 - sidecars: - - name: registry - image: registry -`, helpers.ObjectNameForTest(t), repo, namespace)) -} - -func getTaskRun(t *testing.T, namespace, task, git, image string) *v1alpha1.TaskRun { - return parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - taskRef: - name: %s - timeout: 5m - inputs: - resources: - - name: gitsource - resourceRef: - name: %s - outputs: - resources: - - name: builtImage - resourceRef: - name: %s -`, helpers.ObjectNameForTest(t), namespace, task, git, image)) -} - -// getRemoteDigest starts a pod to query the registry from the namespace itself, using skopeo (and jq). -// The reason we have to do that is because the image is pushed on a local registry that is not exposed -// to the "outside" of the test, this means it can be query by the test itself. It can only be query from -// a pod in the namespace. skopeo is able to do that query and we use jq to extract the digest from its -// output. The image used for this pod is build in the tektoncd/plumbing repository. -func getRemoteDigest(ctx context.Context, t *testing.T, c *clients, namespace, image string) (string, error) { - t.Helper() - podName := "skopeo-jq" - if _, err := c.KubeClient.CoreV1().Pods(namespace).Create(ctx, &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: namespace, - Name: podName, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "skopeo", - Image: "gcr.io/tekton-releases/dogfooding/skopeo:latest", - Command: []string{"/bin/sh", "-c"}, - Args: []string{"skopeo inspect --tls-verify=false docker://" + image + ":latest| jq '.Digest'"}, - }}, - RestartPolicy: corev1.RestartPolicyNever, - }, - }, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create the skopeo-jq pod: %v", err) - } - if err := WaitForPodState(ctx, c, podName, namespace, func(pod *corev1.Pod) (bool, error) { - return pod.Status.Phase == "Succeeded" || pod.Status.Phase == "Failed", nil - }, "PodContainersTerminated"); err != nil { - t.Fatalf("Error waiting for Pod %q to terminate: %v", podName, err) - } - logs, err := getContainerLogsFromPod(ctx, c.KubeClient, podName, "skopeo", namespace) - if err != nil { - t.Fatalf("Could not get logs for pod %s: %s", podName, err) - } - return strings.TrimSpace(strings.ReplaceAll(logs, "\"", "")), nil -} diff --git a/test/v1alpha1/pipelinerun_test.go b/test/v1alpha1/pipelinerun_test.go deleted file mode 100644 index dd390e00141..00000000000 --- a/test/v1alpha1/pipelinerun_test.go +++ /dev/null @@ -1,642 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "encoding/base64" - "fmt" - "strings" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - "github.com/tektoncd/pipeline/pkg/artifacts" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "knative.dev/pkg/apis" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -var ( - secretName = "secret" - saName = "service-account" - task1Name = "task1" - pipelineRunTimeout = 10 * time.Minute -) - -func TestPipelineRun(t *testing.T) { - t.Parallel() - type tests struct { - name string - testSetup func(ctx context.Context, t *testing.T, c *clients, namespace string, index int) (map[string]*v1alpha1.PipelineResource, *v1alpha1.Pipeline) - expectedTaskRuns []string - expectedNumberOfEvents int - pipelineRunFunc func(*testing.T, int, string, string, map[string]*v1alpha1.PipelineResource) *v1alpha1.PipelineRun - } - - tds := []tests{{ - name: "fan-in and fan-out", - testSetup: func(ctx context.Context, t *testing.T, c *clients, namespace string, index int) (map[string]*v1alpha1.PipelineResource, *v1alpha1.Pipeline) { - t.Helper() - tasks := getFanInFanOutTasks(t) - for _, task := range tasks { - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task.Name, err) - } - } - resources := getFanInFanOutGitResources(t) - for _, res := range resources { - if _, err := c.PipelineResourceClient.Create(ctx, res, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline Resource `%s`: %s", res.Name, err) - } - } - - p := getFanInFanOutPipeline(t, tasks) - if _, err := c.PipelineClient.Create(ctx, p, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", p.Name, err) - } - - return resources, p - }, - pipelineRunFunc: getFanInFanOutPipelineRun, - expectedTaskRuns: []string{"create-file-kritis", "create-fan-out-1", "create-fan-out-2", "check-fan-in"}, - // 1 from PipelineRun and 4 from Tasks defined in pipelinerun - expectedNumberOfEvents: 5, - }, { - name: "service account propagation and pipeline param", - testSetup: func(ctx context.Context, t *testing.T, c *clients, namespace string, index int) (map[string]*v1alpha1.PipelineResource, *v1alpha1.Pipeline) { - t.Helper() - t.Skip("build-crd-testing project got removed, the secret-sauce doesn't exist anymore, skipping") - if _, err := c.KubeClient.CoreV1().Secrets(namespace).Create(ctx, getPipelineRunSecret(index), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create secret `%s`: %s", getName(secretName, index), err) - } - - if _, err := c.KubeClient.CoreV1().ServiceAccounts(namespace).Create(ctx, getPipelineRunServiceAccount(index), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create SA `%s`: %s", getName(saName, index), err) - } - - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - params: - - name: path - type: string - - name: dest - type: string - steps: - - name: config-docker - image: gcr.io/tekton-releases/dogfooding/skopeo:latest - command: ['skopeo'] - args: ['copy', '$(inputs.params.path)', '$(inputs.params.dest)'] -`, helpers.ObjectNameForTest(t))) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task.Name, err) - } - - p := getHelloWorldPipelineWithSingularTask(t, task.Name) - if _, err := c.PipelineClient.Create(ctx, p, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", p.Name, err) - } - - return nil, p - }, - expectedTaskRuns: []string{task1Name}, - // 1 from PipelineRun and 1 from Tasks defined in pipelinerun - expectedNumberOfEvents: 2, - pipelineRunFunc: getHelloWorldPipelineRun, - }} - - for i, td := range tds { - i := i // capture range variable - td := td // capture range variable - t.Run(td.name, func(t *testing.T) { - t.Parallel() - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - t.Logf("Setting up test resources for %q test in namespace %s", td.name, namespace) - resources, p := td.testSetup(ctx, t, c, namespace, i) - - pipelineRun, err := c.PipelineRunClient.Create(ctx, td.pipelineRunFunc(t, i, namespace, p.Name, resources), metav1.CreateOptions{}) - if err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", pipelineRun.Name, err) - } - prName := pipelineRun.Name - - t.Logf("Waiting for PipelineRun %s in namespace %s to complete", prName, namespace) - if err := WaitForPipelineRunState(ctx, c, prName, pipelineRunTimeout, PipelineRunSucceed(prName), "PipelineRunSuccess"); err != nil { - t.Fatalf("Error waiting for PipelineRun %s to finish: %s", prName, err) - } - - t.Logf("Making sure the expected TaskRuns %s were created", td.expectedTaskRuns) - actualTaskrunList, err := c.TaskRunClient.List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("tekton.dev/pipelineRun=%s", prName)}) - if err != nil { - t.Fatalf("Error listing TaskRuns for PipelineRun %s: %s", prName, err) - } - expectedTaskRunNames := []string{} - for _, runName := range td.expectedTaskRuns { - taskRunName := strings.Join([]string{prName, runName}, "-") - // check the actual task name starting with prName+runName with a random suffix - for _, actualTaskRunItem := range actualTaskrunList.Items { - if strings.HasPrefix(actualTaskRunItem.Name, taskRunName) { - taskRunName = actualTaskRunItem.Name - } - } - expectedTaskRunNames = append(expectedTaskRunNames, taskRunName) - r, err := c.TaskRunClient.Get(ctx, taskRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected TaskRun %s: %s", taskRunName, err) - } - if !r.Status.GetCondition(apis.ConditionSucceeded).IsTrue() { - t.Fatalf("Expected TaskRun %s to have succeeded but Status is %v", taskRunName, r.Status) - } - - t.Logf("Checking that labels were propagated correctly for TaskRun %s", r.Name) - checkLabelPropagation(ctx, t, c, namespace, prName, r) - t.Logf("Checking that annotations were propagated correctly for TaskRun %s", r.Name) - checkAnnotationPropagation(ctx, t, c, namespace, prName, r) - } - - matchKinds := map[string][]string{"PipelineRun": {prName}, "TaskRun": expectedTaskRunNames} - - t.Logf("Making sure %d events were created from taskrun and pipelinerun with kinds %v", td.expectedNumberOfEvents, matchKinds) - - events, err := collectMatchingEvents(ctx, c.KubeClient, namespace, matchKinds, "Succeeded") - if err != nil { - t.Fatalf("Failed to collect matching events: %q", err) - } - if len(events) != td.expectedNumberOfEvents { - collectedEvents := "" - for i, event := range events { - collectedEvents += fmt.Sprintf("%#v", event) - if i < (len(events) - 1) { - collectedEvents += ", " - } - } - t.Fatalf("Expected %d number of successful events from pipelinerun and taskrun but got %d; list of receieved events : %#v", td.expectedNumberOfEvents, len(events), collectedEvents) - } - - // Wait for up to 10 minutes and restart every second to check if - // the PersistentVolumeClaims has the DeletionTimestamp - if err := wait.PollImmediate(interval, timeout, func() (bool, error) { - // Check to make sure the PipelineRun's artifact storage PVC has been "deleted" at the end of the run. - pvc, errWait := c.KubeClient.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, artifacts.GetPVCName(pipelineRun), metav1.GetOptions{}) - if errWait != nil && !errors.IsNotFound(errWait) { - return true, fmt.Errorf("error looking up PVC %s for PipelineRun %s: %s", artifacts.GetPVCName(pipelineRun), prName, errWait) - } - // If we are not found then we are okay since it got cleaned up - if errors.IsNotFound(errWait) { - return true, nil - } - return pvc.DeletionTimestamp != nil, nil - }); err != nil { - t.Fatalf("Error while waiting for the PVC to be set as deleted: %s: %s: %s", artifacts.GetPVCName(pipelineRun), err, prName) - } - t.Logf("Successfully finished test %q", td.name) - }) - } -} - -func getHelloWorldPipelineWithSingularTask(t *testing.T, taskName string) *v1alpha1.Pipeline { - return parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - params: - - name: path - type: string - - name: dest - type: string - tasks: - - name: %s - params: - - name: path - value: $(params["path"]) - - name: dest - value: $(params.dest) - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), task1Name, taskName)) -} - -func getFanInFanOutTasks(t *testing.T) map[string]*v1alpha1.Task { - return map[string]*v1alpha1.Task{ - "create-file": parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - inputs: - - name: workspace - targetPath: brandnewspace - type: git - outputs: - - name: workspace - type: git - steps: - - args: ['-c', 'echo stuff > $(resources.outputs.workspace.path)/stuff'] - command: ['/bin/bash'] - image: ubuntu - name: write-data-task-0-step-0 - - args: ['-c', 'echo other > $(resources.outputs.workspace.path)/other'] - command: ['/bin/bash'] - image: ubuntu - name: write-data-task-0-step-1 -`, helpers.ObjectNameForTest(t))), - "check-create-files-exists": parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - inputs: - - name: workspace - type: git - outputs: - - name: workspace - type: git - steps: - - args: ['-c', '[[ stuff == $(cat $(inputs.resources.workspace.path)/stuff) ]]'] - command: ['/bin/bash'] - image: ubuntu - name: read-from-task-0 - - args: ['-c', 'echo something > $(outputs.resources.workspace.path)/something'] - command: ['/bin/bash'] - image: ubuntu - name: write-data-task-1 -`, helpers.ObjectNameForTest(t))), - "check-create-files-exists-2": parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - inputs: - - name: workspace - type: git - outputs: - - name: workspace - type: git - steps: - - args: ['-c', '[[ other == $(cat $(inputs.resources.workspace.path)/other) ]]'] - command: ['/bin/bash'] - image: ubuntu - name: read-from-task-0 - - args: ['-c', 'echo else > $(outputs.resources.workspace.path)/else'] - command: ['/bin/bash'] - image: ubuntu - name: write-data-task-1 -`, helpers.ObjectNameForTest(t))), - "read-files": parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - inputs: - - name: workspace - type: git - targetPath: readingspace - steps: - - args: ['-c', '[[ something == $(cat $(inputs.resources.workspace.path)/something) ]]'] - command: ['/bin/bash'] - image: ubuntu - name: read-from-task-0 - - args: ['-c', '[[ else == $(cat $(inputs.resources.workspace.path)/else) ]]'] - command: ['/bin/bash'] - image: ubuntu - name: read-from-task-1 -`, helpers.ObjectNameForTest(t))), - } -} - -func getFanInFanOutPipeline(t *testing.T, tasks map[string]*v1alpha1.Task) *v1alpha1.Pipeline { - return parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - resources: - - name: git-repo - type: git - tasks: - - name: create-file-kritis - resources: - inputs: - - name: workspace - resource: git-repo - outputs: - - name: workspace - resource: git-repo - taskRef: - name: %s - - name: create-fan-out-1 - resources: - inputs: - - from: - - create-file-kritis - name: workspace - resource: git-repo - outputs: - - name: workspace - resource: git-repo - taskRef: - name: %s - - name: create-fan-out-2 - resources: - inputs: - - from: - - create-file-kritis - name: workspace - resource: git-repo - outputs: - - name: workspace - resource: git-repo - taskRef: - name: %s - - name: check-fan-in - resources: - inputs: - - from: - - create-fan-out-2 - - create-fan-out-1 - name: workspace - resource: git-repo - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), tasks["create-file"].Name, tasks["check-create-files-exists"].Name, - tasks["check-create-files-exists-2"].Name, tasks["read-files"].Name)) -} - -func getFanInFanOutGitResources(t *testing.T) map[string]*v1alpha1.PipelineResource { - return map[string]*v1alpha1.PipelineResource{ - "kritis-resource-git": parse.MustParsePipelineResource(t, fmt.Sprintf(` -metadata: - name: %s -spec: - type: git - params: - - name: Url - value: https://github.com/grafeas/kritis - - name: Revision - value: master -`, helpers.ObjectNameForTest(t)))} -} - -func getPipelineRunServiceAccount(suffix int) *corev1.ServiceAccount { - return &corev1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: getName(saName, suffix), - }, - Secrets: []corev1.ObjectReference{{ - Name: getName(secretName, suffix), - }}, - } -} -func getFanInFanOutPipelineRun(t *testing.T, _ int, namespace string, pipelineName string, resources map[string]*v1alpha1.PipelineResource) *v1alpha1.PipelineRun { - return parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - pipelineRef: - name: %s - resources: - - name: git-repo - resourceRef: - name: %s -`, helpers.ObjectNameForTest(t), namespace, pipelineName, resources["kritis-resource-git"].Name)) -} - -func getPipelineRunSecret(suffix int) *corev1.Secret { - // Generated by: - // cat /tmp/key.json | base64 -w 0 - // This service account is JUST a storage reader on gcr.io/build-crd-testing - encoedDockercred := "ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAiYnVpbGQtY3JkLXRlc3RpbmciLAogICJwcml2YXRlX2tleV9pZCI6ICIwNTAyYTQxYTgxMmZiNjRjZTU2YTY4ZWM1ODMyYWIwYmExMWMxMWU2IiwKICAicHJpdmF0ZV9rZXkiOiAiLS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tXG5NSUlFdlFJQkFEQU5CZ2txaGtpRzl3MEJBUUVGQUFTQ0JLY3dnZ1NqQWdFQUFvSUJBUUM5WDRFWU9BUmJ4UU04XG5EMnhYY2FaVGsrZ1k4ZWp1OTh0THFDUXFUckdNVzlSZVQyeE9ZNUF5Z2FsUFArcDd5WEVja3dCRC9IaE0wZ2xJXG43TVRMZGVlS1dyK3JBMUx3SFp5V0ZXN0gwT25mN3duWUhFSExXVW1jM0JDT1JFRHRIUlo3WnJQQmYxSFRBQS8zXG5Nblc1bFpIU045b2p6U1NGdzZBVnU2ajZheGJCSUlKNzU0THJnS2VBWXVyd2ZJUTJSTFR1MjAxazJJcUxZYmhiXG4zbVNWRzVSK3RiS3oxQ3ZNNTNuSENiN0NmdVZlV3NyQThrazd4SHJyTFFLTW1JOXYyc2dSdWd5TUF6d3ovNnpOXG5oNS9pTXh4Z2VxNVc4eGtWeDNKMm5ZOEpKZEhhZi9UNkFHc09ORW80M3B4ZWlRVmpuUmYvS24xMFRDYzJFc0lZXG5TNDlVc1o3QkFnTUJBQUVDZ2dFQUF1cGxkdWtDUVF1RDVVL2dhbUh0N0dnVzNBTVYxOGVxbkhuQ2EyamxhaCtTXG5BZVVHbmhnSmpOdkUrcE1GbFN2NXVmMnAySzRlZC9veEQ2K0NwOVpYRFJqZ3ZmdEl5cWpsemJ3dkZjZ3p3TnVEXG55Z1VrdXA3SGVjRHNEOFR0ZUFvYlQvVnB3cTZ6S01yQndDdk5rdnk2YlZsb0VqNXgzYlhzYXhlOTVETy95cHU2XG53MFc5N3p4d3dESlk2S1FjSVdNamhyR3h2d1g3bmlVQ2VNNGxlV0JEeUd0dzF6ZUpuNGhFYzZOM2FqUWFjWEtjXG4rNFFseGNpYW1ZcVFXYlBudHhXUWhoUXpjSFdMaTJsOWNGYlpENyt1SkxGNGlONnk4bVZOVTNLM0sxYlJZclNEXG5SVXAzYVVWQlhtRmcrWi8ycHVWTCttVTNqM0xMV1l5Qk9rZXZ1T21kZ1FLQmdRRGUzR0lRa3lXSVMxNFRkTU9TXG5CaUtCQ0R5OGg5NmVoTDBIa0RieU9rU3RQS2RGOXB1RXhaeGh5N29qSENJTTVGVnJwUk4yNXA0c0V6d0ZhYyt2XG5KSUZnRXZxN21YZm1YaVhJTmllUG9FUWFDbm54RHhXZ21yMEhVS0VtUzlvTWRnTGNHVStrQ1ZHTnN6N0FPdW0wXG5LcVkzczIyUTlsUTY3Rk95cWl1OFdGUTdRUUtCZ1FEWmlGaFRFWmtQRWNxWmpud0pwVEI1NlpXUDlLVHNsWlA3XG53VTRiemk2eSttZXlmM01KKzRMMlN5SGMzY3BTTWJqdE5PWkN0NDdiOTA4RlVtTFhVR05oY3d1WmpFUXhGZXkwXG5tNDFjUzVlNFA0OWI5bjZ5TEJqQnJCb3FzMldCYWwyZWdkaE5KU3NDV29pWlA4L1pUOGVnWHZoN2I5MWp6b0syXG5xMlBVbUE0RGdRS0JnQVdMMklqdkVJME95eDJTMTFjbi9lM1dKYVRQZ05QVEc5MDNVcGErcW56aE9JeCtNYXFoXG5QRjRXc3VBeTBBb2dHSndnTkpiTjhIdktVc0VUdkE1d3l5TjM5WE43dzBjaGFyRkwzN29zVStXT0F6RGpuamNzXG5BcTVPN0dQR21YdWI2RUJRQlBKaEpQMXd5NHYvSzFmSGcvRjQ3cTRmNDBMQUpPa2FZUkpENUh6QkFvR0JBTlVoXG5uSUJQSnFxNElNdlE2Y0M5ZzhCKzF4WURlYTkvWWsxdytTbVBHdndyRVh5M0dLeDRLN2xLcGJQejdtNFgzM3N4XG5zRVUvK1kyVlFtd1JhMXhRbS81M3JLN1YybDVKZi9ENDAwalJtNlpmU0FPdmdEVHJ0Wm5VR0pNcno5RTd1Tnc3XG5sZ1VIM0pyaXZ5Ri9meE1JOHFzelFid1hQMCt4bnlxQXhFQWdkdUtCQW9HQUlNK1BTTllXQ1pYeERwU0hJMThkXG5qS2tvQWJ3Mk1veXdRSWxrZXVBbjFkWEZhZDF6c1hRR2RUcm1YeXY3TlBQKzhHWEJrbkJMaTNjdnhUaWxKSVN5XG51Y05yQ01pcU5BU24vZHE3Y1dERlVBQmdqWDE2SkgyRE5GWi9sL1VWRjNOREFKalhDczFYN3lJSnlYQjZveC96XG5hU2xxbElNVjM1REJEN3F4Unl1S3Nnaz1cbi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS1cbiIsCiAgImNsaWVudF9lbWFpbCI6ICJwdWxsLXNlY3JldC10ZXN0aW5nQGJ1aWxkLWNyZC10ZXN0aW5nLmlhbS5nc2VydmljZWFjY291bnQuY29tIiwKICAiY2xpZW50X2lkIjogIjEwNzkzNTg2MjAzMzAyNTI1MTM1MiIsCiAgImF1dGhfdXJpIjogImh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi9hdXRoIiwKICAidG9rZW5fdXJpIjogImh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsCiAgImF1dGhfcHJvdmlkZXJfeDUwOV9jZXJ0X3VybCI6ICJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9vYXV0aDIvdjEvY2VydHMiLAogICJjbGllbnRfeDUwOV9jZXJ0X3VybCI6ICJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9yb2JvdC92MS9tZXRhZGF0YS94NTA5L3B1bGwtc2VjcmV0LXRlc3RpbmclNDBidWlsZC1jcmQtdGVzdGluZy5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIKfQo=" - - decoded, err := base64.StdEncoding.DecodeString(encoedDockercred) - if err != nil { - return nil - } - return &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: getName(secretName, suffix), - Annotations: map[string]string{ - "tekton.dev/docker-0": "https://us.gcr.io", - "tekton.dev/docker-1": "https://eu.gcr.io", - "tekton.dev/docker-2": "https://asia.gcr.io", - "tekton.dev/docker-3": "https://gcr.io", - }, - }, - Type: "kubernetes.io/basic-auth", - Data: map[string][]byte{ - "username": []byte("_json_key"), - "password": decoded, - }, - } -} - -func getHelloWorldPipelineRun(t *testing.T, suffix int, namespace string, pipelineName string, _ map[string]*v1alpha1.PipelineResource) *v1alpha1.PipelineRun { - return parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - labels: - hello-world-key: hello-world-value - name: %s - namespace: %s -spec: - params: - - name: path - value: docker://gcr.io/build-crd-testing/secret-sauce - - name: dest - value: dir:///tmp/ - pipelineRef: - name: %s - serviceAccountName: %s%d -`, helpers.ObjectNameForTest(t), namespace, pipelineName, saName, suffix)) -} - -func getName(namespace string, suffix int) string { - return fmt.Sprintf("%s%d", namespace, suffix) -} - -// collectMatchingEvents collects list of events under 5 seconds that match -// 1. matchKinds which is a map of Kind of Object with name of objects -// 2. reason which is the expected reason of event -func collectMatchingEvents(ctx context.Context, kubeClient kubernetes.Interface, namespace string, kinds map[string][]string, reason string) ([]*corev1.Event, error) { - var events []*corev1.Event - - watchEvents, err := kubeClient.CoreV1().Events(namespace).Watch(ctx, metav1.ListOptions{}) - // close watchEvents channel - defer watchEvents.Stop() - if err != nil { - return events, err - } - - // create timer to not wait for events longer than 5 seconds - timer := time.NewTimer(5 * time.Second) - - for { - select { - case wevent := <-watchEvents.ResultChan(): - event := wevent.Object.(*corev1.Event) - if val, ok := kinds[event.InvolvedObject.Kind]; ok { - for _, expectedName := range val { - if event.InvolvedObject.Name == expectedName && event.Reason == reason { - events = append(events, event) - } - } - } - case <-timer.C: - return events, nil - } - } -} - -// checkLabelPropagation checks that labels are correctly propagating from -// Pipelines, PipelineRuns, and Tasks to TaskRuns and Pods. -func checkLabelPropagation(ctx context.Context, t *testing.T, c *clients, namespace string, pipelineRunName string, tr *v1alpha1.TaskRun) { - // Our controllers add 4 labels automatically. If custom labels are set on - // the Pipeline, PipelineRun, or Task then the map will have to be resized. - labels := make(map[string]string, 4) - - // Check label propagation to PipelineRuns. - pr, err := c.PipelineRunClient.Get(ctx, pipelineRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected PipelineRun for %s: %s", tr.Name, err) - } - p, err := c.PipelineClient.Get(ctx, pr.Spec.PipelineRef.Name, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected Pipeline for %s: %s", pr.Name, err) - } - for key, val := range p.ObjectMeta.Labels { - labels[key] = val - } - // This label is added to every PipelineRun by the PipelineRun controller - labels[pipeline.PipelineLabelKey] = p.Name - assertLabelsMatch(t, labels, pr.ObjectMeta.Labels) - - // Check label propagation to TaskRuns. - for key, val := range pr.ObjectMeta.Labels { - labels[key] = val - } - // This label is added to every TaskRun by the PipelineRun controller - labels[pipeline.PipelineRunLabelKey] = pr.Name - if tr.Spec.TaskRef != nil { - task, err := c.TaskClient.Get(ctx, tr.Spec.TaskRef.Name, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected Task for %s: %s", tr.Name, err) - } - for key, val := range task.ObjectMeta.Labels { - labels[key] = val - } - // This label is added to TaskRuns that reference a Task by the TaskRun controller - labels[pipeline.TaskLabelKey] = task.Name - } - assertLabelsMatch(t, labels, tr.ObjectMeta.Labels) - - // PodName is "" iff a retry happened and pod is deleted - // This label is added to every Pod by the TaskRun controller - if tr.Status.PodName != "" { - // Check label propagation to Pods. - pod := getPodForTaskRun(ctx, t, c.KubeClient, namespace, tr) - // This label is added to every Pod by the TaskRun controller - labels[pipeline.TaskRunLabelKey] = tr.Name - assertLabelsMatch(t, labels, pod.ObjectMeta.Labels) - } -} - -// checkAnnotationPropagation checks that annotations are correctly propagating from -// Pipelines, PipelineRuns, and Tasks to TaskRuns and Pods. -func checkAnnotationPropagation(ctx context.Context, t *testing.T, c *clients, namespace string, pipelineRunName string, tr *v1alpha1.TaskRun) { - annotations := make(map[string]string) - - // Check annotation propagation to PipelineRuns. - pr, err := c.PipelineRunClient.Get(ctx, pipelineRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected PipelineRun for %s: %s", tr.Name, err) - } - p, err := c.PipelineClient.Get(ctx, pr.Spec.PipelineRef.Name, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected Pipeline for %s: %s", pr.Name, err) - } - for key, val := range p.ObjectMeta.Annotations { - annotations[key] = val - } - assertAnnotationsMatch(t, annotations, pr.ObjectMeta.Annotations) - - // Check annotation propagation to TaskRuns. - for key, val := range pr.ObjectMeta.Annotations { - annotations[key] = val - } - if tr.Spec.TaskRef != nil { - task, err := c.TaskClient.Get(ctx, tr.Spec.TaskRef.Name, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected Task for %s: %s", tr.Name, err) - } - for key, val := range task.ObjectMeta.Annotations { - annotations[key] = val - } - } - assertAnnotationsMatch(t, annotations, tr.ObjectMeta.Annotations) - - // Check annotation propagation to Pods. - pod := getPodForTaskRun(ctx, t, c.KubeClient, namespace, tr) - assertAnnotationsMatch(t, annotations, pod.ObjectMeta.Annotations) -} - -func getPodForTaskRun(ctx context.Context, t *testing.T, kubeClient kubernetes.Interface, namespace string, tr *v1alpha1.TaskRun) *corev1.Pod { - // The Pod name has a random suffix, so we filter by label to find the one we care about. - pods, err := kubeClient.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{ - LabelSelector: pipeline.TaskRunLabelKey + " = " + tr.Name, - }) - if err != nil { - t.Fatalf("Couldn't get expected Pod for %s: %s", tr.Name, err) - } - if numPods := len(pods.Items); numPods != 1 { - t.Fatalf("Expected 1 Pod for %s, but got %d Pods", tr.Name, numPods) - } - return &pods.Items[0] -} - -func assertLabelsMatch(t *testing.T, expectedLabels, actualLabels map[string]string) { - for key, expectedVal := range expectedLabels { - if actualVal := actualLabels[key]; actualVal != expectedVal { - t.Errorf("Expected labels containing %s=%s but labels were %v", key, expectedVal, actualLabels) - } - } -} - -func assertAnnotationsMatch(t *testing.T, expectedAnnotations, actualAnnotations map[string]string) { - for key, expectedVal := range expectedAnnotations { - if actualVal := actualAnnotations[key]; actualVal != expectedVal { - t.Errorf("Expected annotations containing %s=%s but annotations were %v", key, expectedVal, actualAnnotations) - } - } -} diff --git a/test/v1alpha1/registry_test.go b/test/v1alpha1/registry_test.go deleted file mode 100644 index 017235b97b9..00000000000 --- a/test/v1alpha1/registry_test.go +++ /dev/null @@ -1,95 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "testing" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func withRegistry(ctx context.Context, t *testing.T, c *clients, namespace string) { - deployment := getRegistryDeployment(namespace) - if _, err := c.KubeClient.AppsV1().Deployments(namespace).Create(ctx, deployment, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create the local registry deployment: %v", err) - } - if err := WaitForDeploymentState(ctx, c, deployment.Name, namespace, func(d *appsv1.Deployment) (bool, error) { - var replicas int32 = 1 - if d.Spec.Replicas != nil { - replicas = *d.Spec.Replicas - } - return d.Status.ReadyReplicas == replicas, nil - }, "DeploymentPodRunning"); err != nil { - t.Fatalf("Error waiting for Deployment %q to be ready: %v", deployment.Name, err) - } - - service := getRegistryService(namespace) - if _, err := c.KubeClient.CoreV1().Services(namespace).Create(ctx, service, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create the local registry service: %v", err) - } -} - -func getRegistryDeployment(namespace string) *appsv1.Deployment { - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: namespace, - Name: "registry", - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "registry", - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "app": "registry", - }, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "registry", - Image: "registry", - }}, - }, - }, - }, - } -} - -func getRegistryService(namespace string) *corev1.Service { - return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: namespace, - Name: "registry", - }, - Spec: corev1.ServiceSpec{ - Ports: []corev1.ServicePort{{ - Port: 5000, - }}, - Selector: map[string]string{ - "app": "registry", - }, - }, - } -} diff --git a/test/v1alpha1/retry_test.go b/test/v1alpha1/retry_test.go deleted file mode 100644 index 4fcab644f45..00000000000 --- a/test/v1alpha1/retry_test.go +++ /dev/null @@ -1,176 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/tektoncd/pipeline/test" - - "github.com/tektoncd/pipeline/pkg/apis/config" - - "github.com/tektoncd/pipeline/test/parse" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestTaskRunRetry tests that retries behave as expected, by creating multiple -// Pods for the same TaskRun each time it fails, up to the configured max. -func TestTaskRunRetry(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - embeddedStatus := test.GetEmbeddedStatus(ctx, t, c.KubeClient) - - // Create a PipelineRun with a single TaskRun that can only fail, - // configured to retry 5 times. - pipelineRunName := helpers.ObjectNameForTest(t) - numRetries := 5 - if _, err := c.PipelineRunClient.Create(ctx, parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineSpec: - tasks: - - name: retry-me - retries: %d - taskSpec: - steps: - - image: busybox - script: exit 1 -`, pipelineRunName, numRetries)), metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun %q: %v", pipelineRunName, err) - } - - // Wait for the PipelineRun to fail, when retries are exhausted. - if err := WaitForPipelineRunState(ctx, c, pipelineRunName, 5*time.Minute, PipelineRunFailed(pipelineRunName), "PipelineRunFailed"); err != nil { - t.Fatalf("Waiting for PipelineRun to fail: %v", err) - } - - // Get the status of the PipelineRun. - pr, err := c.PipelineRunClient.Get(ctx, pipelineRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Failed to get PipelineRun %q: %v", pipelineRunName, err) - } - - if embeddedStatus == config.FullEmbeddedStatus || embeddedStatus == config.BothEmbeddedStatus { - // PipelineRunStatus should have 1 TaskRun status, and it should be failed. - if len(pr.Status.TaskRuns) != 1 { - t.Errorf("Got %d TaskRun statuses, wanted %d", len(pr.Status.TaskRuns), numRetries) - } - for taskRunName, trs := range pr.Status.TaskRuns { - if !isFailed(t, taskRunName, trs.Status.Conditions) { - t.Errorf("TaskRun status %q is not failed", taskRunName) - } - } - } - if embeddedStatus == config.MinimalEmbeddedStatus || embeddedStatus == config.BothEmbeddedStatus { - // PipelineRunStatus should have 1 child reference, and the TaskRun it refers to should be failed. - if len(pr.Status.ChildReferences) != 1 { - t.Fatalf("Got %d child references, wanted %d", len(pr.Status.ChildReferences), numRetries) - } - if pr.Status.ChildReferences[0].Kind != "TaskRun" { - t.Errorf("Got a child reference of kind %s, but expected TaskRun", pr.Status.ChildReferences[0].Kind) - } - taskRunName := pr.Status.ChildReferences[0].Name - - tr, err := c.TaskRunClient.Get(ctx, taskRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Failed to get TaskRun %q: %v", taskRunName, err) - } - if !isFailed(t, taskRunName, tr.Status.Conditions) { - t.Errorf("TaskRun status %q is not failed", taskRunName) - } - } - - // There should only be one TaskRun created. - trs, err := c.TaskRunClient.List(ctx, metav1.ListOptions{}) - if err != nil { - t.Fatalf("Failed to list TaskRuns: %v", err) - } else if len(trs.Items) != 1 { - t.Fatalf("Found %d TaskRuns, want 1", len(trs.Items)) - } - - // The TaskRun status should have N retriesStatuses, all failures. - tr := trs.Items[0] - podNames := map[string]struct{}{} - for idx, r := range tr.Status.RetriesStatus { - if !isFailed(t, tr.Name, r.Conditions) { - t.Errorf("TaskRun %q retry status %d is not failed", tr.Name, idx) - } - podNames[r.PodName] = struct{}{} - } - podNames[tr.Status.PodName] = struct{}{} - if len(tr.Status.RetriesStatus) != numRetries { - t.Errorf("TaskRun %q had %d retriesStatuses, want %d", tr.Name, len(tr.Status.RetriesStatus), numRetries) - } - - // There should be N Pods created, all failed, all owned by the TaskRun. - pods, err := c.KubeClient.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{}) - // We expect N+1 Pods total, one for each failed and retried attempt, and one for the final attempt. - wantPods := numRetries + 1 - - if err != nil { - t.Fatalf("Failed to list Pods: %v", err) - } else if len(pods.Items) != wantPods { - t.Errorf("BUG: Found %d Pods, want %d", len(pods.Items), wantPods) - } - for _, p := range pods.Items { - if _, found := podNames[p.Name]; !found { - t.Errorf("BUG: TaskRunStatus.RetriesStatus did not report pod name %q", p.Name) - } - // Check each container in the pod, rather than the phase, since the phase doesn't update to a terminal state instantly. - // See https://github.com/kubernetes/kubernetes/pull/108366 - for _, c := range p.Status.ContainerStatuses { - if c.State.Terminated == nil { - t.Errorf("BUG: Container %s in pod %s is not terminated", c.Name, p.Name) - } else if c.State.Terminated.ExitCode != 1 { - t.Errorf("BUG: Container %s in pod %s has exit code %d, expected 1", c.Name, p.Name, c.State.Terminated.ExitCode) - } - } - } -} - -// This method is necessary because PipelineRunTaskRunStatus and TaskRunStatus -// don't have an IsFailed method. -func isFailed(t *testing.T, taskRunName string, conds duckv1beta1.Conditions) bool { - for _, c := range conds { - if c.Type == apis.ConditionSucceeded { - if c.Status != corev1.ConditionFalse { - t.Errorf("TaskRun status %q is not failed, got %q", taskRunName, c.Status) - } - return true - } - } - t.Errorf("TaskRun status %q had no Succeeded condition", taskRunName) - return false -} diff --git a/test/v1alpha1/secret.go b/test/v1alpha1/secret.go deleted file mode 100644 index a38868c0424..00000000000 --- a/test/v1alpha1/secret.go +++ /dev/null @@ -1,69 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "io/ioutil" - "os" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" -) - -// CreateGCPServiceAccountSecret will create a kube secret called secretName in namespace -// from the value in the GCP_SERVICE_ACCOUNT_KEY_PATH environment variable. If the env var -// doesn't exist, no secret will be created. Returns true if the secret was created, false -// otherwise. -func CreateGCPServiceAccountSecret(t *testing.T, c kubernetes.Interface, namespace string, secretName string) (bool, error) { - t.Helper() - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - file := os.Getenv("GCP_SERVICE_ACCOUNT_KEY_PATH") - if file == "" { - t.Logf("Not creating service account secret, relying on default credentials in namespace %s.", namespace) - return false, nil - } - - sec := &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: secretName, - Namespace: namespace, - }, - } - - bs, err := ioutil.ReadFile(file) - if err != nil { - return false, fmt.Errorf("couldn't read secret json from %s: %w", file, err) - } - - sec.Data = map[string][]byte{ - "config.json": bs, - } - _, err = c.CoreV1().Secrets(namespace).Create(ctx, sec, metav1.CreateOptions{}) - - t.Log("Creating service account secret") - return true, err -} diff --git a/test/v1alpha1/sidecar_test.go b/test/v1alpha1/sidecar_test.go deleted file mode 100644 index 16e4210f390..00000000000 --- a/test/v1alpha1/sidecar_test.go +++ /dev/null @@ -1,188 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -const ( - sidecarContainerName = "sidecar-container" - primaryContainerName = "primary" -) - -// TestSidecarTaskSupport checks whether support for sidecars is working -// as expected by running a Task with a Sidecar defined and confirming -// that both the primary and sidecar containers terminate. -func TestSidecarTaskSupport(t *testing.T) { - tests := []struct { - desc string - stepCommand []string - sidecarCommand []string - }{{ - desc: "A sidecar that runs forever is terminated when Steps complete", - stepCommand: []string{"echo", "\"hello world\""}, - // trapping the exit signals lets us stop the sidecar more - // rapidly than waiting for a force stop. - sidecarCommand: []string{"sh", "-c", "trap exit SIGTERM SIGINT; while [[ true ]] ; do echo \"hello from sidecar\" ; sleep 3 ; done"}, - }, { - desc: "A sidecar that terminates early does not cause problems running Steps", - stepCommand: []string{"echo", "\"hello world\""}, - sidecarCommand: []string{"echo", "\"hello from sidecar\""}, - }} - - ctx := context.Background() - t.Parallel() - - for _, test := range tests { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - - ctx, cancel := context.WithCancel(ctx) - defer cancel() - clients, namespace := setup(ctx, t) - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, clients, namespace) }, t.Logf) - defer tearDown(ctx, t, clients, namespace) - sidecarTaskName := helpers.ObjectNameForTest(t) - sidecarTaskRunName := helpers.ObjectNameForTest(t) - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - name: %s - image: busybox - command: [%s] - sidecars: - - name: %s - image: busybox - command: [%s] -`, sidecarTaskName, primaryContainerName, stringSliceToYAMLArray(test.stepCommand), sidecarContainerName, stringSliceToYAMLArray(test.sidecarCommand))) - - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - taskRef: - name: %s - timeout: 1m -`, sidecarTaskRunName, namespace, sidecarTaskName)) - - t.Logf("Creating Task %q", sidecarTaskName) - if _, err := clients.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Errorf("Failed to create Task %q: %v", sidecarTaskName, err) - } - - t.Logf("Creating TaskRun %q", sidecarTaskRunName) - if _, err := clients.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Errorf("Failed to create TaskRun %q: %v", sidecarTaskRunName, err) - } - - if err := WaitForTaskRunState(ctx, clients, sidecarTaskRunName, Succeed(sidecarTaskRunName), "TaskRunSucceed"); err != nil { - t.Errorf("Error waiting for TaskRun %q to finish: %v", sidecarTaskRunName, err) - } - - tr, err := clients.TaskRunClient.Get(ctx, sidecarTaskRunName, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error getting Taskrun: %v", err) - } - podName := tr.Status.PodName - - if err := WaitForPodState(ctx, clients, podName, namespace, func(pod *corev1.Pod) (bool, error) { - terminatedCount := 0 - for _, c := range pod.Status.ContainerStatuses { - if c.State.Terminated != nil { - terminatedCount++ - } - } - return terminatedCount == 2, nil - }, "PodContainersTerminated"); err != nil { - t.Errorf("Error waiting for Pod %q to terminate both the primary and sidecar containers: %v", podName, err) - } - - pod, err := clients.KubeClient.CoreV1().Pods(namespace).Get(ctx, podName, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error getting TaskRun pod: %v", err) - } - - primaryTerminated := false - sidecarTerminated := false - - for _, c := range pod.Status.ContainerStatuses { - if c.Name == fmt.Sprintf("step-%s", primaryContainerName) { - if c.State.Terminated == nil || c.State.Terminated.Reason != "Completed" { - t.Errorf("Primary container has nil Terminated state or did not complete successfully. Actual Terminated state: %v", c.State.Terminated) - } else { - primaryTerminated = true - } - } - if c.Name == fmt.Sprintf("sidecar-%s", sidecarContainerName) { - if c.State.Terminated == nil { - t.Errorf("Sidecar container has a nil Terminated status but non-nil is expected.") - } else { - sidecarTerminated = true - } - } - } - - if !primaryTerminated || !sidecarTerminated { - t.Errorf("Either the primary or sidecar containers did not terminate") - } - - trCheckSidecarStatus, err := clients.TaskRunClient.Get(ctx, sidecarTaskRunName, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error getting TaskRun: %v", err) - } - - sidecarFromStatus := trCheckSidecarStatus.Status.Sidecars[0] - - // Check if Sidecar ContainerName is present for SidecarStatus - if sidecarFromStatus.ContainerName != fmt.Sprintf("sidecar-%s", sidecarContainerName) { - t.Errorf("Sidecar ContainerName should be: %s", sidecarContainerName) - } - - // Check if Terminated status is present for SidecarStatus - if trCheckSidecarStatus.Name == "sidecar-test-task-run-1" && sidecarFromStatus.Terminated == nil { - t.Errorf("TaskRunStatus: Sidecar container has a nil Terminated status but non-nil is expected.") - } else if trCheckSidecarStatus.Name == "sidecar-test-task-run-1" && sidecarFromStatus.Terminated.Reason != "Completed" { - t.Errorf("TaskRunStatus: Sidecar container has a nil Terminated reason of %s but should be Completed", sidecarFromStatus.Terminated.Reason) - } - }) - } -} - -func stringSliceToYAMLArray(stringSlice []string) string { - var quoted []string - for _, s := range stringSlice { - quoted = append(quoted, fmt.Sprintf("'%s'", s)) - } - return strings.Join(quoted, ", ") -} diff --git a/test/v1alpha1/start_time_test.go b/test/v1alpha1/start_time_test.go deleted file mode 100644 index 2d24a3484f5..00000000000 --- a/test/v1alpha1/start_time_test.go +++ /dev/null @@ -1,98 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestStartTime tests that step start times are reported accurately. -// -// It runs a TaskRun with multiple steps that each sleep for several -// seconds, then checks that the reported step start times are several -// seconds apart from each other. Scheduling and reporting specifics -// can result in start times being later than expected, but they -// shouldn't be earlier. -// -// The number of seconds between each step has a big impact on the total -// duration of the test so smaller is better (while still supporting the -// test's intended purpose). -func TestStartTime(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - c, namespace := setup(ctx, t) - t.Parallel() - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - t.Logf("Creating TaskRun in namespace %q", namespace) - tr, err := c.TaskRunClient.Create(ctx, parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - taskSpec: - steps: - - image: busybox - script: sleep 2 - - image: busybox - script: sleep 2 - - image: busybox - script: sleep 2 - - image: busybox - script: sleep 2 - - image: busybox - script: sleep 2 -`, helpers.ObjectNameForTest(t), namespace)), metav1.CreateOptions{}) - if err != nil { - t.Fatalf("Error creating TaskRun: %v", err) - } - t.Logf("Created TaskRun %q in namespace %q", tr.Name, namespace) - // Wait for the TaskRun to complete. - if err := WaitForTaskRunState(ctx, c, tr.Name, TaskRunSucceed(tr.Name), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun to succeed: %v", err) - } - tr, err = c.TaskRunClient.Get(ctx, tr.Name, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Error getting TaskRun: %v", err) - } - if got, want := len(tr.Status.Steps), len(tr.Spec.TaskSpec.Steps); got != want { - t.Errorf("Got unexpected number of step states: got %d, want %d", got, want) - } - minimumDiff := 2 * time.Second - var lastStart metav1.Time - for idx, s := range tr.Status.Steps { - if s.Terminated == nil { - t.Errorf("Step state %d was not terminated", idx) - continue - } - diff := s.Terminated.StartedAt.Time.Sub(lastStart.Time) - if diff < minimumDiff { - t.Errorf("Step %d start time was %s since last start, wanted > %s", idx, diff, minimumDiff) - } - lastStart = s.Terminated.StartedAt - } -} diff --git a/test/v1alpha1/status_test.go b/test/v1alpha1/status_test.go deleted file mode 100644 index 49745cfb041..00000000000 --- a/test/v1alpha1/status_test.go +++ /dev/null @@ -1,100 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestTaskRunPipelineRunStatus is an integration test that will -// verify a very simple "hello world" TaskRun and PipelineRun failure -// execution lead to the correct TaskRun status. -func TestTaskRunPipelineRunStatus(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - t.Logf("Creating Task and TaskRun in namespace %s", namespace) - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: busybox - command: ['ls', '-la']`, helpers.ObjectNameForTest(t))) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s - serviceAccountName: inexistent`, helpers.ObjectNameForTest(t), task.Name)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to fail", namespace) - if err := WaitForTaskRunState(ctx, c, taskRun.Name, TaskRunFailed(taskRun.Name), "BuildValidationFailed"); err != nil { - t.Errorf("Error waiting for TaskRun to finish: %s", err) - } - - pipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - tasks: - - name: foo - taskRef: - name: %s`, helpers.ObjectNameForTest(t), task.Name)) - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s - serviceAccountName: inexistent`, helpers.ObjectNameForTest(t), pipeline.Name)) - if _, err := c.PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", pipeline.Name, err) - } - if _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", pipelineRun.Name, err) - } - - t.Logf("Waiting for PipelineRun in namespace %s to fail", namespace) - if err := WaitForPipelineRunState(ctx, c, pipelineRun.Name, pipelineRunTimeout, PipelineRunFailed(pipelineRun.Name), "BuildValidationFailed"); err != nil { - t.Errorf("Error waiting for TaskRun to finish: %s", err) - } -} diff --git a/test/v1alpha1/taskrun_test.go b/test/v1alpha1/taskrun_test.go deleted file mode 100644 index 430565cb663..00000000000 --- a/test/v1alpha1/taskrun_test.go +++ /dev/null @@ -1,193 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -func TestTaskRunFailure(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - taskRunName := helpers.ObjectNameForTest(t) - - t.Logf("Creating Task and TaskRun in namespace %s", namespace) - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'echo hello'] - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'exit 1'] - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'sleep 30s'] -`, helpers.ObjectNameForTest(t))) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s -`, taskRunName, task.Name)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to fail", namespace) - if err := WaitForTaskRunState(ctx, c, taskRunName, TaskRunFailed(taskRunName), "TaskRunFailed"); err != nil { - t.Errorf("Error waiting for TaskRun to finish: %s", err) - } - - taskrun, err := c.TaskRunClient.Get(ctx, taskRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected TaskRun %s: %s", taskRunName, err) - } - - expectedStepState := []v1alpha1.StepState{{ - ContainerState: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - ExitCode: 0, - Reason: "Completed", - }, - }, - Name: "unnamed-0", - ContainerName: "step-unnamed-0", - }, { - ContainerState: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - ExitCode: 1, - Reason: "Error", - }, - }, - Name: "unnamed-1", - ContainerName: "step-unnamed-1", - }, { - ContainerState: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - ExitCode: 1, - Reason: "Error", - }, - }, - Name: "unnamed-2", - ContainerName: "step-unnamed-2", - }} - ignoreTerminatedFields := cmpopts.IgnoreFields(corev1.ContainerStateTerminated{}, "StartedAt", "FinishedAt", "ContainerID") - ignoreStepFields := cmpopts.IgnoreFields(v1alpha1.StepState{}, "ImageID") - if d := cmp.Diff(taskrun.Status.Steps, expectedStepState, ignoreTerminatedFields, ignoreStepFields); d != "" { - t.Fatalf("-got, +want: %v", d) - } -} - -func TestTaskRunStatus(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - taskRunName := helpers.ObjectNameForTest(t) - - fqImageName := "busybox@sha256:895ab622e92e18d6b461d671081757af7dbaa3b00e3e28e12505af7817f73649" - t.Logf("Creating Task and TaskRun in namespace %s", namespace) - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: %s - command: ['/bin/sh'] - args: ['-c', 'echo hello'] -`, helpers.ObjectNameForTest(t), fqImageName)) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s -`, taskRunName, task.Name)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to fail", namespace) - if err := WaitForTaskRunState(ctx, c, taskRunName, TaskRunSucceed(taskRunName), "TaskRunSucceed"); err != nil { - t.Errorf("Error waiting for TaskRun to finish: %s", err) - } - - taskrun, err := c.TaskRunClient.Get(ctx, taskRunName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Couldn't get expected TaskRun %s: %s", taskRunName, err) - } - - expectedStepState := []v1alpha1.StepState{{ - ContainerState: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - ExitCode: 0, - Reason: "Completed", - }, - }, - Name: "unnamed-0", - ContainerName: "step-unnamed-0", - }} - - ignoreTerminatedFields := cmpopts.IgnoreFields(corev1.ContainerStateTerminated{}, "StartedAt", "FinishedAt", "ContainerID") - ignoreStepFields := cmpopts.IgnoreFields(v1alpha1.StepState{}, "ImageID") - if d := cmp.Diff(taskrun.Status.Steps, expectedStepState, ignoreTerminatedFields, ignoreStepFields); d != "" { - t.Fatalf("-got, +want: %v", d) - } - // Note(chmouel): Sometime we have docker-pullable:// or docker.io/library as prefix, so let only compare the suffix - if !strings.HasSuffix(taskrun.Status.Steps[0].ImageID, fqImageName) { - t.Fatalf("`ImageID: %s` does not end with `%s`", taskrun.Status.Steps[0].ImageID, fqImageName) - } -} diff --git a/test/v1alpha1/timeout_test.go b/test/v1alpha1/timeout_test.go deleted file mode 100644 index 43d4f5fa249..00000000000 --- a/test/v1alpha1/timeout_test.go +++ /dev/null @@ -1,305 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "sync" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -// TestPipelineRunTimeout is an integration test that will -// verify that pipelinerun timeout works and leads to the the correct TaskRun statuses -// and pod deletions. -func TestPipelineRunTimeout(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), timeout+2*time.Minute) - defer cancel() - c, namespace := setup(ctx, t) - - knativetest.CleanupOnInterrupt(func() { tearDown(context.Background(), t, c, namespace) }, t.Logf) - defer tearDown(context.Background(), t, c, namespace) - - t.Logf("Creating Task in namespace %s", namespace) - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'sleep 10'] -`, helpers.ObjectNameForTest(t))) - - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task %q: %s", task.Name, err) - } - - pipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - tasks: - - name: foo - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), task.Name)) - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s - timeout: 5s -`, helpers.ObjectNameForTest(t), pipeline.Name)) - if _, err := c.PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", pipeline.Name, err) - } - if _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", pipelineRun.Name, err) - } - - t.Logf("Waiting for PipelineRun %s in namespace %s to be timed out", pipelineRun.Name, namespace) - if err := WaitForPipelineRunState(ctx, c, pipelineRun.Name, timeout, FailedWithReason("PipelineRunTimeout", pipelineRun.Name), "PipelineRunTimedOut"); err != nil { - t.Errorf("Error waiting for PipelineRun %s to finish: %s", pipelineRun.Name, err) - } - - taskrunList, err := c.TaskRunClient.List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("tekton.dev/pipelineRun=%s", pipelineRun.Name)}) - if err != nil { - t.Fatalf("Error listing TaskRuns for PipelineRun %s: %s", pipelineRun.Name, err) - } - - t.Logf("Waiting for TaskRuns from PipelineRun %s in namespace %s to be cancelled", pipelineRun.Name, namespace) - var wg sync.WaitGroup - for _, taskrunItem := range taskrunList.Items { - wg.Add(1) - go func(name string) { - defer wg.Done() - err := WaitForTaskRunState(ctx, c, name, FailedWithReason("TaskRunTimeout", name), "TaskRunTimeout") - if err != nil { - t.Errorf("Error waiting for TaskRun %s to timeout: %s", name, err) - } - }(taskrunItem.Name) - } - wg.Wait() - - if _, err := c.PipelineRunClient.Get(ctx, pipelineRun.Name, metav1.GetOptions{}); err != nil { - t.Fatalf("Failed to get PipelineRun `%s`: %s", pipelineRun.Name, err) - } - - // Verify that we can create a second Pipeline using the same Task without a Pipeline-level timeout that will not - // time out - secondPipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - tasks: - - name: foo - taskRef: - name: %s -`, helpers.ObjectNameForTest(t), task.Name)) - secondPipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s -`, helpers.ObjectNameForTest(t), secondPipeline.Name)) - if _, err := c.PipelineClient.Create(ctx, secondPipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", secondPipeline.Name, err) - } - if _, err := c.PipelineRunClient.Create(ctx, secondPipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", secondPipelineRun.Name, err) - } - - t.Logf("Waiting for PipelineRun %s in namespace %s to complete", secondPipelineRun.Name, namespace) - if err := WaitForPipelineRunState(ctx, c, secondPipelineRun.Name, timeout, PipelineRunSucceed(secondPipelineRun.Name), "PipelineRunSuccess"); err != nil { - t.Fatalf("Error waiting for PipelineRun %s to finish: %s", secondPipelineRun.Name, err) - } -} - -// TestTaskRunTimeout is an integration test that will verify a TaskRun can be timed out. -func TestTaskRunTimeout(t *testing.T) { - t.Parallel() - taskTimeout := 1 * time.Second - testTimeout := taskTimeout + (2 * time.Minute) - ctx, cancel := context.WithTimeout(context.Background(), testTimeout) - defer cancel() - c, namespace := setup(ctx, t) - - knativetest.CleanupOnInterrupt(func() { tearDown(context.Background(), t, c, namespace) }, t.Logf) - defer tearDown(context.Background(), t, c, namespace) - - t.Logf("Creating Task and TaskRun in namespace %s", namespace) - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'sleep 3000'] -`, helpers.ObjectNameForTest(t))) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task.Name, err) - } - - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s - namespace: %s -spec: - taskRef: - name: %s - timeout: %s -`, helpers.ObjectNameForTest(t), namespace, task.Name, taskTimeout)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun `%s`: %s", taskRun.Name, err) - } - - t.Logf("Waiting for TaskRun %s in namespace %s to complete", taskRun.Name, namespace) - if err := WaitForTaskRunState(ctx, c, taskRun.Name, FailedWithReason("TaskRunTimeout", taskRun.Name), "TaskRunTimeout"); err != nil { - t.Errorf("Error waiting for TaskRun %s to finish: %s", taskRun.Name, err) - } -} - -func TestPipelineTaskTimeout(t *testing.T) { - t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), timeout+2*time.Minute) - defer cancel() - c, namespace := setup(ctx, t) - - knativetest.CleanupOnInterrupt(func() { tearDown(context.Background(), t, c, namespace) }, t.Logf) - defer tearDown(context.Background(), t, c, namespace) - - t.Logf("Creating Tasks in namespace %s", namespace) - task1 := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'sleep 1s'] -`, helpers.ObjectNameForTest(t))) - task2 := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: busybox - command: ['/bin/sh'] - args: ['-c', 'sleep 10s'] -`, helpers.ObjectNameForTest(t))) - - if _, err := c.TaskClient.Create(ctx, task1, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task1.Name, err) - } - if _, err := c.TaskClient.Create(ctx, task2, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task `%s`: %s", task2.Name, err) - } - - pipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - tasks: - - name: pipelinetask1 - taskRef: - name: %s - timeout: 60s - - name: pipelinetask2 - taskRef: - name: %s - timeout: 5s -`, helpers.ObjectNameForTest(t), task1.Name, task2.Name)) - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s -`, helpers.ObjectNameForTest(t), pipeline.Name)) - - if _, err := c.PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline `%s`: %s", pipeline.Name, err) - } - if _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun `%s`: %s", pipelineRun.Name, err) - } - - t.Logf("Waiting for PipelineRun %s with PipelineTask timeout in namespace %s to fail", pipelineRun.Name, namespace) - if err := WaitForPipelineRunState(ctx, c, pipelineRun.Name, timeout, FailedWithReason("Failed", pipelineRun.Name), "PipelineRunTimedOut"); err != nil { - t.Errorf("Error waiting for PipelineRun %s to finish: %s", pipelineRun.Name, err) - } - - taskrunList, err := c.TaskRunClient.List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("tekton.dev/pipelineRun=%s", pipelineRun.Name)}) - if err != nil { - t.Fatalf("Error listing TaskRuns for PipelineRun %s: %s", pipelineRun.Name, err) - } - - t.Logf("Waiting for TaskRun from PipelineRun %s in namespace %s to be timed out", pipelineRun.Name, namespace) - var wg sync.WaitGroup - for _, taskrunItem := range taskrunList.Items { - wg.Add(1) - go func(tr v1alpha1.TaskRun) { - defer wg.Done() - name := tr.Name - err := WaitForTaskRunState(ctx, c, name, func(ca apis.ConditionAccessor) (bool, error) { - cond := ca.GetCondition(apis.ConditionSucceeded) - if cond != nil { - if tr.Spec.TaskRef.Name == task1.Name && cond.Status == corev1.ConditionTrue { - if cond.Reason == "Succeeded" { - return true, nil - } - return true, fmt.Errorf("taskRun %q completed with the wrong reason: %s", task1.Name, cond.Reason) - } else if tr.Spec.TaskRef.Name == task1.Name && cond.Status == corev1.ConditionFalse { - return true, fmt.Errorf("taskRun %q failed, but should have been Succeeded", name) - } - - if tr.Spec.TaskRef.Name == task2.Name && cond.Status == corev1.ConditionFalse { - if cond.Reason == "TaskRunTimeout" { - return true, nil - } - return true, fmt.Errorf("taskRun %q completed with the wrong reason: %s", task2.Name, cond.Reason) - } else if tr.Spec.TaskRef.Name == task2.Name && cond.Status == corev1.ConditionTrue { - return true, fmt.Errorf("taskRun %q should have timed out", name) - } - } - return false, nil - }, "TaskRunTimeout") - if err != nil { - t.Errorf("Error waiting for TaskRun %s to timeout: %s", name, err) - } - }(taskrunItem) - } - wg.Wait() -} diff --git a/test/v1alpha1/wait.go b/test/v1alpha1/wait.go deleted file mode 100644 index c5d6978d954..00000000000 --- a/test/v1alpha1/wait.go +++ /dev/null @@ -1,280 +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. -*/ - -/* -Poll Pipeline resources - -After creating Pipeline resources or making changes to them, you will need to -wait for the system to realize those changes. You can use polling methods to -check the resources reach the desired state. - -The WaitFor* functions use the kubernetes -wait package (https://godoc.org/k8s.io/apimachinery/pkg/util/wait). To poll -they use -PollImmediate (https://godoc.org/k8s.io/apimachinery/pkg/util/wait#PollImmediate) -and the return values of the function you provide behave the same as -ConditionFunc (https://godoc.org/k8s.io/apimachinery/pkg/util/wait#ConditionFunc): -a boolean to indicate if the function should stop or continue polling, and an -error to indicate if there has been an error. - - -For example, you can poll a TaskRun object to wait for it to have a Status.Condition: - - err = WaitForTaskRunState(c, hwTaskRunName, func(tr *v1alpha1.TaskRun) (bool, error) { - if len(tr.Status.Conditions) > 0 { - return true, nil - } - return false, nil - }, "TaskRunHasCondition") - -*/ - -package test - -import ( - "context" - "fmt" - "strings" - "time" - - "go.opencensus.io/trace" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "knative.dev/pkg/apis" -) - -const ( - interval = 1 * time.Second - timeout = 10 * time.Minute -) - -// ConditionAccessorFn is a condition function used polling functions -type ConditionAccessorFn func(ca apis.ConditionAccessor) (bool, error) - -func pollImmediateWithContext(ctx context.Context, fn func() (bool, error)) error { - return wait.PollImmediate(interval, timeout, func() (bool, error) { - select { - case <-ctx.Done(): - return true, ctx.Err() - default: - } - return fn() - }) -} - -// WaitForTaskRunState polls the status of the TaskRun called name from client every -// interval until inState returns `true` indicating it is done, returns an -// error or timeout. desc will be used to name the metric that is emitted to -// track how long it took for name to get into the state checked by inState. -func WaitForTaskRunState(ctx context.Context, c *clients, name string, inState ConditionAccessorFn, desc string) error { - metricName := fmt.Sprintf("WaitForTaskRunState/%s/%s", name, desc) - _, span := trace.StartSpan(context.Background(), metricName) - defer span.End() - - return pollImmediateWithContext(ctx, func() (bool, error) { - r, err := c.TaskRunClient.Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return true, err - } - return inState(&r.Status) - }) -} - -// WaitForDeploymentState polls the status of the Deployment called name -// from client every interval until inState returns `true` indicating it is done, -// returns an error or timeout. desc will be used to name the metric that is emitted to -// track how long it took for name to get into the state checked by inState. -func WaitForDeploymentState(ctx context.Context, c *clients, name string, namespace string, inState func(d *appsv1.Deployment) (bool, error), desc string) error { - metricName := fmt.Sprintf("WaitForDeploymentState/%s/%s", name, desc) - _, span := trace.StartSpan(context.Background(), metricName) - defer span.End() - - return pollImmediateWithContext(ctx, func() (bool, error) { - d, err := c.KubeClient.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return true, err - } - return inState(d) - }) -} - -// WaitForPodState polls the status of the Pod called name from client every -// interval until inState returns `true` indicating it is done, returns an -// error or timeout. desc will be used to name the metric that is emitted to -// track how long it took for name to get into the state checked by inState. -func WaitForPodState(ctx context.Context, c *clients, name string, namespace string, inState func(r *corev1.Pod) (bool, error), desc string) error { - metricName := fmt.Sprintf("WaitForPodState/%s/%s", name, desc) - _, span := trace.StartSpan(context.Background(), metricName) - defer span.End() - - return pollImmediateWithContext(ctx, func() (bool, error) { - r, err := c.KubeClient.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return true, err - } - return inState(r) - }) -} - -// WaitForPipelineRunState polls the status of the PipelineRun called name from client every -// interval until inState returns `true` indicating it is done, returns an -// error or timeout. desc will be used to name the metric that is emitted to -// track how long it took for name to get into the state checked by inState. -func WaitForPipelineRunState(ctx context.Context, c *clients, name string, polltimeout time.Duration, inState ConditionAccessorFn, desc string) error { - metricName := fmt.Sprintf("WaitForPipelineRunState/%s/%s", name, desc) - _, span := trace.StartSpan(context.Background(), metricName) - defer span.End() - - ctx, cancel := context.WithTimeout(ctx, polltimeout) - defer cancel() - return pollImmediateWithContext(ctx, func() (bool, error) { - r, err := c.PipelineRunClient.Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return true, err - } - return inState(&r.Status) - }) -} - -// WaitForServiceExternalIPState polls the status of the a k8s Service called name from client every -// interval until an external ip is assigned indicating it is done, returns an -// error or timeout. desc will be used to name the metric that is emitted to -// track how long it took for name to get into the state checked by inState. -func WaitForServiceExternalIPState(ctx context.Context, c *clients, namespace, name string, inState func(s *corev1.Service) (bool, error), desc string) error { - metricName := fmt.Sprintf("WaitForServiceExternalIPState/%s/%s", name, desc) - _, span := trace.StartSpan(context.Background(), metricName) - defer span.End() - - return pollImmediateWithContext(ctx, func() (bool, error) { - r, err := c.KubeClient.CoreV1().Services(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return true, err - } - return inState(r) - }) -} - -// Succeed provides a poll condition function that checks if the ConditionAccessor -// resource has successfully completed or not. -func Succeed(name string) ConditionAccessorFn { - return func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionTrue { - return true, nil - } else if c.Status == corev1.ConditionFalse { - return true, fmt.Errorf("%q failed", name) - } - } - return false, nil - } -} - -// Failed provides a poll condition function that checks if the ConditionAccessor -// resource has failed or not. -func Failed(name string) ConditionAccessorFn { - return func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionTrue { - return true, fmt.Errorf("%q succeeded", name) - } else if c.Status == corev1.ConditionFalse { - return true, nil - } - } - return false, nil - } -} - -// FailedWithReason provides a poll function that checks if the ConditionAccessor -// resource has failed with the TimeoudOut reason -func FailedWithReason(reason, name string) ConditionAccessorFn { - return func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionFalse { - if c.Reason == reason { - return true, nil - } - return true, fmt.Errorf("%q completed with the wrong reason: %s (message: %s)", name, c.Reason, c.Message) - } else if c.Status == corev1.ConditionTrue { - return true, fmt.Errorf("%q completed successfully, should have been failed with reason %q", name, reason) - } - } - return false, nil - } -} - -// FailedWithMessage provides a poll function that checks if the ConditionAccessor -// resource has failed with the TimeoudOut reason -func FailedWithMessage(message, name string) ConditionAccessorFn { - return func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionFalse { - if strings.Contains(c.Message, message) { - return true, nil - } - return true, fmt.Errorf("%q completed with the wrong message: %s", name, c.Message) - } else if c.Status == corev1.ConditionTrue { - return true, fmt.Errorf("%q completed successfully, should have been failed with message %q", name, message) - } - } - return false, nil - } -} - -// Running provides a poll condition function that checks if the ConditionAccessor -// resource is currently running. -func Running(name string) ConditionAccessorFn { - return func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionTrue || c.Status == corev1.ConditionFalse { - return true, fmt.Errorf(`%q already finished`, name) - } else if c.Status == corev1.ConditionUnknown && (c.Reason == "Running" || c.Reason == "Pending") { - return true, nil - } - } - return false, nil - } -} - -// TaskRunSucceed provides a poll condition function that checks if the TaskRun -// has successfully completed. -func TaskRunSucceed(name string) ConditionAccessorFn { - return Succeed(name) -} - -// TaskRunFailed provides a poll condition function that checks if the TaskRun -// has failed. -func TaskRunFailed(name string) ConditionAccessorFn { - return Failed(name) -} - -// PipelineRunSucceed provides a poll condition function that checks if the PipelineRun -// has successfully completed. -func PipelineRunSucceed(name string) ConditionAccessorFn { - return Succeed(name) -} - -// PipelineRunFailed provides a poll condition function that checks if the PipelineRun -// has failed. -func PipelineRunFailed(name string) ConditionAccessorFn { - return Failed(name) -} diff --git a/test/v1alpha1/wait_example_test.go b/test/v1alpha1/wait_example_test.go deleted file mode 100644 index c4d79978cdf..00000000000 --- a/test/v1alpha1/wait_example_test.go +++ /dev/null @@ -1,79 +0,0 @@ -//go:build examples -// +build examples - -/* -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 test - -import ( - "context" - "time" - - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" -) - -var ( - // This is a "hack" to make the example "look" like tests. - // Golang Example functions do not take `t *testing.T` as argument, so we "fake" - // it so that examples still compiles (`go test` tries to compile those) and look - // nice in the go documentation. - t testingT - c *clients -) - -type testingT interface { - Errorf(string, ...interface{}) -} - -func ExampleWaitForTaskRunState() { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - // […] setup the test, get clients - if err := WaitForTaskRunState(ctx, c, "taskRunName", func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionTrue { - return true, nil - } - } - return false, nil - }, "TaskRunHasCondition"); err != nil { - t.Errorf("Error waiting for TaskRun taskRunName to finish: %s", err) - } -} - -func ExampleWaitForPipelineRunState() { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - // […] setup the test, get clients - if err := WaitForPipelineRunState(ctx, c, "pipelineRunName", 1*time.Minute, func(ca apis.ConditionAccessor) (bool, error) { - c := ca.GetCondition(apis.ConditionSucceeded) - if c != nil { - if c.Status == corev1.ConditionTrue { - return true, nil - } - } - return false, nil - }, "PipelineRunHasCondition"); err != nil { - t.Errorf("Error waiting for PipelineRun pipelineRunName to finish: %s", err) - } -} diff --git a/test/v1alpha1/wait_test.go b/test/v1alpha1/wait_test.go deleted file mode 100644 index db3a582abaa..00000000000 --- a/test/v1alpha1/wait_test.go +++ /dev/null @@ -1,115 +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 test - -import ( - "context" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" - ttesting "github.com/tektoncd/pipeline/pkg/reconciler/testing" -) - -func TestWaitForTaskRunStateSucceed(t *testing.T) { - d := Data{ - TaskRuns: []*v1alpha1.TaskRun{parse.MustParseAlphaTaskRun(t, ` -metadata: - name: foo -status: - conditions: - - status: "True" - type: Succeeded -`)}, - } - c, ctx, cancel := fakeClients(t, d) - defer cancel() - if err := WaitForTaskRunState(ctx, c, "foo", Succeed("foo"), "TestTaskRunSucceed"); err != nil { - t.Fatal(err) - } -} -func TestWaitForTaskRunStateFailed(t *testing.T) { - d := Data{ - TaskRuns: []*v1alpha1.TaskRun{parse.MustParseAlphaTaskRun(t, ` -metadata: - name: foo -status: - conditions: - - status: "False" - type: Succeeded -`)}, - } - c, ctx, cancel := fakeClients(t, d) - defer cancel() - err := WaitForTaskRunState(ctx, c, "foo", TaskRunFailed("foo"), "TestTaskRunFailed") - if err != nil { - t.Fatal(err) - } -} - -func TestWaitForPipelineRunStateSucceed(t *testing.T) { - d := Data{ - PipelineRuns: []*v1alpha1.PipelineRun{parse.MustParseAlphaPipelineRun(t, ` -metadata: - name: bar -status: - conditions: - - status: "True" - type: Succeeded -`)}, - } - c, ctx, cancel := fakeClients(t, d) - defer cancel() - err := WaitForPipelineRunState(ctx, c, "bar", 2*time.Second, PipelineRunSucceed("bar"), "TestWaitForPipelineRunSucceed") - if err != nil { - t.Fatal(err) - } -} - -func TestWaitForPipelineRunStateFailed(t *testing.T) { - d := Data{ - PipelineRuns: []*v1alpha1.PipelineRun{parse.MustParseAlphaPipelineRun(t, ` -metadata: - name: bar -status: - conditions: - - status: "False" - type: Succeeded -`)}, - } - c, ctx, cancel := fakeClients(t, d) - defer cancel() - err := WaitForPipelineRunState(ctx, c, "bar", 2*time.Second, Failed("bar"), "TestWaitForPipelineRunFailed") - if err != nil { - t.Fatal(err) - } -} - -func fakeClients(t *testing.T, d Data) (*clients, context.Context, func()) { - ctx, _ := ttesting.SetupFakeContext(t) - ctx, cancel := context.WithCancel(ctx) - fakeClients, _ := SeedTestData(t, ctx, d) - return &clients{ - PipelineClient: fakeClients.Pipeline.TektonV1alpha1().Pipelines(""), - PipelineResourceClient: fakeClients.Resource.TektonV1alpha1().PipelineResources(""), - PipelineRunClient: fakeClients.Pipeline.TektonV1alpha1().PipelineRuns(""), - TaskClient: fakeClients.Pipeline.TektonV1alpha1().Tasks(""), - TaskRunClient: fakeClients.Pipeline.TektonV1alpha1().TaskRuns(""), - }, ctx, cancel -} diff --git a/test/v1alpha1/workingdir_test.go b/test/v1alpha1/workingdir_test.go deleted file mode 100644 index 2d87da24253..00000000000 --- a/test/v1alpha1/workingdir_test.go +++ /dev/null @@ -1,166 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/tektoncd/pipeline/test/parse" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -func TestWorkingDirCreated(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - wdTaskName := helpers.ObjectNameForTest(t) - wdTaskRunName := helpers.ObjectNameForTest(t) - - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: ubuntu - workingDir: /workspace/HELLOMOTO - args: ['-c', 'echo YES'] -`, wdTaskName)) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - - t.Logf("Creating TaskRun namespace %s", namespace) - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s - serviceAccountName: default -`, wdTaskRunName, wdTaskName)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to finish successfully", namespace) - if err := WaitForTaskRunState(ctx, c, wdTaskRunName, TaskRunSucceed(wdTaskRunName), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun to finish successfully: %s", err) - } - - tr, err := c.TaskRunClient.Get(ctx, wdTaskRunName, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error retrieving taskrun: %s", err) - } - if tr.Status.PodName == "" { - t.Fatal("Error getting a PodName (empty)") - } - p, err := c.KubeClient.CoreV1().Pods(namespace).Get(ctx, tr.Status.PodName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Error getting pod `%s` in namespace `%s`", tr.Status.PodName, namespace) - } - for _, stat := range p.Status.ContainerStatuses { - if strings.HasPrefix(stat.Name, "working-dir-initializer") { - if stat.State.Terminated != nil { - req := c.KubeClient.CoreV1().Pods(namespace).GetLogs(p.Name, &corev1.PodLogOptions{Container: stat.Name}) - logContent, err := req.Do(ctx).Raw() - if err != nil { - t.Fatalf("Error getting pod logs for pod `%s` and container `%s` in namespace `%s`", tr.Status.PodName, stat.Name, namespace) - } - if string(logContent) != "" { - t.Logf("Found some content in workingdir pod: %s, `%s` when it should be empty", tr.Status.PodName, logContent) - } - } - } - } -} - -func TestWorkingDirIgnoredNonSlashWorkspace(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - t.Parallel() - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - wdTaskName := helpers.ObjectNameForTest(t) - wdTaskRunName := helpers.ObjectNameForTest(t) - - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: ubuntu - workingDir: /HELLOMOTO - args: ['-c', 'echo YES'] -`, wdTaskName)) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - - t.Logf("Creating TaskRun namespace %s", namespace) - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s - serviceAccountName: default -`, wdTaskRunName, wdTaskName)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to finish successfully", namespace) - if err := WaitForTaskRunState(ctx, c, wdTaskRunName, TaskRunSucceed(wdTaskRunName), "TaskRunSuccess"); err != nil { - t.Errorf("Error waiting for TaskRun to finish successfully: %s", err) - } - - tr, err := c.TaskRunClient.Get(ctx, wdTaskRunName, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error retrieving taskrun: %s", err) - } - - p, err := c.KubeClient.CoreV1().Pods(namespace).Get(ctx, tr.Status.PodName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("Error getting pod `%s` in namespace `%s`", tr.Status.PodName, namespace) - } - for _, stat := range p.Status.ContainerStatuses { - if strings.HasPrefix(stat.Name, "working-dir-initializer") { - t.Logf("Found a working dir container called `%s` in `%s` when it should have been excluded:", stat.Name, tr.Status.PodName) - } - } - -} diff --git a/test/v1alpha1/workspace_test.go b/test/v1alpha1/workspace_test.go deleted file mode 100644 index 0036973c9c2..00000000000 --- a/test/v1alpha1/workspace_test.go +++ /dev/null @@ -1,242 +0,0 @@ -//go:build e2e -// +build e2e - -/* -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 test - -import ( - "context" - "fmt" - "strings" - "testing" - "time" - - "github.com/tektoncd/pipeline/test/parse" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - knativetest "knative.dev/pkg/test" - "knative.dev/pkg/test/helpers" -) - -func TestWorkspaceReadOnlyDisallowsWrite(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - - taskName := helpers.ObjectNameForTest(t) - taskRunName := helpers.ObjectNameForTest(t) - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: alpine - script: 'echo foo > /workspace/test/file' - workspaces: - - name: test - description: 'test workspace' - mountPath: /workspace/test - readOnly: true -`, taskName)) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - - taskRun := parse.MustParseAlphaTaskRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - taskRef: - name: %s - serviceAccountName: default - workspaces: - - name: test - emptyDir: {} -`, taskRunName, taskName)) - if _, err := c.TaskRunClient.Create(ctx, taskRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create TaskRun: %s", err) - } - - t.Logf("Waiting for TaskRun in namespace %s to finish", namespace) - if err := WaitForTaskRunState(ctx, c, taskRunName, TaskRunFailed(taskRunName), "error"); err != nil { - t.Errorf("Error waiting for TaskRun to finish with error: %s", err) - } - - tr, err := c.TaskRunClient.Get(ctx, taskRunName, metav1.GetOptions{}) - if err != nil { - t.Errorf("Error retrieving taskrun: %s", err) - } - if tr.Status.PodName == "" { - t.Fatal("Error getting a PodName (empty)") - } - p, err := c.KubeClient.CoreV1().Pods(namespace).Get(ctx, tr.Status.PodName, metav1.GetOptions{}) - - if err != nil { - t.Fatalf("Error getting pod `%s` in namespace `%s`", tr.Status.PodName, namespace) - } - for _, stat := range p.Status.ContainerStatuses { - if strings.Contains(stat.Name, "step-attempt-write") { - req := c.KubeClient.CoreV1().Pods(namespace).GetLogs(p.Name, &corev1.PodLogOptions{Container: stat.Name}) - logContent, err := req.Do(ctx).Raw() - if err != nil { - t.Fatalf("Error getting pod logs for pod `%s` and container `%s` in namespace `%s`", tr.Status.PodName, stat.Name, namespace) - } - if !strings.Contains(string(logContent), "Read-only file system") { - t.Fatalf("Expected read-only file system error but received %v", logContent) - } - } - } -} - -func TestWorkspacePipelineRunDuplicateWorkspaceEntriesInvalid(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - - taskName := helpers.ObjectNameForTest(t) - pipelineName := helpers.ObjectNameForTest(t) - pipelineRunName := helpers.ObjectNameForTest(t) - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: alpine - script: 'cat /workspace/test/file' - workspaces: - - name: test - description: 'test workspace' - mountPath: /workspace/test - readOnly: true -`, taskName)) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - - pipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - workspaces: - - name: foo - tasks: - - name: %s - taskRef: - name: %s - workspaces: - - name: test - workspace: foo -`, pipelineName, taskName, taskName)) - if _, err := c.PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline: %s", err) - } - - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s - workspaces: - - name: foo - emptyDir: {} - - name: foo - emptyDir: {} -`, pipelineRunName, pipelineName)) - _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}) - - if err == nil || !strings.Contains(err.Error(), "provided by pipelinerun more than once") { - t.Fatalf("Expected error when creating pipelinerun with duplicate workspace entries but received: %v", err) - } -} - -func TestWorkspacePipelineRunMissingWorkspaceInvalid(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - c, namespace := setup(ctx, t) - - taskName := helpers.ObjectNameForTest(t) - pipelineName := helpers.ObjectNameForTest(t) - pipelineRunName := helpers.ObjectNameForTest(t) - - knativetest.CleanupOnInterrupt(func() { tearDown(ctx, t, c, namespace) }, t.Logf) - defer tearDown(ctx, t, c, namespace) - - task := parse.MustParseAlphaTask(t, fmt.Sprintf(` -metadata: - name: %s -spec: - steps: - - image: alpine - script: 'cat /workspace/test/file' - workspaces: - - name: test - description: 'test workspace' - mountPath: /workspace/test/file - readOnly: true -`, taskName)) - if _, err := c.TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Task: %s", err) - } - - pipeline := parse.MustParseAlphaPipeline(t, fmt.Sprintf(` -metadata: - name: %s -spec: - workspaces: - - name: foo - tasks: - - name: %s - taskRef: - name: %s - workspaces: - - name: test - workspace: foo -`, pipelineName, taskName, taskName)) - if _, err := c.PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create Pipeline: %s", err) - } - - pipelineRun := parse.MustParseAlphaPipelineRun(t, fmt.Sprintf(` -metadata: - name: %s -spec: - pipelineRef: - name: %s -`, pipelineRunName, pipelineName)) - if _, err := c.PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil { - t.Fatalf("Failed to create PipelineRun: %s", err) - } - - if err := WaitForPipelineRunState(ctx, c, pipelineRunName, 10*time.Second, FailedWithMessage(`pipeline requires workspace with name "foo" be provided by pipelinerun`, pipelineRunName), "PipelineRunHasCondition"); err != nil { - t.Fatalf("Failed to wait for PipelineRun %q to finish: %s", pipelineRunName, err) - } - -}