diff --git a/cmd/controller/main.go b/cmd/controller/main.go index 45cd44ae7d4..bc69db773d0 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -25,9 +25,6 @@ import ( "knative.dev/eventing/pkg/reconciler/apiserversource" "knative.dev/eventing/pkg/reconciler/channel" "knative.dev/eventing/pkg/reconciler/eventtype" - "knative.dev/eventing/pkg/reconciler/legacyapiserversource" - "knative.dev/eventing/pkg/reconciler/legacycontainersource" - "knative.dev/eventing/pkg/reconciler/legacycronjobsource" "knative.dev/eventing/pkg/reconciler/parallel" "knative.dev/eventing/pkg/reconciler/pingsource" "knative.dev/eventing/pkg/reconciler/sequence" @@ -53,11 +50,5 @@ func main() { // Sources apiserversource.NewController, pingsource.NewController, - - // Legacy Sources - // TODO(#2312): Remove this after v0.13. - legacyapiserversource.NewController, - legacycontainersource.NewController, - legacycronjobsource.NewController, ) } diff --git a/cmd/cronjob_receive_adapter/kodata/HEAD b/cmd/cronjob_receive_adapter/kodata/HEAD deleted file mode 120000 index 8f63681d362..00000000000 --- a/cmd/cronjob_receive_adapter/kodata/HEAD +++ /dev/null @@ -1 +0,0 @@ -../../../.git/HEAD \ No newline at end of file diff --git a/cmd/cronjob_receive_adapter/kodata/LICENSE b/cmd/cronjob_receive_adapter/kodata/LICENSE deleted file mode 120000 index 5853aaea53b..00000000000 --- a/cmd/cronjob_receive_adapter/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../LICENSE \ No newline at end of file diff --git a/cmd/cronjob_receive_adapter/kodata/VENDOR-LICENSE b/cmd/cronjob_receive_adapter/kodata/VENDOR-LICENSE deleted file mode 120000 index 3cc89764519..00000000000 --- a/cmd/cronjob_receive_adapter/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/cmd/cronjob_receive_adapter/kodata/refs b/cmd/cronjob_receive_adapter/kodata/refs deleted file mode 120000 index 739d35bf96a..00000000000 --- a/cmd/cronjob_receive_adapter/kodata/refs +++ /dev/null @@ -1 +0,0 @@ -../../../.git/refs \ No newline at end of file diff --git a/cmd/cronjob_receive_adapter/main.go b/cmd/cronjob_receive_adapter/main.go deleted file mode 100644 index 34805b225df..00000000000 --- a/cmd/cronjob_receive_adapter/main.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2019 The Knative 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 main - -import ( - "knative.dev/eventing/pkg/adapter" - "knative.dev/eventing/pkg/adapter/cronjobevents" -) - -func main() { - adapter.Main("cronjobsource", cronjobevents.NewEnvConfig, cronjobevents.NewAdapter) -} diff --git a/cmd/webhook/main.go b/cmd/webhook/main.go index d6147b5a461..d3221ed0be2 100644 --- a/cmd/webhook/main.go +++ b/cmd/webhook/main.go @@ -24,7 +24,6 @@ import ( "k8s.io/apimachinery/pkg/types" "knative.dev/eventing/pkg/logconfig" - "knative.dev/eventing/pkg/reconciler/legacysinkbinding" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" "knative.dev/pkg/injection" @@ -50,7 +49,6 @@ import ( "knative.dev/eventing/pkg/apis/flows" flowsv1alpha1 "knative.dev/eventing/pkg/apis/flows/v1alpha1" flowsv1beta1 "knative.dev/eventing/pkg/apis/flows/v1beta1" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" "knative.dev/eventing/pkg/apis/messaging" channeldefaultconfig "knative.dev/eventing/pkg/apis/messaging/config" messagingv1alpha1 "knative.dev/eventing/pkg/apis/messaging/v1alpha1" @@ -93,13 +91,6 @@ var ourTypes = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ sourcesv1alpha2.SchemeGroupVersion.WithKind("PingSource"): &sourcesv1alpha2.PingSource{}, sourcesv1alpha2.SchemeGroupVersion.WithKind("SinkBinding"): &sourcesv1alpha2.SinkBinding{}, - // For group sources.eventing.knative.dev. - // TODO(#2312): Remove this after v0.13. - legacysourcesv1alpha1.SchemeGroupVersion.WithKind("ApiServerSource"): &legacysourcesv1alpha1.ApiServerSource{}, - legacysourcesv1alpha1.SchemeGroupVersion.WithKind("ContainerSource"): &legacysourcesv1alpha1.ContainerSource{}, - legacysourcesv1alpha1.SchemeGroupVersion.WithKind("SinkBinding"): &legacysourcesv1alpha1.SinkBinding{}, - legacysourcesv1alpha1.SchemeGroupVersion.WithKind("CronJobSource"): &legacysourcesv1alpha1.CronJobSource{}, - // For group flows.knative.dev // v1alpha1 flowsv1alpha1.SchemeGroupVersion.WithKind("Parallel"): &flowsv1alpha1.Parallel{}, @@ -217,29 +208,6 @@ func NewSinkBindingWebhook(opts ...psbinding.ReconcilerOption) injection.Control } } -// TODO(#2312): Remove this after v0.13. -func NewLegacySinkBindingWebhook(opts ...psbinding.ReconcilerOption) injection.ControllerConstructor { - return func(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - sbresolver := legacysinkbinding.WithContextFactory(ctx, func(types.NamespacedName) {}) - - return psbinding.NewAdmissionController(ctx, - - // Name of the resource webhook. - "legacysinkbindings.webhook.sources.knative.dev", - - // The path on which to serve the webhook. - "/legacysinkbindings", - - // How to get all the Bindables for configuring the mutating webhook. - legacysinkbinding.ListAll, - - // How to setup the context prior to invoking Do/Undo. - sbresolver, - opts..., - ) - } -} - func NewConversionController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { // Decorate contexts with the current state of the config. store := defaultconfig.NewStore(logging.FromContext(ctx).Named("config-store")) @@ -383,7 +351,5 @@ func main() { // For each binding we have a controller and a binding webhook. sinkbinding.NewController, NewSinkBindingWebhook(sbSelector), - // TODO(#2312): Remove this after v0.13. - legacysinkbinding.NewController, NewLegacySinkBindingWebhook(sbSelector), ) } diff --git a/config/300-legacyapiserversource.yaml b/config/300-legacyapiserversource.yaml deleted file mode 120000 index 54eb144d6ef..00000000000 --- a/config/300-legacyapiserversource.yaml +++ /dev/null @@ -1 +0,0 @@ -core/resources/legacyapiserversource.yaml \ No newline at end of file diff --git a/config/300-legacycontainersource.yaml b/config/300-legacycontainersource.yaml deleted file mode 120000 index e886370d298..00000000000 --- a/config/300-legacycontainersource.yaml +++ /dev/null @@ -1 +0,0 @@ -core/resources/legacycontainersource.yaml \ No newline at end of file diff --git a/config/300-legacycronjobsource.yaml b/config/300-legacycronjobsource.yaml deleted file mode 120000 index 78c1bfeab84..00000000000 --- a/config/300-legacycronjobsource.yaml +++ /dev/null @@ -1 +0,0 @@ -core/resources/legacycronjobsource.yaml \ No newline at end of file diff --git a/config/300-legacysinkbinding.yaml b/config/300-legacysinkbinding.yaml deleted file mode 120000 index f773fe11396..00000000000 --- a/config/300-legacysinkbinding.yaml +++ /dev/null @@ -1 +0,0 @@ -core/resources/legacysinkbinding.yaml \ No newline at end of file diff --git a/config/500-webhook-legacysinkbindings.yaml b/config/500-webhook-legacysinkbindings.yaml deleted file mode 120000 index fe3c1c893ba..00000000000 --- a/config/500-webhook-legacysinkbindings.yaml +++ /dev/null @@ -1 +0,0 @@ -core/webhooks/legacysinkbindings.yaml \ No newline at end of file diff --git a/config/core/deployments/controller.yaml b/config/core/deployments/controller.yaml index ca09e97b9e7..a23acc9e850 100644 --- a/config/core/deployments/controller.yaml +++ b/config/core/deployments/controller.yaml @@ -53,9 +53,6 @@ spec: value: config-observability - name: METRICS_DOMAIN value: knative.dev/eventing - # Legacy CronJobSource - - name: CRONJOB_RA_IMAGE - value: knative.dev/eventing/cmd/cronjob_receive_adapter # PingSource - name: PING_IMAGE value: knative.dev/eventing/cmd/ping diff --git a/config/core/resources/legacyapiserversource.yaml b/config/core/resources/legacyapiserversource.yaml deleted file mode 100644 index 093b62cd844..00000000000 --- a/config/core/resources/legacyapiserversource.yaml +++ /dev/null @@ -1,166 +0,0 @@ -# Copyright 2019 The Knative 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: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - eventing.knative.dev/release: devel - eventing.knative.dev/source: "true" - duck.knative.dev/source: "true" - knative.dev/crd-install: "true" - annotations: - # TODO add schemas and descriptions - registry.knative.dev/eventTypes: | - [ - { "type": "dev.knative.apiserver.resource.add" }, - { "type": "dev.knative.apiserver.resource.delete" }, - { "type": "dev.knative.apiserver.resource.update" }, - { "type": "dev.knative.apiserver.ref.add" }, - { "type": "dev.knative.apiserver.ref.delete" }, - { "type": "dev.knative.apiserver.ref.update" } - ] - name: apiserversources.sources.eventing.knative.dev -spec: - group: sources.eventing.knative.dev - names: - categories: - - all - - knative - - eventing - - sources - kind: ApiServerSource - plural: apiserversources - scope: Namespaced - subresources: - status: {} - additionalPrinterColumns: - - name: Ready - type: string - JSONPath: ".status.conditions[?(@.type==\"Ready\")].status" - - name: Age - type: date - JSONPath: .metadata.creationTimestamp - validation: - openAPIV3Schema: - properties: - spec: - properties: - serviceAccountName: - type: string - description: "name of the ServiceAccount to use to run the receive adapter. More info: https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/." - sink: - anyOf: - - type: object - description: "the destination that should receive events." - properties: - ref: - type: object - description: "a reference to a Kubernetes object from which to retrieve the target URI." - required: - - apiVersion - - kind - - name - properties: - apiVersion: - type: string - minLength: 1 - kind: - type: string - minLength: 1 - name: - type: string - minLength: 1 - uri: - type: string - description: "the target URI. If ref is provided, this must be relative URI reference." - - type: object - description: "DEPRECATED: a reference to a Kubernetes object from which to retrieve the target URI." - required: - - apiVersion - - kind - - name - properties: - apiVersion: - type: string - minLength: 1 - kind: - type: string - minLength: 1 - name: - type: string - minLength: 1 - mode: - type: string - description: "Mode controls the content of the event payload. One of: 'Ref' (only references of resources), 'Resource' (full resource)." - resources: - items: - properties: - apiVersion: - type: string - description: "API version of the objects to watch." - kind: - type: string - description: "Kind of the objects to watch." - controller: - type: boolean - description: "If true, emits the managing controller ref. Only supported for mode=Ref. More info: https://kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/" - labelSelector: - type: object - description: "Label selector restricting this list of objects to watch by their labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/" - controllerSelector: - type: object - description: "Controller selector restricting the list of objects to watch by a controlling owner reference of the specified kind." - properties: - apiVersion: - type: string - description: "API version of the controlling owner reference." - kind: - type: string - description: "Kind of the controlling owner reference." - type: array - required: - - resources - - sink - type: object - status: - properties: - conditions: - items: - properties: - lastTransitionTime: - type: string - message: - type: string - reason: - type: string - severity: - type: string - status: - type: string - type: - type: string - required: - - type - - status - type: object - type: array - sinkUri: - type: string - type: object - versions: - - name: v1alpha1 - served: true - storage: true diff --git a/config/core/resources/legacycontainersource.yaml b/config/core/resources/legacycontainersource.yaml deleted file mode 100644 index 9d641e07c9f..00000000000 --- a/config/core/resources/legacycontainersource.yaml +++ /dev/null @@ -1,135 +0,0 @@ -# Copyright 2019 The Knative 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: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - labels: - eventing.knative.dev/release: devel - eventing.knative.dev/source: "true" - duck.knative.dev/source: "true" - knative.dev/crd-install: "true" - name: containersources.sources.eventing.knative.dev -spec: - group: sources.eventing.knative.dev - names: - categories: - - all - - knative - - eventing - - sources - kind: ContainerSource - plural: containersources - scope: Namespaced - subresources: - status: {} - validation: - openAPIV3Schema: - properties: - apiVersion: - type: string - kind: - type: string - metadata: - type: object - spec: - properties: - args: - items: - type: string - type: array - env: - items: - type: object - type: array - image: - minLength: 1 - type: string - serviceAccountName: - type: string - template: - type: object - sink: - anyOf: - - type: object - description: "the destination that should receive events." - properties: - ref: - type: object - description: "a reference to a Kubernetes object from which to retrieve the target URI." - required: - - apiVersion - - kind - - name - properties: - apiVersion: - type: string - minLength: 1 - kind: - type: string - minLength: 1 - name: - type: string - minLength: 1 - uri: - type: string - description: "the target URI. If ref is provided, this must be relative URI reference." - - type: object - description: "DEPRECATED: a reference to a Kubernetes object from which to retrieve the target URI." - required: - - apiVersion - - kind - - name - properties: - apiVersion: - type: string - minLength: 1 - kind: - type: string - minLength: 1 - name: - type: string - minLength: 1 - type: object - status: - properties: - conditions: - items: - properties: - lastTransitionTime: - # we use a string in the stored object but a wrapper object - # at runtime. - type: string - message: - type: string - reason: - type: string - severity: - type: string - status: - type: string - type: - type: string - required: - - type - - status - type: object - type: array - sinkUri: - type: string - type: object - versions: - - name: v1alpha1 - served: true - storage: true diff --git a/config/core/resources/legacycronjobsource.yaml b/config/core/resources/legacycronjobsource.yaml deleted file mode 100644 index 86c971c12fc..00000000000 --- a/config/core/resources/legacycronjobsource.yaml +++ /dev/null @@ -1,152 +0,0 @@ -# Copyright 2019 The Knative 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: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - labels: - eventing.knative.dev/release: devel - eventing.knative.dev/source: "true" - duck.knative.dev/source: "true" - knative.dev/crd-install: "true" - annotations: - # TODO add schemas and descriptions - registry.knative.dev/eventTypes: | - [ - { "type": "dev.knative.cronjob.event" } - ] - name: cronjobsources.sources.eventing.knative.dev -spec: - group: sources.eventing.knative.dev - names: - categories: - - all - - knative - - eventing - - sources - kind: CronJobSource - plural: cronjobsources - scope: Namespaced - subresources: - status: {} - additionalPrinterColumns: - - name: Ready - type: string - JSONPath: ".status.conditions[?(@.type==\"Ready\")].status" - - name: Age - type: date - JSONPath: .metadata.creationTimestamp - validation: - openAPIV3Schema: - properties: - spec: - properties: - data: - type: string - schedule: - type: string - serviceAccountName: - type: string - sink: - anyOf: - - type: object - description: "the destination that should receive events." - properties: - ref: - type: object - description: "a reference to a Kubernetes object from which to retrieve the target URI." - required: - - apiVersion - - kind - - name - properties: - apiVersion: - type: string - minLength: 1 - kind: - type: string - minLength: 1 - name: - type: string - minLength: 1 - uri: - type: string - description: "the target URI. If ref is provided, this must be relative URI reference." - - type: object - description: "DEPRECATED: a reference to a Kubernetes object from which to retrieve the target URI." - required: - - apiVersion - - kind - - name - properties: - apiVersion: - type: string - minLength: 1 - kind: - type: string - minLength: 1 - name: - type: string - minLength: 1 - resources: - properties: - limits: - properties: - cpu: - type: string - memory: - type: string - type: object - requests: - properties: - cpu: - type: string - memory: - type: string - type: object - type: object - required: - - schedule - type: object - status: - properties: - conditions: - items: - properties: - lastTransitionTime: - # we use a string in the stored object but a wrapper object - # at runtime. - type: string - message: - type: string - reason: - type: string - severity: - type: string - status: - type: string - type: - type: string - required: - - type - - status - type: object - type: array - sinkUri: - type: string - type: object - versions: - - name: v1alpha1 - served: true - storage: true diff --git a/config/core/resources/legacysinkbinding.yaml b/config/core/resources/legacysinkbinding.yaml deleted file mode 100644 index c5bdf72005f..00000000000 --- a/config/core/resources/legacysinkbinding.yaml +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright 2019 The Knative 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: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - labels: - eventing.knative.dev/release: devel - eventing.knative.dev/source: "true" - duck.knative.dev/source: "true" - duck.knative.dev/binding: "true" - knative.dev/crd-install: "true" - name: sinkbindings.sources.eventing.knative.dev -spec: - group: sources.eventing.knative.dev - names: - categories: - - all - - knative - - eventing - - sources - - bindings - kind: SinkBinding - plural: sinkbindings - scope: Namespaced - subresources: - status: {} - versions: - - name: v1alpha1 - served: true - storage: true - additionalPrinterColumns: - - name: Ready - type: string - JSONPath: ".status.conditions[?(@.type=='Ready')].status" - - name: Reason - type: string - JSONPath: ".status.conditions[?(@.type=='Ready')].reason" diff --git a/config/core/roles/clusterrole-namespaced.yaml b/config/core/roles/clusterrole-namespaced.yaml index aebdad248a8..c09e11ecf5f 100644 --- a/config/core/roles/clusterrole-namespaced.yaml +++ b/config/core/roles/clusterrole-namespaced.yaml @@ -50,18 +50,6 @@ rules: --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: knative-eventing-sources-namespaced-admin - labels: - eventing.knative.dev/release: devel - rbac.authorization.k8s.io/aggregate-to-admin: "true" -rules: - - apiGroups: ["sources.eventing.knative.dev"] - resources: ["*"] - verbs: ["*"] ---- -kind: ClusterRole -apiVersion: rbac.authorization.k8s.io/v1 metadata: name: knative-sources-namespaced-admin labels: @@ -81,7 +69,7 @@ metadata: rbac.authorization.k8s.io/aggregate-to-edit: "true" eventing.knative.dev/release: devel rules: - - apiGroups: ["eventing.knative.dev", "messaging.knative.dev", "sources.eventing.knative.dev", "sources.knative.dev", "flows.knative.dev"] + - apiGroups: ["eventing.knative.dev", "messaging.knative.dev", "flows.knative.dev"] resources: ["*"] verbs: ["create", "update", "patch", "delete"] --- @@ -93,6 +81,6 @@ metadata: rbac.authorization.k8s.io/aggregate-to-view: "true" eventing.knative.dev/release: devel rules: - - apiGroups: ["eventing.knative.dev", "messaging.knative.dev", "sources.eventing.knative.dev", "sources.knative.dev", flows.knative.dev] + - apiGroups: ["eventing.knative.dev", "messaging.knative.dev", "sources.knative.dev", flows.knative.dev] resources: ["*"] verbs: ["get", "list", "watch"] diff --git a/config/core/roles/source-observer-clusterrole.yaml b/config/core/roles/source-observer-clusterrole.yaml index 8128042e458..6f54856054b 100644 --- a/config/core/roles/source-observer-clusterrole.yaml +++ b/config/core/roles/source-observer-clusterrole.yaml @@ -41,16 +41,7 @@ rules: resources: - apiserversources - pingsources - verbs: - - get - - list - - watch - - apiGroups: - - sources.eventing.knative.dev - resources: - - containersources - - cronjobsources - - apiserversources + - sinkbinding verbs: - get - list diff --git a/config/core/roles/sources-controller-clusterroles.yaml b/config/core/roles/sources-controller-clusterroles.yaml index a3cdcf4098d..bdf0bbca582 100644 --- a/config/core/roles/sources-controller-clusterroles.yaml +++ b/config/core/roles/sources-controller-clusterroles.yaml @@ -56,24 +56,6 @@ rules: - "pingsources/finalizers" verbs: *everything - # Legacy Source resources and statuses we care about. - - apiGroups: - - "sources.eventing.knative.dev" - resources: - - "cronjobsources" - - "cronjobsources/status" - - "cronjobsources/finalizers" - - "containersources" - - "containersources/status" - - "containersources/finalizers" - - "sinkbindings" - - "sinkbindings/status" - - "sinkbindings/finalizers" - - "apiserversources" - - "apiserversources/status" - - "apiserversources/finalizers" - verbs: *everything - # Knative Services admin - apiGroups: - serving.knative.dev diff --git a/config/core/roles/webhook-clusterrole.yaml b/config/core/roles/webhook-clusterrole.yaml index d2d870f71b1..6f7c18d6a5c 100644 --- a/config/core/roles/webhook-clusterrole.yaml +++ b/config/core/roles/webhook-clusterrole.yaml @@ -71,16 +71,6 @@ rules: - "patch" - "watch" - # For running the SinkBinding reconciler. - # TODO(#2312): Remove this after v0.13. - - apiGroups: - - "sources.eventing.knative.dev" - resources: - - "sinkbindings" - - "sinkbindings/status" - - "sinkbindings/finalizers" - verbs: *everything - # For running the SinkBinding reconciler. - apiGroups: - "sources.knative.dev" diff --git a/config/core/webhooks/legacysinkbindings.yaml b/config/core/webhooks/legacysinkbindings.yaml deleted file mode 100644 index ac4782083dc..00000000000 --- a/config/core/webhooks/legacysinkbindings.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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: admissionregistration.k8s.io/v1beta1 -kind: MutatingWebhookConfiguration -metadata: - name: legacysinkbindings.webhook.sources.knative.dev - labels: - eventing.knative.dev/release: devel -webhooks: - - admissionReviewVersions: - - v1beta1 - clientConfig: - service: - name: eventing-webhook - namespace: knative-eventing - failurePolicy: Fail - sideEffects: None - name: legacysinkbindings.webhook.sources.knative.dev diff --git a/config/monitoring/metrics/prometheus/100-prometheus-scrape-kn-eventing.yaml b/config/monitoring/metrics/prometheus/100-prometheus-scrape-kn-eventing.yaml index be8e7b2339d..2e6053140ee 100644 --- a/config/monitoring/metrics/prometheus/100-prometheus-scrape-kn-eventing.yaml +++ b/config/monitoring/metrics/prometheus/100-prometheus-scrape-kn-eventing.yaml @@ -110,8 +110,8 @@ - source_labels: [__meta_kubernetes_service_name] target_label: service -# cronjob-source -- job_name: cronjob-source +# pingsource +- job_name: ping-source scrape_interval: 3s scrape_timeout: 3s kubernetes_sd_configs: diff --git a/docs/metrics.md b/docs/metrics.md index 11a4e881f4d..4c02a564c78 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -31,7 +31,7 @@ These are exported by core sources. | ------------- | ----- | --------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `event_count` | count | Number of events sent | `namespace_name`, `name`, `source_resource_group`, `event_source`, `event_type`, `response_code`, `response_code_class` | -### CronJobSource +### PingSource | Name | Type | Description | Tags | | ------------- | ----- | --------------------- | ----------------------------------------------------------------------------------------------------------------------- | diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index 570c095ec4a..a2a151015a8 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -33,12 +33,6 @@ ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ "eventing:v1alpha1 eventing:v1beta1 messaging:v1alpha1 messaging:v1beta1 flows:v1alpha1 flows:v1beta1 sources:v1alpha1 sources:v1alpha2 configs:v1alpha1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt -# TODO(#2312): Remove this after v0.13. -${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ - knative.dev/eventing/pkg/legacyclient knative.dev/eventing/pkg/apis \ - "legacysources:v1alpha1" \ - --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt - # Deep copy config ${GOPATH}/bin/deepcopy-gen \ -O zz_generated.deepcopy \ @@ -58,11 +52,5 @@ ${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \ "eventing:v1alpha1 eventing:v1beta1 messaging:v1alpha1 messaging:v1beta1 flows:v1alpha1 flows:v1beta1 sources:v1alpha1 sources:v1alpha2 duck:v1alpha1 duck:v1beta1 configs:v1alpha1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt -# TODO(#2312): Remove this after v0.13. -${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \ - knative.dev/eventing/pkg/legacyclient knative.dev/eventing/pkg/apis \ - "legacysources:v1alpha1" \ - --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt - # Make sure our dependencies are up-to-date ${REPO_ROOT_DIR}/hack/update-deps.sh diff --git a/pkg/adapter/apiserver/adapter.go b/pkg/adapter/apiserver/adapter.go index f28f89d32ea..586056c8bcf 100644 --- a/pkg/adapter/apiserver/adapter.go +++ b/pkg/adapter/apiserver/adapter.go @@ -73,7 +73,7 @@ const ( // ResourceMode produces payloads of ResourceEvent ResourceMode = "Resource" - resourceGroup = "apiserversources.sources.eventing.knative.dev" + resourceGroup = "apiserversources.sources.knative.dev" ) // GVRC is a combination of GroupVersionResource, Controller flag, LabelSelector and OwnerRef diff --git a/pkg/adapter/apiserver/controller_test.go b/pkg/adapter/apiserver/controller_test.go index 30bb3506c3e..e77c0eeead2 100644 --- a/pkg/adapter/apiserver/controller_test.go +++ b/pkg/adapter/apiserver/controller_test.go @@ -19,7 +19,7 @@ package apiserver import ( "testing" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" + sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" kncetesting "knative.dev/eventing/pkg/kncloudevents/testing" ) diff --git a/pkg/adapter/apiserver/events/events.go b/pkg/adapter/apiserver/events/events.go index 013910a9314..b2f62ecddc8 100644 --- a/pkg/adapter/apiserver/events/events.go +++ b/pkg/adapter/apiserver/events/events.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" cloudevents "github.com/cloudevents/sdk-go" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" + sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" ) func MakeAddEvent(source string, obj interface{}) (*cloudevents.Event, error) { diff --git a/pkg/adapter/apiserver/ref_test.go b/pkg/adapter/apiserver/ref_test.go index 9566b9f0a7d..76cdb71197b 100644 --- a/pkg/adapter/apiserver/ref_test.go +++ b/pkg/adapter/apiserver/ref_test.go @@ -4,7 +4,7 @@ import ( "testing" "k8s.io/apimachinery/pkg/runtime/schema" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" + sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" ) func TestRefAddEvent(t *testing.T) { diff --git a/pkg/adapter/apiserver/resource_test.go b/pkg/adapter/apiserver/resource_test.go index bb842fd82bf..91e930379b4 100644 --- a/pkg/adapter/apiserver/resource_test.go +++ b/pkg/adapter/apiserver/resource_test.go @@ -4,7 +4,7 @@ import ( "testing" "k8s.io/apimachinery/pkg/runtime/schema" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" + sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" ) func TestResourceAddEvent(t *testing.T) { diff --git a/pkg/adapter/cronjobevents/adapter.go b/pkg/adapter/cronjobevents/adapter.go deleted file mode 100644 index 04dcd833834..00000000000 --- a/pkg/adapter/cronjobevents/adapter.go +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright 2019 The Knative 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 cronjobevents - -import ( - "context" - "encoding/json" - "fmt" - - cloudevents "github.com/cloudevents/sdk-go" - "github.com/robfig/cron" - "go.uber.org/zap" - "knative.dev/eventing/pkg/adapter" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/pkg/logging" - "knative.dev/pkg/source" -) - -type envConfig struct { - adapter.EnvConfig - - // Environment variable container schedule. - Schedule string `envconfig:"SCHEDULE" required:"true"` - - // Environment variable containing data. - Data string `envconfig:"DATA" required:"true"` - - // Environment variable containing the name of the cron job. - Name string `envconfig:"NAME" required:"true"` -} - -// cronJobAdapter implements the Cron Job adapter to trigger a Sink. -type cronJobAdapter struct { - // Schedule is a cron format string such as 0 * * * * or @hourly - Schedule string - - // Data is the data to be posted to the target. - Data string - - // Name is the name of the Cron Job. - Name string - - // Namespace is the namespace of the Cron Job. - Namespace string - - // client sends cloudevents. - Client cloudevents.Client - - Reporter source.StatsReporter -} - -const ( - resourceGroup = "cronjobsources.sources.eventing.knative.dev" -) - -func NewEnvConfig() adapter.EnvConfigAccessor { - return &envConfig{} -} - -func NewAdapter(ctx context.Context, processed adapter.EnvConfigAccessor, ceClient cloudevents.Client, reporter source.StatsReporter) adapter.Adapter { - env := processed.(*envConfig) - - return &cronJobAdapter{ - Schedule: env.Schedule, - Data: env.Data, - Name: env.Name, - Namespace: env.Namespace, - Reporter: reporter, - Client: ceClient, - } -} - -func (a *cronJobAdapter) Start(stopCh <-chan struct{}) error { - sched, err := cron.ParseStandard(a.Schedule) - if err != nil { - return fmt.Errorf("Unparseable schedule %s: %v", a.Schedule, err) - } - - c := cron.New() - c.Schedule(sched, cron.FuncJob(a.cronTick)) - c.Start() - <-stopCh - c.Stop() - return nil -} - -func (a *cronJobAdapter) cronTick() { - logger := logging.FromContext(context.TODO()) - - event := cloudevents.NewEvent(cloudevents.VersionV1) - event.SetType(sourcesv1alpha1.CronJobEventType) - event.SetSource(sourcesv1alpha1.CronJobEventSource(a.Namespace, a.Name)) - event.SetData(message(a.Data)) - event.SetDataContentType(cloudevents.ApplicationJSON) - reportArgs := &source.ReportArgs{ - Namespace: a.Namespace, - EventSource: event.Source(), - EventType: event.Type(), - Name: a.Name, - ResourceGroup: resourceGroup, - } - - rctx, _, err := a.Client.Send(context.TODO(), event) - rtctx := cloudevents.HTTPTransportContextFrom(rctx) - if err != nil { - logger.Error("failed to send cloudevent", zap.Error(err)) - } - a.Reporter.ReportEventCount(reportArgs, rtctx.StatusCode) -} - -type Message struct { - Body string `json:"body"` -} - -func message(body string) interface{} { - // try to marshal the body into an interface. - var objmap map[string]*json.RawMessage - if err := json.Unmarshal([]byte(body), &objmap); err != nil { - //default to a wrapped message. - return Message{Body: body} - } - return objmap -} diff --git a/pkg/adapter/cronjobevents/adapter_test.go b/pkg/adapter/cronjobevents/adapter_test.go deleted file mode 100644 index 67645c45e84..00000000000 --- a/pkg/adapter/cronjobevents/adapter_test.go +++ /dev/null @@ -1,204 +0,0 @@ -/* -Copyright 2019 The Knative 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 cronjobevents - -import ( - "encoding/json" - "log" - "net/http" - "testing" - - "github.com/google/go-cmp/cmp" - kncetesting "knative.dev/eventing/pkg/kncloudevents/testing" - "knative.dev/pkg/source" -) - -type mockReporter struct { - eventCount int -} - -func (r *mockReporter) ReportEventCount(args *source.ReportArgs, responseCode int) error { - r.eventCount++ - return nil -} - -func TestStart_ServeHTTP(t *testing.T) { - testCases := map[string]struct { - schedule string - sink func(http.ResponseWriter, *http.Request) - data string - error bool - }{ - "happy": { - schedule: "* * * * *", // every minute - sink: sinkAccepted, - data: `{"body":"data"}`, - }, - "rejected": { - schedule: "* * * * *", // every minute - sink: sinkRejected, - data: `{"body":"data"}`, - error: true, - }, - } - for n, tc := range testCases { - t.Run(n, func(t *testing.T) { - ce := kncetesting.NewTestClient() - - r := &mockReporter{} - a := &cronJobAdapter{ - Schedule: tc.schedule, - Data: "data", - Reporter: r, - Client: ce, - } - - stop := make(chan struct{}) - go func() { - if err := a.Start(stop); err != nil { - if tc.error { - // skip - } else { - t.Errorf("failed to start, %v", err) - } - } - }() - - a.cronTick() // force a tick. - validateMetric(t, a.Reporter, 1) - validateSent(t, ce, tc.data) - - log.Print("test done") - }) - } -} - -func TestStartBadCron(t *testing.T) { - schedule := "bad" - - r := &mockReporter{} - a := &cronJobAdapter{ - Schedule: schedule, - Reporter: r, - } - - stop := make(chan struct{}) - if err := a.Start(stop); err == nil { - - t.Errorf("failed to fail, %v", err) - - } - - validateMetric(t, a.Reporter, 0) -} - -func TestPostMessage_ServeHTTP(t *testing.T) { - testCases := map[string]struct { - sink func(http.ResponseWriter, *http.Request) - data string - error bool - }{ - "happy": { - sink: sinkAccepted, - data: `{"body":"data"}`, - }, - "rejected": { - sink: sinkRejected, - data: `{"body":"data"}`, - error: true, - }, - } - for n, tc := range testCases { - t.Run(n, func(t *testing.T) { - - ce := kncetesting.NewTestClient() - - r := &mockReporter{} - a := &cronJobAdapter{ - Data: "data", - Reporter: r, - Client: ce, - } - - a.cronTick() - validateSent(t, ce, tc.data) - validateMetric(t, a.Reporter, 1) - }) - } -} - -func TestMessage(t *testing.T) { - testCases := map[string]struct { - body string - want string - }{ - "json simple": { - body: `{"message": "Hello world!"}`, - want: `{"message":"Hello world!"}`, - }, - "json complex": { - body: `{"message": "Hello world!","extra":{"a":"sub", "b":[1,2,3]}}`, - want: `{"extra":{"a":"sub","b":[1,2,3]},"message":"Hello world!"}`, - }, - "string": { - body: "Hello, World!", - want: `{"body":"Hello, World!"}`, - }, - } - for n, tc := range testCases { - t.Run(n, func(t *testing.T) { - - m := message(tc.body) - - j, err := json.Marshal(m) - if err != nil { - t.Errorf("failed to marshel message: %v", err) - } - - got := string(j) - if diff := cmp.Diff(tc.want, got); diff != "" { - t.Errorf("%s: (-want, +got) = %v", n, diff) - } - }) - } -} - -func sinkAccepted(writer http.ResponseWriter, req *http.Request) { - writer.WriteHeader(http.StatusOK) -} - -func sinkRejected(writer http.ResponseWriter, _ *http.Request) { - writer.WriteHeader(http.StatusRequestTimeout) -} - -func validateMetric(t *testing.T, reporter source.StatsReporter, want int) { - if mockReporter, ok := reporter.(*mockReporter); !ok { - t.Errorf("reporter is not a mockReporter") - } else if mockReporter.eventCount != want { - t.Errorf("Expected %d for metric, got %d", want, mockReporter.eventCount) - } -} - -func validateSent(t *testing.T, ce *kncetesting.TestCloudEventsClient, wantData string) { - if got := len(ce.Sent()); got != 1 { - t.Errorf("Expected 1 event to be sent, got %d", got) - } - - if got := ce.Sent()[0].Data; string(got.([]byte)) != wantData { - t.Errorf("Expected %q event to be sent, got %q", wantData, string(got.([]byte))) - } -} diff --git a/pkg/apis/eventing/v1alpha1/test_helper.go b/pkg/apis/eventing/v1alpha1/test_helper.go index 3324427c1f1..b395d52c562 100644 --- a/pkg/apis/eventing/v1alpha1/test_helper.go +++ b/pkg/apis/eventing/v1alpha1/test_helper.go @@ -18,7 +18,6 @@ package v1alpha1 import ( v1 "k8s.io/api/apps/v1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" "knative.dev/pkg/apis" pkgduckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" @@ -123,9 +122,3 @@ func (t testHelper) AvailableDeployment() *v1.Deployment { } return d } - -func (t testHelper) UnknownCronJobSourceStatus() *v1alpha1.CronJobSourceStatus { - cjss := &v1alpha1.CronJobSourceStatus{} - cjss.InitializeConditions() - return cjss -} diff --git a/pkg/apis/eventing/v1alpha1/trigger_validation_test.go b/pkg/apis/eventing/v1alpha1/trigger_validation_test.go index d73d53fe052..11f0839eeee 100644 --- a/pkg/apis/eventing/v1alpha1/trigger_validation_test.go +++ b/pkg/apis/eventing/v1alpha1/trigger_validation_test.go @@ -67,7 +67,6 @@ var ( }, } // Dependency annotation - validDependencyAnnotation = "{\"kind\":\"CronJobSource\",\"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}" invalidDependencyAnnotation = "invalid dependency annotation" dependencyAnnotationPath = fmt.Sprintf("metadata.annotations[%s]", DependencyAnnotation) // Create default broker annotation @@ -158,7 +157,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns-1", Annotations: map[string]string{ - DependencyAnnotation: "{\"kind\":\"CronJobSource\",\"namespace\":\"test-ns-2\", \"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}", + DependencyAnnotation: "{\"kind\":\"PingSource\",\"namespace\":\"test-ns-2\", \"name\":\"test-ping-source\",\"apiVersion\":\"sources.knative.dev/v1alpha1\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", @@ -176,7 +175,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns", Annotations: map[string]string{ - DependencyAnnotation: "{\"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}", + DependencyAnnotation: "{\"name\":\"test-ping-source\",\"apiVersion\":\"sources.knative.dev/v1alpha1\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", @@ -193,7 +192,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns", Annotations: map[string]string{ - DependencyAnnotation: "{\"kind\":\"CronJobSource\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}", + DependencyAnnotation: "{\"kind\":\"PingSource\",\"apiVersion\":\"sources.knative.dev/v1alpha1\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", @@ -210,7 +209,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns", Annotations: map[string]string{ - DependencyAnnotation: "{\"kind\":\"CronJobSource\",\"name\":\"test-cronjob-source\"}", + DependencyAnnotation: "{\"kind\":\"PingSource\",\"name\":\"test-ping-source\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", diff --git a/pkg/apis/eventing/v1beta1/trigger_validation_test.go b/pkg/apis/eventing/v1beta1/trigger_validation_test.go index 627112a7d69..bdb96b77d47 100644 --- a/pkg/apis/eventing/v1beta1/trigger_validation_test.go +++ b/pkg/apis/eventing/v1beta1/trigger_validation_test.go @@ -51,7 +51,6 @@ var ( }, } // Dependency annotation - validDependencyAnnotation = "{\"kind\":\"CronJobSource\",\"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}" invalidDependencyAnnotation = "invalid dependency annotation" dependencyAnnotationPath = fmt.Sprintf("metadata.annotations[%s]", DependencyAnnotation) // Create default broker annotation @@ -99,7 +98,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns-1", Annotations: map[string]string{ - DependencyAnnotation: "{\"kind\":\"CronJobSource\",\"namespace\":\"test-ns-2\", \"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}", + DependencyAnnotation: "{\"kind\":\"PingSource\",\"namespace\":\"test-ns-2\", \"name\":\"test-ping-source\",\"apiVersion\":\"sources.knative.dev/v1alpha1\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", @@ -117,7 +116,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns", Annotations: map[string]string{ - DependencyAnnotation: "{\"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}", + DependencyAnnotation: "{\"name\":\"test-ping-source\",\"apiVersion\":\"sources.knative.dev/v1alpha1\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", @@ -134,7 +133,7 @@ func TestTriggerValidation(t *testing.T) { ObjectMeta: v1.ObjectMeta{ Namespace: "test-ns", Annotations: map[string]string{ - DependencyAnnotation: "{\"kind\":\"CronJobSource\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}", + DependencyAnnotation: "{\"kind\":\"PingSource\",\"apiVersion\":\"sources.knative.dev/v1alpha1\"}", }}, Spec: TriggerSpec{ Broker: "test_broker", diff --git a/pkg/apis/legacysources/register.go b/pkg/apis/legacysources/register.go deleted file mode 100644 index 9483995420c..00000000000 --- a/pkg/apis/legacysources/register.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacysources - -const ( - GroupName = "sources.eventing.knative.dev" -) diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_defaults.go b/pkg/apis/legacysources/v1alpha1/apiserver_defaults.go deleted file mode 100644 index 18891cdb98f..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_defaults.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -func (s *ApiServerSource) SetDefaults(ctx context.Context) { - s.Spec.SetDefaults(ctx) -} - -func (ss *ApiServerSourceSpec) SetDefaults(ctx context.Context) { - // TODO anything? -} diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_defaults_test.go b/pkg/apis/legacysources/v1alpha1/apiserver_defaults_test.go deleted file mode 100644 index 66e19395405..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_defaults_test.go +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -// No-op test because method does nothing. -func TestAPIServerSourceDefaults(t *testing.T) { - s := ApiServerSource{} - s.SetDefaults(context.TODO()) -} diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle.go b/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle.go deleted file mode 100644 index d18d72eba9e..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - - "knative.dev/pkg/apis" - - "knative.dev/eventing/pkg/apis/duck" -) - -const ( - // ApiServerConditionReady has status True when the ApiServerSource is ready to send events. - ApiServerConditionReady = apis.ConditionReady - - // ApiServerConditionSinkProvided has status True when the ApiServerSource has been configured with a sink target. - ApiServerConditionSinkProvided apis.ConditionType = "SinkProvided" - - // ApiServerConditionDeployed has status True when the ApiServerSource has had it's deployment created. - ApiServerConditionDeployed apis.ConditionType = "Deployed" - - // ApiServerConditionSufficientPermissions has status True when the ApiServerSource has sufficient permissions to access resources. - ApiServerConditionSufficientPermissions apis.ConditionType = "SufficientPermissions" - - // ApiServerConditionEventTypeProvided has status True when the ApiServerSource has been configured with its event types. - ApiServerConditionEventTypeProvided apis.ConditionType = "EventTypesProvided" -) - -var apiserverCondSet = apis.NewLivingConditionSet( - ApiServerConditionSinkProvided, - ApiServerConditionDeployed, - ApiServerConditionSufficientPermissions, -) - -// GetCondition returns the condition currently associated with the given type, or nil. -func (s *ApiServerSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return apiserverCondSet.Manage(s).GetCondition(t) -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (s *ApiServerSourceStatus) InitializeConditions() { - apiserverCondSet.Manage(s).InitializeConditions() -} - -// MarkSink sets the condition that the source has a sink configured. -func (s *ApiServerSourceStatus) MarkSink(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSinkProvided) - } else { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkSinkWarnDeprecated sets the condition that the source has a sink configured and warns ref is deprecated. -func (s *ApiServerSourceStatus) MarkSinkWarnRefDeprecated(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - c := apis.Condition{ - Type: ApiServerConditionSinkProvided, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityError, - Message: "Using deprecated object ref fields when specifying spec.sink. Update to spec.sink.ref. These will be removed in the future.", - } - apiserverCondSet.Manage(s).SetCondition(c) - } else { - apiserverCondSet.Manage(s).MarkUnknown(ApiServerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkNoSink sets the condition that the source does not have a sink configured. -func (s *ApiServerSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSinkProvided, reason, messageFormat, messageA...) -} - -// PropagateDeploymentAvailability uses the availability of the provided Deployment to determine if -// ApiServerConditionDeployed should be marked as true or false. -func (s *ApiServerSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) { - if duck.DeploymentIsAvailable(&d.Status, false) { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionDeployed) - } else { - // I don't know how to propagate the status well, so just give the name of the Deployment - // for now. - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) - } -} - -// MarkEventTypes sets the condition that the source has set its event type. -func (s *ApiServerSourceStatus) MarkEventTypes() { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionEventTypeProvided) -} - -// MarkNoEventTypes sets the condition that the source does not its event type configured. -func (s *ApiServerSourceStatus) MarkNoEventTypes(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionEventTypeProvided, reason, messageFormat, messageA...) -} - -// MarkSufficientPermissions sets the condition that the source has enough permissions to access the resources. -func (s *ApiServerSourceStatus) MarkSufficientPermissions() { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSufficientPermissions) -} - -// MarkNoSufficientPermissions sets the condition that the source does not have enough permissions to access the resources -func (s *ApiServerSourceStatus) MarkNoSufficientPermissions(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSufficientPermissions, reason, messageFormat, messageA...) -} - -// IsReady returns true if the resource is ready overall. -func (s *ApiServerSourceStatus) IsReady() bool { - return apiserverCondSet.Manage(s).IsHappy() -} diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle_test.go b/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle_test.go deleted file mode 100644 index 852b332d5a4..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle_test.go +++ /dev/null @@ -1,250 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" -) - -var ( - availableDeployment = &appsv1.Deployment{ - Status: appsv1.DeploymentStatus{ - Conditions: []appsv1.DeploymentCondition{ - { - Type: appsv1.DeploymentAvailable, - Status: corev1.ConditionTrue, - }, - }, - }, - } -) - -func TestApiServerSourceStatusIsReady(t *testing.T) { - tests := []struct { - name string - s *ApiServerSourceStatus - want bool - }{{ - name: "uninitialized", - s: &ApiServerSourceStatus{}, - want: false, - }, { - name: "initialized", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - return s - }(), - want: false, - }, { - name: "mark deployed", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - want: false, - }, { - name: "mark sink", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - want: false, - }, { - name: "mark sufficient permissions", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSufficientPermissions() - return s - }(), - want: false, - }, { - name: "mark event types", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkEventTypes() - return s - }(), - want: false, - }, { - name: "mark sink and sufficient permissions and deployed", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkSufficientPermissions() - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - want: true, - }, { - name: "mark sink and sufficient permissions and deployed and event types", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkSufficientPermissions() - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkEventTypes() - return s - }(), - want: true, - }, { - name: "mark sink and not enough permissions", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkNoSufficientPermissions("areason", "amessage") - return s - }(), - want: false, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.IsReady() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("%s: unexpected condition (-want, +got) = %v", test.name, diff) - } - }) - } -} - -func TestApiServerSourceStatusGetCondition(t *testing.T) { - tests := []struct { - name string - s *ApiServerSourceStatus - condQuery apis.ConditionType - want *apis.Condition - }{{ - name: "uninitialized", - s: &ApiServerSourceStatus{}, - condQuery: ApiServerConditionReady, - want: nil, - }, { - name: "initialized", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - return s - }(), - condQuery: ApiServerConditionReady, - want: &apis.Condition{ - Type: ApiServerConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark deployed", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - condQuery: ApiServerConditionReady, - want: &apis.Condition{ - Type: ApiServerConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark sink", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - condQuery: ApiServerConditionReady, - want: &apis.Condition{ - Type: ApiServerConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark sink and enough permissions and deployed", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkSufficientPermissions() - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - condQuery: ApiServerConditionReady, - want: &apis.Condition{ - Type: ApiServerConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark sink and enough permissions and deployed and event types", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkSufficientPermissions() - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkEventTypes() - return s - }(), - condQuery: ApiServerConditionReady, - want: &apis.Condition{ - Type: ApiServerConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark sink empty and enough permissions and deployed and event types", - s: func() *ApiServerSourceStatus { - s := &ApiServerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkSufficientPermissions() - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkEventTypes() - return s - }(), - condQuery: ApiServerConditionReady, - want: &apis.Condition{ - Type: ApiServerConditionReady, - Status: corev1.ConditionFalse, - Reason: "SinkEmpty", - Message: "Sink has resolved to empty.", - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.GetCondition(test.condQuery) - ignoreTime := cmpopts.IgnoreFields(apis.Condition{}, - "LastTransitionTime", "Severity") - if diff := cmp.Diff(test.want, got, ignoreTime); diff != "" { - t.Errorf("unexpected condition (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_types.go b/pkg/apis/legacysources/v1alpha1/apiserver_types.go deleted file mode 100644 index 34232838dbe..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_types.go +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright 2019 The Knative 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" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ApiServerSource is the Schema for the apiserversources API -type ApiServerSource struct { - // Deprecated allows ApiServerSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ApiServerSourceSpec `json:"spec,omitempty"` - Status ApiServerSourceStatus `json:"status,omitempty"` -} - -var ( - // Check that we can create OwnerReferences to an ApiServerSource. - _ kmeta.OwnerRefable = (*ApiServerSource)(nil) - - // Check that ApiServerSource can return its spec untyped. - _ apis.HasSpec = (*ApiServerSource)(nil) -) - -const ( - // ApiServerSourceAddEventType is the ApiServerSource CloudEvent type for adds. - ApiServerSourceAddEventType = "dev.knative.apiserver.resource.add" - // ApiServerSourceUpdateEventType is the ApiServerSource CloudEvent type for updates. - ApiServerSourceUpdateEventType = "dev.knative.apiserver.resource.update" - // ApiServerSourceDeleteEventType is the ApiServerSource CloudEvent type for deletions. - ApiServerSourceDeleteEventType = "dev.knative.apiserver.resource.delete" - - // ApiServerSourceAddRefEventType is the ApiServerSource CloudEvent type for ref adds. - ApiServerSourceAddRefEventType = "dev.knative.apiserver.ref.add" - // ApiServerSourceUpdateRefEventType is the ApiServerSource CloudEvent type for ref updates. - ApiServerSourceUpdateRefEventType = "dev.knative.apiserver.ref.update" - // ApiServerSourceDeleteRefEventType is the ApiServerSource CloudEvent type for ref deletions. - ApiServerSourceDeleteRefEventType = "dev.knative.apiserver.ref.delete" -) - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *ApiServerSource) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("ApiServerSource") -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ApiServerSourceList contains a list of ApiServerSource -type ApiServerSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []ApiServerSource `json:"items"` -} - -// ApiServerSourceSpec defines the desired state of ApiServerSource -type ApiServerSourceSpec struct { - // Resources is the list of resources to watch - Resources []ApiServerResource `json:"resources"` - - // ServiceAccountName is the name of the ServiceAccount to use to run this - // source. - // +optional - ServiceAccountName string `json:"serviceAccountName,omitempty"` - - // Sink is a reference to an object that will resolve to a domain name to use as the sink. - // +optional - Sink *duckv1beta1.Destination `json:"sink,omitempty"` - - // Mode is the mode the receive adapter controller runs under: Ref or Resource. - // `Ref` sends only the reference to the resource. - // `Resource` send the full resource. - Mode string `json:"mode,omitempty"` -} - -// ApiServerSourceStatus defines the observed state of ApiServerSource -type ApiServerSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the ApiServerSource. - // +optional - SinkURI string `json:"sinkUri,omitempty"` -} - -// ApiServerResource defines the resource to watch -type ApiServerResource struct { - // API version of the resource to watch. - APIVersion string `json:"apiVersion"` - - // Kind of the resource to watch. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - Kind string `json:"kind"` - - // LabelSelector restricts this source to objects with the selected labels - // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - LabelSelector metav1.LabelSelector `json:"labelSelector"` - - // ControllerSelector restricts this source to objects with a controlling owner reference of the specified kind. - // Only apiVersion and kind are used. Both are optional. - ControllerSelector metav1.OwnerReference `json:"controllerSelector"` - - // If true, send an event referencing the object controlling the resource - Controller bool `json:"controller"` -} - -// GetUntypedSpec returns the spec of the ApiServerSource. -func (a *ApiServerSource) GetUntypedSpec() interface{} { - return a.Spec -} diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_validation.go b/pkg/apis/legacysources/v1alpha1/apiserver_validation.go deleted file mode 100644 index 0987c190765..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_validation.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -const ( - // RefMode produces payloads of ObjectReference - RefMode = "Ref" - // ResourceMode produces payloads of ResourceEvent - ResourceMode = "Resource" -) - -func (c *ApiServerSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") -} - -func (cs *ApiServerSourceSpec) Validate(ctx context.Context) *apis.FieldError { - var errs *apis.FieldError - - // Validate mode, if can be empty or set as certain value - if cs.Mode != "" && cs.Mode != RefMode && cs.Mode != ResourceMode { - fe := &apis.FieldError{ - Message: "Mode is not valid", - Paths: []string{"mode"}, - } - errs = errs.Also(fe) - } - - // Validate sink - if cs.Sink == nil { - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - } else if fe := cs.Sink.Validate(ctx); fe != nil { - errs = errs.Also(fe.ViaField("sink")) - } - return errs -} diff --git a/pkg/apis/legacysources/v1alpha1/apiserver_validation_test.go b/pkg/apis/legacysources/v1alpha1/apiserver_validation_test.go deleted file mode 100644 index 87b00cb556a..00000000000 --- a/pkg/apis/legacysources/v1alpha1/apiserver_validation_test.go +++ /dev/null @@ -1,98 +0,0 @@ -/* -Copyright 2019 The Knative 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" - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" -) - -func TestAPIServerValidation(t *testing.T) { - tests := []struct { - name string - spec ApiServerSourceSpec - want *apis.FieldError - }{{ - name: "valid spec", - spec: ApiServerSourceSpec{ - Mode: "Resource", - Resources: []ApiServerResource{ - {}, - }, - Sink: &duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - APIVersion: "v1alpha1", - Kind: "broker", - Name: "default", - }, - }, - }, - want: nil, - }, { - name: "empty sink", - spec: ApiServerSourceSpec{ - Mode: "Resource", - Resources: []ApiServerResource{ - {}, - }, - }, - want: func() *apis.FieldError { - var errs *apis.FieldError - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - return errs - }(), - }, { - name: "invalid mode", - spec: ApiServerSourceSpec{ - Mode: "Test", - Resources: []ApiServerResource{ - {}, - }, - Sink: &duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - APIVersion: "v1alpha1", - Kind: "broker", - Name: "default", - }, - }, - }, - want: func() *apis.FieldError { - var errs *apis.FieldError - fe := &apis.FieldError{ - Message: "Mode is not valid", - Paths: []string{"mode"}, - } - errs = errs.Also(fe) - return errs - }(), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.spec.Validate(context.TODO()) - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("APIServerSourceSpec.Validate (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_defaults.go b/pkg/apis/legacysources/v1alpha1/containersource_defaults.go deleted file mode 100644 index d9918e38971..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_defaults.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -func (s *ContainerSource) SetDefaults(ctx context.Context) { - s.Spec.SetDefaults(ctx) -} - -func (ss *ContainerSourceSpec) SetDefaults(ctx context.Context) { - // TODO anything? -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_defaults_test.go b/pkg/apis/legacysources/v1alpha1/containersource_defaults_test.go deleted file mode 100644 index 7d1816a7f10..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_defaults_test.go +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -// No-op test because method does nothing. -func TestContainerSourceDefaults(t *testing.T) { - s := ContainerSource{} - s.SetDefaults(context.TODO()) -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_lifecycle.go b/pkg/apis/legacysources/v1alpha1/containersource_lifecycle.go deleted file mode 100644 index efe7d7ef499..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_lifecycle.go +++ /dev/null @@ -1,109 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" -) - -const ( - // ContainerSourceConditionReady has status True when the ContainerSource is ready to send events. - ContainerConditionReady = apis.ConditionReady - - // ContainerConditionSinkProvided has status True when the ContainerSource has been configured with a sink target. - ContainerConditionSinkProvided apis.ConditionType = "SinkProvided" - - // ContainerConditionDeployed has status True when the ContainerSource has had it's deployment created. - ContainerConditionDeployed apis.ConditionType = "Deployed" -) - -var containerCondSet = apis.NewLivingConditionSet( - ContainerConditionSinkProvided, - ContainerConditionDeployed, -) - -// GetCondition returns the condition currently associated with the given type, or nil. -func (s *ContainerSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return containerCondSet.Manage(s).GetCondition(t) -} - -// IsReady returns true if the resource is ready overall. -func (s *ContainerSourceStatus) IsReady() bool { - return containerCondSet.Manage(s).IsHappy() -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (s *ContainerSourceStatus) InitializeConditions() { - containerCondSet.Manage(s).InitializeConditions() -} - -// MarkSink sets the condition that the source has a sink configured. -func (s *ContainerSourceStatus) MarkSink(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - containerCondSet.Manage(s).MarkTrue(ContainerConditionSinkProvided) - } else { - containerCondSet.Manage(s).MarkFalse(ContainerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkSinkWarnDeprecated sets the condition that the source has a sink configured and warns ref is deprecated. -func (s *ContainerSourceStatus) MarkSinkWarnRefDeprecated(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - c := apis.Condition{ - Type: ContainerConditionSinkProvided, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityError, - Message: "Using deprecated object ref fields when specifying spec.sink. Update to spec.sink.ref. These will be removed in the future.", - } - apiserverCondSet.Manage(s).SetCondition(c) - } else { - apiserverCondSet.Manage(s).MarkUnknown(ContainerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkNoSink sets the condition that the source does not have a sink configured. -func (s *ContainerSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { - containerCondSet.Manage(s).MarkFalse(ContainerConditionSinkProvided, reason, messageFormat, messageA...) -} - -// IsDeployed returns true if the Deployed condition has status true, otherwise -// false. -func (s *ContainerSourceStatus) IsDeployed() bool { - c := containerCondSet.Manage(s).GetCondition(ContainerConditionDeployed) - if c != nil { - return c.IsTrue() - } - return false -} - -// MarkDeployed sets the condition that the source has been deployed. -func (s *ContainerSourceStatus) MarkDeployed() { - containerCondSet.Manage(s).MarkTrue(ContainerConditionDeployed) -} - -// MarkDeploying sets the condition that the source is deploying. -func (s *ContainerSourceStatus) MarkDeploying(reason, messageFormat string, messageA ...interface{}) { - containerCondSet.Manage(s).MarkUnknown(ContainerConditionDeployed, reason, messageFormat, messageA...) -} - -// MarkNotDeployed sets the condition that the source has not been deployed. -func (s *ContainerSourceStatus) MarkNotDeployed(reason, messageFormat string, messageA ...interface{}) { - containerCondSet.Manage(s).MarkFalse(ContainerConditionDeployed, reason, messageFormat, messageA...) -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_lifecycle_test.go b/pkg/apis/legacysources/v1alpha1/containersource_lifecycle_test.go deleted file mode 100644 index 6c43667dd13..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_lifecycle_test.go +++ /dev/null @@ -1,448 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - "testing" - - "github.com/google/go-cmp/cmp/cmpopts" - - "github.com/google/go-cmp/cmp" - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" -) - -func TestContainerSourceStatusIsReady(t *testing.T) { - tests := []struct { - name string - s *ContainerSourceStatus - want bool - }{{ - name: "uninitialized", - s: &ContainerSourceStatus{}, - want: false, - }, { - name: "initialized", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - return s - }(), - want: false, - }, { - name: "mark deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkDeployed() - return s - }(), - want: false, - }, { - name: "mark sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - want: false, - }, { - name: "mark sink and deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - return s - }(), - want: true, - }, { - name: "mark sink and deployed then no sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkNoSink("Testing", "") - return s - }(), - want: false, - }, { - name: "mark sink and deployed then deploying", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkDeploying("Testing", "") - return s - }(), - want: false, - }, { - name: "mark sink and deployed then not deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkNotDeployed("Testing", "") - return s - }(), - want: false, - }, { - name: "mark sink and not deployed then deploying then deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkNotDeployed("MarkNotDeployed", "") - s.MarkDeploying("MarkDeploying", "") - s.MarkDeployed() - return s - }(), - want: true, - }, { - name: "mark sink empty and deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkDeployed() - return s - }(), - want: false, - }, { - name: "mark sink empty and deployed then sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkDeployed() - s.MarkSink("uri://example") - return s - }(), - want: true, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.IsReady() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("%s: unexpected condition (-want, +got) = %v", test.name, diff) - } - }) - } -} - -func TestContainerSourceStatusGetCondition(t *testing.T) { - tests := []struct { - name string - s *ContainerSourceStatus - condQuery apis.ConditionType - want *apis.Condition - }{{ - name: "uninitialized", - s: &ContainerSourceStatus{}, - condQuery: ContainerConditionReady, - want: nil, - }, { - name: "initialized", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkDeployed() - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark sink and deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark sink and deployed then no sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkNoSink("Testing", "hi%s", "") - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionFalse, - Reason: "Testing", - Message: "hi", - }, - }, { - name: "mark sink and deployed then deploying", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkDeploying("Testing", "hi%s", "") - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionUnknown, - Reason: "Testing", - Message: "hi", - }, - }, { - name: "mark sink and deployed then not deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkNotDeployed("Testing", "hi%s", "") - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionFalse, - Reason: "Testing", - Message: "hi", - }, - }, { - name: "mark sink and not deployed then deploying then deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkNotDeployed("MarkNotDeployed", "%s", "") - s.MarkDeploying("MarkDeploying", "%s", "") - s.MarkDeployed() - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark sink empty and deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkDeployed() - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionFalse, - Reason: "SinkEmpty", - Message: "Sink has resolved to empty.", - }, - }, { - name: "mark sink empty and deployed then sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkDeployed() - s.MarkSink("uri://example") - return s - }(), - condQuery: ContainerConditionReady, - want: &apis.Condition{ - Type: ContainerConditionReady, - Status: corev1.ConditionTrue, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.GetCondition(test.condQuery) - ignoreTime := cmpopts.IgnoreFields(apis.Condition{}, - "LastTransitionTime", "Severity") - if diff := cmp.Diff(test.want, got, ignoreTime); diff != "" { - t.Errorf("unexpected condition (-want, +got) = %v", diff) - } - }) - } -} - -func TestContainerSourceStatusIsDeployed(t *testing.T) { - tests := []struct { - name string - s *ContainerSourceStatus - want bool - }{{ - name: "uninitialized", - s: &ContainerSourceStatus{}, - want: false, - }, { - name: "initialized", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - return s - }(), - want: false, - }, { - name: "mark deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkDeployed() - return s - }(), - want: true, - }, { - name: "mark sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - want: false, - }, { - name: "mark sink and deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - return s - }(), - want: true, - }, { - name: "mark sink and deployed then no sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkNoSink("Testing", "") - return s - }(), - want: true, - }, { - name: "mark sink and deployed then deploying", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkDeploying("Testing", "") - return s - }(), - want: false, - }, { - name: "mark sink and deployed then not deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkDeployed() - s.MarkNotDeployed("Testing", "") - return s - }(), - want: false, - }, { - name: "mark sink and not deployed then deploying then deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.MarkNotDeployed("MarkNotDeployed", "") - s.MarkDeploying("MarkDeploying", "") - s.MarkDeployed() - return s - }(), - want: true, - }, { - name: "mark sink empty and deployed", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkDeployed() - return s - }(), - want: true, - }, { - name: "mark sink empty and deployed then sink", - s: func() *ContainerSourceStatus { - s := &ContainerSourceStatus{} - s.InitializeConditions() - s.MarkSink("") - s.MarkDeployed() - s.MarkSink("uri://example") - return s - }(), - want: true, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.IsDeployed() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("%s: unexpected condition (-want, +got) = %v", test.name, diff) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_types.go b/pkg/apis/legacysources/v1alpha1/containersource_types.go deleted file mode 100644 index 1b010984049..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_types.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// ContainerSource is the Schema for the containersources API -type ContainerSource struct { - // Deprecated allows ContainerSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ContainerSourceSpec `json:"spec,omitempty"` - Status ContainerSourceStatus `json:"status,omitempty"` -} - -var ( - _ runtime.Object = (*ContainerSource)(nil) - - // Check that we can create OwnerReferences to a ContainerSource. - _ kmeta.OwnerRefable = (*ContainerSource)(nil) - - // Check that ContainerSource can return its spec untyped. - _ apis.HasSpec = (*ContainerSource)(nil) -) - -// ContainerSourceSpec defines the desired state of ContainerSource -type ContainerSourceSpec struct { - // Template describes the pods that will be created - // +optional - Template *corev1.PodTemplateSpec `json:"template,omitempty"` - - // DeprecatedImage is the image to run inside of the container. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - // +kubebuilder:validation:MinLength=1 - DeprecatedImage string `json:"image,omitempty"` - - // DeprecatedArgs are passed to the ContainerSpec as they are. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - DeprecatedArgs []string `json:"args,omitempty"` - - // DeprecatedEnv is the list of environment variables to set in the container. - // Cannot be updated. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - // +optional - // +patchMergeKey=name - // +patchStrategy=merge - DeprecatedEnv []corev1.EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - - // DeprecatedServiceAccountName is the name of the ServiceAccount to use to run this - // source. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - // +optional - DeprecatedServiceAccountName string `json:"serviceAccountName,omitempty"` - - // Sink is a reference to an object that will resolve to a domain name to use as the sink. - Sink *duckv1beta1.Destination `json:"sink,omitempty"` -} - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *ContainerSource) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("ContainerSource") -} - -// ContainerSourceStatus defines the observed state of ContainerSource -type ContainerSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the ContainerSource. - // +optional - SinkURI string `json:"sinkUri,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ContainerSourceList contains a list of ContainerSource -type ContainerSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []ContainerSource `json:"items"` -} - -// GetUntypedSpec returns the spec of the ContainerSource. -func (c *ContainerSource) GetUntypedSpec() interface{} { - return c.Spec -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_validation.go b/pkg/apis/legacysources/v1alpha1/containersource_validation.go deleted file mode 100644 index 5d4f9c6d7c2..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_validation.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -func (c *ContainerSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") -} - -func (cs *ContainerSourceSpec) Validate(ctx context.Context) *apis.FieldError { - var errs *apis.FieldError - if cs.Sink == nil { - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - } else if fe := cs.Sink.Validate(ctx); fe != nil { - errs = errs.Also(fe.ViaField("sink")) - } - return errs -} diff --git a/pkg/apis/legacysources/v1alpha1/containersource_validation_test.go b/pkg/apis/legacysources/v1alpha1/containersource_validation_test.go deleted file mode 100644 index d9c3f0e8ad3..00000000000 --- a/pkg/apis/legacysources/v1alpha1/containersource_validation_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2019 The Knative 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" - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" -) - -func TestContainerSourceValidation(t *testing.T) { - tests := []struct { - name string - spec ContainerSourceSpec - want *apis.FieldError - }{{ - name: "valid spec", - spec: ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{}, - Sink: &duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - APIVersion: "v1alpha1", - Kind: "broker", - Name: "default", - }, - }, - }, - want: nil, - }, { - name: "empty sink", - spec: ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{}, - }, - want: func() *apis.FieldError { - var errs *apis.FieldError - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - return errs - }(), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.spec.Validate(context.TODO()) - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("ContainerSourceSpec.Validate (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_defaults.go b/pkg/apis/legacysources/v1alpha1/cron_job_defaults.go deleted file mode 100644 index 25a58dbf19d..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_defaults.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -func (s *CronJobSource) SetDefaults(ctx context.Context) { - s.Spec.SetDefaults(ctx) -} - -func (ss *CronJobSourceSpec) SetDefaults(ctx context.Context) { - // TODO anything? -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_defaults_test.go b/pkg/apis/legacysources/v1alpha1/cron_job_defaults_test.go deleted file mode 100644 index 4ee9ec07ef9..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_defaults_test.go +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -// No-op test because method does nothing. -func TestCronJobSourceDefaults(t *testing.T) { - s := CronJobSource{} - s.SetDefaults(context.TODO()) -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle.go b/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle.go deleted file mode 100644 index 319c738cc48..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle.go +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - - "knative.dev/pkg/apis" - - "knative.dev/eventing/pkg/apis/duck" -) - -const ( - // CronJobConditionReady has status True when the CronJobSource is ready to send events. - CronJobConditionReady = apis.ConditionReady - - // CronJobConditionValidSchedule has status True when the CronJobSource has been configured with a valid schedule. - CronJobConditionValidSchedule apis.ConditionType = "ValidSchedule" - - // CronJobConditionSinkProvided has status True when the CronJobSource has been configured with a sink target. - CronJobConditionSinkProvided apis.ConditionType = "SinkProvided" - - // CronJobConditionDeployed has status True when the CronJobSource has had it's receive adapter deployment created. - CronJobConditionDeployed apis.ConditionType = "Deployed" - - // CronJobConditionEventTypeProvided has status True when the CronJobSource has been configured with its event type. - CronJobConditionEventTypeProvided apis.ConditionType = "EventTypeProvided" - - // CronJobConditionResources is True when the resources listed for the CronJobSource have been properly - // parsed and match specified syntax for resource quantities - CronJobConditionResources apis.ConditionType = "ResourcesCorrect" -) - -var cronJobSourceCondSet = apis.NewLivingConditionSet( - CronJobConditionValidSchedule, - CronJobConditionSinkProvided, - CronJobConditionDeployed) - -// GetCondition returns the condition currently associated with the given type, or nil. -func (s *CronJobSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return cronJobSourceCondSet.Manage(s).GetCondition(t) -} - -// IsReady returns true if the resource is ready overall. -func (s *CronJobSourceStatus) IsReady() bool { - return cronJobSourceCondSet.Manage(s).IsHappy() -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (s *CronJobSourceStatus) InitializeConditions() { - cronJobSourceCondSet.Manage(s).InitializeConditions() -} - -// TODO: this is a bad method name, change it. -// MarkSchedule sets the condition that the source has a valid schedule configured. -func (s *CronJobSourceStatus) MarkSchedule() { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionValidSchedule) -} - -// MarkInvalidSchedule sets the condition that the source does not have a valid schedule configured. -func (s *CronJobSourceStatus) MarkInvalidSchedule(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionValidSchedule, reason, messageFormat, messageA...) -} - -// MarkSink sets the condition that the source has a sink configured. -func (s *CronJobSourceStatus) MarkSink(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionSinkProvided) - } else { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkSinkWarnDeprecated sets the condition that the source has a sink configured and warns ref is deprecated. -func (s *CronJobSourceStatus) MarkSinkWarnRefDeprecated(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - c := apis.Condition{ - Type: CronJobConditionSinkProvided, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityError, - Message: "Using deprecated object ref fields when specifying spec.sink. Update to spec.sink.ref. These will be removed in the future.", - } - apiserverCondSet.Manage(s).SetCondition(c) - } else { - apiserverCondSet.Manage(s).MarkUnknown(CronJobConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkNoSink sets the condition that the source does not have a sink configured. -func (s *CronJobSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionSinkProvided, reason, messageFormat, messageA...) -} - -// PropagateDeploymentAvailability uses the availability of the provided Deployment to determine if -// CronJobConditionDeployed should be marked as true or false. -func (s *CronJobSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) { - if duck.DeploymentIsAvailable(&d.Status, false) { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionDeployed) - } else { - // I don't know how to propagate the status well, so just give the name of the Deployment - // for now. - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) - } -} - -// MarkEventType sets the condition that the source has set its event type. -func (s *CronJobSourceStatus) MarkEventType() { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionEventTypeProvided) -} - -// MarkNoEventType sets the condition that the source does not its event type configured. -func (s *CronJobSourceStatus) MarkNoEventType(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionEventTypeProvided, reason, messageFormat, messageA...) -} - -// MarkResourcesCorrect sets the condition that the source resources are properly parsable quantities -func (s *CronJobSourceStatus) MarkResourcesCorrect() { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionResources) -} - -// MarkResourcesIncorrect sets the condition that the source resources are not properly parsable quantities -func (s *CronJobSourceStatus) MarkResourcesIncorrect(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionResources, reason, messageFormat, messageA...) -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle_test.go b/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle_test.go deleted file mode 100644 index 358d85c202e..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle_test.go +++ /dev/null @@ -1,426 +0,0 @@ -/* -Copyright 2019 The Knative 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" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/pkg/apis" -) - -var ( - availableDeployment = &appsv1.Deployment{ - Status: appsv1.DeploymentStatus{ - Conditions: []appsv1.DeploymentCondition{ - { - Type: appsv1.DeploymentAvailable, - Status: corev1.ConditionTrue, - }, - }, - }, - } -) - -func TestCronJobSourceStatusIsReady(t *testing.T) { - tests := []struct { - name string - s *v1alpha1.CronJobSourceStatus - want bool - }{{ - name: "uninitialized", - s: &v1alpha1.CronJobSourceStatus{}, - want: false, - }, { - name: "initialized", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - return s - }(), - want: false, - }, { - name: "mark deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - want: false, - }, { - name: "mark sink", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - want: false, - }, { - name: "mark schedule", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - return s - }(), - want: false, - }, { - name: "mark event types", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkEventType() - return s - }(), - want: false, - }, { - name: "mark sink and deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - want: false, - }, { - name: "mark schedule and sink", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - return s - }(), - want: false, - }, { - name: "mark schedule, sink and deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - want: true, - }, { - name: "mark schedule, sink, deployed, and event types", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkEventType() - return s - }(), - want: true, - }, { - name: "mark schedule, sink and deployed then not deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.PropagateDeploymentAvailability(&appsv1.Deployment{}) - return s - }(), - want: false, - }, { - name: "mark schedule, sink, deployed and event types then no event types", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkNoEventType("Testing", "") - return s - }(), - want: true, - }, { - name: "mark schedule validated, sink empty and deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("") - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - want: false, - }, { - name: "mark schedule validated, sink empty and deployed then sink", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkSink("uri://example") - return s - }(), - want: true, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.IsReady() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("%s: unexpected condition (-want, +got) = %v", test.name, diff) - } - }) - } -} - -func TestCronJobSourceStatusGetCondition(t *testing.T) { - tests := []struct { - name string - s *v1alpha1.CronJobSourceStatus - condQuery apis.ConditionType - want *apis.Condition - }{{ - name: "uninitialized", - s: &v1alpha1.CronJobSourceStatus{}, - condQuery: v1alpha1.CronJobConditionReady, - want: nil, - }, { - name: "initialized", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark sink", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSink("uri://example") - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark schedule", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionUnknown, - }, - }, { - name: "mark schedule, sink and deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark schedule, sink, deployed, and event types", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkEventType() - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark schedule, sink and deployed then no sink", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkNoSink("Testing", "hi%s", "") - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionFalse, - Reason: "Testing", - Message: "hi", - }, - }, { - name: "mark schedule, sink and deployed then invalid schedule", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkInvalidSchedule("Testing", "hi%s", "") - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionFalse, - Reason: "Testing", - Message: "hi", - }, - }, { - name: "mark schedule, sink and deployed then deploying", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.PropagateDeploymentAvailability(&appsv1.Deployment{}) - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionFalse, - Reason: "DeploymentUnavailable", - Message: "The Deployment '' is unavailable.", - }, - }, { - name: "mark schedule, sink and deployed then not deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.PropagateDeploymentAvailability(&appsv1.Deployment{}) - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionFalse, - Reason: "DeploymentUnavailable", - Message: "The Deployment '' is unavailable.", - }, - }, { - name: "mark schedule, sink, deployed and event types, then no event types", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("uri://example") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkEventType() - s.MarkNoEventType("Testing", "hi") - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionTrue, - }, - }, { - name: "mark schedule, sink empty and deployed", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("") - s.PropagateDeploymentAvailability(availableDeployment) - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionFalse, - Reason: "SinkEmpty", - Message: "Sink has resolved to empty.", - }, - }, { - name: "mark schedule, sink empty and deployed then sink", - s: func() *v1alpha1.CronJobSourceStatus { - s := &v1alpha1.CronJobSourceStatus{} - s.InitializeConditions() - s.MarkSchedule() - s.MarkSink("") - s.PropagateDeploymentAvailability(availableDeployment) - s.MarkSink("uri://example") - return s - }(), - condQuery: v1alpha1.CronJobConditionReady, - want: &apis.Condition{ - Type: v1alpha1.CronJobConditionReady, - Status: corev1.ConditionTrue, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.GetCondition(test.condQuery) - ignoreTime := cmpopts.IgnoreFields(apis.Condition{}, - "LastTransitionTime", "Severity") - if diff := cmp.Diff(test.want, got, ignoreTime); diff != "" { - t.Errorf("unexpected condition (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_types.go b/pkg/apis/legacysources/v1alpha1/cron_job_types.go deleted file mode 100644 index 510a145c931..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_types.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2019 The Knative 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" - - "knative.dev/pkg/apis" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// CronJobSource is the Schema for the cronjobsources API. -type CronJobSource struct { - // Deprecated allows CronJobSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec CronJobSourceSpec `json:"spec,omitempty"` - Status CronJobSourceStatus `json:"status,omitempty"` -} - -// TODO: Check that CronJobSource can be validated and can be defaulted. - -var ( - // Check that it is a runtime object. - _ runtime.Object = (*CronJobSource)(nil) - - // Check that we can create OwnerReferences to a CronJobSource. - _ kmeta.OwnerRefable = (*CronJobSource)(nil) - - // Check that CronJobSource can return its spec untyped. - _ apis.HasSpec = (*CronJobSource)(nil) -) - -const ( - // CronJobEventType is the CronJob CloudEvent type. - CronJobEventType = "dev.knative.cronjob.event" -) - -// CronJobEventSource returns the CronJob CloudEvent source. -func CronJobEventSource(namespace, cronJobName string) string { - return fmt.Sprintf("/apis/v1/namespaces/%s/cronjobsources/%s", namespace, cronJobName) -} - -type CronJobRequestsSpec struct { - ResourceCPU string `json:"cpu,omitempty"` - ResourceMemory string `json:"memory,omitempty"` -} - -type CronJobLimitsSpec struct { - ResourceCPU string `json:"cpu,omitempty"` - ResourceMemory string `json:"memory,omitempty"` -} - -type CronJobResourceSpec struct { - Requests CronJobRequestsSpec `json:"requests,omitempty"` - Limits CronJobLimitsSpec `json:"limits,omitempty"` -} - -// CronJobSourceSpec defines the desired state of the CronJobSource. -type CronJobSourceSpec struct { - // Schedule is the cronjob schedule. - // +required - Schedule string `json:"schedule"` - - // Data is the data posted to the target function. - Data string `json:"data,omitempty"` - - // Sink is a reference to an object that will resolve to a domain name to use as the sink. - Sink *duckv1beta1.Destination `json:"sink,omitempty"` - - // ServiceAccoutName is the name of the ServiceAccount that will be used to run the Receive - // Adapter Deployment. - ServiceAccountName string `json:"serviceAccountName,omitempty"` - - // Resource limits and Request specifications of the Receive Adapter Deployment - Resources CronJobResourceSpec `json:"resources,omitempty"` -} - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *CronJobSource) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("CronJobSource") -} - -// CronJobSourceStatus defines the observed state of CronJobSource. -type CronJobSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the CronJobSource. - // +optional - SinkURI string `json:"sinkUri,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// CronJobSourceList contains a list of CronJobSources. -type CronJobSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []CronJobSource `json:"items"` -} - -// GetUntypedSpec returns the spec of the CronJobSource. -func (c *CronJobSource) GetUntypedSpec() interface{} { - return c.Spec -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_types_test.go b/pkg/apis/legacysources/v1alpha1/cron_job_types_test.go deleted file mode 100644 index 521c6f238bc..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_types_test.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2019 The Knative 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 "testing" - -func TestCronJobSource_GetGroupVersionKind(t *testing.T) { - src := CronJobSource{} - gvk := src.GetGroupVersionKind() - - if gvk.Kind != "CronJobSource" { - t.Errorf("Should be CronJobSource.") - } -} - -func TestCronJobSource_CronJobEventSource(t *testing.T) { - ceCronJobSource := CronJobEventSource("ns1", "job1") - - if ceCronJobSource != "/apis/v1/namespaces/ns1/cronjobsources/job1" { - t.Errorf("Should be '/apis/v1/namespaces/ns1/cronjobsources/job1'") - } -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_validation.go b/pkg/apis/legacysources/v1alpha1/cron_job_validation.go deleted file mode 100644 index d268f53193e..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_validation.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2019 The Knative 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/robfig/cron" - "knative.dev/pkg/apis" -) - -func (c *CronJobSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") -} - -func (cs *CronJobSourceSpec) Validate(ctx context.Context) *apis.FieldError { - var errs *apis.FieldError - - if _, err := cron.ParseStandard(cs.Schedule); err != nil { - fe := apis.ErrInvalidValue(cs.Schedule, "schedule") - errs = errs.Also(fe) - } - - if cs.Sink == nil { - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - } else if fe := cs.Sink.Validate(ctx); fe != nil { - errs = errs.Also(fe.ViaField("sink")) - } - return errs -} diff --git a/pkg/apis/legacysources/v1alpha1/cron_job_validation_test.go b/pkg/apis/legacysources/v1alpha1/cron_job_validation_test.go deleted file mode 100644 index dd376ebd3ff..00000000000 --- a/pkg/apis/legacysources/v1alpha1/cron_job_validation_test.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2019 The Knative 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" - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" -) - -func TestCronJobSourceValidation(t *testing.T) { - tests := []struct { - name string - spec CronJobSourceSpec - want *apis.FieldError - }{{ - name: "valid spec", - spec: CronJobSourceSpec{ - Schedule: "*/2 * * * *", - Sink: &duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - APIVersion: "v1alpha1", - Kind: "broker", - Name: "default", - }, - }, - }, - want: nil, - }, { - name: "empty sink", - spec: CronJobSourceSpec{ - Schedule: "*/2 * * * *", - }, - want: func() *apis.FieldError { - var errs *apis.FieldError - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - return errs - }(), - }, { - name: "invalid schedule", - spec: CronJobSourceSpec{ - Schedule: "2", - Sink: &duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - APIVersion: "v1alpha1", - Kind: "broker", - Name: "default", - }, - }, - }, - want: func() *apis.FieldError { - var errs *apis.FieldError - fe := apis.ErrInvalidValue("2", "schedule") - errs = errs.Also(fe) - return errs - }(), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.spec.Validate(context.TODO()) - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("ContainerSourceSpec.Validate (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/deprecated.go b/pkg/apis/legacysources/v1alpha1/deprecated.go deleted file mode 100644 index 145570bb131..00000000000 --- a/pkg/apis/legacysources/v1alpha1/deprecated.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "time" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -const ( - // StatusConditionTypeDeprecated is the status.conditions.type used to provide deprecation - // warnings. - StatusConditionTypeDeprecated = "Deprecated" -) - -type Deprecated struct{} - -// MarkDeprecated adds a warning condition that this object's spec is using deprecated fields -// and will stop working in the future. -func (d *Deprecated) MarkDeprecated(s *duckv1.Status, reason, msg string) { - dc := apis.Condition{ - Type: StatusConditionTypeDeprecated, - Reason: reason, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityWarning, - Message: msg, - LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Now())}, - } - for i, c := range s.Conditions { - if c.Type == dc.Type { - s.Conditions[i] = dc - return - } - } - s.Conditions = append(s.Conditions, dc) -} diff --git a/pkg/apis/legacysources/v1alpha1/deprecated_test.go b/pkg/apis/legacysources/v1alpha1/deprecated_test.go deleted file mode 100644 index 8a7fd7fe7c4..00000000000 --- a/pkg/apis/legacysources/v1alpha1/deprecated_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2020 The Knative 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" - - corev1 "k8s.io/api/core/v1" - duckv1 "knative.dev/pkg/apis/duck/v1" - - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -func TestMarkDeprecated_empty(t *testing.T) { - s := &duckv1.Status{} - d := &v1alpha1.Deprecated{} - - d.MarkDeprecated(s, "Dep", "unit test") - - ds := s.GetCondition(v1alpha1.StatusConditionTypeDeprecated) - if ds == nil { - t.Errorf("Expected to get a Deprecated type condition, but found none.") - return - } - if ds.Status != corev1.ConditionTrue { - t.Errorf("Expected Deprecated status to be true, got %s.", ds.Status) - } - if ds.Reason != "Dep" { - t.Errorf("Expected Deprecated reason to be 'Dep', got %s.", ds.Reason) - } - if ds.Message != "unit test" { - t.Errorf("Expected Deprecated message to be 'unit test', got %s.", ds.Message) - } -} - -func TestMarkDeprecated_set(t *testing.T) { - s := &duckv1.Status{} - d := &v1alpha1.Deprecated{} - - d.MarkDeprecated(s, "Pre", "prefill") - d.MarkDeprecated(s, "Dep", "unit test") - - ds := s.GetCondition(v1alpha1.StatusConditionTypeDeprecated) - if ds == nil { - t.Errorf("Expected to get a Deprecated type condition, but found none.") - return - } - if ds.Status != corev1.ConditionTrue { - t.Errorf("Expected Deprecated status to be true, got %s.", ds.Status) - } - if ds.Reason != "Dep" { - t.Errorf("Expected Deprecated reason to be 'Dep', got %s.", ds.Reason) - } - if ds.Message != "unit test" { - t.Errorf("Expected Deprecated message to be 'unit test', got %s.", ds.Message) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/doc.go b/pkg/apis/legacysources/v1alpha1/doc.go deleted file mode 100644 index 7d7f6738fbc..00000000000 --- a/pkg/apis/legacysources/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2019 The Knative 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 contains API Schema definitions for the sources v1alpha1 API group -// +k8s:deepcopy-gen=package -// +groupName=sources.eventing.knative.dev -package v1alpha1 diff --git a/pkg/apis/legacysources/v1alpha1/implements_test.go b/pkg/apis/legacysources/v1alpha1/implements_test.go deleted file mode 100644 index ff80f4095f5..00000000000 --- a/pkg/apis/legacysources/v1alpha1/implements_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - "testing" - - "knative.dev/pkg/apis/duck" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" -) - -func TestTypesImplements(t *testing.T) { - testCases := []struct { - instance interface{} - iface duck.Implementable - }{ - // CronJobSource - {instance: &CronJobSource{}, iface: &duckv1.Conditions{}}, - // ContainerSource - {instance: &ContainerSource{}, iface: &duckv1.Conditions{}}, - // SinkBinding - {instance: &SinkBinding{}, iface: &duckv1.Conditions{}}, - {instance: &SinkBinding{}, iface: &duckv1beta1.Source{}}, - {instance: &SinkBinding{}, iface: &duckv1alpha1.Binding{}}, - } - for _, tc := range testCases { - if err := duck.VerifyType(tc.instance, tc.iface); err != nil { - t.Error(err) - } - } -} diff --git a/pkg/apis/legacysources/v1alpha1/register.go b/pkg/apis/legacysources/v1alpha1/register.go deleted file mode 100644 index a1affadb401..00000000000 --- a/pkg/apis/legacysources/v1alpha1/register.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - "knative.dev/eventing/pkg/apis/legacysources" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: legacysources.GroupName, Version: "v1alpha1"} - -// Kind takes an unqualified kind and returns back a Group qualified GroupKind -func Kind(kind string) schema.GroupKind { - return SchemeGroupVersion.WithKind(kind).GroupKind() -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -// Adds the list of known types to Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &CronJobSource{}, - &CronJobSourceList{}, - &ContainerSource{}, - &ContainerSourceList{}, - &ApiServerSource{}, - &ApiServerSourceList{}, - &SinkBinding{}, - &SinkBindingList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/pkg/apis/legacysources/v1alpha1/register_test.go b/pkg/apis/legacysources/v1alpha1/register_test.go deleted file mode 100644 index 19055cf4a66..00000000000 --- a/pkg/apis/legacysources/v1alpha1/register_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2019 The Knative 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 ( - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - - "github.com/google/go-cmp/cmp" -) - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func TestResource(t *testing.T) { - want := schema.GroupResource{ - Group: "sources.eventing.knative.dev", - Resource: "foo", - } - - got := Resource("foo") - - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("unexpected resource (-want, +got) = %v", diff) - } -} - -// Kind takes an unqualified resource and returns a Group qualified GroupKind -func TestKind(t *testing.T) { - want := schema.GroupKind{ - Group: "sources.eventing.knative.dev", - Kind: "kind", - } - - got := Kind("kind") - - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("unexpected resource (-want, +got) = %v", diff) - } -} - -// TestKnownTypes makes sure that expected types get added. -func TestKnownTypes(t *testing.T) { - scheme := runtime.NewScheme() - addKnownTypes(scheme) - types := scheme.KnownTypes(SchemeGroupVersion) - - for _, name := range []string{ - "CronJobSource", - "CronJobSourceList", - "ContainerSource", - "ContainerSourceList", - "ApiServerSource", - "ApiServerSourceList", - } { - if _, ok := types[name]; !ok { - t.Errorf("Did not find %q as registered type", name) - } - } - -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_context.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_context.go deleted file mode 100644 index 420807fcd59..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_context.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -// sinkURIKey is used as the key for associating information -// with a context.Context. -type sinkURIKey struct{} - -// WithSinkURI notes on the context for binding that the resolved SinkURI -// is the provided apis.URL. -func WithSinkURI(ctx context.Context, uri *apis.URL) context.Context { - return context.WithValue(ctx, sinkURIKey{}, uri) -} - -// GetSinkURI accesses the apis.URL for the Sink URI that has been associated -// with this context. -func GetSinkURI(ctx context.Context) *apis.URL { - value := ctx.Value(sinkURIKey{}) - if value == nil { - return nil - } - return value.(*apis.URL) -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_context_test.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_context_test.go deleted file mode 100644 index 5ff2c85e457..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_context_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2019 The Knative 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" - - "knative.dev/pkg/apis" -) - -func TestGetSinkURI(t *testing.T) { - ctx := context.Background() - - if uri := GetSinkURI(ctx); uri != nil { - t.Errorf("GetSinkURI() = %v, wanted nil", uri) - } - - want := &apis.URL{ - Scheme: "https", - Host: "knobots.io", - Path: "/omg/a/path", - } - ctx = WithSinkURI(ctx, want) - - if got := GetSinkURI(ctx); got != want { - t.Errorf("GetSinkURI() = %v, wanted %v", got, want) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults.go deleted file mode 100644 index fc006ec1418..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -// SetDefaults implements apis.Defaultable -func (fb *SinkBinding) SetDefaults(ctx context.Context) { - withNS := apis.WithinParent(ctx, fb.ObjectMeta) - fb.Spec.Sink.SetDefaults(withNS) - if fb.Spec.Subject.Namespace == "" { - // Default the subject's namespace to our namespace. - fb.Spec.Subject.Namespace = fb.Namespace - } -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults_test.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults_test.go deleted file mode 100644 index 95b8fe9b8f6..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults_test.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2019 The Knative 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" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - "knative.dev/pkg/tracker" -) - -func TestSinkBindingDefaulting(t *testing.T) { - tests := []struct { - name string - in *SinkBinding - want *SinkBinding - }{{ - name: "namespace is defaulted", - in: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{ - Ref: &duckv1.KReference{ - APIVersion: "serving.knative.dev/v1", - Kind: "Service", - Name: "gemma", - }, - }, - }, - }, - }, - want: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - // This is filled in by defaulting. - Namespace: "moore", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{ - Ref: &duckv1.KReference{ - APIVersion: "serving.knative.dev/v1", - Kind: "Service", - Name: "gemma", - // This is filled in by defaulting. - Namespace: "moore", - }, - }, - }, - }, - }, - }, { - name: "no ref, given namespace", - in: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - Namespace: "lorefice", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{ - URI: &apis.URL{ - Scheme: "http", - Host: "moore.dev", - }, - }, - }, - }, - }, - want: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - Namespace: "lorefice", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{ - URI: &apis.URL{ - Scheme: "http", - Host: "moore.dev", - }, - }, - }, - }, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.in - got.SetDefaults(context.Background()) - if !cmp.Equal(test.want, got) { - t.Errorf("SetDefaults (-want, +got) = %v", cmp.Diff(test.want, got)) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle.go deleted file mode 100644 index 283730d7a06..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2019 The Knative 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" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/eventing/pkg/logging" - "knative.dev/pkg/apis" - "knative.dev/pkg/apis/duck" - duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/pkg/tracker" -) - -var sbCondSet = apis.NewLivingConditionSet() - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *SinkBinding) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("SinkBinding") -} - -// GetUntypedSpec implements apis.HasSpec -func (c *SinkBinding) GetUntypedSpec() interface{} { - return c.Spec -} - -// GetSubject implements psbinding.Bindable -func (fb *SinkBinding) GetSubject() tracker.Reference { - return fb.Spec.Subject -} - -// GetBindingStatus implements psbinding.Bindable -func (fb *SinkBinding) GetBindingStatus() duck.BindableStatus { - return &fb.Status -} - -// SetObservedGeneration implements psbinding.BindableStatus -func (fbs *SinkBindingStatus) SetObservedGeneration(gen int64) { - fbs.ObservedGeneration = gen -} - -// InitializeConditions populates the SinkBindingStatus's conditions field -// with all of its conditions configured to Unknown. -func (fbs *SinkBindingStatus) InitializeConditions() { - sbCondSet.Manage(fbs).InitializeConditions() -} - -// MarkBindingUnavailable marks the SinkBinding's Ready condition to False with -// the provided reason and message. -func (fbs *SinkBindingStatus) MarkBindingUnavailable(reason, message string) { - sbCondSet.Manage(fbs).MarkFalse(SinkBindingConditionReady, reason, message) -} - -// MarkBindingAvailable marks the SinkBinding's Ready condition to True. -func (fbs *SinkBindingStatus) MarkBindingAvailable() { - sbCondSet.Manage(fbs).MarkTrue(SinkBindingConditionReady) -} - -// Do implements psbinding.Bindable -func (fb *SinkBinding) Do(ctx context.Context, ps *duckv1.WithPod) { - fb.MarkDeprecated(&fb.Status.Status, "SinkBindingDeprecated", "sinkbindings.sources.eventing.knative.dev are deprecated and will be removed in the future. Use sinkbindings.sources.knative.dev instead.") - - // First undo so that we can just unconditionally append below. - fb.Undo(ctx, ps) - - uri := GetSinkURI(ctx) - if uri == nil { - logging.FromContext(ctx).Error(fmt.Sprintf("No sink URI associated with context for %+v", fb)) - return - } - - spec := ps.Spec.Template.Spec - for i := range spec.InitContainers { - spec.InitContainers[i].Env = append(spec.InitContainers[i].Env, corev1.EnvVar{ - Name: "K_SINK", - Value: uri.String(), - }) - } - for i := range spec.Containers { - spec.Containers[i].Env = append(spec.Containers[i].Env, corev1.EnvVar{ - Name: "K_SINK", - Value: uri.String(), - }) - } -} - -func (fb *SinkBinding) Undo(ctx context.Context, ps *duckv1.WithPod) { - spec := ps.Spec.Template.Spec - for i, c := range spec.InitContainers { - for j, ev := range c.Env { - if ev.Name == "K_SINK" { - spec.InitContainers[i].Env = append(spec.InitContainers[i].Env[:j], spec.InitContainers[i].Env[j+1:]...) - break - } - } - } - for i, c := range spec.Containers { - for j, ev := range c.Env { - if ev.Name == "K_SINK" { - spec.Containers[i].Env = append(spec.Containers[i].Env[:j], spec.Containers[i].Env[j+1:]...) - break - } - } - } -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle_test.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle_test.go deleted file mode 100644 index 8c4986a0e1b..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle_test.go +++ /dev/null @@ -1,460 +0,0 @@ -/* -Copyright 2019 The Knative 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" - "reflect" - "testing" - - "github.com/google/go-cmp/cmp" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - "knative.dev/pkg/tracker" -) - -func TestSinkBindingGetGroupVersionKind(t *testing.T) { - r := &SinkBinding{} - want := schema.GroupVersionKind{ - Group: "sources.eventing.knative.dev", - Version: "v1alpha1", - Kind: "SinkBinding", - } - if got := r.GetGroupVersionKind(); got != want { - t.Errorf("got: %v, want: %v", got, want) - } -} - -func TestSinkBindingGetters(t *testing.T) { - r := &SinkBinding{ - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "foo", - }, - }, - }, - } - if got, want := r.GetUntypedSpec(), r.Spec; !reflect.DeepEqual(got, want) { - t.Errorf("GetUntypedSpec() = %v, want: %v", got, want) - } - if got, want := r.GetSubject(), r.Spec.Subject; !reflect.DeepEqual(got, want) { - t.Errorf("GetSubject() = %v, want: %v", got, want) - } - if got, want := r.GetBindingStatus(), &r.Status; !reflect.DeepEqual(got, want) { - t.Errorf("GetBindingStatus() = %v, want: %v", got, want) - } -} - -func TestSinkBindingSetObsGen(t *testing.T) { - r := &SinkBinding{ - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "foo", - }, - }, - }, - } - want := int64(3762) - r.GetBindingStatus().SetObservedGeneration(want) - if got := r.Status.ObservedGeneration; got != want { - t.Errorf("SetObservedGeneration() = %d, wanted %d", got, want) - } -} - -func TestSinkBindingStatusIsReady(t *testing.T) { - tests := []struct { - name string - s *SinkBindingStatus - want bool - }{{ - name: "uninitialized", - s: &SinkBindingStatus{}, - want: false, - }, { - name: "initialized", - s: func() *SinkBindingStatus { - s := &SinkBindingStatus{} - s.InitializeConditions() - return s - }(), - want: false, - }, { - name: "mark available", - s: func() *SinkBindingStatus { - s := &SinkBindingStatus{} - s.InitializeConditions() - s.MarkBindingUnavailable("TheReason", "this is the message") - return s - }(), - want: false, - }, { - name: "mark available", - s: func() *SinkBindingStatus { - s := &SinkBindingStatus{} - s.InitializeConditions() - s.MarkBindingAvailable() - return s - }(), - want: true, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.IsReady() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("%s: unexpected condition (-want, +got) = %v", test.name, diff) - } - }) - } -} - -func TestSinkBindingUndo(t *testing.T) { - tests := []struct { - name string - in *duckv1.WithPod - want *duckv1.WithPod - }{{ - name: "nothing to remove", - in: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - }}, - }, - }, - }, - }, - want: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - }}, - }, - }, - }, - }, - }, { - name: "lots to remove", - in: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - InitContainers: []corev1.Container{{ - Name: "setup", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: "http://localhost:8080", - }}, - }}, - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "FOO", - Value: "BAR", - }, { - Name: "K_SINK", - Value: "http://localhost:8080", - }, { - Name: "BAZ", - Value: "INGA", - }}, - }, { - Name: "sidecar", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: "http://localhost:8080", - }, { - Name: "BAZ", - Value: "INGA", - }}, - }}, - }, - }, - }, - }, - want: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - InitContainers: []corev1.Container{{ - Name: "setup", - Image: "busybox", - Env: []corev1.EnvVar{}, - }}, - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "FOO", - Value: "BAR", - }, { - Name: "BAZ", - Value: "INGA", - }}, - }, { - Name: "sidecar", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "BAZ", - Value: "INGA", - }}, - }}, - }, - }, - }, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.in - sb := &SinkBinding{} - sb.Undo(context.Background(), got) - - if !cmp.Equal(got, test.want) { - t.Errorf("Undo (-want, +got): %s", cmp.Diff(test.want, got)) - } - }) - } -} - -func TestSinkBindingDo(t *testing.T) { - sinkURI := &apis.URL{ - Scheme: "http", - Host: "thing.ns.svc.cluster.local", - Path: "/a/path", - } - - tests := []struct { - name string - in *duckv1.WithPod - want *duckv1.WithPod - }{{ - name: "nothing to add", - in: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: sinkURI.String(), - }}, - }}, - }, - }, - }, - }, - want: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: sinkURI.String(), - }}, - }}, - }, - }, - }, - }, - }, { - name: "fix the URI", - in: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: "the wrong value", - }}, - }}, - }, - }, - }, - }, - want: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: sinkURI.String(), - }}, - }}, - }, - }, - }, - }, - }, { - name: "lots of uris", - in: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - InitContainers: []corev1.Container{{ - Name: "setup", - Image: "busybox", - }}, - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "FOO", - Value: "BAR", - }, { - Name: "BAZ", - Value: "INGA", - }}, - }, { - Name: "sidecar", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "BAZ", - Value: "INGA", - }}, - }}, - }, - }, - }, - }, - want: &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - InitContainers: []corev1.Container{{ - Name: "setup", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: sinkURI.String(), - }}, - }}, - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "FOO", - Value: "BAR", - }, { - Name: "BAZ", - Value: "INGA", - }, { - Name: "K_SINK", - Value: sinkURI.String(), - }}, - }, { - Name: "sidecar", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "BAZ", - Value: "INGA", - }, { - Name: "K_SINK", - Value: sinkURI.String(), - }}, - }}, - }, - }, - }, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.in - - ctx := WithSinkURI(context.Background(), sinkURI) - - sb := &SinkBinding{} - sb.Do(ctx, got) - - dep := sb.Status.GetCondition(StatusConditionTypeDeprecated) - if dep == nil { - t.Errorf("expected Deprecated type condition to be set, found nil") - } - - if !cmp.Equal(got, test.want) { - t.Errorf("Undo (-want, +got): %s", cmp.Diff(test.want, got)) - } - }) - } -} - -func TestSinkBindingDoNoURI(t *testing.T) { - want := &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{}, - }}, - }, - }, - }, - } - got := &duckv1.WithPod{ - Spec: duckv1.WithPodSpec{ - Template: duckv1.PodSpecable{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "blah", - Image: "busybox", - Env: []corev1.EnvVar{{ - Name: "K_SINK", - Value: "this should be removed", - }}, - }}, - }, - }, - }, - } - - sb := &SinkBinding{} - sb.Do(context.Background(), got) - - if !cmp.Equal(got, want) { - t.Errorf("Undo (-want, +got): %s", cmp.Diff(want, got)) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_types.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_types.go deleted file mode 100644 index b9a1f0eafa2..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_types.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2019 The Knative 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" - "k8s.io/apimachinery/pkg/runtime" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// SinkBinding describes a Binding that is also a Source. -// The `sink` (from the Source duck) is resolved to a URL and -// then projected into the `subject` by augmenting the runtime -// contract of the referenced containers to have a `K_SINK` -// environment variable holding the endpoint to which to send -// cloud events. -type SinkBinding struct { - // Deprecated allows ApiServerSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec SinkBindingSpec `json:"spec"` - Status SinkBindingStatus `json:"status"` -} - -// Check the interfaces that SinkBinding should be implementing. -var ( - _ runtime.Object = (*SinkBinding)(nil) - _ kmeta.OwnerRefable = (*SinkBinding)(nil) - _ apis.Validatable = (*SinkBinding)(nil) - _ apis.Defaultable = (*SinkBinding)(nil) - _ apis.HasSpec = (*SinkBinding)(nil) -) - -// SinkBindingSpec holds the desired state of the SinkBinding (from the client). -type SinkBindingSpec struct { - duckv1.SourceSpec `json:",inline"` - duckv1alpha1.BindingSpec `json:",inline"` -} - -const ( - // SinkBindingConditionReady is configured to indicate whether the Binding - // has been configured for resources subject to its runtime contract. - SinkBindingConditionReady = apis.ConditionReady -) - -// SinkBindingStatus communicates the observed state of the SinkBinding (from the controller). -type SinkBindingStatus struct { - duckv1.SourceStatus `json:",inline"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// SinkBindingList contains a list of SinkBinding -type SinkBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []SinkBinding `json:"items"` -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_validation.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_validation.go deleted file mode 100644 index e76f18abe7b..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_validation.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2019 The Knative 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" -) - -// Validate implements apis.Validatable -func (fb *SinkBinding) Validate(ctx context.Context) *apis.FieldError { - err := fb.Spec.Validate(ctx).ViaField("spec") - if fb.Spec.Subject.Namespace != "" && fb.Namespace != fb.Spec.Subject.Namespace { - err = err.Also(apis.ErrInvalidValue(fb.Spec.Subject.Namespace, "spec.subject.namespace")) - } - return err -} - -// Validate implements apis.Validatable -func (fbs *SinkBindingSpec) Validate(ctx context.Context) *apis.FieldError { - return fbs.Subject.Validate(ctx).ViaField("subject").Also( - fbs.Sink.Validate(ctx).ViaField("sink")) -} diff --git a/pkg/apis/legacysources/v1alpha1/sinkbinding_validation_test.go b/pkg/apis/legacysources/v1alpha1/sinkbinding_validation_test.go deleted file mode 100644 index 38d8142afab..00000000000 --- a/pkg/apis/legacysources/v1alpha1/sinkbinding_validation_test.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2019 The Knative 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" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - "knative.dev/pkg/tracker" -) - -func TestSinkBindingValidation(t *testing.T) { - tests := []struct { - name string - in *SinkBinding - want *apis.FieldError - }{{ - name: "missing subject namespace", - in: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{ - Ref: &duckv1.KReference{ - APIVersion: "serving.knative.dev/v1", - Kind: "Service", - Name: "gemma", - Namespace: "namespace", - }, - }, - }, - }, - }, - want: apis.ErrMissingField("spec.subject.namespace"), - }, { - name: "invalid subject namespace", - in: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - Namespace: "lorefice", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{ - Ref: &duckv1.KReference{ - APIVersion: "serving.knative.dev/v1", - Kind: "Service", - Name: "gemma", - Namespace: "namespace", - }, - }, - }, - }, - }, - want: apis.ErrInvalidValue("lorefice", "spec.subject.namespace"), - }, { - name: "missing sink information", - in: &SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "matt", - Namespace: "moore", - }, - Spec: SinkBindingSpec{ - BindingSpec: duckv1alpha1.BindingSpec{ - Subject: tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Name: "jeanne", - Namespace: "moore", - }, - }, - SourceSpec: duckv1.SourceSpec{ - Sink: duckv1.Destination{}, - }, - }, - }, - want: apis.ErrGeneric("expected at least one, got none", "spec.sink.ref", "spec.sink.uri"), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.in.Validate(context.Background()) - if (test.want != nil) != (got != nil) { - t.Errorf("Validation() = %v, wanted %v", got, test.want) - } else if test.want != nil && test.want.Error() != got.Error() { - t.Errorf("Validation() = %v, wanted %v", got, test.want) - } - }) - } -} diff --git a/pkg/apis/legacysources/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/legacysources/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 8167839f555..00000000000 --- a/pkg/apis/legacysources/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,533 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2020 The Knative 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 deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1 "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - v1beta1 "knative.dev/pkg/apis/duck/v1beta1" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerResource) DeepCopyInto(out *ApiServerResource) { - *out = *in - in.LabelSelector.DeepCopyInto(&out.LabelSelector) - in.ControllerSelector.DeepCopyInto(&out.ControllerSelector) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerResource. -func (in *ApiServerResource) DeepCopy() *ApiServerResource { - if in == nil { - return nil - } - out := new(ApiServerResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerSource) DeepCopyInto(out *ApiServerSource) { - *out = *in - out.Deprecated = in.Deprecated - 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 ApiServerSource. -func (in *ApiServerSource) DeepCopy() *ApiServerSource { - if in == nil { - return nil - } - out := new(ApiServerSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ApiServerSource) 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 *ApiServerSourceList) DeepCopyInto(out *ApiServerSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ApiServerSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceList. -func (in *ApiServerSourceList) DeepCopy() *ApiServerSourceList { - if in == nil { - return nil - } - out := new(ApiServerSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ApiServerSourceList) 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 *ApiServerSourceSpec) DeepCopyInto(out *ApiServerSourceSpec) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]ApiServerResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Sink != nil { - in, out := &in.Sink, &out.Sink - *out = new(v1beta1.Destination) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceSpec. -func (in *ApiServerSourceSpec) DeepCopy() *ApiServerSourceSpec { - if in == nil { - return nil - } - out := new(ApiServerSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerSourceStatus) DeepCopyInto(out *ApiServerSourceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceStatus. -func (in *ApiServerSourceStatus) DeepCopy() *ApiServerSourceStatus { - if in == nil { - return nil - } - out := new(ApiServerSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerSource) DeepCopyInto(out *ContainerSource) { - *out = *in - out.Deprecated = in.Deprecated - 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 ContainerSource. -func (in *ContainerSource) DeepCopy() *ContainerSource { - if in == nil { - return nil - } - out := new(ContainerSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ContainerSource) 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 *ContainerSourceList) DeepCopyInto(out *ContainerSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ContainerSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceList. -func (in *ContainerSourceList) DeepCopy() *ContainerSourceList { - if in == nil { - return nil - } - out := new(ContainerSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ContainerSourceList) 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 *ContainerSourceSpec) DeepCopyInto(out *ContainerSourceSpec) { - *out = *in - if in.Template != nil { - in, out := &in.Template, &out.Template - *out = new(v1.PodTemplateSpec) - (*in).DeepCopyInto(*out) - } - if in.DeprecatedArgs != nil { - in, out := &in.DeprecatedArgs, &out.DeprecatedArgs - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.DeprecatedEnv != nil { - in, out := &in.DeprecatedEnv, &out.DeprecatedEnv - *out = make([]v1.EnvVar, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Sink != nil { - in, out := &in.Sink, &out.Sink - *out = new(v1beta1.Destination) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceSpec. -func (in *ContainerSourceSpec) DeepCopy() *ContainerSourceSpec { - if in == nil { - return nil - } - out := new(ContainerSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerSourceStatus) DeepCopyInto(out *ContainerSourceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceStatus. -func (in *ContainerSourceStatus) DeepCopy() *ContainerSourceStatus { - if in == nil { - return nil - } - out := new(ContainerSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobLimitsSpec) DeepCopyInto(out *CronJobLimitsSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobLimitsSpec. -func (in *CronJobLimitsSpec) DeepCopy() *CronJobLimitsSpec { - if in == nil { - return nil - } - out := new(CronJobLimitsSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobRequestsSpec) DeepCopyInto(out *CronJobRequestsSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobRequestsSpec. -func (in *CronJobRequestsSpec) DeepCopy() *CronJobRequestsSpec { - if in == nil { - return nil - } - out := new(CronJobRequestsSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobResourceSpec) DeepCopyInto(out *CronJobResourceSpec) { - *out = *in - out.Requests = in.Requests - out.Limits = in.Limits - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobResourceSpec. -func (in *CronJobResourceSpec) DeepCopy() *CronJobResourceSpec { - if in == nil { - return nil - } - out := new(CronJobResourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobSource) DeepCopyInto(out *CronJobSource) { - *out = *in - out.Deprecated = in.Deprecated - 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 CronJobSource. -func (in *CronJobSource) DeepCopy() *CronJobSource { - if in == nil { - return nil - } - out := new(CronJobSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CronJobSource) 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 *CronJobSourceList) DeepCopyInto(out *CronJobSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]CronJobSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSourceList. -func (in *CronJobSourceList) DeepCopy() *CronJobSourceList { - if in == nil { - return nil - } - out := new(CronJobSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CronJobSourceList) 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 *CronJobSourceSpec) DeepCopyInto(out *CronJobSourceSpec) { - *out = *in - if in.Sink != nil { - in, out := &in.Sink, &out.Sink - *out = new(v1beta1.Destination) - (*in).DeepCopyInto(*out) - } - out.Resources = in.Resources - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSourceSpec. -func (in *CronJobSourceSpec) DeepCopy() *CronJobSourceSpec { - if in == nil { - return nil - } - out := new(CronJobSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobSourceStatus) DeepCopyInto(out *CronJobSourceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSourceStatus. -func (in *CronJobSourceStatus) DeepCopy() *CronJobSourceStatus { - if in == nil { - return nil - } - out := new(CronJobSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Deprecated) DeepCopyInto(out *Deprecated) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Deprecated. -func (in *Deprecated) DeepCopy() *Deprecated { - if in == nil { - return nil - } - out := new(Deprecated) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkBinding) DeepCopyInto(out *SinkBinding) { - *out = *in - out.Deprecated = in.Deprecated - 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 SinkBinding. -func (in *SinkBinding) DeepCopy() *SinkBinding { - if in == nil { - return nil - } - out := new(SinkBinding) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SinkBinding) 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 *SinkBindingList) DeepCopyInto(out *SinkBindingList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]SinkBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBindingList. -func (in *SinkBindingList) DeepCopy() *SinkBindingList { - if in == nil { - return nil - } - out := new(SinkBindingList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SinkBindingList) 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 *SinkBindingSpec) DeepCopyInto(out *SinkBindingSpec) { - *out = *in - in.SourceSpec.DeepCopyInto(&out.SourceSpec) - in.BindingSpec.DeepCopyInto(&out.BindingSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBindingSpec. -func (in *SinkBindingSpec) DeepCopy() *SinkBindingSpec { - if in == nil { - return nil - } - out := new(SinkBindingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkBindingStatus) DeepCopyInto(out *SinkBindingStatus) { - *out = *in - in.SourceStatus.DeepCopyInto(&out.SourceStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBindingStatus. -func (in *SinkBindingStatus) DeepCopy() *SinkBindingStatus { - if in == nil { - return nil - } - out := new(SinkBindingStatus) - in.DeepCopyInto(out) - return out -} diff --git a/pkg/legacyclient/clientset/versioned/clientset.go b/pkg/legacyclient/clientset/versioned/clientset.go deleted file mode 100644 index dd80148e8e6..00000000000 --- a/pkg/legacyclient/clientset/versioned/clientset.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2020 The Knative 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 versioned - -import ( - "fmt" - - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" - sourcesv1alpha1 "knative.dev/eventing/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - SourcesV1alpha1() sourcesv1alpha1.SourcesV1alpha1Interface -} - -// Clientset contains the clients for groups. Each group has exactly one -// version included in a Clientset. -type Clientset struct { - *discovery.DiscoveryClient - sourcesV1alpha1 *sourcesv1alpha1.SourcesV1alpha1Client -} - -// SourcesV1alpha1 retrieves the SourcesV1alpha1Client -func (c *Clientset) SourcesV1alpha1() sourcesv1alpha1.SourcesV1alpha1Interface { - return c.sourcesV1alpha1 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - var cs Clientset - var err error - cs.sourcesV1alpha1, err = sourcesv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.sourcesV1alpha1 = sourcesv1alpha1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.sourcesV1alpha1 = sourcesv1alpha1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/pkg/legacyclient/clientset/versioned/doc.go b/pkg/legacyclient/clientset/versioned/doc.go deleted file mode 100644 index e48c2aa4460..00000000000 --- a/pkg/legacyclient/clientset/versioned/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative 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. - -// This package has the automatically generated clientset. -package versioned diff --git a/pkg/legacyclient/clientset/versioned/fake/clientset_generated.go b/pkg/legacyclient/clientset/versioned/fake/clientset_generated.go deleted file mode 100644 index e132eb842e6..00000000000 --- a/pkg/legacyclient/clientset/versioned/fake/clientset_generated.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/discovery" - fakediscovery "k8s.io/client-go/discovery/fake" - "k8s.io/client-go/testing" - clientset "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - sourcesv1alpha1 "knative.dev/eventing/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1" - fakesourcesv1alpha1 "knative.dev/eventing/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake" -) - -// NewSimpleClientset returns a clientset that will respond with the provided objects. -// It's backed by a very simple object tracker that processes creates, updates and deletions as-is, -// without applying any validations and/or defaults. It shouldn't be considered a replacement -// for a real clientset and is mostly useful in simple unit tests. -func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - cs := &Clientset{tracker: o} - cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} - cs.AddReactor("*", "*", testing.ObjectReaction(o)) - cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { - gvr := action.GetResource() - ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns) - if err != nil { - return false, nil, err - } - return true, watch, nil - }) - - return cs -} - -// Clientset implements clientset.Interface. Meant to be embedded into a -// struct to get a default implementation. This makes faking out just the method -// you want to test easier. -type Clientset struct { - testing.Fake - discovery *fakediscovery.FakeDiscovery - tracker testing.ObjectTracker -} - -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - return c.discovery -} - -func (c *Clientset) Tracker() testing.ObjectTracker { - return c.tracker -} - -var _ clientset.Interface = &Clientset{} - -// SourcesV1alpha1 retrieves the SourcesV1alpha1Client -func (c *Clientset) SourcesV1alpha1() sourcesv1alpha1.SourcesV1alpha1Interface { - return &fakesourcesv1alpha1.FakeSourcesV1alpha1{Fake: &c.Fake} -} diff --git a/pkg/legacyclient/clientset/versioned/fake/doc.go b/pkg/legacyclient/clientset/versioned/fake/doc.go deleted file mode 100644 index 2c4903250c4..00000000000 --- a/pkg/legacyclient/clientset/versioned/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative 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. - -// This package has the automatically generated fake clientset. -package fake diff --git a/pkg/legacyclient/clientset/versioned/fake/register.go b/pkg/legacyclient/clientset/versioned/fake/register.go deleted file mode 100644 index 55da1bc184d..00000000000 --- a/pkg/legacyclient/clientset/versioned/fake/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -var scheme = runtime.NewScheme() -var codecs = serializer.NewCodecFactory(scheme) -var parameterCodec = runtime.NewParameterCodec(scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - sourcesv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(scheme)) -} diff --git a/pkg/legacyclient/clientset/versioned/scheme/doc.go b/pkg/legacyclient/clientset/versioned/scheme/doc.go deleted file mode 100644 index 7acc2dcf252..00000000000 --- a/pkg/legacyclient/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative 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. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/pkg/legacyclient/clientset/versioned/scheme/register.go b/pkg/legacyclient/clientset/versioned/scheme/register.go deleted file mode 100644 index 0ddcfe7b67c..00000000000 --- a/pkg/legacyclient/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Knative 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 scheme - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - sourcesv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/apiserversource.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/apiserversource.go deleted file mode 100644 index f337d69f589..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/apiserversource.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "time" - - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - scheme "knative.dev/eventing/pkg/legacyclient/clientset/versioned/scheme" -) - -// ApiServerSourcesGetter has a method to return a ApiServerSourceInterface. -// A group's client should implement this interface. -type ApiServerSourcesGetter interface { - ApiServerSources(namespace string) ApiServerSourceInterface -} - -// ApiServerSourceInterface has methods to work with ApiServerSource resources. -type ApiServerSourceInterface interface { - Create(*v1alpha1.ApiServerSource) (*v1alpha1.ApiServerSource, error) - Update(*v1alpha1.ApiServerSource) (*v1alpha1.ApiServerSource, error) - UpdateStatus(*v1alpha1.ApiServerSource) (*v1alpha1.ApiServerSource, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ApiServerSource, error) - List(opts v1.ListOptions) (*v1alpha1.ApiServerSourceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ApiServerSource, err error) - ApiServerSourceExpansion -} - -// apiServerSources implements ApiServerSourceInterface -type apiServerSources struct { - client rest.Interface - ns string -} - -// newApiServerSources returns a ApiServerSources -func newApiServerSources(c *SourcesV1alpha1Client, namespace string) *apiServerSources { - return &apiServerSources{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the apiServerSource, and returns the corresponding apiServerSource object, and an error if there is any. -func (c *apiServerSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ApiServerSource, err error) { - result = &v1alpha1.ApiServerSource{} - err = c.client.Get(). - Namespace(c.ns). - Resource("apiserversources"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ApiServerSources that match those selectors. -func (c *apiServerSources) List(opts v1.ListOptions) (result *v1alpha1.ApiServerSourceList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.ApiServerSourceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("apiserversources"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested apiServerSources. -func (c *apiServerSources) Watch(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("apiserversources"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch() -} - -// Create takes the representation of a apiServerSource and creates it. Returns the server's representation of the apiServerSource, and an error, if there is any. -func (c *apiServerSources) Create(apiServerSource *v1alpha1.ApiServerSource) (result *v1alpha1.ApiServerSource, err error) { - result = &v1alpha1.ApiServerSource{} - err = c.client.Post(). - Namespace(c.ns). - Resource("apiserversources"). - Body(apiServerSource). - Do(). - Into(result) - return -} - -// Update takes the representation of a apiServerSource and updates it. Returns the server's representation of the apiServerSource, and an error, if there is any. -func (c *apiServerSources) Update(apiServerSource *v1alpha1.ApiServerSource) (result *v1alpha1.ApiServerSource, err error) { - result = &v1alpha1.ApiServerSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("apiserversources"). - Name(apiServerSource.Name). - Body(apiServerSource). - Do(). - 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 *apiServerSources) UpdateStatus(apiServerSource *v1alpha1.ApiServerSource) (result *v1alpha1.ApiServerSource, err error) { - result = &v1alpha1.ApiServerSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("apiserversources"). - Name(apiServerSource.Name). - SubResource("status"). - Body(apiServerSource). - Do(). - Into(result) - return -} - -// Delete takes name of the apiServerSource and deletes it. Returns an error if one occurs. -func (c *apiServerSources) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("apiserversources"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *apiServerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("apiserversources"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched apiServerSource. -func (c *apiServerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ApiServerSource, err error) { - result = &v1alpha1.ApiServerSource{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("apiserversources"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/containersource.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/containersource.go deleted file mode 100644 index a06e561699d..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/containersource.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "time" - - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - scheme "knative.dev/eventing/pkg/legacyclient/clientset/versioned/scheme" -) - -// ContainerSourcesGetter has a method to return a ContainerSourceInterface. -// A group's client should implement this interface. -type ContainerSourcesGetter interface { - ContainerSources(namespace string) ContainerSourceInterface -} - -// ContainerSourceInterface has methods to work with ContainerSource resources. -type ContainerSourceInterface interface { - Create(*v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) - Update(*v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) - UpdateStatus(*v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ContainerSource, error) - List(opts v1.ListOptions) (*v1alpha1.ContainerSourceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ContainerSource, err error) - ContainerSourceExpansion -} - -// containerSources implements ContainerSourceInterface -type containerSources struct { - client rest.Interface - ns string -} - -// newContainerSources returns a ContainerSources -func newContainerSources(c *SourcesV1alpha1Client, namespace string) *containerSources { - return &containerSources{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the containerSource, and returns the corresponding containerSource object, and an error if there is any. -func (c *containerSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ContainerSource, err error) { - result = &v1alpha1.ContainerSource{} - err = c.client.Get(). - Namespace(c.ns). - Resource("containersources"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ContainerSources that match those selectors. -func (c *containerSources) List(opts v1.ListOptions) (result *v1alpha1.ContainerSourceList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.ContainerSourceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("containersources"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested containerSources. -func (c *containerSources) Watch(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("containersources"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch() -} - -// Create takes the representation of a containerSource and creates it. Returns the server's representation of the containerSource, and an error, if there is any. -func (c *containerSources) Create(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { - result = &v1alpha1.ContainerSource{} - err = c.client.Post(). - Namespace(c.ns). - Resource("containersources"). - Body(containerSource). - Do(). - Into(result) - return -} - -// Update takes the representation of a containerSource and updates it. Returns the server's representation of the containerSource, and an error, if there is any. -func (c *containerSources) Update(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { - result = &v1alpha1.ContainerSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("containersources"). - Name(containerSource.Name). - Body(containerSource). - Do(). - 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 *containerSources) UpdateStatus(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { - result = &v1alpha1.ContainerSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("containersources"). - Name(containerSource.Name). - SubResource("status"). - Body(containerSource). - Do(). - Into(result) - return -} - -// Delete takes name of the containerSource and deletes it. Returns an error if one occurs. -func (c *containerSources) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("containersources"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *containerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("containersources"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched containerSource. -func (c *containerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ContainerSource, err error) { - result = &v1alpha1.ContainerSource{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("containersources"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/cronjobsource.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/cronjobsource.go deleted file mode 100644 index 1d87c64b7d9..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/cronjobsource.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "time" - - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - scheme "knative.dev/eventing/pkg/legacyclient/clientset/versioned/scheme" -) - -// CronJobSourcesGetter has a method to return a CronJobSourceInterface. -// A group's client should implement this interface. -type CronJobSourcesGetter interface { - CronJobSources(namespace string) CronJobSourceInterface -} - -// CronJobSourceInterface has methods to work with CronJobSource resources. -type CronJobSourceInterface interface { - Create(*v1alpha1.CronJobSource) (*v1alpha1.CronJobSource, error) - Update(*v1alpha1.CronJobSource) (*v1alpha1.CronJobSource, error) - UpdateStatus(*v1alpha1.CronJobSource) (*v1alpha1.CronJobSource, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.CronJobSource, error) - List(opts v1.ListOptions) (*v1alpha1.CronJobSourceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.CronJobSource, err error) - CronJobSourceExpansion -} - -// cronJobSources implements CronJobSourceInterface -type cronJobSources struct { - client rest.Interface - ns string -} - -// newCronJobSources returns a CronJobSources -func newCronJobSources(c *SourcesV1alpha1Client, namespace string) *cronJobSources { - return &cronJobSources{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the cronJobSource, and returns the corresponding cronJobSource object, and an error if there is any. -func (c *cronJobSources) Get(name string, options v1.GetOptions) (result *v1alpha1.CronJobSource, err error) { - result = &v1alpha1.CronJobSource{} - err = c.client.Get(). - Namespace(c.ns). - Resource("cronjobsources"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of CronJobSources that match those selectors. -func (c *cronJobSources) List(opts v1.ListOptions) (result *v1alpha1.CronJobSourceList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.CronJobSourceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("cronjobsources"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested cronJobSources. -func (c *cronJobSources) Watch(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("cronjobsources"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch() -} - -// Create takes the representation of a cronJobSource and creates it. Returns the server's representation of the cronJobSource, and an error, if there is any. -func (c *cronJobSources) Create(cronJobSource *v1alpha1.CronJobSource) (result *v1alpha1.CronJobSource, err error) { - result = &v1alpha1.CronJobSource{} - err = c.client.Post(). - Namespace(c.ns). - Resource("cronjobsources"). - Body(cronJobSource). - Do(). - Into(result) - return -} - -// Update takes the representation of a cronJobSource and updates it. Returns the server's representation of the cronJobSource, and an error, if there is any. -func (c *cronJobSources) Update(cronJobSource *v1alpha1.CronJobSource) (result *v1alpha1.CronJobSource, err error) { - result = &v1alpha1.CronJobSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("cronjobsources"). - Name(cronJobSource.Name). - Body(cronJobSource). - Do(). - 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 *cronJobSources) UpdateStatus(cronJobSource *v1alpha1.CronJobSource) (result *v1alpha1.CronJobSource, err error) { - result = &v1alpha1.CronJobSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("cronjobsources"). - Name(cronJobSource.Name). - SubResource("status"). - Body(cronJobSource). - Do(). - Into(result) - return -} - -// Delete takes name of the cronJobSource and deletes it. Returns an error if one occurs. -func (c *cronJobSources) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("cronjobsources"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *cronJobSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("cronjobsources"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched cronJobSource. -func (c *cronJobSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.CronJobSource, err error) { - result = &v1alpha1.CronJobSource{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("cronjobsources"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/doc.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/doc.go deleted file mode 100644 index 41e872fe9a9..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative 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. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/doc.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/doc.go deleted file mode 100644 index c7f6e65cab8..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2020 The Knative 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 has the automatically generated clients. -package fake diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_apiserversource.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_apiserversource.go deleted file mode 100644 index 8286e2e14ba..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_apiserversource.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// FakeApiServerSources implements ApiServerSourceInterface -type FakeApiServerSources struct { - Fake *FakeSourcesV1alpha1 - ns string -} - -var apiserversourcesResource = schema.GroupVersionResource{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Resource: "apiserversources"} - -var apiserversourcesKind = schema.GroupVersionKind{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Kind: "ApiServerSource"} - -// Get takes name of the apiServerSource, and returns the corresponding apiServerSource object, and an error if there is any. -func (c *FakeApiServerSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ApiServerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(apiserversourcesResource, c.ns, name), &v1alpha1.ApiServerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ApiServerSource), err -} - -// List takes label and field selectors, and returns the list of ApiServerSources that match those selectors. -func (c *FakeApiServerSources) List(opts v1.ListOptions) (result *v1alpha1.ApiServerSourceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(apiserversourcesResource, apiserversourcesKind, c.ns, opts), &v1alpha1.ApiServerSourceList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ApiServerSourceList{ListMeta: obj.(*v1alpha1.ApiServerSourceList).ListMeta} - for _, item := range obj.(*v1alpha1.ApiServerSourceList).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 apiServerSources. -func (c *FakeApiServerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(apiserversourcesResource, c.ns, opts)) - -} - -// Create takes the representation of a apiServerSource and creates it. Returns the server's representation of the apiServerSource, and an error, if there is any. -func (c *FakeApiServerSources) Create(apiServerSource *v1alpha1.ApiServerSource) (result *v1alpha1.ApiServerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(apiserversourcesResource, c.ns, apiServerSource), &v1alpha1.ApiServerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ApiServerSource), err -} - -// Update takes the representation of a apiServerSource and updates it. Returns the server's representation of the apiServerSource, and an error, if there is any. -func (c *FakeApiServerSources) Update(apiServerSource *v1alpha1.ApiServerSource) (result *v1alpha1.ApiServerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(apiserversourcesResource, c.ns, apiServerSource), &v1alpha1.ApiServerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ApiServerSource), 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 *FakeApiServerSources) UpdateStatus(apiServerSource *v1alpha1.ApiServerSource) (*v1alpha1.ApiServerSource, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(apiserversourcesResource, "status", c.ns, apiServerSource), &v1alpha1.ApiServerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ApiServerSource), err -} - -// Delete takes name of the apiServerSource and deletes it. Returns an error if one occurs. -func (c *FakeApiServerSources) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(apiserversourcesResource, c.ns, name), &v1alpha1.ApiServerSource{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeApiServerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(apiserversourcesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ApiServerSourceList{}) - return err -} - -// Patch applies the patch and returns the patched apiServerSource. -func (c *FakeApiServerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ApiServerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(apiserversourcesResource, c.ns, name, pt, data, subresources...), &v1alpha1.ApiServerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ApiServerSource), err -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_containersource.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_containersource.go deleted file mode 100644 index 76a952ae5bc..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_containersource.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// FakeContainerSources implements ContainerSourceInterface -type FakeContainerSources struct { - Fake *FakeSourcesV1alpha1 - ns string -} - -var containersourcesResource = schema.GroupVersionResource{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Resource: "containersources"} - -var containersourcesKind = schema.GroupVersionKind{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Kind: "ContainerSource"} - -// Get takes name of the containerSource, and returns the corresponding containerSource object, and an error if there is any. -func (c *FakeContainerSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ContainerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(containersourcesResource, c.ns, name), &v1alpha1.ContainerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ContainerSource), err -} - -// List takes label and field selectors, and returns the list of ContainerSources that match those selectors. -func (c *FakeContainerSources) List(opts v1.ListOptions) (result *v1alpha1.ContainerSourceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(containersourcesResource, containersourcesKind, c.ns, opts), &v1alpha1.ContainerSourceList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ContainerSourceList{ListMeta: obj.(*v1alpha1.ContainerSourceList).ListMeta} - for _, item := range obj.(*v1alpha1.ContainerSourceList).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 containerSources. -func (c *FakeContainerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(containersourcesResource, c.ns, opts)) - -} - -// Create takes the representation of a containerSource and creates it. Returns the server's representation of the containerSource, and an error, if there is any. -func (c *FakeContainerSources) Create(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(containersourcesResource, c.ns, containerSource), &v1alpha1.ContainerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ContainerSource), err -} - -// Update takes the representation of a containerSource and updates it. Returns the server's representation of the containerSource, and an error, if there is any. -func (c *FakeContainerSources) Update(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(containersourcesResource, c.ns, containerSource), &v1alpha1.ContainerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ContainerSource), 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 *FakeContainerSources) UpdateStatus(containerSource *v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(containersourcesResource, "status", c.ns, containerSource), &v1alpha1.ContainerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ContainerSource), err -} - -// Delete takes name of the containerSource and deletes it. Returns an error if one occurs. -func (c *FakeContainerSources) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(containersourcesResource, c.ns, name), &v1alpha1.ContainerSource{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeContainerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(containersourcesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ContainerSourceList{}) - return err -} - -// Patch applies the patch and returns the patched containerSource. -func (c *FakeContainerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ContainerSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(containersourcesResource, c.ns, name, pt, data, subresources...), &v1alpha1.ContainerSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ContainerSource), err -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_cronjobsource.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_cronjobsource.go deleted file mode 100644 index d0f95d6b944..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_cronjobsource.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// FakeCronJobSources implements CronJobSourceInterface -type FakeCronJobSources struct { - Fake *FakeSourcesV1alpha1 - ns string -} - -var cronjobsourcesResource = schema.GroupVersionResource{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Resource: "cronjobsources"} - -var cronjobsourcesKind = schema.GroupVersionKind{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Kind: "CronJobSource"} - -// Get takes name of the cronJobSource, and returns the corresponding cronJobSource object, and an error if there is any. -func (c *FakeCronJobSources) Get(name string, options v1.GetOptions) (result *v1alpha1.CronJobSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(cronjobsourcesResource, c.ns, name), &v1alpha1.CronJobSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CronJobSource), err -} - -// List takes label and field selectors, and returns the list of CronJobSources that match those selectors. -func (c *FakeCronJobSources) List(opts v1.ListOptions) (result *v1alpha1.CronJobSourceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(cronjobsourcesResource, cronjobsourcesKind, c.ns, opts), &v1alpha1.CronJobSourceList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.CronJobSourceList{ListMeta: obj.(*v1alpha1.CronJobSourceList).ListMeta} - for _, item := range obj.(*v1alpha1.CronJobSourceList).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 cronJobSources. -func (c *FakeCronJobSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(cronjobsourcesResource, c.ns, opts)) - -} - -// Create takes the representation of a cronJobSource and creates it. Returns the server's representation of the cronJobSource, and an error, if there is any. -func (c *FakeCronJobSources) Create(cronJobSource *v1alpha1.CronJobSource) (result *v1alpha1.CronJobSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(cronjobsourcesResource, c.ns, cronJobSource), &v1alpha1.CronJobSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CronJobSource), err -} - -// Update takes the representation of a cronJobSource and updates it. Returns the server's representation of the cronJobSource, and an error, if there is any. -func (c *FakeCronJobSources) Update(cronJobSource *v1alpha1.CronJobSource) (result *v1alpha1.CronJobSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(cronjobsourcesResource, c.ns, cronJobSource), &v1alpha1.CronJobSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CronJobSource), 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 *FakeCronJobSources) UpdateStatus(cronJobSource *v1alpha1.CronJobSource) (*v1alpha1.CronJobSource, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(cronjobsourcesResource, "status", c.ns, cronJobSource), &v1alpha1.CronJobSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CronJobSource), err -} - -// Delete takes name of the cronJobSource and deletes it. Returns an error if one occurs. -func (c *FakeCronJobSources) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(cronjobsourcesResource, c.ns, name), &v1alpha1.CronJobSource{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeCronJobSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(cronjobsourcesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.CronJobSourceList{}) - return err -} - -// Patch applies the patch and returns the patched cronJobSource. -func (c *FakeCronJobSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.CronJobSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(cronjobsourcesResource, c.ns, name, pt, data, subresources...), &v1alpha1.CronJobSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CronJobSource), err -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_legacysources_client.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_legacysources_client.go deleted file mode 100644 index 834449a64c8..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_legacysources_client.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" - v1alpha1 "knative.dev/eventing/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1" -) - -type FakeSourcesV1alpha1 struct { - *testing.Fake -} - -func (c *FakeSourcesV1alpha1) ApiServerSources(namespace string) v1alpha1.ApiServerSourceInterface { - return &FakeApiServerSources{c, namespace} -} - -func (c *FakeSourcesV1alpha1) ContainerSources(namespace string) v1alpha1.ContainerSourceInterface { - return &FakeContainerSources{c, namespace} -} - -func (c *FakeSourcesV1alpha1) CronJobSources(namespace string) v1alpha1.CronJobSourceInterface { - return &FakeCronJobSources{c, namespace} -} - -func (c *FakeSourcesV1alpha1) SinkBindings(namespace string) v1alpha1.SinkBindingInterface { - return &FakeSinkBindings{c, namespace} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeSourcesV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_sinkbinding.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_sinkbinding.go deleted file mode 100644 index 117c49c89cd..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/fake/fake_sinkbinding.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// FakeSinkBindings implements SinkBindingInterface -type FakeSinkBindings struct { - Fake *FakeSourcesV1alpha1 - ns string -} - -var sinkbindingsResource = schema.GroupVersionResource{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Resource: "sinkbindings"} - -var sinkbindingsKind = schema.GroupVersionKind{Group: "sources.eventing.knative.dev", Version: "v1alpha1", Kind: "SinkBinding"} - -// Get takes name of the sinkBinding, and returns the corresponding sinkBinding object, and an error if there is any. -func (c *FakeSinkBindings) Get(name string, options v1.GetOptions) (result *v1alpha1.SinkBinding, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(sinkbindingsResource, c.ns, name), &v1alpha1.SinkBinding{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SinkBinding), err -} - -// List takes label and field selectors, and returns the list of SinkBindings that match those selectors. -func (c *FakeSinkBindings) List(opts v1.ListOptions) (result *v1alpha1.SinkBindingList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(sinkbindingsResource, sinkbindingsKind, c.ns, opts), &v1alpha1.SinkBindingList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.SinkBindingList{ListMeta: obj.(*v1alpha1.SinkBindingList).ListMeta} - for _, item := range obj.(*v1alpha1.SinkBindingList).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 sinkBindings. -func (c *FakeSinkBindings) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(sinkbindingsResource, c.ns, opts)) - -} - -// Create takes the representation of a sinkBinding and creates it. Returns the server's representation of the sinkBinding, and an error, if there is any. -func (c *FakeSinkBindings) Create(sinkBinding *v1alpha1.SinkBinding) (result *v1alpha1.SinkBinding, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(sinkbindingsResource, c.ns, sinkBinding), &v1alpha1.SinkBinding{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SinkBinding), err -} - -// Update takes the representation of a sinkBinding and updates it. Returns the server's representation of the sinkBinding, and an error, if there is any. -func (c *FakeSinkBindings) Update(sinkBinding *v1alpha1.SinkBinding) (result *v1alpha1.SinkBinding, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(sinkbindingsResource, c.ns, sinkBinding), &v1alpha1.SinkBinding{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SinkBinding), 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 *FakeSinkBindings) UpdateStatus(sinkBinding *v1alpha1.SinkBinding) (*v1alpha1.SinkBinding, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(sinkbindingsResource, "status", c.ns, sinkBinding), &v1alpha1.SinkBinding{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SinkBinding), err -} - -// Delete takes name of the sinkBinding and deletes it. Returns an error if one occurs. -func (c *FakeSinkBindings) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(sinkbindingsResource, c.ns, name), &v1alpha1.SinkBinding{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeSinkBindings) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(sinkbindingsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.SinkBindingList{}) - return err -} - -// Patch applies the patch and returns the patched sinkBinding. -func (c *FakeSinkBindings) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.SinkBinding, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(sinkbindingsResource, c.ns, name, pt, data, subresources...), &v1alpha1.SinkBinding{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.SinkBinding), err -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/generated_expansion.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/generated_expansion.go deleted file mode 100644 index 4ad31e2ba85..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2020 The Knative 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 - -type ApiServerSourceExpansion interface{} - -type ContainerSourceExpansion interface{} - -type CronJobSourceExpansion interface{} - -type SinkBindingExpansion interface{} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/legacysources_client.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/legacysources_client.go deleted file mode 100644 index 922fd26ec70..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/legacysources_client.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - rest "k8s.io/client-go/rest" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/legacyclient/clientset/versioned/scheme" -) - -type SourcesV1alpha1Interface interface { - RESTClient() rest.Interface - ApiServerSourcesGetter - ContainerSourcesGetter - CronJobSourcesGetter - SinkBindingsGetter -} - -// SourcesV1alpha1Client is used to interact with features provided by the sources.eventing.knative.dev group. -type SourcesV1alpha1Client struct { - restClient rest.Interface -} - -func (c *SourcesV1alpha1Client) ApiServerSources(namespace string) ApiServerSourceInterface { - return newApiServerSources(c, namespace) -} - -func (c *SourcesV1alpha1Client) ContainerSources(namespace string) ContainerSourceInterface { - return newContainerSources(c, namespace) -} - -func (c *SourcesV1alpha1Client) CronJobSources(namespace string) CronJobSourceInterface { - return newCronJobSources(c, namespace) -} - -func (c *SourcesV1alpha1Client) SinkBindings(namespace string) SinkBindingInterface { - return newSinkBindings(c, namespace) -} - -// NewForConfig creates a new SourcesV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*SourcesV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &SourcesV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new SourcesV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *SourcesV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new SourcesV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *SourcesV1alpha1Client { - return &SourcesV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *SourcesV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/sinkbinding.go b/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/sinkbinding.go deleted file mode 100644 index 2813f32fd79..00000000000 --- a/pkg/legacyclient/clientset/versioned/typed/legacysources/v1alpha1/sinkbinding.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "time" - - 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" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - scheme "knative.dev/eventing/pkg/legacyclient/clientset/versioned/scheme" -) - -// SinkBindingsGetter has a method to return a SinkBindingInterface. -// A group's client should implement this interface. -type SinkBindingsGetter interface { - SinkBindings(namespace string) SinkBindingInterface -} - -// SinkBindingInterface has methods to work with SinkBinding resources. -type SinkBindingInterface interface { - Create(*v1alpha1.SinkBinding) (*v1alpha1.SinkBinding, error) - Update(*v1alpha1.SinkBinding) (*v1alpha1.SinkBinding, error) - UpdateStatus(*v1alpha1.SinkBinding) (*v1alpha1.SinkBinding, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.SinkBinding, error) - List(opts v1.ListOptions) (*v1alpha1.SinkBindingList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.SinkBinding, err error) - SinkBindingExpansion -} - -// sinkBindings implements SinkBindingInterface -type sinkBindings struct { - client rest.Interface - ns string -} - -// newSinkBindings returns a SinkBindings -func newSinkBindings(c *SourcesV1alpha1Client, namespace string) *sinkBindings { - return &sinkBindings{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the sinkBinding, and returns the corresponding sinkBinding object, and an error if there is any. -func (c *sinkBindings) Get(name string, options v1.GetOptions) (result *v1alpha1.SinkBinding, err error) { - result = &v1alpha1.SinkBinding{} - err = c.client.Get(). - Namespace(c.ns). - Resource("sinkbindings"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of SinkBindings that match those selectors. -func (c *sinkBindings) List(opts v1.ListOptions) (result *v1alpha1.SinkBindingList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.SinkBindingList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("sinkbindings"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested sinkBindings. -func (c *sinkBindings) Watch(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("sinkbindings"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch() -} - -// Create takes the representation of a sinkBinding and creates it. Returns the server's representation of the sinkBinding, and an error, if there is any. -func (c *sinkBindings) Create(sinkBinding *v1alpha1.SinkBinding) (result *v1alpha1.SinkBinding, err error) { - result = &v1alpha1.SinkBinding{} - err = c.client.Post(). - Namespace(c.ns). - Resource("sinkbindings"). - Body(sinkBinding). - Do(). - Into(result) - return -} - -// Update takes the representation of a sinkBinding and updates it. Returns the server's representation of the sinkBinding, and an error, if there is any. -func (c *sinkBindings) Update(sinkBinding *v1alpha1.SinkBinding) (result *v1alpha1.SinkBinding, err error) { - result = &v1alpha1.SinkBinding{} - err = c.client.Put(). - Namespace(c.ns). - Resource("sinkbindings"). - Name(sinkBinding.Name). - Body(sinkBinding). - Do(). - 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 *sinkBindings) UpdateStatus(sinkBinding *v1alpha1.SinkBinding) (result *v1alpha1.SinkBinding, err error) { - result = &v1alpha1.SinkBinding{} - err = c.client.Put(). - Namespace(c.ns). - Resource("sinkbindings"). - Name(sinkBinding.Name). - SubResource("status"). - Body(sinkBinding). - Do(). - Into(result) - return -} - -// Delete takes name of the sinkBinding and deletes it. Returns an error if one occurs. -func (c *sinkBindings) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("sinkbindings"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *sinkBindings) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("sinkbindings"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched sinkBinding. -func (c *sinkBindings) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.SinkBinding, err error) { - result = &v1alpha1.SinkBinding{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("sinkbindings"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/legacyclient/informers/externalversions/factory.go b/pkg/legacyclient/informers/externalversions/factory.go deleted file mode 100644 index f83a782e413..00000000000 --- a/pkg/legacyclient/informers/externalversions/factory.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright 2020 The Knative 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 externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" - legacysources "knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -// Start initializes all requested informers. -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - go informer.Run(stopCh) - f.startedInformers[informerType] = true - } - } -} - -// WaitForCacheSync waits for all started informers' cache were synced. -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InternalInformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - Sources() legacysources.Interface -} - -func (f *sharedInformerFactory) Sources() legacysources.Interface { - return legacysources.New(f, f.namespace, f.tweakListOptions) -} diff --git a/pkg/legacyclient/informers/externalversions/generic.go b/pkg/legacyclient/informers/externalversions/generic.go deleted file mode 100644 index e6b466761fe..00000000000 --- a/pkg/legacyclient/informers/externalversions/generic.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2020 The Knative 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 externalversions - -import ( - "fmt" - - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=sources.eventing.knative.dev, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("apiserversources"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1alpha1().ApiServerSources().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("containersources"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1alpha1().ContainerSources().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("cronjobsources"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1alpha1().CronJobSources().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("sinkbindings"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1alpha1().SinkBindings().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/pkg/legacyclient/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/legacyclient/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index 34ab2f05ede..00000000000 --- a/pkg/legacyclient/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative 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 internalinterfaces - -import ( - time "time" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/pkg/legacyclient/informers/externalversions/legacysources/interface.go b/pkg/legacyclient/informers/externalversions/legacysources/interface.go deleted file mode 100644 index ac65129f495..00000000000 --- a/pkg/legacyclient/informers/externalversions/legacysources/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2020 The Knative 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 legacysources - -import ( - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/apiserversource.go b/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/apiserversource.go deleted file mode 100644 index 41653da5300..00000000000 --- a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/apiserversource.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - time "time" - - 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" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" -) - -// ApiServerSourceInformer provides access to a shared informer and lister for -// ApiServerSources. -type ApiServerSourceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ApiServerSourceLister -} - -type apiServerSourceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewApiServerSourceInformer constructs a new informer for ApiServerSource 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 NewApiServerSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredApiServerSourceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredApiServerSourceInformer constructs a new informer for ApiServerSource 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 NewFilteredApiServerSourceInformer(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.SourcesV1alpha1().ApiServerSources(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.SourcesV1alpha1().ApiServerSources(namespace).Watch(options) - }, - }, - &legacysourcesv1alpha1.ApiServerSource{}, - resyncPeriod, - indexers, - ) -} - -func (f *apiServerSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredApiServerSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *apiServerSourceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&legacysourcesv1alpha1.ApiServerSource{}, f.defaultInformer) -} - -func (f *apiServerSourceInformer) Lister() v1alpha1.ApiServerSourceLister { - return v1alpha1.NewApiServerSourceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/containersource.go b/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/containersource.go deleted file mode 100644 index 0d6c7b0a276..00000000000 --- a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/containersource.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - time "time" - - 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" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" -) - -// ContainerSourceInformer provides access to a shared informer and lister for -// ContainerSources. -type ContainerSourceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ContainerSourceLister -} - -type containerSourceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewContainerSourceInformer constructs a new informer for ContainerSource 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 NewContainerSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredContainerSourceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredContainerSourceInformer constructs a new informer for ContainerSource 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 NewFilteredContainerSourceInformer(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.SourcesV1alpha1().ContainerSources(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.SourcesV1alpha1().ContainerSources(namespace).Watch(options) - }, - }, - &legacysourcesv1alpha1.ContainerSource{}, - resyncPeriod, - indexers, - ) -} - -func (f *containerSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredContainerSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *containerSourceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&legacysourcesv1alpha1.ContainerSource{}, f.defaultInformer) -} - -func (f *containerSourceInformer) Lister() v1alpha1.ContainerSourceLister { - return v1alpha1.NewContainerSourceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/cronjobsource.go b/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/cronjobsource.go deleted file mode 100644 index 411ad2552e6..00000000000 --- a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/cronjobsource.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - time "time" - - 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" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" -) - -// CronJobSourceInformer provides access to a shared informer and lister for -// CronJobSources. -type CronJobSourceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.CronJobSourceLister -} - -type cronJobSourceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewCronJobSourceInformer constructs a new informer for CronJobSource 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 NewCronJobSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredCronJobSourceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredCronJobSourceInformer constructs a new informer for CronJobSource 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 NewFilteredCronJobSourceInformer(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.SourcesV1alpha1().CronJobSources(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.SourcesV1alpha1().CronJobSources(namespace).Watch(options) - }, - }, - &legacysourcesv1alpha1.CronJobSource{}, - resyncPeriod, - indexers, - ) -} - -func (f *cronJobSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredCronJobSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *cronJobSourceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&legacysourcesv1alpha1.CronJobSource{}, f.defaultInformer) -} - -func (f *cronJobSourceInformer) Lister() v1alpha1.CronJobSourceLister { - return v1alpha1.NewCronJobSourceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/interface.go b/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/interface.go deleted file mode 100644 index aa9e6721278..00000000000 --- a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/interface.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // ApiServerSources returns a ApiServerSourceInformer. - ApiServerSources() ApiServerSourceInformer - // ContainerSources returns a ContainerSourceInformer. - ContainerSources() ContainerSourceInformer - // CronJobSources returns a CronJobSourceInformer. - CronJobSources() CronJobSourceInformer - // SinkBindings returns a SinkBindingInformer. - SinkBindings() SinkBindingInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// ApiServerSources returns a ApiServerSourceInformer. -func (v *version) ApiServerSources() ApiServerSourceInformer { - return &apiServerSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// ContainerSources returns a ContainerSourceInformer. -func (v *version) ContainerSources() ContainerSourceInformer { - return &containerSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// CronJobSources returns a CronJobSourceInformer. -func (v *version) CronJobSources() CronJobSourceInformer { - return &cronJobSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// SinkBindings returns a SinkBindingInformer. -func (v *version) SinkBindings() SinkBindingInformer { - return &sinkBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/sinkbinding.go b/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/sinkbinding.go deleted file mode 100644 index 1bba1c150d1..00000000000 --- a/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1/sinkbinding.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - time "time" - - 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" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - internalinterfaces "knative.dev/eventing/pkg/legacyclient/informers/externalversions/internalinterfaces" - v1alpha1 "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" -) - -// SinkBindingInformer provides access to a shared informer and lister for -// SinkBindings. -type SinkBindingInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.SinkBindingLister -} - -type sinkBindingInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewSinkBindingInformer constructs a new informer for SinkBinding 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 NewSinkBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredSinkBindingInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredSinkBindingInformer constructs a new informer for SinkBinding 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 NewFilteredSinkBindingInformer(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.SourcesV1alpha1().SinkBindings(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.SourcesV1alpha1().SinkBindings(namespace).Watch(options) - }, - }, - &legacysourcesv1alpha1.SinkBinding{}, - resyncPeriod, - indexers, - ) -} - -func (f *sinkBindingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredSinkBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *sinkBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&legacysourcesv1alpha1.SinkBinding{}, f.defaultInformer) -} - -func (f *sinkBindingInformer) Lister() v1alpha1.SinkBindingLister { - return v1alpha1.NewSinkBindingLister(f.Informer().GetIndexer()) -} diff --git a/pkg/legacyclient/injection/client/client.go b/pkg/legacyclient/injection/client/client.go deleted file mode 100644 index 016ef0e0df1..00000000000 --- a/pkg/legacyclient/injection/client/client.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2020 The Knative 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 client - -import ( - context "context" - - rest "k8s.io/client-go/rest" - versioned "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterClient(withClient) -} - -// Key is used as the key for associating information with a context.Context. -type Key struct{} - -func withClient(ctx context.Context, cfg *rest.Config) context.Context { - return context.WithValue(ctx, Key{}, versioned.NewForConfigOrDie(cfg)) -} - -// Get extracts the versioned.Interface client from the context. -func Get(ctx context.Context) versioned.Interface { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/clientset/versioned.Interface from context.") - } - return untyped.(versioned.Interface) -} diff --git a/pkg/legacyclient/injection/client/fake/fake.go b/pkg/legacyclient/injection/client/fake/fake.go deleted file mode 100644 index 8221f81f057..00000000000 --- a/pkg/legacyclient/injection/client/fake/fake.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 The Knative 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" - - runtime "k8s.io/apimachinery/pkg/runtime" - rest "k8s.io/client-go/rest" - fake "knative.dev/eventing/pkg/legacyclient/clientset/versioned/fake" - client "knative.dev/eventing/pkg/legacyclient/injection/client" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Fake.RegisterClient(withClient) -} - -func withClient(ctx context.Context, cfg *rest.Config) context.Context { - ctx, _ = With(ctx) - return ctx -} - -func With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) { - cs := fake.NewSimpleClientset(objects...) - return context.WithValue(ctx, client.Key{}, cs), cs -} - -// Get extracts the Kubernetes client from the context. -func Get(ctx context.Context) *fake.Clientset { - untyped := ctx.Value(client.Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/clientset/versioned/fake.Clientset from context.") - } - return untyped.(*fake.Clientset) -} diff --git a/pkg/legacyclient/injection/informers/factory/factory.go b/pkg/legacyclient/injection/informers/factory/factory.go deleted file mode 100644 index ef7e947c148..00000000000 --- a/pkg/legacyclient/injection/informers/factory/factory.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2020 The Knative 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 factory - -import ( - context "context" - - externalversions "knative.dev/eventing/pkg/legacyclient/informers/externalversions" - client "knative.dev/eventing/pkg/legacyclient/injection/client" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformerFactory(withInformerFactory) -} - -// Key is used as the key for associating information with a context.Context. -type Key struct{} - -func withInformerFactory(ctx context.Context) context.Context { - c := client.Get(ctx) - opts := make([]externalversions.SharedInformerOption, 0, 1) - if injection.HasNamespaceScope(ctx) { - opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) - } - return context.WithValue(ctx, Key{}, - externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) -} - -// Get extracts the InformerFactory from the context. -func Get(ctx context.Context) externalversions.SharedInformerFactory { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/informers/externalversions.SharedInformerFactory from context.") - } - return untyped.(externalversions.SharedInformerFactory) -} diff --git a/pkg/legacyclient/injection/informers/factory/fake/fake.go b/pkg/legacyclient/injection/informers/factory/fake/fake.go deleted file mode 100644 index 6403dee9708..00000000000 --- a/pkg/legacyclient/injection/informers/factory/fake/fake.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2020 The Knative 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" - - externalversions "knative.dev/eventing/pkg/legacyclient/informers/externalversions" - fake "knative.dev/eventing/pkg/legacyclient/injection/client/fake" - factory "knative.dev/eventing/pkg/legacyclient/injection/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = factory.Get - -func init() { - injection.Fake.RegisterInformerFactory(withInformerFactory) -} - -func withInformerFactory(ctx context.Context) context.Context { - c := fake.Get(ctx) - opts := make([]externalversions.SharedInformerOption, 0, 1) - if injection.HasNamespaceScope(ctx) { - opts = append(opts, externalversions.WithNamespace(injection.GetNamespaceScope(ctx))) - } - return context.WithValue(ctx, factory.Key{}, - externalversions.NewSharedInformerFactoryWithOptions(c, controller.GetResyncPeriod(ctx), opts...)) -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/apiserversource.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/apiserversource.go deleted file mode 100644 index 7c7e79606b4..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/apiserversource.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative 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 apiserversource - -import ( - context "context" - - v1alpha1 "knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1" - factory "knative.dev/eventing/pkg/legacyclient/injection/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) -} - -// 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.Sources().V1alpha1().ApiServerSources() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.ApiServerSourceInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1.ApiServerSourceInformer from context.") - } - return untyped.(v1alpha1.ApiServerSourceInformer) -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/fake/fake.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/fake/fake.go deleted file mode 100644 index 0e2decf401f..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative 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 "knative.dev/eventing/pkg/legacyclient/injection/informers/factory/fake" - apiserversource "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = apiserversource.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Sources().V1alpha1().ApiServerSources() - return context.WithValue(ctx, apiserversource.Key{}, inf), inf.Informer() -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/containersource.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/containersource.go deleted file mode 100644 index e72925717d6..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/containersource.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative 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 containersource - -import ( - context "context" - - v1alpha1 "knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1" - factory "knative.dev/eventing/pkg/legacyclient/injection/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) -} - -// 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.Sources().V1alpha1().ContainerSources() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.ContainerSourceInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1.ContainerSourceInformer from context.") - } - return untyped.(v1alpha1.ContainerSourceInformer) -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/fake/fake.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/fake/fake.go deleted file mode 100644 index c9276ce9f1c..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative 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 "knative.dev/eventing/pkg/legacyclient/injection/informers/factory/fake" - containersource "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = containersource.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Sources().V1alpha1().ContainerSources() - return context.WithValue(ctx, containersource.Key{}, inf), inf.Informer() -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/cronjobsource.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/cronjobsource.go deleted file mode 100644 index 04a88ec6698..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/cronjobsource.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative 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 cronjobsource - -import ( - context "context" - - v1alpha1 "knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1" - factory "knative.dev/eventing/pkg/legacyclient/injection/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) -} - -// 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.Sources().V1alpha1().CronJobSources() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.CronJobSourceInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1.CronJobSourceInformer from context.") - } - return untyped.(v1alpha1.CronJobSourceInformer) -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/fake/fake.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/fake/fake.go deleted file mode 100644 index c51d64ca00e..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative 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 "knative.dev/eventing/pkg/legacyclient/injection/informers/factory/fake" - cronjobsource "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = cronjobsource.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Sources().V1alpha1().CronJobSources() - return context.WithValue(ctx, cronjobsource.Key{}, inf), inf.Informer() -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding/fake/fake.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding/fake/fake.go deleted file mode 100644 index 714897e8daa..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Knative 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 "knative.dev/eventing/pkg/legacyclient/injection/informers/factory/fake" - sinkbinding "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = sinkbinding.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Sources().V1alpha1().SinkBindings() - return context.WithValue(ctx, sinkbinding.Key{}, inf), inf.Informer() -} diff --git a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding/sinkbinding.go b/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding/sinkbinding.go deleted file mode 100644 index b1bc3757ad7..00000000000 --- a/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding/sinkbinding.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Knative 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 sinkbinding - -import ( - context "context" - - v1alpha1 "knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1" - factory "knative.dev/eventing/pkg/legacyclient/injection/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) -} - -// 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.Sources().V1alpha1().SinkBindings() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.SinkBindingInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch knative.dev/eventing/pkg/legacyclient/informers/externalversions/legacysources/v1alpha1.SinkBindingInformer from context.") - } - return untyped.(v1alpha1.SinkBindingInformer) -} diff --git a/pkg/legacyclient/listers/legacysources/v1alpha1/apiserversource.go b/pkg/legacyclient/listers/legacysources/v1alpha1/apiserversource.go deleted file mode 100644 index 20298acc6b8..00000000000 --- a/pkg/legacyclient/listers/legacysources/v1alpha1/apiserversource.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// ApiServerSourceLister helps list ApiServerSources. -type ApiServerSourceLister interface { - // List lists all ApiServerSources in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ApiServerSource, err error) - // ApiServerSources returns an object that can list and get ApiServerSources. - ApiServerSources(namespace string) ApiServerSourceNamespaceLister - ApiServerSourceListerExpansion -} - -// apiServerSourceLister implements the ApiServerSourceLister interface. -type apiServerSourceLister struct { - indexer cache.Indexer -} - -// NewApiServerSourceLister returns a new ApiServerSourceLister. -func NewApiServerSourceLister(indexer cache.Indexer) ApiServerSourceLister { - return &apiServerSourceLister{indexer: indexer} -} - -// List lists all ApiServerSources in the indexer. -func (s *apiServerSourceLister) List(selector labels.Selector) (ret []*v1alpha1.ApiServerSource, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ApiServerSource)) - }) - return ret, err -} - -// ApiServerSources returns an object that can list and get ApiServerSources. -func (s *apiServerSourceLister) ApiServerSources(namespace string) ApiServerSourceNamespaceLister { - return apiServerSourceNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// ApiServerSourceNamespaceLister helps list and get ApiServerSources. -type ApiServerSourceNamespaceLister interface { - // List lists all ApiServerSources in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.ApiServerSource, err error) - // Get retrieves the ApiServerSource from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.ApiServerSource, error) - ApiServerSourceNamespaceListerExpansion -} - -// apiServerSourceNamespaceLister implements the ApiServerSourceNamespaceLister -// interface. -type apiServerSourceNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all ApiServerSources in the indexer for a given namespace. -func (s apiServerSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ApiServerSource, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ApiServerSource)) - }) - return ret, err -} - -// Get retrieves the ApiServerSource from the indexer for a given namespace and name. -func (s apiServerSourceNamespaceLister) Get(name string) (*v1alpha1.ApiServerSource, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("apiserversource"), name) - } - return obj.(*v1alpha1.ApiServerSource), nil -} diff --git a/pkg/legacyclient/listers/legacysources/v1alpha1/containersource.go b/pkg/legacyclient/listers/legacysources/v1alpha1/containersource.go deleted file mode 100644 index e28028f904e..00000000000 --- a/pkg/legacyclient/listers/legacysources/v1alpha1/containersource.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// ContainerSourceLister helps list ContainerSources. -type ContainerSourceLister interface { - // List lists all ContainerSources in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ContainerSource, err error) - // ContainerSources returns an object that can list and get ContainerSources. - ContainerSources(namespace string) ContainerSourceNamespaceLister - ContainerSourceListerExpansion -} - -// containerSourceLister implements the ContainerSourceLister interface. -type containerSourceLister struct { - indexer cache.Indexer -} - -// NewContainerSourceLister returns a new ContainerSourceLister. -func NewContainerSourceLister(indexer cache.Indexer) ContainerSourceLister { - return &containerSourceLister{indexer: indexer} -} - -// List lists all ContainerSources in the indexer. -func (s *containerSourceLister) List(selector labels.Selector) (ret []*v1alpha1.ContainerSource, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ContainerSource)) - }) - return ret, err -} - -// ContainerSources returns an object that can list and get ContainerSources. -func (s *containerSourceLister) ContainerSources(namespace string) ContainerSourceNamespaceLister { - return containerSourceNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// ContainerSourceNamespaceLister helps list and get ContainerSources. -type ContainerSourceNamespaceLister interface { - // List lists all ContainerSources in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.ContainerSource, err error) - // Get retrieves the ContainerSource from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.ContainerSource, error) - ContainerSourceNamespaceListerExpansion -} - -// containerSourceNamespaceLister implements the ContainerSourceNamespaceLister -// interface. -type containerSourceNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all ContainerSources in the indexer for a given namespace. -func (s containerSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ContainerSource, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ContainerSource)) - }) - return ret, err -} - -// Get retrieves the ContainerSource from the indexer for a given namespace and name. -func (s containerSourceNamespaceLister) Get(name string) (*v1alpha1.ContainerSource, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("containersource"), name) - } - return obj.(*v1alpha1.ContainerSource), nil -} diff --git a/pkg/legacyclient/listers/legacysources/v1alpha1/cronjobsource.go b/pkg/legacyclient/listers/legacysources/v1alpha1/cronjobsource.go deleted file mode 100644 index 681196f5b81..00000000000 --- a/pkg/legacyclient/listers/legacysources/v1alpha1/cronjobsource.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// CronJobSourceLister helps list CronJobSources. -type CronJobSourceLister interface { - // List lists all CronJobSources in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.CronJobSource, err error) - // CronJobSources returns an object that can list and get CronJobSources. - CronJobSources(namespace string) CronJobSourceNamespaceLister - CronJobSourceListerExpansion -} - -// cronJobSourceLister implements the CronJobSourceLister interface. -type cronJobSourceLister struct { - indexer cache.Indexer -} - -// NewCronJobSourceLister returns a new CronJobSourceLister. -func NewCronJobSourceLister(indexer cache.Indexer) CronJobSourceLister { - return &cronJobSourceLister{indexer: indexer} -} - -// List lists all CronJobSources in the indexer. -func (s *cronJobSourceLister) List(selector labels.Selector) (ret []*v1alpha1.CronJobSource, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.CronJobSource)) - }) - return ret, err -} - -// CronJobSources returns an object that can list and get CronJobSources. -func (s *cronJobSourceLister) CronJobSources(namespace string) CronJobSourceNamespaceLister { - return cronJobSourceNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// CronJobSourceNamespaceLister helps list and get CronJobSources. -type CronJobSourceNamespaceLister interface { - // List lists all CronJobSources in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.CronJobSource, err error) - // Get retrieves the CronJobSource from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.CronJobSource, error) - CronJobSourceNamespaceListerExpansion -} - -// cronJobSourceNamespaceLister implements the CronJobSourceNamespaceLister -// interface. -type cronJobSourceNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all CronJobSources in the indexer for a given namespace. -func (s cronJobSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.CronJobSource, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.CronJobSource)) - }) - return ret, err -} - -// Get retrieves the CronJobSource from the indexer for a given namespace and name. -func (s cronJobSourceNamespaceLister) Get(name string) (*v1alpha1.CronJobSource, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("cronjobsource"), name) - } - return obj.(*v1alpha1.CronJobSource), nil -} diff --git a/pkg/legacyclient/listers/legacysources/v1alpha1/expansion_generated.go b/pkg/legacyclient/listers/legacysources/v1alpha1/expansion_generated.go deleted file mode 100644 index 378c18ee4dd..00000000000 --- a/pkg/legacyclient/listers/legacysources/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2020 The Knative 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 - -// ApiServerSourceListerExpansion allows custom methods to be added to -// ApiServerSourceLister. -type ApiServerSourceListerExpansion interface{} - -// ApiServerSourceNamespaceListerExpansion allows custom methods to be added to -// ApiServerSourceNamespaceLister. -type ApiServerSourceNamespaceListerExpansion interface{} - -// ContainerSourceListerExpansion allows custom methods to be added to -// ContainerSourceLister. -type ContainerSourceListerExpansion interface{} - -// ContainerSourceNamespaceListerExpansion allows custom methods to be added to -// ContainerSourceNamespaceLister. -type ContainerSourceNamespaceListerExpansion interface{} - -// CronJobSourceListerExpansion allows custom methods to be added to -// CronJobSourceLister. -type CronJobSourceListerExpansion interface{} - -// CronJobSourceNamespaceListerExpansion allows custom methods to be added to -// CronJobSourceNamespaceLister. -type CronJobSourceNamespaceListerExpansion interface{} - -// SinkBindingListerExpansion allows custom methods to be added to -// SinkBindingLister. -type SinkBindingListerExpansion interface{} - -// SinkBindingNamespaceListerExpansion allows custom methods to be added to -// SinkBindingNamespaceLister. -type SinkBindingNamespaceListerExpansion interface{} diff --git a/pkg/legacyclient/listers/legacysources/v1alpha1/sinkbinding.go b/pkg/legacyclient/listers/legacysources/v1alpha1/sinkbinding.go deleted file mode 100644 index 85c39f3f158..00000000000 --- a/pkg/legacyclient/listers/legacysources/v1alpha1/sinkbinding.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2020 The Knative 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 ( - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" - v1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// SinkBindingLister helps list SinkBindings. -type SinkBindingLister interface { - // List lists all SinkBindings in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.SinkBinding, err error) - // SinkBindings returns an object that can list and get SinkBindings. - SinkBindings(namespace string) SinkBindingNamespaceLister - SinkBindingListerExpansion -} - -// sinkBindingLister implements the SinkBindingLister interface. -type sinkBindingLister struct { - indexer cache.Indexer -} - -// NewSinkBindingLister returns a new SinkBindingLister. -func NewSinkBindingLister(indexer cache.Indexer) SinkBindingLister { - return &sinkBindingLister{indexer: indexer} -} - -// List lists all SinkBindings in the indexer. -func (s *sinkBindingLister) List(selector labels.Selector) (ret []*v1alpha1.SinkBinding, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.SinkBinding)) - }) - return ret, err -} - -// SinkBindings returns an object that can list and get SinkBindings. -func (s *sinkBindingLister) SinkBindings(namespace string) SinkBindingNamespaceLister { - return sinkBindingNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// SinkBindingNamespaceLister helps list and get SinkBindings. -type SinkBindingNamespaceLister interface { - // List lists all SinkBindings in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.SinkBinding, err error) - // Get retrieves the SinkBinding from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.SinkBinding, error) - SinkBindingNamespaceListerExpansion -} - -// sinkBindingNamespaceLister implements the SinkBindingNamespaceLister -// interface. -type sinkBindingNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all SinkBindings in the indexer for a given namespace. -func (s sinkBindingNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SinkBinding, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.SinkBinding)) - }) - return ret, err -} - -// Get retrieves the SinkBinding from the indexer for a given namespace and name. -func (s sinkBindingNamespaceLister) Get(name string) (*v1alpha1.SinkBinding, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("sinkbinding"), name) - } - return obj.(*v1alpha1.SinkBinding), nil -} diff --git a/pkg/reconciler/broker/broker_test.go b/pkg/reconciler/broker/broker_test.go index 1770c955cb7..872e2ce762a 100644 --- a/pkg/reconciler/broker/broker_test.go +++ b/pkg/reconciler/broker/broker_test.go @@ -19,6 +19,7 @@ package broker import ( "context" "fmt" + sourcesv1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" "testing" corev1 "k8s.io/api/core/v1" @@ -33,7 +34,6 @@ import ( eventingduckv1beta1 "knative.dev/eventing/pkg/apis/duck/v1beta1" "knative.dev/eventing/pkg/apis/eventing" "knative.dev/eventing/pkg/apis/eventing/v1alpha1" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" messagingv1alpha1 "knative.dev/eventing/pkg/apis/messaging/v1alpha1" "knative.dev/eventing/pkg/client/injection/ducks/duck/v1alpha1/channelable" "knative.dev/eventing/pkg/client/injection/reconciler/eventing/v1alpha1/broker" @@ -87,12 +87,11 @@ const ( brokerGeneration = 79 - cronJobSourceName = "test-cronjob-source" - cronJobSourceAPIVersion = "sources.eventing.knative.dev/v1alpha1" + pingSourceName = "test-ping-source" testSchedule = "*/2 * * * *" testData = "data" sinkName = "testsink" - dependencyAnnotation = "{\"kind\":\"CronJobSource\",\"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}" + dependencyAnnotation = "{\"kind\":\"PingSource\",\"name\":\"test-ping-source\",\"apiVersion\":\"sources.knative.dev/v1alpha2\"}" subscriberURIReference = "foo" subscriberResolvedTargetURI = "http://example.com/subscriber/foo" @@ -155,6 +154,13 @@ var ( APIVersion: "eventing.knative.dev/v1alpha1", }, } + brokerDestv1 = duckv1.Destination{ + Ref: &duckv1.KReference{ + Name: sinkName, + Kind: "Broker", + APIVersion: "eventing.knative.dev/v1alpha1", + }, + } sinkDNS = "sink.mynamespace.svc." + utils.GetClusterDomainName() sinkURI = "http://" + sinkDNS finalizerUpdatedEvent = Eventf(corev1.EventTypeNormal, "FinalizerUpdate", `Updated "test-broker" finalizers`) @@ -1247,7 +1253,7 @@ func TestReconcile(t *testing.T) { WithDependencyAnnotation(dependencyAnnotation), )}...), WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "TriggerReconcileFailed", "Trigger reconcile failed: propagating dependency readiness: getting the dependency: cronjobsources.sources.eventing.knative.dev \"test-cronjob-source\" not found"), + Eventf(corev1.EventTypeWarning, "TriggerReconcileFailed", "Trigger reconcile failed: propagating dependency readiness: getting the dependency: pingsources.sources.knative.dev \"test-ping-source\" not found"), }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: NewTrigger(triggerName, testNS, brokerName, @@ -1260,7 +1266,7 @@ func TestReconcile(t *testing.T) { WithTriggerSubscribed(), WithTriggerStatusSubscriberURI(subscriberURI), WithTriggerSubscriberResolvedSucceeded(), - WithTriggerDependencyFailed("DependencyDoesNotExist", "Dependency does not exist: cronjobsources.sources.eventing.knative.dev \"test-cronjob-source\" not found"), + WithTriggerDependencyFailed("DependencyDoesNotExist", "Dependency does not exist: pingsources.sources.knative.dev \"test-ping-source\" not found"), ), }}, }, { @@ -1268,7 +1274,7 @@ func TestReconcile(t *testing.T) { Key: testKey, Objects: allBrokerObjectsReadyPlus([]runtime.Object{ makeReadySubscription(), - makeFalseStatusCronJobSource(), + makeFalseStatusPingSource(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(triggerUID), WithTriggerSubscriberURI(subscriberURI), @@ -1327,7 +1333,7 @@ func TestReconcile(t *testing.T) { Key: testKey, Objects: allBrokerObjectsReadyPlus([]runtime.Object{ makeReadySubscription(), - makeGenerationNotEqualCronJobSource(), + makeGenerationNotEqualPingSource(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(triggerUID), WithTriggerSubscriberURI(subscriberURI), @@ -1356,7 +1362,7 @@ func TestReconcile(t *testing.T) { Key: testKey, Objects: allBrokerObjectsReadyPlus([]runtime.Object{ makeReadySubscription(), - makeReadyCronJobSource(), + makeReadyPingSource(), NewTrigger(triggerName, testNS, brokerName, WithTriggerUID(triggerUID), WithTriggerSubscriberURI(subscriberURI), @@ -1795,37 +1801,39 @@ func makeFalseStatusSubscription() *messagingv1alpha1.Subscription { return s } -func makeFalseStatusCronJobSource() *sourcesv1alpha1.CronJobSource { - return NewCronJobSource(cronJobSourceName, testNS, WithCronJobApiVersion(cronJobSourceAPIVersion), WithCronJobSourceSinkNotFound) +func makeFalseStatusPingSource() *sourcesv1alpha2.PingSource { + return NewPingSourceV1Alpha2(pingSourceName, testNS, WithPingSourceV1A2SinkNotFound) } -func makeUnknownStatusCronJobSource() *sourcesv1alpha1.CronJobSource { - cjs := NewCronJobSource(cronJobSourceName, testNS, WithCronJobApiVersion(cronJobSourceAPIVersion)) - cjs.Status = *v1alpha1.TestHelper.UnknownCronJobSourceStatus() +func makeUnknownStatusCronJobSource() *sourcesv1alpha2.PingSource { + cjs := NewPingSourceV1Alpha2(pingSourceName, testNS) + cjs.Status.InitializeConditions() return cjs } -func makeGenerationNotEqualCronJobSource() *sourcesv1alpha1.CronJobSource { - c := makeFalseStatusCronJobSource() +func makeGenerationNotEqualPingSource() *sourcesv1alpha2.PingSource { + c := makeFalseStatusPingSource() c.Generation = currentGeneration c.Status.ObservedGeneration = outdatedGeneration return c } -func makeReadyCronJobSource() *sourcesv1alpha1.CronJobSource { - return NewCronJobSource(cronJobSourceName, testNS, - WithCronJobApiVersion(cronJobSourceAPIVersion), - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ +func makeReadyPingSource() *sourcesv1alpha2.PingSource { + u, _ := apis.ParseURL(sinkURI) + return NewPingSourceV1Alpha2(pingSourceName, testNS, + WithPingSourceV1A2Spec(sourcesv1alpha2.PingSourceSpec{ Schedule: testSchedule, - Data: testData, - Sink: &brokerDest, + JsonData: testData, + SourceSpec: duckv1.SourceSpec{ + Sink: brokerDestv1, + }, }), - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceEventType, - WithCronJobSourceSink(sinkURI), + WithInitPingSourceV1A2Conditions, + WithValidPingSourceV1A2Schedule, + WithValidPingSourceV1A2Resources, + WithPingSourceV1A2Deployed, + WithPingSourceV1A2EventType, + WithPingSourceV1A2Sink(u), ) } func makeSubscriberKubernetesServiceAsUnstructured() *unstructured.Unstructured { diff --git a/pkg/reconciler/legacyapiserversource/apiserversource.go b/pkg/reconciler/legacyapiserversource/apiserversource.go deleted file mode 100644 index b0a4560e85a..00000000000 --- a/pkg/reconciler/legacyapiserversource/apiserversource.go +++ /dev/null @@ -1,521 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacyapiserversource - -import ( - "context" - "fmt" - "reflect" - "time" - - "go.uber.org/zap" - appsv1 "k8s.io/api/apps/v1" - authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - appsv1listers "k8s.io/client-go/listers/apps/v1" - corev1listers "k8s.io/client-go/listers/core/v1" - rbacv1listers "k8s.io/client-go/listers/rbac/v1" - "k8s.io/client-go/tools/cache" - pkgLogging "knative.dev/pkg/logging" - "knative.dev/pkg/metrics" - "knative.dev/pkg/resolver" - - eventingv1alpha1 "knative.dev/eventing/pkg/apis/eventing/v1alpha1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - eventinglisters "knative.dev/eventing/pkg/client/listers/eventing/v1alpha1" - listers "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" - "knative.dev/eventing/pkg/logging" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/eventing/pkg/reconciler/legacyapiserversource/resources" -) - -const ( - // Name of the corev1.Events emitted from the reconciliation process - apiserversourceReconciled = "ApiServerSourceReconciled" - apiServerSourceReadinessChanged = "ApiServerSourceReadinessChanged" - apiserversourceUpdateStatusFailed = "ApiServerSourceUpdateStatusFailed" - apiserversourceDeploymentCreated = "ApiServerSourceDeploymentCreated" - apiserversourceDeploymentUpdated = "ApiServerSourceDeploymentUpdated" - - // raImageEnvVar is the name of the environment variable that contains the receive adapter's - // image. It must be defined. - raImageEnvVar = "APISERVER_RA_IMAGE" - - component = "apiserversource" -) - -var ( - deploymentGVK = appsv1.SchemeGroupVersion.WithKind("Deployment") -) - -var apiServerEventTypes = []string{ - v1alpha1.ApiServerSourceAddEventType, - v1alpha1.ApiServerSourceDeleteEventType, - v1alpha1.ApiServerSourceUpdateEventType, - v1alpha1.ApiServerSourceAddRefEventType, - v1alpha1.ApiServerSourceDeleteRefEventType, - v1alpha1.ApiServerSourceUpdateRefEventType, -} - -// Reconciler reconciles a ApiServerSource object -type Reconciler struct { - *reconciler.Base - - receiveAdapterImage string - - // listers index properties about resources - apiserversourceLister listers.ApiServerSourceLister - deploymentLister appsv1listers.DeploymentLister - eventTypeLister eventinglisters.EventTypeLister - roleLister rbacv1listers.RoleLister - roleBindingLister rbacv1listers.RoleBindingLister - clusterRoleLister rbacv1listers.ClusterRoleLister - clusterRoleBindingLister rbacv1listers.ClusterRoleBindingLister - serviceAccountLister corev1listers.ServiceAccountLister - - source string - sinkResolver *resolver.URIResolver - loggingContext context.Context - loggingConfig *pkgLogging.Config - metricsConfig *metrics.ExporterOptions -} - -// Reconcile compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the ApiServerSource -// resource with the current status of the resource. -func (r *Reconciler) Reconcile(ctx context.Context, key string) error { - // Convert the namespace/name string into a distinct namespace and name - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - logging.FromContext(ctx).Error("invalid resource key") - return nil - } - - // Get the ApiServerSource resource with this namespace/name - original, err := r.apiserversourceLister.ApiServerSources(namespace).Get(name) - if apierrors.IsNotFound(err) { - // The resource may no longer exist, in which case we stop processing. - logging.FromContext(ctx).Error("ApiServerSource key in work queue no longer exists") - return nil - } else if err != nil { - return err - } - - // Don't modify the informers copy - apiserversource := original.DeepCopy() - - // Reconcile this copy of the ApiServerSource and then write back any status - // updates regardless of whether the reconcile error out. - err = r.reconcile(ctx, apiserversource) - if err != nil { - logging.FromContext(ctx).Warn("Error reconciling ApiServerSource", zap.Error(err)) - } else { - logging.FromContext(ctx).Debug("ApiServerSource reconciled") - r.Recorder.Eventf(apiserversource, corev1.EventTypeNormal, apiserversourceReconciled, `ApiServerSource reconciled: "%s/%s"`, apiserversource.Namespace, apiserversource.Name) - } - - if _, updateStatusErr := r.updateStatus(ctx, apiserversource.DeepCopy()); updateStatusErr != nil { - logging.FromContext(ctx).Warn("Failed to update the ApiServerSource", zap.Error(err)) - r.Recorder.Eventf(apiserversource, corev1.EventTypeWarning, apiserversourceUpdateStatusFailed, "Failed to update ApiServerSource's status: %v", err) - return updateStatusErr - } - - // Requeue if the resource is not ready: - return err -} - -func (r *Reconciler) reconcile(ctx context.Context, source *v1alpha1.ApiServerSource) error { - // This Source attempts to reconcile three things. - // 1. Determine the sink's URI. - // - Nothing to delete. - // 2. Create a receive adapter in the form of a Deployment. - // - Will be garbage collected by K8s when this CronJobSource is deleted. - // 3. Create the EventType that it can emit. - // - Will be garbage collected by K8s when this CronJobSource is deleted. - source.Status.ObservedGeneration = source.Generation - - source.Status.InitializeConditions() - - source.MarkDeprecated(&source.Status.Status, "ApiServerSourceDeprecated", "apiserversources.sources.eventing.knative.dev are deprecated and will be removed in the future. Use apiserversources.sources.knative.dev instead.") - - if source.Spec.Sink == nil { - source.Status.MarkNoSink("SinkMissing", "") - return fmt.Errorf("spec.sink missing") - } - - dest := source.Spec.Sink.DeepCopy() - if dest.Ref != nil { - // To call URIFromDestination(), dest.Ref must have a Namespace. If there is - // no Namespace defined in dest.Ref, we will use the Namespace of the source - // as the Namespace of dest.Ref. - if dest.Ref.Namespace == "" { - //TODO how does this work with deprecated fields - dest.Ref.Namespace = source.GetNamespace() - } - } else if dest.DeprecatedName != "" && dest.DeprecatedNamespace == "" { - // If Ref is nil and the deprecated ref is present, we need to check for - // DeprecatedNamespace. This can be removed when DeprecatedNamespace is - // removed. - dest.DeprecatedNamespace = source.GetNamespace() - } - - sinkURI, err := r.sinkResolver.URIFromDestination(*dest, source) - if err != nil { - source.Status.MarkNoSink("NotFound", "") - return fmt.Errorf("getting sink URI: %v", err) - } - if source.Spec.Sink.DeprecatedAPIVersion != "" && - source.Spec.Sink.DeprecatedKind != "" && - source.Spec.Sink.DeprecatedName != "" { - source.Status.MarkSinkWarnRefDeprecated(sinkURI) - } else { - source.Status.MarkSink(sinkURI) - } - - err = r.runAccessCheck(source) - if err != nil { - logging.FromContext(ctx).Error("Not enough permission", zap.Error(err)) - return err - } - - ra, err := r.createReceiveAdapter(ctx, source, sinkURI) - if err != nil { - logging.FromContext(ctx).Error("Unable to create the receive adapter", zap.Error(err)) - return err - } - source.Status.PropagateDeploymentAvailability(ra) - - err = r.reconcileEventTypes(ctx, source) - if err != nil { - source.Status.MarkNoEventTypes("EventTypesReconcileFailed", "") - return fmt.Errorf("reconciling event types: %v", err) - } - source.Status.MarkEventTypes() - - return nil -} - -func (r *Reconciler) createReceiveAdapter(ctx context.Context, src *v1alpha1.ApiServerSource, sinkURI string) (*appsv1.Deployment, error) { - // TODO: missing. - // if err := checkResourcesStatus(src); err != nil { - // return nil, err - // } - - loggingConfig, err := pkgLogging.LoggingConfigToJson(r.loggingConfig) - if err != nil { - logging.FromContext(ctx).Error("error while converting logging config to json", zap.Any("receiveAdapter", err)) - } - - metricsConfig, err := metrics.MetricsOptionsToJson(r.metricsConfig) - if err != nil { - logging.FromContext(ctx).Error("error while converting metrics config to json", zap.Any("receiveAdapter", err)) - } - - adapterArgs := resources.ReceiveAdapterArgs{ - Image: r.receiveAdapterImage, - Source: src, - Labels: resources.Labels(src.Name), - SinkURI: sinkURI, - LoggingConfig: loggingConfig, - MetricsConfig: metricsConfig, - } - expected := resources.MakeReceiveAdapter(&adapterArgs) - - ra, err := r.KubeClientSet.AppsV1().Deployments(src.Namespace).Get(expected.Name, metav1.GetOptions{}) - if apierrors.IsNotFound(err) { - ra, err = r.KubeClientSet.AppsV1().Deployments(src.Namespace).Create(expected) - msg := "Deployment created" - if err != nil { - msg = fmt.Sprintf("Deployment created, error: %v", err) - } - r.Recorder.Eventf(src, corev1.EventTypeNormal, apiserversourceDeploymentCreated, "%s", msg) - return ra, err - } else if err != nil { - return nil, fmt.Errorf("error getting receive adapter: %v", err) - } else if !metav1.IsControlledBy(ra, src) { - return nil, fmt.Errorf("deployment %q is not owned by ApiServerSource %q", ra.Name, src.Name) - } else if r.podSpecChanged(ra.Spec.Template.Spec, expected.Spec.Template.Spec) { - ra.Spec.Template.Spec = expected.Spec.Template.Spec - if ra, err = r.KubeClientSet.AppsV1().Deployments(src.Namespace).Update(ra); err != nil { - return ra, err - } - r.Recorder.Eventf(src, corev1.EventTypeNormal, apiserversourceDeploymentUpdated, "Deployment %q updated", ra.Name) - return ra, nil - } else { - logging.FromContext(ctx).Debug("Reusing existing receive adapter", zap.Any("receiveAdapter", ra)) - } - return ra, nil -} - -func (r *Reconciler) podSpecChanged(oldPodSpec corev1.PodSpec, newPodSpec corev1.PodSpec) bool { - if !equality.Semantic.DeepDerivative(newPodSpec, oldPodSpec) { - return true - } - if len(oldPodSpec.Containers) != len(newPodSpec.Containers) { - return true - } - for i := range newPodSpec.Containers { - if !equality.Semantic.DeepEqual(newPodSpec.Containers[i].Env, oldPodSpec.Containers[i].Env) { - return true - } - } - return false -} - -func (r *Reconciler) reconcileEventTypes(ctx context.Context, src *v1alpha1.ApiServerSource) error { - current, err := r.getEventTypes(ctx, src) - if err != nil { - logging.FromContext(ctx).Error("Unable to get existing event types", zap.Error(err)) - return err - } - - expected, err := r.makeEventTypes(src) - if err != nil { - return err - } - - toCreate, toDelete := r.computeDiff(current, expected) - - for _, eventType := range toDelete { - if err = r.EventingClientSet.EventingV1alpha1().EventTypes(src.Namespace).Delete(eventType.Name, &metav1.DeleteOptions{}); err != nil { - logging.FromContext(ctx).Error("Error deleting eventType", zap.Any("eventType", eventType)) - return err - } - } - - for _, eventType := range toCreate { - if _, err = r.EventingClientSet.EventingV1alpha1().EventTypes(src.Namespace).Create(&eventType); err != nil { - logging.FromContext(ctx).Error("Error creating eventType", zap.Any("eventType", eventType)) - return err - } - } - - return nil -} - -func (r *Reconciler) getEventTypes(ctx context.Context, src *v1alpha1.ApiServerSource) ([]eventingv1alpha1.EventType, error) { - etl, err := r.eventTypeLister.EventTypes(src.Namespace).List(r.getLabelSelector(src)) - if err != nil { - logging.FromContext(ctx).Error("Unable to list event types: %v", zap.Error(err)) - return nil, err - } - eventTypes := make([]eventingv1alpha1.EventType, 0) - for _, et := range etl { - if metav1.IsControlledBy(et, src) { - eventTypes = append(eventTypes, *et) - } - } - return eventTypes, nil -} - -func (r *Reconciler) makeEventTypes(src *v1alpha1.ApiServerSource) ([]eventingv1alpha1.EventType, error) { - eventTypes := make([]eventingv1alpha1.EventType, 0) - - // Only create EventTypes for Broker sinks. - // We add this check here in case the APIServerSource was changed from Broker to non-Broker sink. - // If so, we need to delete the existing ones, thus we return empty expected. - if ref := src.Spec.Sink.GetRef(); ref == nil || ref.Kind != "Broker" { - return eventTypes, nil - } - - args := &resources.EventTypeArgs{ - Src: src, - Source: r.source, - } - for _, apiEventType := range apiServerEventTypes { - args.Type = apiEventType - eventType := resources.MakeEventType(args) - eventTypes = append(eventTypes, eventType) - } - return eventTypes, nil -} - -func (r *Reconciler) computeDiff(current []eventingv1alpha1.EventType, expected []eventingv1alpha1.EventType) ([]eventingv1alpha1.EventType, []eventingv1alpha1.EventType) { - toCreate := make([]eventingv1alpha1.EventType, 0) - toDelete := make([]eventingv1alpha1.EventType, 0) - currentMap := asMap(current, keyFromEventType) - expectedMap := asMap(expected, keyFromEventType) - - // Iterate over the slices instead of the maps for predictable UT expectations. - for _, e := range expected { - if c, ok := currentMap[keyFromEventType(&e)]; !ok { - toCreate = append(toCreate, e) - } else { - if !equality.Semantic.DeepEqual(e.Spec, c.Spec) { - toDelete = append(toDelete, c) - toCreate = append(toCreate, e) - } - } - } - // Need to check whether the current EventTypes are not in the expected map. If so, we have to delete them. - // This could happen if the ApiServerSource CO changes its broker. - for _, c := range current { - if _, ok := expectedMap[keyFromEventType(&c)]; !ok { - toDelete = append(toDelete, c) - } - } - return toCreate, toDelete -} - -func asMap(eventTypes []eventingv1alpha1.EventType, keyFunc func(*eventingv1alpha1.EventType) string) map[string]eventingv1alpha1.EventType { - eventTypesAsMap := make(map[string]eventingv1alpha1.EventType, 0) - for _, eventType := range eventTypes { - key := keyFunc(&eventType) - eventTypesAsMap[key] = eventType - } - return eventTypesAsMap -} - -func keyFromEventType(eventType *eventingv1alpha1.EventType) string { - return fmt.Sprintf("%s_%s_%s_%s", eventType.Spec.Type, eventType.Spec.Source, eventType.Spec.Schema, eventType.Spec.Broker) -} - -func (r *Reconciler) getLabelSelector(src *v1alpha1.ApiServerSource) labels.Selector { - return labels.SelectorFromSet(resources.Labels(src.Name)) -} - -func (r *Reconciler) updateStatus(ctx context.Context, desired *v1alpha1.ApiServerSource) (*v1alpha1.ApiServerSource, error) { - apiserversource, err := r.apiserversourceLister.ApiServerSources(desired.Namespace).Get(desired.Name) - if err != nil { - return nil, err - } - - // If there's nothing to update, just return. - if reflect.DeepEqual(apiserversource.Status, desired.Status) { - return apiserversource, nil - } - - becomesReady := desired.Status.IsReady() && !apiserversource.Status.IsReady() - - // Don't modify the informers copy. - existing := apiserversource.DeepCopy() - existing.Status = desired.Status - - cj, err := r.LegacyClientSet.SourcesV1alpha1().ApiServerSources(desired.Namespace).UpdateStatus(existing) - if err == nil && becomesReady { - duration := time.Since(cj.ObjectMeta.CreationTimestamp.Time) - logging.FromContext(ctx).Info("ApiServerSource became ready after", zap.Duration("duration", duration)) - r.Recorder.Event(apiserversource, corev1.EventTypeNormal, apiServerSourceReadinessChanged, fmt.Sprintf("ApiServerSource %q became ready", apiserversource.Name)) - if err := r.StatsReporter.ReportReady("ApiServerSource", apiserversource.Namespace, apiserversource.Name, duration); err != nil { - logging.FromContext(ctx).Sugar().Infof("failed to record ready for ApiServerSource, %v", err) - } - } - - return cj, err -} - -// TODO determine how to push the updated logging config to existing data plane Pods. -func (r *Reconciler) UpdateFromLoggingConfigMap(cfg *corev1.ConfigMap) { - if cfg != nil { - delete(cfg.Data, "_example") - } - - logcfg, err := pkgLogging.NewConfigFromConfigMap(cfg) - if err != nil { - logging.FromContext(r.loggingContext).Warn("failed to create logging config from configmap", zap.String("cfg.Name", cfg.Name)) - return - } - r.loggingConfig = logcfg - logging.FromContext(r.loggingContext).Info("Update from logging ConfigMap", zap.Any("ConfigMap", cfg)) -} - -// TODO determine how to push the updated metrics config to existing data plane Pods. -func (r *Reconciler) UpdateFromMetricsConfigMap(cfg *corev1.ConfigMap) { - if cfg != nil { - delete(cfg.Data, "_example") - } - - r.metricsConfig = &metrics.ExporterOptions{ - Domain: metrics.Domain(), - Component: component, - ConfigMap: cfg.Data, - } - logging.FromContext(r.loggingContext).Info("Update from metrics ConfigMap", zap.Any("ConfigMap", cfg)) -} - -func (r *Reconciler) runAccessCheck(src *v1alpha1.ApiServerSource) error { - if src.Spec.Resources == nil || len(src.Spec.Resources) == 0 { - src.Status.MarkSufficientPermissions() - return nil - } - - user := "system:serviceaccount:" + src.Namespace + ":" - if src.Spec.ServiceAccountName == "" { - user += "default" - } else { - user += src.Spec.ServiceAccountName - } - - verbs := []string{"get", "list", "watch"} - resources := src.Spec.Resources - lastReason := "" - - // Collect all missing permissions. - missing := "" - sep := "" - - for _, res := range resources { - gv, err := schema.ParseGroupVersion(res.APIVersion) - if err != nil { // shouldn't happened after #2134 is fixed - return err - } - gvr, _ := meta.UnsafeGuessKindToResource(schema.GroupVersionKind{Kind: res.Kind, Group: gv.Group, Version: gv.Version}) - missingVerbs := "" - sep1 := "" - for _, verb := range verbs { - sar := &authorizationv1.SubjectAccessReview{ - Spec: authorizationv1.SubjectAccessReviewSpec{ - ResourceAttributes: &authorizationv1.ResourceAttributes{ - Namespace: src.Namespace, - Verb: verb, - Group: gv.Group, - Resource: gvr.Resource, - }, - User: user, - }, - } - - response, err := r.KubeClientSet.AuthorizationV1().SubjectAccessReviews().Create(sar) - if err != nil { - return err - } - - if !response.Status.Allowed { - missingVerbs += sep1 + verb - sep1 = ", " - } - } - if missingVerbs != "" { - missing += sep + missingVerbs + ` resource "` + gvr.Resource + `" in API group "` + gv.Group + `"` - sep = ", " - } - } - if missing == "" { - src.Status.MarkSufficientPermissions() - return nil - } - - src.Status.MarkNoSufficientPermissions(lastReason, "User %s cannot %s", user, missing) - return fmt.Errorf("Insufficient permission: user %s cannot %s", user, missing) - -} diff --git a/pkg/reconciler/legacyapiserversource/apiserversource_test.go b/pkg/reconciler/legacyapiserversource/apiserversource_test.go deleted file mode 100644 index 0ed89f4ff83..00000000000 --- a/pkg/reconciler/legacyapiserversource/apiserversource_test.go +++ /dev/null @@ -1,1029 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacyapiserversource - -import ( - "context" - "fmt" - "testing" - - appsv1 "k8s.io/api/apps/v1" - authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - clientgotesting "k8s.io/client-go/testing" - - "knative.dev/eventing/pkg/apis/eventing/v1alpha1" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/eventing/pkg/reconciler/legacyapiserversource/resources" - "knative.dev/eventing/pkg/utils" - "knative.dev/pkg/apis" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/client/injection/ducks/duck/v1/addressable" - _ "knative.dev/pkg/client/injection/ducks/duck/v1beta1/addressable/fake" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/resolver" - - . "knative.dev/eventing/pkg/reconciler/testing" - logtesting "knative.dev/pkg/logging/testing" - . "knative.dev/pkg/reconciler/testing" -) - -var ( - sinkDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Channel", - APIVersion: "messaging.knative.dev/v1alpha1", - }, - } - brokerDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Broker", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - } - sinkDNS = "sink.mynamespace.svc." + utils.GetClusterDomainName() - sinkURI = "http://" + sinkDNS - sinkURIReference = "/foo" - sinkTargetURI = sinkURI + sinkURIReference - sinkDestURI = duckv1beta1.Destination{ - URI: apis.HTTP(sinkDNS), - } -) - -const ( - image = "github.com/knative/test/image" - sourceName = "test-apiserver-source" - sourceUID = "1234" - testNS = "testnamespace" - - sinkName = "testsink" - source = "apiserveraddr" - - generation = 1 -) - -func init() { - // Add types to scheme - _ = appsv1.AddToScheme(scheme.Scheme) - _ = corev1.AddToScheme(scheme.Scheme) - _ = duckv1alpha1.AddToScheme(scheme.Scheme) -} - -func TestReconcile(t *testing.T) { - table := TableTest{ - { - Name: "missing sink", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - WithLegacyApiServerSourceSinkNotFound, - ), - }}, - }, { - Name: "not enough permissions", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceNoSufficientPermissions, - ), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WantErr: true, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(false)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with sink URI", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDestURI, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDestURI, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with deprecated sink fields", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &duckv1beta1.Destination{ - DeprecatedAPIVersion: sinkDest.Ref.APIVersion, - DeprecatedKind: sinkDest.Ref.Kind, - DeprecatedName: sinkDest.Ref.Name, - }, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &duckv1beta1.Destination{ - DeprecatedAPIVersion: sinkDest.Ref.APIVersion, - DeprecatedKind: sinkDest.Ref.Kind, - DeprecatedName: sinkDest.Ref.Name, - }, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSinkDepRef(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with relative uri reference", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &duckv1beta1.Destination{ - Ref: sinkDest.Ref, - URI: &apis.URL{Path: sinkURIReference}, - }, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapterWithTargetURI(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &duckv1beta1.Destination{ - Ref: sinkDest.Ref, - URI: &apis.URL{Path: sinkURIReference}, - }, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkTargetURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "deployment update due to env", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeReceiveAdapterWithDifferentEnv(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceDeploymentUpdated", "Deployment \"apiserversource-test-apiserver-source-1234\" updated"), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceDeploymentUnavailable, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantUpdates: []clientgotesting.UpdateActionImpl{{ - Object: makeReceiveAdapter(), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "deployment update due to service account", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - ServiceAccountName: "malin", - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeReceiveAdapterWithDifferentServiceAccount("morgan"), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceDeploymentUpdated", "Deployment \"apiserversource-test-apiserver-source-1234\" updated"), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - ServiceAccountName: "malin", - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeploymentUnavailable, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantUpdates: []clientgotesting.UpdateActionImpl{{ - Object: makeReceiveAdapterWithDifferentServiceAccount("malin"), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "malin"), - makeSubjectAccessReview("namespaces", "list", "malin"), - makeSubjectAccessReview("namespaces", "watch", "malin"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "deployment update due to container count", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeReceiveAdapterWithDifferentContainerCount(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceDeploymentUpdated", "Deployment \"apiserversource-test-apiserver-source-1234\" updated"), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeploymentUnavailable, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantUpdates: []clientgotesting.UpdateActionImpl{{ - Object: makeReceiveAdapter(), - }}, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with event types to delete", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeEventTypeWithName(sourcesv1alpha1.ApiServerSourceAddEventType, "name-1"), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantDeletes: []clientgotesting.DeleteActionImpl{ - {Name: "name-1"}, - }, - WantCreates: []runtime.Object{ - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with broker sink", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewBroker(sinkName, testNS, - WithInitBrokerConditions, - WithBrokerAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeEventType(sourcesv1alpha1.ApiServerSourceAddEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceDeleteEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceUpdateEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceAddRefEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceDeleteRefEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceUpdateRefEventType), - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with broker sink and missing event types", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewBroker(sinkName, testNS, - WithInitBrokerConditions, - WithBrokerAddress(sinkDNS), - ), - makeEventTypeWithName(sourcesv1alpha1.ApiServerSourceAddEventType, "name-1"), - makeEventTypeWithName(sourcesv1alpha1.ApiServerSourceDeleteEventType, "name-2"), - makeEventTypeWithName(sourcesv1alpha1.ApiServerSourceUpdateEventType, "name-3"), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeEventType(sourcesv1alpha1.ApiServerSourceAddRefEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceDeleteRefEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceUpdateRefEventType), - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - { - Name: "valid with broker sink and event types to delete", - Objects: []runtime.Object{ - NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - ), - NewBroker(sinkName, testNS, - WithInitBrokerConditions, - WithBrokerAddress(sinkDNS), - ), - // https://github.com/knative/pkg/issues/411 - // Be careful adding more EventTypes here, the current unit test lister does not - // return items in a fixed order, so the EventTypes can come back in any order. - // WantDeletes requires the order to be correct, so will be flaky if we add more - // than one EventType here. - makeEventTypeWithName("type1", "name-1"), - makeAvailableReceiveAdapter(), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "ApiServerSourceReconciled", `ApiServerSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "ApiServerSourceReadinessChanged", `ApiServerSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - WithLegacyApiServerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - WithLegacyApiServerSourceSufficientPermissions, - WithLegacyApiServerSourceEventTypes, - WithLegacyApiServerSourceStatusObservedGeneration(generation), - ), - }}, - WantDeletes: []clientgotesting.DeleteActionImpl{ - {Name: "name-1"}, - }, - WantCreates: []runtime.Object{ - makeEventType(sourcesv1alpha1.ApiServerSourceAddEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceDeleteEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceUpdateEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceAddRefEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceDeleteRefEventType), - makeEventType(sourcesv1alpha1.ApiServerSourceUpdateRefEventType), - makeSubjectAccessReview("namespaces", "get", "default"), - makeSubjectAccessReview("namespaces", "list", "default"), - makeSubjectAccessReview("namespaces", "watch", "default"), - }, - WithReactors: []clientgotesting.ReactionFunc{subjectAccessReviewCreateReactor(true)}, - SkipNamespaceValidation: true, // SubjectAccessReview objects are cluster-scoped. - }, - } - - logger := logtesting.TestLogger(t) - table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler { - ctx = addressable.WithDuck(ctx) - r := &Reconciler{ - Base: reconciler.NewBase(ctx, controllerAgentName, cmw), - apiserversourceLister: listers.GetLegacyApiServerSourceLister(), - deploymentLister: listers.GetDeploymentLister(), - eventTypeLister: listers.GetEventTypeLister(), - source: source, - receiveAdapterImage: image, - sinkResolver: resolver.NewURIResolver(ctx, func(types.NamespacedName) {}), - } - return r - }, - true, - logger, - )) -} - -func makeReceiveAdapter() *appsv1.Deployment { - src := NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - ) - - args := resources.ReceiveAdapterArgs{ - Image: image, - Source: src, - Labels: resources.Labels(sourceName), - SinkURI: sinkURI, - } - return resources.MakeReceiveAdapter(&args) -} - -func makeAvailableReceiveAdapter() *appsv1.Deployment { - ra := makeReceiveAdapter() - WithDeploymentAvailable()(ra) - return ra -} - -func makeAvailableReceiveAdapterWithTargetURI() *appsv1.Deployment { - src := NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &sinkDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - // Status Update: - WithInitLegacyApiServerSourceConditions, - WithLegacyApiServerSourceDeployed, - WithLegacyApiServerSourceSink(sinkURI), - ) - - args := resources.ReceiveAdapterArgs{ - Image: image, - Source: src, - Labels: resources.Labels(sourceName), - SinkURI: sinkTargetURI, - } - ra := resources.MakeReceiveAdapter(&args) - WithDeploymentAvailable()(ra) - return ra -} - -func makeReceiveAdapterWithDifferentEnv() *appsv1.Deployment { - ra := makeReceiveAdapter() - ra.Spec.Template.Spec.Containers[0].Env = append(ra.Spec.Template.Spec.Containers[0].Env, corev1.EnvVar{ - Name: "not-in", - Value: "the-original", - }) - return ra -} - -func makeReceiveAdapterWithDifferentServiceAccount(name string) *appsv1.Deployment { - ra := makeReceiveAdapter() - ra.Spec.Template.Spec.ServiceAccountName = name - return ra -} - -func makeReceiveAdapterWithDifferentContainerCount() *appsv1.Deployment { - ra := makeReceiveAdapter() - ra.Spec.Template.Spec.Containers = append(ra.Spec.Template.Spec.Containers, corev1.Container{}) - return ra -} - -func makeEventTypeWithName(eventType, name string) *v1alpha1.EventType { - et := makeEventType(eventType) - et.Name = name - return et -} - -func makeEventType(eventType string) *v1alpha1.EventType { - return &v1alpha1.EventType{ - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("%s-%s", eventType, sourceUID), - Labels: resources.Labels(sourceName), - Namespace: testNS, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(makeApiServerSource(), schema.GroupVersionKind{ - Group: sourcesv1alpha1.SchemeGroupVersion.Group, - Version: sourcesv1alpha1.SchemeGroupVersion.Version, - Kind: "ApiServerSource", - }), - }, - }, - Spec: v1alpha1.EventTypeSpec{ - Type: eventType, - Source: source, - Broker: sinkName, - }, - } -} - -func makeSubjectAccessReview(resource, verb, sa string) *authorizationv1.SubjectAccessReview { - return &authorizationv1.SubjectAccessReview{ - Spec: authorizationv1.SubjectAccessReviewSpec{ - ResourceAttributes: &authorizationv1.ResourceAttributes{ - Namespace: testNS, - Verb: verb, - Group: "", - Resource: resource, - }, - User: "system:serviceaccount:" + testNS + ":" + sa, - }, - } -} - -func makeApiServerSource() *sourcesv1alpha1.ApiServerSource { - return NewLegacyApiServerSource(sourceName, testNS, - WithLegacyApiServerSourceSpec(sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - }, - Sink: &brokerDest, - }), - WithLegacyApiServerSourceUID(sourceUID), - ) -} - -func subjectAccessReviewCreateReactor(allowed bool) clientgotesting.ReactionFunc { - return func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) { - if action.GetVerb() == "create" && action.GetResource().Resource == "subjectaccessreviews" { - ret := action.(clientgotesting.CreateAction).GetObject().DeepCopyObject().(*authorizationv1.SubjectAccessReview) - ret.Status.Allowed = allowed - return true, ret, nil - } - return false, nil, nil - } -} diff --git a/pkg/reconciler/legacyapiserversource/cfg_host.go b/pkg/reconciler/legacyapiserversource/cfg_host.go deleted file mode 100644 index 875305ead16..00000000000 --- a/pkg/reconciler/legacyapiserversource/cfg_host.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacyapiserversource - -import ( - "context" - - "k8s.io/client-go/rest" - "knative.dev/pkg/injection" - "knative.dev/pkg/logging" -) - -func init() { - // This is a hack to gain access to the rest config. - injection.Default.RegisterClient(withCfgHost) -} - -// HostKey is used as the key for associating information -// with a context.Context. -type HostKey struct{} - -func withCfgHost(ctx context.Context, cfg *rest.Config) context.Context { - return context.WithValue(ctx, HostKey{}, cfg.Host) -} - -// GetCfgHost extracts the k8s rest config host from the context. -func GetCfgHost(ctx context.Context) string { - untyped := ctx.Value(HostKey{}) - if untyped == nil { - logging.FromContext(ctx).Fatal("Failed to load cfg host from context.") - } - return untyped.(string) -} diff --git a/pkg/reconciler/legacyapiserversource/controller.go b/pkg/reconciler/legacyapiserversource/controller.go deleted file mode 100644 index bb645cef214..00000000000 --- a/pkg/reconciler/legacyapiserversource/controller.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacyapiserversource - -import ( - "context" - - "github.com/kelseyhightower/envconfig" - "k8s.io/client-go/tools/cache" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/metrics" - "knative.dev/pkg/resolver" - - eventtypeinformer "knative.dev/eventing/pkg/client/injection/informers/eventing/v1alpha1/eventtype" - apiserversourceinformer "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource" - deploymentinformer "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment" - - "knative.dev/pkg/logging" -) - -const ( - // ReconcilerName is the name of the reconciler - ReconcilerName = "ApiServerSources" - - // controllerAgentName is the string used by this controller to identify - // itself when creating events. - controllerAgentName = "legacy-apiserver-source-controller" -) - -// envConfig will be used to extract the required environment variables using -// github.com/kelseyhightower/envconfig. If this configuration cannot be extracted, then -// NewController will panic. -type envConfig struct { - Image string `envconfig:"APISERVER_RA_IMAGE" required:"true"` -} - -// NewController initializes the controller and is called by the generated code -// Registers event handlers to enqueue events -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - - deploymentInformer := deploymentinformer.Get(ctx) - apiServerSourceInformer := apiserversourceinformer.Get(ctx) - eventTypeInformer := eventtypeinformer.Get(ctx) - - r := &Reconciler{ - Base: reconciler.NewBase(ctx, controllerAgentName, cmw), - apiserversourceLister: apiServerSourceInformer.Lister(), - deploymentLister: deploymentInformer.Lister(), - eventTypeLister: eventTypeInformer.Lister(), - source: GetCfgHost(ctx), - loggingContext: ctx, - } - - env := &envConfig{} - if err := envconfig.Process("", env); err != nil { - r.Logger.Panicf("unable to process APIServerSource's required environment variables: %v", err) - } - r.receiveAdapterImage = env.Image - - impl := controller.NewImpl(r, r.Logger, ReconcilerName) - - r.sinkResolver = resolver.NewURIResolver(ctx, impl.EnqueueKey) - - r.Logger.Info("Setting up event handlers") - apiServerSourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - - deploymentInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.Filter(v1alpha1.SchemeGroupVersion.WithKind("ApiServerSource")), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }) - - eventTypeInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.Filter(v1alpha1.SchemeGroupVersion.WithKind("ApiServerSource")), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }) - - cmw.Watch(logging.ConfigMapName(), r.UpdateFromLoggingConfigMap) - cmw.Watch(metrics.ConfigMapName(), r.UpdateFromMetricsConfigMap) - - return impl -} diff --git a/pkg/reconciler/legacyapiserversource/controller_test.go b/pkg/reconciler/legacyapiserversource/controller_test.go deleted file mode 100644 index b39eefbf5ed..00000000000 --- a/pkg/reconciler/legacyapiserversource/controller_test.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacyapiserversource - -import ( - "os" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - "knative.dev/pkg/configmap" - . "knative.dev/pkg/reconciler/testing" - - // Fake injection informers - _ "knative.dev/eventing/pkg/client/injection/informers/eventing/v1alpha1/eventtype/fake" - _ "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/apiserversource/fake" - "knative.dev/pkg/client/injection/ducks/duck/v1/addressable" - _ "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment/fake" -) - -func TestNew(t *testing.T) { - ctx, _ := SetupFakeContext(t) - ctx = withCfgHost(ctx, &rest.Config{Host: "unit_test"}) - ctx = addressable.WithDuck(ctx) - os.Setenv("METRICS_DOMAIN", "knative.dev/eventing") - os.Setenv("APISERVER_RA_IMAGE", "knative.dev/example") - c := NewController(ctx, configmap.NewStaticWatcher(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: "config-observability", - Namespace: "knative-eventing", - }, - Data: map[string]string{ - "_example": "test-config", - }, - }, &corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: "config-logging", - Namespace: "knative-eventing", - }, - Data: map[string]string{ - "zap-logger-config": "test-config", - "loglevel.controller": "info", - "loglevel.webhook": "info", - }, - })) - - if c == nil { - t.Fatal("Expected NewController to return a non-nil value") - } -} diff --git a/pkg/reconciler/legacyapiserversource/doc.go b/pkg/reconciler/legacyapiserversource/doc.go deleted file mode 100644 index 48036ded3b5..00000000000 --- a/pkg/reconciler/legacyapiserversource/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2019 The Knative 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 apiserversource implements the ApiSource controller. -package legacyapiserversource diff --git a/pkg/reconciler/legacyapiserversource/resources/eventtype.go b/pkg/reconciler/legacyapiserversource/resources/eventtype.go deleted file mode 100644 index 31b44be85b0..00000000000 --- a/pkg/reconciler/legacyapiserversource/resources/eventtype.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - eventingv1alpha1 "knative.dev/eventing/pkg/apis/eventing/v1alpha1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/utils" -) - -// EventTypeArgs are the arguments needed to create an EventType for an Api Server Source. -type EventTypeArgs struct { - Src *v1alpha1.ApiServerSource - Type string - Source string -} - -// MakeEventType creates the in-memory representation of the EventType for the specified ApiServerSource. -func MakeEventType(args *EventTypeArgs) eventingv1alpha1.EventType { - return eventingv1alpha1.EventType{ - ObjectMeta: metav1.ObjectMeta{ - Name: utils.GenerateFixedName(args.Src, utils.ToDNS1123Subdomain(args.Type)), - Labels: Labels(args.Src.Name), - Namespace: args.Src.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(args.Src, schema.GroupVersionKind{ - Group: v1alpha1.SchemeGroupVersion.Group, - Version: v1alpha1.SchemeGroupVersion.Version, - Kind: "ApiServerSource", - }), - }, - }, - Spec: eventingv1alpha1.EventTypeSpec{ - Type: args.Type, - Source: args.Source, - Broker: args.Src.Spec.Sink.GetRef().Name, - }, - } -} diff --git a/pkg/reconciler/legacyapiserversource/resources/labels.go b/pkg/reconciler/legacyapiserversource/resources/labels.go deleted file mode 100644 index 72364eed98b..00000000000 --- a/pkg/reconciler/legacyapiserversource/resources/labels.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -const ( - // controllerAgentName is the string used by this controller to identify - // itself when creating events. - controllerAgentName = "apiserver-source-controller" -) - -func Labels(name string) map[string]string { - return map[string]string{ - "eventing.knative.dev/source": controllerAgentName, - "eventing.knative.dev/sourceName": name, - } -} diff --git a/pkg/reconciler/legacyapiserversource/resources/receive_adapter.go b/pkg/reconciler/legacyapiserversource/resources/receive_adapter.go deleted file mode 100644 index 87148fb006e..00000000000 --- a/pkg/reconciler/legacyapiserversource/resources/receive_adapter.go +++ /dev/null @@ -1,161 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "fmt" - - v1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/utils" - "knative.dev/pkg/kmeta" -) - -// ReceiveAdapterArgs are the arguments needed to create a ApiServer Receive Adapter. -// Every field is required. -type ReceiveAdapterArgs struct { - Image string - Source *v1alpha1.ApiServerSource - Labels map[string]string - SinkURI string - MetricsConfig string - LoggingConfig string -} - -// MakeReceiveAdapter generates (but does not insert into K8s) the Receive Adapter Deployment for -// ApiServer Sources. -func MakeReceiveAdapter(args *ReceiveAdapterArgs) *v1.Deployment { - replicas := int32(1) - return &v1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: args.Source.Namespace, - Name: utils.GenerateFixedName(args.Source, fmt.Sprintf("apiserversource-%s", args.Source.Name)), - Labels: args.Labels, - OwnerReferences: []metav1.OwnerReference{ - *kmeta.NewControllerRef(args.Source), - }, - }, - Spec: v1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: args.Labels, - }, - Replicas: &replicas, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "false", // needs to talk to the api server. - }, - Labels: args.Labels, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: args.Source.Spec.ServiceAccountName, - Containers: []corev1.Container{ - { - Name: "receive-adapter", - Image: args.Image, - Env: makeEnv(args.SinkURI, args.LoggingConfig, args.MetricsConfig, &args.Source.Spec, args.Source.ObjectMeta.Name), - Ports: []corev1.ContainerPort{{ - Name: "metrics", - ContainerPort: 9090, - }}, - }, - }, - }, - }, - }, - } -} - -func makeEnv(sinkURI, loggingConfig, metricsConfig string, spec *v1alpha1.ApiServerSourceSpec, name string) []corev1.EnvVar { - apiversions := "" - kinds := "" - controlled := "" - selectors := "" - ownerapiversions := "" - ownerkinds := "" - sep := "" - boolsep := "" - - for _, res := range spec.Resources { - apiversions += sep + res.APIVersion - kinds += sep + res.Kind - ownerapiversions += sep + res.ControllerSelector.APIVersion - ownerkinds += sep + res.ControllerSelector.Kind - - if res.Controller { - controlled += boolsep + "true" - } else { - controlled += boolsep + "false" - } - - // No need to check for error here. - selector, _ := metav1.LabelSelectorAsSelector(&res.LabelSelector) - labelSelector := selector.String() - - selectors += sep + labelSelector - - sep = ";" - boolsep = "," - } - - return []corev1.EnvVar{{ - Name: "SINK_URI", - Value: sinkURI, - }, { - Name: "MODE", - Value: spec.Mode, - }, { - Name: "API_VERSION", - Value: apiversions, - }, { - Name: "KIND", - Value: kinds, - }, { - Name: "OWNER_API_VERSION", - Value: ownerapiversions, - }, { - Name: "OWNER_KIND", - Value: ownerkinds, - }, { - Name: "CONTROLLER", - Value: controlled, - }, { - Name: "SELECTOR", - Value: selectors, - }, { - Name: "NAMESPACE", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, { - Name: "NAME", - Value: name, - }, { - Name: "METRICS_DOMAIN", - Value: "knative.dev/eventing", - }, { - Name: "K_METRICS_CONFIG", - Value: metricsConfig, - }, { - Name: "K_LOGGING_CONFIG", - Value: loggingConfig, - }} -} diff --git a/pkg/reconciler/legacyapiserversource/resources/receive_adapter_test.go b/pkg/reconciler/legacyapiserversource/resources/receive_adapter_test.go deleted file mode 100644 index fb090357157..00000000000 --- a/pkg/reconciler/legacyapiserversource/resources/receive_adapter_test.go +++ /dev/null @@ -1,202 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "fmt" - "testing" - - "github.com/google/go-cmp/cmp" - v1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - _ "knative.dev/pkg/metrics/testing" -) - -func TestMakeReceiveAdapter(t *testing.T) { - name := "source-name" - src := &v1alpha1.ApiServerSource{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: "source-namespace", - UID: "1234", - }, - Spec: v1alpha1.ApiServerSourceSpec{ - ServiceAccountName: "source-svc-acct", - Resources: []v1alpha1.ApiServerResource{ - { - APIVersion: "", - Kind: "Namespace", - }, - { - APIVersion: "", - Kind: "Pod", - Controller: true, - }, - { - APIVersion: "", - Kind: "Pod", - LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"test-key1": "test-value1"}, - }, - }, - { - APIVersion: "", - Kind: "Pod", - LabelSelector: metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - {Key: "akey", Operator: "Exists"}, - {Key: "anotherkey", Operator: "DoesNotExist"}, - }, - }, - }, - { - APIVersion: "", - Kind: "Pod", - LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"test-key2": "test-value2"}, - MatchExpressions: []metav1.LabelSelectorRequirement{ - {Key: "akey", Operator: "Exists"}, - {Key: "anotherkey", Operator: "DoesNotExist"}, - }, - }, - ControllerSelector: metav1.OwnerReference{ - APIVersion: "foo/v1alpha1", - Kind: "Foo", - }, - }, - }, - }, - } - - got := MakeReceiveAdapter(&ReceiveAdapterArgs{ - Image: "test-image", - Source: src, - Labels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - SinkURI: "sink-uri", - }) - - one := int32(1) - trueValue := true - - want := &v1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "source-namespace", - Name: fmt.Sprintf("apiserversource-%s-1234", name), - Labels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ApiServerSource", - Name: name, - UID: "1234", - Controller: &trueValue, - BlockOwnerDeletion: &trueValue, - }, - }, - }, - Spec: v1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - }, - Replicas: &one, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "false", - }, - Labels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "source-svc-acct", - Containers: []corev1.Container{ - { - Name: "receive-adapter", - Image: "test-image", - Ports: []corev1.ContainerPort{{ - Name: "metrics", - ContainerPort: 9090, - }}, - Env: []corev1.EnvVar{ - { - Name: "SINK_URI", - Value: "sink-uri", - }, { - Name: "MODE", - }, { - Name: "API_VERSION", - Value: ";;;;", - }, { - Name: "KIND", - Value: "Namespace;Pod;Pod;Pod;Pod", - }, { - Name: "OWNER_API_VERSION", - Value: ";;;;foo/v1alpha1", - }, { - Name: "OWNER_KIND", - Value: ";;;;Foo", - }, { - Name: "CONTROLLER", - Value: "false,true,false,false,false", - }, { - Name: "SELECTOR", - Value: ";;test-key1=test-value1;akey,!anotherkey;akey,!anotherkey,test-key2=test-value2", - }, { - Name: "NAMESPACE", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, { - Name: "NAME", - Value: name, - }, { - Name: "METRICS_DOMAIN", - Value: "knative.dev/eventing", - }, { - Name: "K_METRICS_CONFIG", - Value: "", - }, { - Name: "K_LOGGING_CONFIG", - Value: "", - }, - }, - }, - }, - }, - }, - }, - } - - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("unexpected deploy (-want, +got) = %v", diff) - } -} diff --git a/pkg/reconciler/legacycontainersource/containersource.go b/pkg/reconciler/legacycontainersource/containersource.go deleted file mode 100644 index a767f964f7f..00000000000 --- a/pkg/reconciler/legacycontainersource/containersource.go +++ /dev/null @@ -1,326 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacycontainersource - -import ( - "context" - "errors" - "fmt" - "reflect" - "strings" - "time" - - "knative.dev/pkg/resolver" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - appsv1listers "k8s.io/client-go/listers/apps/v1" - "k8s.io/client-go/tools/cache" - - "go.uber.org/zap" - "knative.dev/pkg/controller" - - status "knative.dev/eventing/pkg/apis/duck" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - listers "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" - "knative.dev/eventing/pkg/logging" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/eventing/pkg/reconciler/legacycontainersource/resources" -) - -const ( - // Name of the corev1.Events emitted from the reconciliation process - sourceReconciled = "ContainerSourceReconciled" - sourceReadinessChanged = "ContainerSourceReadinessChanged" - sourceUpdateStatusFailed = "ContainerSourceUpdateStatusFailed" -) - -type Reconciler struct { - *reconciler.Base - - // listers index properties about resources - containerSourceLister listers.ContainerSourceLister - deploymentLister appsv1listers.DeploymentLister - - sinkResolver *resolver.URIResolver -} - -// Check that our Reconciler implements controller.Reconciler -var _ controller.Reconciler = (*Reconciler)(nil) - -// Reconcile compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the CronJobSource -// resource with the current status of the resource. -func (r *Reconciler) Reconcile(ctx context.Context, key string) error { - // Convert the namespace/name string into a distinct namespace and name - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - r.Logger.Errorf("invalid resource key: %s", key) - return nil - } - - // Get the CronJobSource resource with this namespace/name - original, err := r.containerSourceLister.ContainerSources(namespace).Get(name) - if apierrors.IsNotFound(err) { - // The resource may no longer exist, in which case we stop processing. - logging.FromContext(ctx).Error("ContainerSource key in work queue no longer exists", zap.Any("key", key)) - return nil - } else if err != nil { - return err - } - - // Don't modify the informers copy - source := original.DeepCopy() - - // Reconcile this copy of the ContainerSource and then write back any status - // updates regardless of whether the reconcile error out. - err = r.reconcile(ctx, source) - if err != nil { - logging.FromContext(ctx).Warn("Error reconciling ContainerSource", zap.Error(err)) - } else { - logging.FromContext(ctx).Debug("ContainerSource reconciled") - r.Recorder.Eventf(source, corev1.EventTypeNormal, sourceReconciled, `ContainerSource reconciled: "%s/%s"`, source.Namespace, source.Name) - } - - if _, updateStatusErr := r.updateStatus(ctx, source.DeepCopy()); updateStatusErr != nil { - logging.FromContext(ctx).Warn("Failed to update the ContainerSource", zap.Error(err)) - r.Recorder.Eventf(source, corev1.EventTypeWarning, sourceUpdateStatusFailed, "Failed to update ContainerSource's status: %v", err) - return updateStatusErr - } - - // Requeue if the resource is not ready: - return err -} - -func (r *Reconciler) reconcile(ctx context.Context, source *v1alpha1.ContainerSource) error { - // No need to reconcile if the source has been marked for deletion. - if source.DeletionTimestamp != nil { - return nil - } - - source.Status.ObservedGeneration = source.Generation - source.Status.InitializeConditions() - - source.MarkDeprecated(&source.Status.Status, "ContainerSourceDeprecated", "containersources.sources.eventing.knative.dev are deprecated and will be removed in the future. Use a Deployment and SinkBinding.sources.knative.dev instead.") - - annotations := make(map[string]string) - // Then wire through any annotations / labels from the Source - if source.ObjectMeta.Annotations != nil { - for k, v := range source.ObjectMeta.Annotations { - annotations[k] = v - } - } - labels := make(map[string]string) - if source.ObjectMeta.Labels != nil { - for k, v := range source.ObjectMeta.Labels { - labels[k] = v - } - } - - args := resources.ContainerArguments{ - Source: source, - Name: source.Name, - Namespace: source.Namespace, - Template: source.Spec.Template, - Image: source.Spec.DeprecatedImage, - Args: source.Spec.DeprecatedArgs, - Env: source.Spec.DeprecatedEnv, - ServiceAccountName: source.Spec.DeprecatedServiceAccountName, - Annotations: annotations, - Labels: labels, - } - - err := r.setSinkURIArg(ctx, source, &args) - if err != nil { - r.Recorder.Eventf(source, corev1.EventTypeWarning, "SetSinkURIFailed", "Failed to set Sink URI: %v", err) - return err - } - - ra, err := r.reconcileReceiveAdapter(ctx, source, args) - if err != nil { - return fmt.Errorf("reconciling receive adapter: %v", err) - } - - if status.DeploymentIsAvailable(&ra.Status, false) { - source.Status.MarkDeployed() - r.Recorder.Eventf(source, corev1.EventTypeNormal, "DeploymentReady", "Deployment %q has %d ready replicas", ra.Name, ra.Status.ReadyReplicas) - } - return nil -} - -// setSinkURIArg attempts to get the sink URI from the sink reference and -// set it in the source status. On failure, the source's Sink condition is -// updated to reflect the error. -// If an error is returned from this function, the caller should also record -// an Event containing the error string. -func (r *Reconciler) setSinkURIArg(ctx context.Context, source *v1alpha1.ContainerSource, args *resources.ContainerArguments) error { - - if uri, ok := sinkArg(source); ok { - source.Status.MarkSink(uri) - return nil - } - - if source.Spec.Sink == nil { - source.Status.MarkNoSink("Missing", "Sink missing from spec") - return errors.New("sink missing from spec") - } - - dest := source.Spec.Sink.DeepCopy() - if dest.Ref != nil { - // To call URIFromDestination(), dest.Ref must have a Namespace. If there is - // no Namespace defined in dest.Ref, we will use the Namespace of the source - // as the Namespace of dest.Ref. - if dest.Ref.Namespace == "" { - //TODO how does this work with deprecated fields - dest.Ref.Namespace = source.GetNamespace() - } - } else if dest.DeprecatedName != "" && dest.DeprecatedNamespace == "" { - // If Ref is nil and the deprecated ref is present, we need to check for - // DeprecatedNamespace. This can be removed when DeprecatedNamespace is - // removed. - dest.DeprecatedNamespace = source.GetNamespace() - } - - sinkURI, err := r.sinkResolver.URIFromDestination(*dest, source) - if err != nil { - source.Status.MarkNoSink("NotFound", `Couldn't get Sink URI from %+v`, dest) - return fmt.Errorf("getting sink URI: %v", err) - } - if source.Spec.Sink.DeprecatedAPIVersion != "" && - source.Spec.Sink.DeprecatedKind != "" && - source.Spec.Sink.DeprecatedName != "" { - source.Status.MarkSinkWarnRefDeprecated(sinkURI) - } else { - source.Status.MarkSink(sinkURI) - } - - args.Sink = sinkURI - - return nil -} - -func sinkArg(source *v1alpha1.ContainerSource) (string, bool) { - var args []string - - if source.Spec.Template != nil { - for _, c := range source.Spec.Template.Spec.Containers { - args = append(args, c.Args...) - } - } - - args = append(args, source.Spec.DeprecatedArgs...) - - for _, a := range args { - if strings.HasPrefix(a, "--sink=") { - return strings.Replace(a, "--sink=", "", -1), true - } - } - - return "", false -} - -func (r *Reconciler) reconcileReceiveAdapter(ctx context.Context, src *v1alpha1.ContainerSource, args resources.ContainerArguments) (*appsv1.Deployment, error) { - expected := resources.MakeDeployment(args) - - ra, err := r.KubeClientSet.AppsV1().Deployments(src.Namespace).Get(expected.Name, metav1.GetOptions{}) - if apierrors.IsNotFound(err) { - ra, err = r.KubeClientSet.AppsV1().Deployments(src.Namespace).Create(expected) - if err != nil { - r.markNotDeployedRecordEvent(src, corev1.EventTypeWarning, "DeploymentCreateFailed", "Could not create deployment: %v", err) - return nil, fmt.Errorf("creating new deployment: %v", err) - } - r.markDeployingAndRecordEvent(src, corev1.EventTypeNormal, "DeploymentCreated", "Created deployment %q", ra.Name) - return ra, nil - } else if err != nil { - r.markDeployingAndRecordEvent(src, corev1.EventTypeWarning, "DeploymentGetFailed", "Error getting deployment: %v", err) - return nil, fmt.Errorf("getting deployment: %v", err) - } else if !metav1.IsControlledBy(ra, src) { - r.markDeployingAndRecordEvent(src, corev1.EventTypeWarning, "DeploymentNotOwned", "Deployment %q is not owned by this ContainerSource", ra.Name) - return nil, fmt.Errorf("deployment %q is not owned by ContainerSource %q", ra.Name, src.Name) - } else if r.podSpecChanged(ra.Spec.Template.Spec, expected.Spec.Template.Spec) { - ra.Spec.Template.Spec = expected.Spec.Template.Spec - ra, err = r.KubeClientSet.AppsV1().Deployments(src.Namespace).Update(ra) - if err != nil { - return ra, fmt.Errorf("updating deployment: %v", err) - } - return ra, nil - } else { - logging.FromContext(ctx).Debug("Reusing existing receive adapter", zap.Any("receiveAdapter", ra)) - } - return ra, nil -} - -func (r *Reconciler) podSpecChanged(oldPodSpec corev1.PodSpec, newPodSpec corev1.PodSpec) bool { - // Since the Deployment spec has fields defaulted by the webhook, it won't - // be equal to expected. Use DeepDerivative to compare only the fields that - // are set in newPodSpec. - if !equality.Semantic.DeepDerivative(newPodSpec, oldPodSpec) { - return true - } - if len(oldPodSpec.Containers) != len(newPodSpec.Containers) { - return true - } - for i := range newPodSpec.Containers { - if !equality.Semantic.DeepEqual(newPodSpec.Containers[i].Env, oldPodSpec.Containers[i].Env) { - return true - } - } - return false -} - -func (r *Reconciler) markDeployingAndRecordEvent(source *v1alpha1.ContainerSource, evType string, reason string, messageFmt string, args ...interface{}) { - r.Recorder.Eventf(source, evType, reason, messageFmt, args...) - source.Status.MarkDeploying(reason, messageFmt, args...) -} - -func (r *Reconciler) markNotDeployedRecordEvent(source *v1alpha1.ContainerSource, evType string, reason string, messageFmt string, args ...interface{}) { - r.Recorder.Eventf(source, evType, reason, messageFmt, args...) - source.Status.MarkNotDeployed(reason, messageFmt, args...) -} - -func (r *Reconciler) updateStatus(ctx context.Context, desired *v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) { - source, err := r.containerSourceLister.ContainerSources(desired.Namespace).Get(desired.Name) - if err != nil { - return nil, err - } - - // If there's nothing to update, just return. - if reflect.DeepEqual(source.Status, desired.Status) { - return source, nil - } - - becomesReady := desired.Status.IsReady() && !source.Status.IsReady() - - // Don't modify the informers copy. - existing := source.DeepCopy() - existing.Status = desired.Status - - cj, err := r.LegacyClientSet.SourcesV1alpha1().ContainerSources(desired.Namespace).UpdateStatus(existing) - if err == nil && becomesReady { - duration := time.Since(cj.ObjectMeta.CreationTimestamp.Time) - r.Logger.Infof("ContainerSource %q became ready after %v", source.Name, duration) - r.Recorder.Event(source, corev1.EventTypeNormal, sourceReadinessChanged, fmt.Sprintf("ContainerSource %q became ready", source.Name)) - if reportErr := r.StatsReporter.ReportReady("ContainerSource", source.Namespace, source.Name, duration); reportErr != nil { - logging.FromContext(ctx).Sugar().Infof("failed to record ready for ContainerSource, %v", reportErr) - } - } - - return cj, err -} diff --git a/pkg/reconciler/legacycontainersource/containersource_test.go b/pkg/reconciler/legacycontainersource/containersource_test.go deleted file mode 100644 index d850720eb58..00000000000 --- a/pkg/reconciler/legacycontainersource/containersource_test.go +++ /dev/null @@ -1,865 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 legacycontainersource - -import ( - "context" - "fmt" - "testing" - - "knative.dev/pkg/apis" - "knative.dev/pkg/resolver" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - clientgotesting "k8s.io/client-go/testing" - - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/client/injection/ducks/duck/v1/addressable" - _ "knative.dev/pkg/client/injection/ducks/duck/v1/addressable/fake" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/eventing/pkg/utils" - - logtesting "knative.dev/pkg/logging/testing" - . "knative.dev/pkg/reconciler/testing" - - . "knative.dev/eventing/pkg/reconciler/testing" -) - -const ( - image = "github.com/knative/test/image" - sourceName = "test-container-source" - sourceUID = "1234-5678-90" - testNS = "testnamespace" - sinkName = "testsink" - generation = 1 -) - -var ( - trueVal = true - - nonsinkDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Trigger", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - } - nonsinkDestWithNamespace = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Namespace: testNS, - Kind: "Trigger", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - } - - deploymentName = fmt.Sprintf("containersource-%s-%s", sourceName, sourceUID) - - // We cannot take the address of constants, so copy it into a var. - conditionTrue = corev1.ConditionTrue - - serviceDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Service", - APIVersion: "v1", - }, - } - serviceURI = fmt.Sprintf("http://%s.%s.svc.cluster.local/", sinkName, testNS) - - deprecatedSinkDest = duckv1beta1.Destination{ - DeprecatedName: sinkName, - DeprecatedKind: "Channel", - DeprecatedAPIVersion: "messaging.knative.dev/v1alpha1", - } - - deprecatedSinkDestWithNamespace = duckv1beta1.Destination{ - DeprecatedName: sinkName, - DeprecatedKind: "Channel", - DeprecatedNamespace: testNS, - DeprecatedAPIVersion: "messaging.knative.dev/v1alpha1", - } - - sinkDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Channel", - APIVersion: "messaging.knative.dev/v1alpha1", - }, - } - sinkDestWithNamespace = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Namespace: testNS, - Kind: "Channel", - APIVersion: "messaging.knative.dev/v1alpha1", - }, - } - sinkDNS = "sink.mynamespace.svc." + utils.GetClusterDomainName() - sinkURI = "http://" + sinkDNS - sinkDestURI = duckv1beta1.Destination{ - URI: apis.HTTP(sinkDNS), - } -) - -func init() { - // Add types to scheme - _ = appsv1.AddToScheme(scheme.Scheme) - _ = corev1.AddToScheme(scheme.Scheme) - _ = duckv1alpha1.AddToScheme(scheme.Scheme) -} - -func TestAllCases(t *testing.T) { - table := TableTest{ - { - Name: "bad workqueue key", - // Make sure Reconcile handles bad keys. - Key: "too/many/parts", - }, { - Name: "key not found", - // Make sure Reconcile handles good keys that don't exist. - Key: "foo/not-found", - }, { - Name: "missing sink", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - ), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "SetSinkURIFailed", `Failed to set Sink URI: getting sink URI: failed to get ref &ObjectReference{Kind:Channel,Namespace:testnamespace,Name:testsink,UID:,APIVersion:messaging.knative.dev/v1alpha1,ResourceVersion:,FieldPath:,}: channels.messaging.knative.dev "testsink" not found`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceStatusObservedGeneration(generation), - WithContainerSourceSinkNotFound(fmt.Sprintf("Couldn't get Sink URI from %+v", &sinkDestWithNamespace)), - ), - }}, - }, { - Name: "sink not addressable", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &nonsinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - ), - NewTrigger(sinkName, testNS, ""), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "SetSinkURIFailed", `Failed to set Sink URI: getting sink URI: address not set for &ObjectReference{Kind:Trigger,Namespace:testnamespace,Name:testsink,UID:,APIVersion:eventing.knative.dev/v1alpha1,ResourceVersion:,FieldPath:,}`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &nonsinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceStatusObservedGeneration(generation), - WithContainerSourceSinkNotFound(fmt.Sprintf("Couldn't get Sink URI from %+v", &nonsinkDestWithNamespace)), - ), - }}, - }, { - Name: "sink not ready", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "SetSinkURIFailed", `Failed to set Sink URI: getting sink URI: address not set for &ObjectReference{Kind:Channel,Namespace:testnamespace,Name:testsink,UID:,APIVersion:messaging.knative.dev/v1alpha1,ResourceVersion:,FieldPath:,}`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceStatusObservedGeneration(generation), - WithContainerSourceSinkNotFound(fmt.Sprintf("Couldn't get Sink URI from %+v", &sinkDestWithNamespace)), - ), - }}, - }, {}, { - Name: "deprecated sink not ready", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &deprecatedSinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "SetSinkURIFailed", `Failed to set Sink URI: getting sink URI: address not set for &ObjectReference{Kind:Channel,Namespace:testnamespace,Name:testsink,UID:,APIVersion:messaging.knative.dev/v1alpha1,ResourceVersion:,FieldPath:,}`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &deprecatedSinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceStatusObservedGeneration(generation), - WithContainerSourceSinkNotFound(fmt.Sprintf("Couldn't get Sink URI from %+v", &deprecatedSinkDestWithNamespace)), - ), - }}, - }, { - Name: "sink is nil", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceObjectMetaGeneration(generation), - ), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "SetSinkURIFailed", `Failed to set Sink URI: sink missing from spec`), - Eventf(corev1.EventTypeWarning, "ContainerSourceUpdateStatusFailed", `Failed to update ContainerSource's status: sink missing from spec`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceStatusObservedGeneration(generation), - WithContainerSourceSinkMissing("Sink missing from spec"), - ), - }}, - }, { - Name: "valid first pass with template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - WithContainerSourceUID(sourceUID), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentCreated", `Created deployment "%s"`, deploymentName), // TODO on noes - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(fmt.Sprintf(`Created deployment "%s"`, deploymentName)), - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), nil, sinkURI, nil, nil), - }, - }, { - Name: "valid first pass without template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentCreated", `Created deployment "%s"`, deploymentName), // TODO on noes - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceObjectMetaGeneration(generation), - WithContainerSourceUID(sourceUID), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(fmt.Sprintf(`Created deployment "%s"`, deploymentName)), - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), nil, sinkURI, nil, nil), - }, - }, { - Name: "valid, with ready deployment with template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(`Created deployment ""`), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), &conditionTrue, sinkURI, nil, nil), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentReady", `Deployment "%s" has 1 ready replicas`, deploymentName), - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - Eventf(corev1.EventTypeNormal, "ContainerSourceReadinessChanged", `ContainerSource "test-container-source" became ready`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - // Status Update: - WithContainerSourceDeployed, - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - }, { - Name: "valid, with ready deployment with template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDestURI, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(`Created deployment ""`), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), &conditionTrue, sinkURI, nil, nil), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentReady", `Deployment "%s" has 1 ready replicas`, deploymentName), - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - Eventf(corev1.EventTypeNormal, "ContainerSourceReadinessChanged", `ContainerSource "test-container-source" became ready`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDestURI, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - // Status Update: - WithContainerSourceDeployed, - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - }, { - Name: "valid, with ready deployment without template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(`Created deployment ""`), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), &conditionTrue, sinkURI, nil, nil), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentReady", `Deployment "%s" has 1 ready replicas`, deploymentName), - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - Eventf(corev1.EventTypeNormal, "ContainerSourceReadinessChanged", `ContainerSource "test-container-source" became ready`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - // Status Update: - WithContainerSourceDeployed, - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - }, { - Name: "valid first pass, with annotations and labels with template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithContainerSourceLabels(map[string]string{"label": "labeled"}), - WithContainerSourceAnnotations(map[string]string{"annotation": "annotated"}), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentCreated", `Created deployment "%s"`, deploymentName), // TODO on noes - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "source", - Image: image, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithContainerSourceLabels(map[string]string{"label": "labeled"}), - WithContainerSourceAnnotations(map[string]string{"annotation": "annotated"}), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(fmt.Sprintf(`Created deployment "%s"`, deploymentName)), - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), nil, sinkURI, map[string]string{"label": "labeled"}, map[string]string{"annotation": "annotated"}), - }, - }, { - Name: "valid first pass, with annotations and labels without template", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithContainerSourceLabels(map[string]string{"label": "labeled"}), - WithContainerSourceAnnotations(map[string]string{"annotation": "annotated"}), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentCreated", `Created deployment "%s"`, deploymentName), // TODO on noes - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - WithContainerSourceLabels(map[string]string{"label": "labeled"}), - WithContainerSourceAnnotations(map[string]string{"annotation": "annotated"}), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceSink(sinkURI), - WithContainerSourceDeploying(fmt.Sprintf(`Created deployment "%s"`, deploymentName)), - WithContainerSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), nil, sinkURI, map[string]string{"label": "labeled"}, map[string]string{"annotation": "annotated"}), - }, - }, { - Name: "error for create deployment", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithChannelAddress(sinkDNS), - ), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "DeploymentCreateFailed", "Could not create deployment: inducing failure for create deployments"), - }, - WithReactors: []clientgotesting.ReactionFunc{ - InduceFailure("create", "deployments"), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &sinkDest, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceObjectMetaGeneration(generation), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceStatusObservedGeneration(generation), - WithContainerSourceSink(sinkURI), - WithContainerSourceDeployFailed(`Could not create deployment: inducing failure for create deployments`), - ), - }}, - WantCreates: []runtime.Object{ - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - ), nil, sinkURI, nil, nil), - }, - }, { - Name: "valid, with sink as service", - Objects: []runtime.Object{ - NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &serviceDest, - }), - WithContainerSourceUID(sourceUID), - ), - NewService(sinkName, testNS), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "DeploymentCreated", `Created deployment "containersource-test-container-source-1234-5678-90"`), - Eventf(corev1.EventTypeNormal, "ContainerSourceReconciled", `ContainerSource reconciled: "testnamespace/test-container-source"`), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - Sink: &serviceDest, - }), - WithContainerSourceUID(sourceUID), - // Status Update: - WithInitContainerSourceConditions, - WithContainerSourceSink(serviceURI), - WithContainerSourceDeploying(`Created deployment "containersource-test-container-source-1234-5678-90"`), - ), - }}, - WantCreates: []runtime.Object{ - makeDeployment(NewContainerSource(sourceName, testNS, - WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - DeprecatedImage: image, - }), - WithContainerSourceUID(sourceUID), - WithContainerSourceSink(serviceURI), - ), nil, serviceURI, nil, nil), - }, - }, - } - - logger := logtesting.TestLogger(t) - table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler { - ctx = addressable.WithDuck(ctx) - r := &Reconciler{ - Base: reconciler.NewBase(ctx, controllerAgentName, cmw), - containerSourceLister: listers.GetLegacyContainerSourceLister(), - deploymentLister: listers.GetDeploymentLister(), - } - r.sinkResolver = resolver.NewURIResolver(ctx, func(types.NamespacedName) {}) - return r - }, - true, - logger, - )) -} - -func makeDeployment(source *sourcesv1alpha1.ContainerSource, available *corev1.ConditionStatus, sinkURI string, labels map[string]string, annotations map[string]string) *appsv1.Deployment { - args := append(source.Spec.DeprecatedArgs, fmt.Sprintf("--sink=%s", sinkURI)) - env := append(source.Spec.DeprecatedEnv, corev1.EnvVar{Name: "SINK", Value: sinkURI}) - - labs := map[string]string{ - "sources.eventing.knative.dev/containerSource": source.Name, - } - for k, v := range labels { - labs[k] = v - } - - status := appsv1.DeploymentStatus{} - if available != nil { - status.Conditions = []appsv1.DeploymentCondition{ - { - Type: appsv1.DeploymentAvailable, - Status: *available, - }, - } - if *available == corev1.ConditionTrue { - status.ReadyReplicas = 1 - } - } - - return &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: appsv1.SchemeGroupVersion.String(), - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: deploymentName, - Namespace: source.Namespace, - OwnerReferences: getOwnerReferences(), - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": source.Name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": source.Name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: annotations, - Labels: labs, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "source", - Image: source.Spec.DeprecatedImage, - Args: args, - Env: env, - ImagePullPolicy: corev1.PullIfNotPresent, - }}, - ServiceAccountName: source.Spec.DeprecatedServiceAccountName, - }, - }, - }, - Status: status, - } -} - -func getOwnerReferences() []metav1.OwnerReference { - return []metav1.OwnerReference{{ - APIVersion: sourcesv1alpha1.SchemeGroupVersion.String(), - Kind: "ContainerSource", - Name: sourceName, - Controller: &trueVal, - BlockOwnerDeletion: &trueVal, - UID: sourceUID, - }} -} diff --git a/pkg/reconciler/legacycontainersource/controller.go b/pkg/reconciler/legacycontainersource/controller.go deleted file mode 100644 index 448c0c9adab..00000000000 --- a/pkg/reconciler/legacycontainersource/controller.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacycontainersource - -import ( - "context" - - "knative.dev/pkg/resolver" - - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/reconciler" - - deploymentinformer "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment" - - containersourceinformer "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource" -) - -const ( - // ReconcilerName is the name of the reconciler - ReconcilerName = "ContainerSources" - // controllerAgentName is the string used by this controller to identify - // itself when creating events. - controllerAgentName = "container-source-controller" -) - -// NewController initializes the controller and is called by the generated code -// Registers event handlers to enqueue events -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - - containerSourceInformer := containersourceinformer.Get(ctx) - deploymentInformer := deploymentinformer.Get(ctx) - - r := &Reconciler{ - Base: reconciler.NewBase(ctx, controllerAgentName, cmw), - containerSourceLister: containerSourceInformer.Lister(), - deploymentLister: deploymentInformer.Lister(), - } - impl := controller.NewImpl(r, r.Logger, ReconcilerName) - r.sinkResolver = resolver.NewURIResolver(ctx, impl.EnqueueKey) - - r.Logger.Info("Setting up event handlers") - containerSourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - - deploymentInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.Filter(v1alpha1.SchemeGroupVersion.WithKind("ContainerSource")), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }) - - return impl -} diff --git a/pkg/reconciler/legacycontainersource/controller_test.go b/pkg/reconciler/legacycontainersource/controller_test.go deleted file mode 100644 index dd1f88f9686..00000000000 --- a/pkg/reconciler/legacycontainersource/controller_test.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 legacycontainersource - -import ( - "testing" - - "knative.dev/pkg/configmap" - - . "knative.dev/pkg/reconciler/testing" - - // Fake injection informers - _ "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/containersource/fake" - _ "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment/fake" -) - -func TestNew(t *testing.T) { - ctx, _ := SetupFakeContext(t) - - c := NewController(ctx, configmap.NewStaticWatcher()) - - if c == nil { - t.Fatal("Expected NewController to return a non-nil value") - } -} diff --git a/pkg/reconciler/legacycontainersource/doc.go b/pkg/reconciler/legacycontainersource/doc.go deleted file mode 100644 index 5fc517a592b..00000000000 --- a/pkg/reconciler/legacycontainersource/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2019 The Knative 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 containersource implements the ContainerSource controller. -package legacycontainersource diff --git a/pkg/reconciler/legacycontainersource/resources/arguments.go b/pkg/reconciler/legacycontainersource/resources/arguments.go deleted file mode 100644 index 0084c5197b6..00000000000 --- a/pkg/reconciler/legacycontainersource/resources/arguments.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - corev1 "k8s.io/api/core/v1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -type ContainerArguments struct { - Source *v1alpha1.ContainerSource - Name string - Namespace string - Template *corev1.PodTemplateSpec - Sink string - Annotations map[string]string - Labels map[string]string - - // TODO(jingweno): The following fields are to be deprecated - // Use `Template` instead - Image string - Args []string - Env []corev1.EnvVar - ServiceAccountName string -} diff --git a/pkg/reconciler/legacycontainersource/resources/deployment.go b/pkg/reconciler/legacycontainersource/resources/deployment.go deleted file mode 100644 index bfe28057eb8..00000000000 --- a/pkg/reconciler/legacycontainersource/resources/deployment.go +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "fmt" - "strings" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/eventing/pkg/utils" - "knative.dev/pkg/kmeta" -) - -const ( - sourceLabelKey = "sources.eventing.knative.dev/containerSource" -) - -func MakeDeployment(args ContainerArguments) *appsv1.Deployment { - template := args.Template - if template == nil { - template = &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - ServiceAccountName: args.ServiceAccountName, - Containers: []corev1.Container{ - { - Name: "source", - Image: args.Image, - Args: args.Args, - Env: args.Env, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - } - } - - if template.ObjectMeta.Labels == nil { - template.ObjectMeta.Labels = make(map[string]string) - } - template.ObjectMeta.Labels[sourceLabelKey] = args.Name - - containers := []corev1.Container{} - for _, c := range template.Spec.Containers { - sink, hasSinkArg := sinkArg(c.Args) - if sink == "" { - sink = args.Sink - } - - // if sink is already in the provided, don't attempt to add - if !hasSinkArg { - c.Args = append(c.Args, "--sink="+sink) - } - - c.Env = append(c.Env, corev1.EnvVar{Name: "SINK", Value: sink}) - containers = append(containers, c) - } - template.Spec.Containers = containers - - deploy := &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: utils.GenerateFixedName(args.Source, fmt.Sprintf("containersource-%s", args.Source.Name)), - Namespace: args.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *kmeta.NewControllerRef(args.Source), - }, - Labels: map[string]string{ - sourceLabelKey: args.Name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - sourceLabelKey: args.Name, - }, - }, - Template: *template, - }, - } - - // Then wire through any annotations from the source. - if args.Annotations != nil { - if deploy.Spec.Template.ObjectMeta.Annotations == nil { - deploy.Spec.Template.ObjectMeta.Annotations = make(map[string]string, len(args.Annotations)) - } - for k, v := range args.Annotations { - deploy.Spec.Template.ObjectMeta.Annotations[k] = v - } - } - - // Then wire through any labels from the source. Do not allow to override - // our source name. This seems like it would be way errorprone by allowing - // the matchlabels then to not match, or we'd have to force them to match, etc. - // just don't allow it. - if args.Labels != nil { - for k, v := range args.Labels { - if k != sourceLabelKey { - deploy.Spec.Template.ObjectMeta.Labels[k] = v - } - } - } - return deploy -} - -func sinkArg(args []string) (string, bool) { - for _, arg := range args { - if strings.HasPrefix(arg, "--sink=") { - return strings.Replace(arg, "--sink=", "", -1), true - } - } - - return "", false -} diff --git a/pkg/reconciler/legacycontainersource/resources/deployment_test.go b/pkg/reconciler/legacycontainersource/resources/deployment_test.go deleted file mode 100644 index 68fc4107eed..00000000000 --- a/pkg/reconciler/legacycontainersource/resources/deployment_test.go +++ /dev/null @@ -1,886 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "fmt" - "testing" - - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - - "github.com/google/go-cmp/cmp" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - name = "test-name" - uid = "uid" -) - -func TestMakeDeployment_template(t *testing.T) { - yes := true - tests := []struct { - name string - args ContainerArguments - want *appsv1.Deployment - }{ - { - name: "sink override and annotation label not allowed", - args: ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Name: "test-source", - Image: "test-image", - Args: []string{"--test1=args1", "--test2=args2"}, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - }, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - Sink: "test-sink", - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": "not-allowed", - "anotherlabel": "extra-label", - }, - Annotations: map[string]string{ - "sidecar.istio.io/inject": "false", - "anotherannotation": "extra-annotation", - }, - }, - want: &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "false", - "anotherannotation": "extra-annotation", - }, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - "anotherlabel": "extra-label", - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Name: "test-source", - Image: "test-image", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, { - Name: "SINK", - Value: "test-sink", - }}, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - }, - }, - }, - - { - name: "sink", - args: ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Image: "test-image1", - Args: []string{"--test1=args1", "--test2=args2"}, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - }, - }, - { - Image: "test-image2", - Args: []string{"--test3=args3", "--test4=args4"}, - Env: []corev1.EnvVar{ - { - Name: "test3", - Value: "arg3", - }, - { - Name: "test4", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test4-secret", - }, - }, - }, - }, - }, - }, - }, - }, - Sink: "test-sink", - }, - want: &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Image: "test-image1", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - { - Name: "SINK", - Value: "test-sink", - }, - }, - }, - { - Image: "test-image2", - Args: []string{ - "--test3=args3", - "--test4=args4", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test3", - Value: "arg3", - }, - { - Name: "test4", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test4-secret", - }, - }, - }, - { - Name: "SINK", - Value: "test-sink", - }, - }, - }, - }, - }, - }, - }, - }, - }, - - { - name: "sink in args", - args: ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Image: "test-image1", - Args: []string{"--test1=args1", "--test2=args2", "--sink=test-sink1"}, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - }, - }, - { - Image: "test-image2", - Args: []string{"--test3=args3", "--test4=args4", "--sink=test-sink2"}, - Env: []corev1.EnvVar{ - { - Name: "test3", - Value: "arg3", - }, - { - Name: "test4", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test4-secret", - }, - }, - }, - }, - }, - }, - }, - }, - Labels: map[string]string{"sources.eventing.knative.dev/containerSource": name}, - }, - want: &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Image: "test-image1", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink1", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - { - Name: "SINK", - Value: "test-sink1", - }, - }, - }, - { - Image: "test-image2", - Args: []string{ - "--test3=args3", - "--test4=args4", - "--sink=test-sink2", - }, - Env: []corev1.EnvVar{ - { - Name: "test3", - Value: "arg3", - }, - { - Name: "test4", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test4-secret", - }, - }, - }, - { - Name: "SINK", - Value: "test-sink2", - }, - }, - }, - }, - }, - }, - }, - }, - }, - - { - name: "template takes precedence", - args: ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Template: &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Image: "test-image", - Args: []string{"--test1=args1", "--test2=args2"}, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - }, - }, - }, - }, - }, - Image: "test-image2", - Args: []string{"--test3=args3", "--test4=args4"}, - Env: []corev1.EnvVar{ - { - Name: "test3", - Value: "arg3", - }, - { - Name: "test4", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test4-secret", - }, - }, - }, - }, - ServiceAccountName: "test-service-account2", - Sink: "test-sink", - }, - want: &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Image: "test-image", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, - { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, - { - Name: "SINK", - Value: "test-sink", - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - for _, test := range tests { - tt := test - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - got := MakeDeployment(tt.args) - if diff := cmp.Diff(tt.want, got); diff != "" { - t.Errorf("unexpected deploy (-want, +got) = %v", diff) - } - }) - } -} - -func TestMakeDeployment_sinkoverrideannotationlabelnotallowed(t *testing.T) { - yes := true - got := MakeDeployment(ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Image: "test-image", - Args: []string{"--test1=args1", "--test2=args2"}, - Env: []corev1.EnvVar{{ - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }}, - ServiceAccountName: "test-service-account", - Sink: "test-sink", - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": "not-allowed", - "anotherlabel": "extra-label", - }, - Annotations: map[string]string{ - "sidecar.istio.io/inject": "false", - "anotherannotation": "extra-annotation", - }, - }) - - want := &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "false", - "anotherannotation": "extra-annotation", - }, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - "anotherlabel": "extra-label", - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Name: "source", - Image: "test-image", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, { - Name: "SINK", - Value: "test-sink", - }}, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - }, - } - - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("unexpected deploy (-want, +got) = %v", diff) - } -} - -func TestMakeDeployment_sink(t *testing.T) { - yes := true - got := MakeDeployment(ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Image: "test-image", - Args: []string{"--test1=args1", "--test2=args2"}, - Env: []corev1.EnvVar{{ - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }}, - ServiceAccountName: "test-service-account", - Sink: "test-sink", - }) - want := &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Name: "source", - Image: "test-image", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, { - Name: "SINK", - Value: "test-sink", - }}, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - }, - } - - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("unexpected deploy (-want, +got) = %v", diff) - } -} - -func TestMakeDeployment_sinkinargs(t *testing.T) { - yes := true - got := MakeDeployment(ContainerArguments{ - Source: &v1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{Name: name, UID: uid}, - }, - Name: name, - Namespace: "test-namespace", - Image: "test-image", - Args: []string{"--test1=args1", "--test2=args2", "--sink=test-sink"}, - Env: []corev1.EnvVar{{ - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }}, - ServiceAccountName: "test-service-account", - Labels: map[string]string{"sources.eventing.knative.dev/containerSource": name}, - }) - - want := &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("containersource-%s-%s", name, uid), - Namespace: "test-namespace", - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "ContainerSource", - Name: name, - UID: uid, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "sources.eventing.knative.dev/containerSource": name, - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "test-service-account", - Containers: []corev1.Container{ - { - Name: "source", - Image: "test-image", - Args: []string{ - "--test1=args1", - "--test2=args2", - "--sink=test-sink", - }, - Env: []corev1.EnvVar{ - { - Name: "test1", - Value: "arg1", - }, { - Name: "test2", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - Key: "test2-secret", - }, - }, - }, { - Name: "SINK", - Value: "test-sink", - }}, - ImagePullPolicy: corev1.PullIfNotPresent, - }, - }, - }, - }, - }, - } - - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("unexpected deploy (-want, +got) = %v", diff) - } -} diff --git a/pkg/reconciler/legacycronjobsource/controller.go b/pkg/reconciler/legacycronjobsource/controller.go deleted file mode 100644 index 4884826c27f..00000000000 --- a/pkg/reconciler/legacycronjobsource/controller.go +++ /dev/null @@ -1,98 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacycronjobsource - -import ( - "context" - - "knative.dev/pkg/resolver" - - "github.com/kelseyhightower/envconfig" - "k8s.io/client-go/tools/cache" - deploymentinformer "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/logging" - "knative.dev/pkg/metrics" - - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - eventtypeinformer "knative.dev/eventing/pkg/client/injection/informers/eventing/v1alpha1/eventtype" - cronjobsourceinformer "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource" - "knative.dev/eventing/pkg/reconciler" -) - -const ( - // ReconcilerName is the name of the reconciler - ReconcilerName = "CronJobSources" - // controllerAgentName is the string used by this controller to identify - // itself when creating events. - controllerAgentName = "cronjob-source-controller" -) - -// envConfig will be used to extract the required environment variables using -// github.com/kelseyhightower/envconfig. If this configuration cannot be extracted, then -// NewController will panic. -type envConfig struct { - Image string `envconfig:"CRONJOB_RA_IMAGE" required:"true"` -} - -// NewController initializes the controller and is called by the generated code -// Registers event handlers to enqueue events -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - - deploymentInformer := deploymentinformer.Get(ctx) - cronJobSourceInformer := cronjobsourceinformer.Get(ctx) - eventTypeInformer := eventtypeinformer.Get(ctx) - - r := &Reconciler{ - Base: reconciler.NewBase(ctx, controllerAgentName, cmw), - cronjobLister: cronJobSourceInformer.Lister(), - deploymentLister: deploymentInformer.Lister(), - eventTypeLister: eventTypeInformer.Lister(), - loggingContext: ctx, - } - - env := &envConfig{} - if err := envconfig.Process("", env); err != nil { - r.Logger.Panicf("unable to process CronJobSource's required environment variables: %v", err) - } - r.receiveAdapterImage = env.Image - - impl := controller.NewImpl(r, r.Logger, ReconcilerName) - - r.sinkResolver = resolver.NewURIResolver(ctx, impl.EnqueueKey) - - r.Logger.Info("Setting up event handlers") - cronJobSourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - - deploymentInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.Filter(v1alpha1.SchemeGroupVersion.WithKind("CronJobSource")), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }) - - eventTypeInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.Filter(v1alpha1.SchemeGroupVersion.WithKind("CronJobSource")), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }) - cmw.Watch(logging.ConfigMapName(), r.UpdateFromLoggingConfigMap) - cmw.Watch(metrics.ConfigMapName(), r.UpdateFromMetricsConfigMap) - - return impl -} diff --git a/pkg/reconciler/legacycronjobsource/controller_test.go b/pkg/reconciler/legacycronjobsource/controller_test.go deleted file mode 100644 index 243c931269c..00000000000 --- a/pkg/reconciler/legacycronjobsource/controller_test.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 legacycronjobsource - -import ( - "os" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/configmap" - . "knative.dev/pkg/reconciler/testing" - - // Fake injection informers - _ "knative.dev/eventing/pkg/client/injection/informers/eventing/v1alpha1/eventtype/fake" - _ "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/cronjobsource/fake" - _ "knative.dev/pkg/client/injection/ducks/duck/v1/addressable/fake" - _ "knative.dev/pkg/client/injection/kube/informers/apps/v1/deployment/fake" -) - -func TestNew(t *testing.T) { - testCases := map[string]struct { - setEnv bool - }{ - "image not set": {}, - "image set": { - setEnv: true, - }, - } - for n, tc := range testCases { - t.Run(n, func(t *testing.T) { - if tc.setEnv { - if err := os.Setenv("CRONJOB_RA_IMAGE", "anything"); err != nil { - t.Fatalf("Failed to set env var: %v", err) - } - defer func() { - if err := os.Unsetenv("CRONJOB_RA_IMAGE"); err != nil { - t.Fatalf("Failed to unset env var: %v", err) - } - }() - - if err := os.Setenv("METRICS_DOMAIN", "knative.dev/eventing"); err != nil { - t.Fatalf("Failed to set env var: %v", err) - } - defer func() { - if err := os.Unsetenv("METRICS_DOMAIN"); err != nil { - t.Fatalf("Failed to unset env var: %v", err) - } - }() - } else { - defer func() { - r := recover() - if r == nil { - t.Errorf("Expected NewController to panic, nothing recovered.") - } - }() - } - - ctx, _ := SetupFakeContext(t) - c := NewController(ctx, configmap.NewStaticWatcher( - &corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: "config-observability", - Namespace: "knative-eventing", - }, - Data: map[string]string{ - "_example": "test-config", - }, - }, &corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: "config-logging", - Namespace: "knative-eventing", - }, - Data: map[string]string{ - "zap-logger-config": "test-config", - "loglevel.controller": "info", - "loglevel.webhook": "info", - }, - }, - )) - - if c == nil { - t.Fatal("Expected NewController to return a non-nil value") - } - }) - } -} diff --git a/pkg/reconciler/legacycronjobsource/cronjobsource.go b/pkg/reconciler/legacycronjobsource/cronjobsource.go deleted file mode 100644 index c6f8601ca40..00000000000 --- a/pkg/reconciler/legacycronjobsource/cronjobsource.go +++ /dev/null @@ -1,392 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacycronjobsource - -import ( - "context" - "fmt" - "reflect" - "time" - - "knative.dev/pkg/resolver" - - "github.com/robfig/cron" - "go.uber.org/zap" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - appsv1listers "k8s.io/client-go/listers/apps/v1" - "k8s.io/client-go/tools/cache" - "knative.dev/pkg/controller" - pkgLogging "knative.dev/pkg/logging" - "knative.dev/pkg/metrics" - - eventingv1alpha1 "knative.dev/eventing/pkg/apis/eventing/v1alpha1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - eventinglisters "knative.dev/eventing/pkg/client/listers/eventing/v1alpha1" - listers "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" - "knative.dev/eventing/pkg/logging" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/eventing/pkg/reconciler/legacycronjobsource/resources" -) - -var ( - deploymentGVK = appsv1.SchemeGroupVersion.WithKind("Deployment") -) - -const ( - // Name of the corev1.Events emitted from the reconciliation process - cronJobReconciled = "CronJobSourceReconciled" - cronJobReadinessChanged = "CronJobSourceReadinessChanged" - cronJobUpdateStatusFailed = "CronJobSourceUpdateStatusFailed" - cronJobSourceDeploymentCreated = "CronJobSurceDeploymentCreated" - cronJobSourceDeploymentUpdated = "CronJobSourceDeploymentUpdated" - component = "cronjobsource" -) - -type Reconciler struct { - *reconciler.Base - - receiveAdapterImage string - - // listers index properties about resources - cronjobLister listers.CronJobSourceLister - deploymentLister appsv1listers.DeploymentLister - eventTypeLister eventinglisters.EventTypeLister - - loggingContext context.Context - sinkResolver *resolver.URIResolver - loggingConfig *pkgLogging.Config - metricsConfig *metrics.ExporterOptions -} - -// Check that our Reconciler implements controller.Reconciler -var _ controller.Reconciler = (*Reconciler)(nil) - -// Reconcile compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the CronJobSource -// resource with the current status of the resource. -func (r *Reconciler) Reconcile(ctx context.Context, key string) error { - // Convert the namespace/name string into a distinct namespace and name - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - logging.FromContext(ctx).Error("invalid resource key") - return nil - } - - // Get the CronJobSource resource with this namespace/name - original, err := r.cronjobLister.CronJobSources(namespace).Get(name) - if apierrors.IsNotFound(err) { - // The resource may no longer exist, in which case we stop processing. - logging.FromContext(ctx).Error("CronJobSource key in work queue no longer exists") - return nil - } else if err != nil { - return err - } - - // Don't modify the informers copy - cronjob := original.DeepCopy() - - // Reconcile this copy of the CronJobSource and then write back any status - // updates regardless of whether the reconcile error out. - err = r.reconcile(ctx, cronjob) - if err != nil { - logging.FromContext(ctx).Warn("Error reconciling CronJobSource", zap.Error(err)) - } else { - logging.FromContext(ctx).Debug("CronJobSource reconciled") - r.Recorder.Eventf(cronjob, corev1.EventTypeNormal, cronJobReconciled, `CronJobSource reconciled: "%s/%s"`, cronjob.Namespace, cronjob.Name) - } - - if _, updateStatusErr := r.updateStatus(ctx, cronjob.DeepCopy()); updateStatusErr != nil { - logging.FromContext(ctx).Warn("Failed to update the CronJobSource", zap.Error(err)) - r.Recorder.Eventf(cronjob, corev1.EventTypeWarning, cronJobUpdateStatusFailed, "Failed to update CronJobSource's status: %v", err) - return updateStatusErr - } - - // Requeue if the resource is not ready: - return err -} - -func (r *Reconciler) reconcile(ctx context.Context, source *v1alpha1.CronJobSource) error { - // This Source attempts to reconcile three things. - // 1. Determine the sink's URI. - // - Nothing to delete. - // 2. Create a receive adapter in the form of a Deployment. - // - Will be garbage collected by K8s when this CronJobSource is deleted. - // 3. Create the EventType that it can emit. - // - Will be garbage collected by K8s when this CronJobSource is deleted. - source.Status.ObservedGeneration = source.Generation - - source.Status.InitializeConditions() - - source.MarkDeprecated(&source.Status.Status, "CronJobSourceDeprecated", "cronjobsources.sources.eventing.knative.dev are deprecated and will be removed in the future. Use a CronJob and SinkBinding.sources.knative.dev instead.") - - dest := source.Spec.Sink.DeepCopy() - if dest.Ref != nil { - // To call URIFromDestination(), dest.Ref must have a Namespace. If there is - // no Namespace defined in dest.Ref, we will use the Namespace of the source - // as the Namespace of dest.Ref. - if dest.Ref.Namespace == "" { - //TODO how does this work with deprecated fields - dest.Ref.Namespace = source.GetNamespace() - } - } else if dest.DeprecatedName != "" && dest.DeprecatedNamespace == "" { - // If Ref is nil and the deprecated ref is present, we need to check for - // DeprecatedNamespace. This can be removed when DeprecatedNamespace is - // removed. - dest.DeprecatedNamespace = source.GetNamespace() - } - - sinkURI, err := r.sinkResolver.URIFromDestination(*dest, source) - if err != nil { - source.Status.MarkNoSink("NotFound", "") - return fmt.Errorf("getting sink URI: %v", err) - } - if source.Spec.Sink.DeprecatedAPIVersion != "" && - source.Spec.Sink.DeprecatedKind != "" && - source.Spec.Sink.DeprecatedName != "" { - source.Status.MarkSinkWarnRefDeprecated(sinkURI) - } else { - source.Status.MarkSink(sinkURI) - } - - _, err = cron.ParseStandard(source.Spec.Schedule) - if err != nil { - source.Status.MarkInvalidSchedule("Invalid", "") - return fmt.Errorf("invalid schedule: %v", err) - } - source.Status.MarkSchedule() - - ra, err := r.createReceiveAdapter(ctx, source, sinkURI) - if err != nil { - logging.FromContext(ctx).Error("Unable to create the receive adapter", zap.Error(err)) - return fmt.Errorf("creating receive adapter: %v", err) - } - source.Status.PropagateDeploymentAvailability(ra) - - _, err = r.reconcileEventType(ctx, source) - if err != nil { - source.Status.MarkNoEventType("EventTypeReconcileFailed", "") - return fmt.Errorf("reconciling event types: %v", err) - } - source.Status.MarkEventType() - - return nil -} - -func (r *Reconciler) createReceiveAdapter(ctx context.Context, src *v1alpha1.CronJobSource, sinkURI string) (*appsv1.Deployment, error) { - if err := checkResourcesStatus(src); err != nil { - return nil, err - } - - loggingConfig, err := pkgLogging.LoggingConfigToJson(r.loggingConfig) - if err != nil { - logging.FromContext(ctx).Error("error while converting logging config to JSON", zap.Any("receiveAdapter", err)) - } - - metricsConfig, err := metrics.MetricsOptionsToJson(r.metricsConfig) - if err != nil { - logging.FromContext(ctx).Error("error while converting metrics config to JSON", zap.Any("receiveAdapter", err)) - } - - adapterArgs := resources.ReceiveAdapterArgs{ - Image: r.receiveAdapterImage, - Source: src, - Labels: resources.Labels(src.Name), - SinkURI: sinkURI, - LoggingConfig: loggingConfig, - MetricsConfig: metricsConfig, - } - expected := resources.MakeReceiveAdapter(&adapterArgs) - - ra, err := r.KubeClientSet.AppsV1().Deployments(src.Namespace).Get(expected.Name, metav1.GetOptions{}) - if apierrors.IsNotFound(err) { - ra, err = r.KubeClientSet.AppsV1().Deployments(src.Namespace).Create(expected) - msg := "Deployment created" - if err != nil { - msg = fmt.Sprintf("Deployment created, error: %v", err) - } - r.Recorder.Eventf(src, corev1.EventTypeNormal, cronJobSourceDeploymentCreated, "%s", msg) - return ra, err - } else if err != nil { - return nil, fmt.Errorf("error getting receive adapter: %v", err) - } else if !metav1.IsControlledBy(ra, src) { - return nil, fmt.Errorf("deployment %q is not owned by CronJobSource %q", ra.Name, src.Name) - } else if podSpecChanged(ra.Spec.Template.Spec, expected.Spec.Template.Spec) { - ra.Spec.Template.Spec = expected.Spec.Template.Spec - if ra, err = r.KubeClientSet.AppsV1().Deployments(src.Namespace).Update(ra); err != nil { - return ra, err - } - r.Recorder.Eventf(src, corev1.EventTypeNormal, cronJobSourceDeploymentUpdated, "Deployment %q updated", ra.Name) - return ra, nil - } else { - logging.FromContext(ctx).Debug("Reusing existing receive adapter", zap.Any("receiveAdapter", ra)) - } - return ra, nil -} - -func checkResourcesStatus(src *v1alpha1.CronJobSource) error { - for _, rsrc := range []struct { - key string - field string - }{{ - key: "Request.CPU", - field: src.Spec.Resources.Requests.ResourceCPU, - }, { - key: "Request.Memory", - field: src.Spec.Resources.Requests.ResourceMemory, - }, { - key: "Limit.CPU", - field: src.Spec.Resources.Limits.ResourceCPU, - }, { - key: "Limit.Memory", - field: src.Spec.Resources.Limits.ResourceMemory, - }} { - // In the event the field isn't specified, we assign a default in the receive_adapter - if rsrc.field != "" { - if _, err := resource.ParseQuantity(rsrc.field); err != nil { - src.Status.MarkResourcesIncorrect("Incorrect Resource", "%s: %q, Error: %s", rsrc.key, rsrc.field, err) - return fmt.Errorf("incorrect resource specification, %s: %q: %v", rsrc.key, rsrc.field, err) - } - } - } - src.Status.MarkResourcesCorrect() - return nil -} - -func podSpecChanged(oldPodSpec corev1.PodSpec, newPodSpec corev1.PodSpec) bool { - if !equality.Semantic.DeepDerivative(newPodSpec, oldPodSpec) { - return true - } - if len(oldPodSpec.Containers) != len(newPodSpec.Containers) { - return true - } - for i := range newPodSpec.Containers { - if !equality.Semantic.DeepEqual(newPodSpec.Containers[i].Env, oldPodSpec.Containers[i].Env) { - return true - } - } - return false -} - -func (r *Reconciler) reconcileEventType(ctx context.Context, src *v1alpha1.CronJobSource) (*eventingv1alpha1.EventType, error) { - sinkRef := src.Spec.Sink.GetRef() - if sinkRef == nil { - // Can't figure out the broker so return - return nil, nil - } - expected := resources.MakeEventType(src) - current, err := r.eventTypeLister.EventTypes(src.Namespace).Get(expected.Name) - if err != nil && !apierrors.IsNotFound(err) { - logging.FromContext(ctx).Error("Unable to get an existing event type", zap.Error(err)) - return nil, fmt.Errorf("getting event types: %v", err) - } - - // Only create EventTypes for Broker sinks. But if there is an EventType and the src has a non-Broker sink - // (possibly because it was updated), then we need to delete it. - if sinkRef.Kind != "Broker" { - if current != nil { - if err = r.EventingClientSet.EventingV1alpha1().EventTypes(src.Namespace).Delete(current.Name, &metav1.DeleteOptions{}); err != nil { - logging.FromContext(ctx).Error("Error deleting existing event type", zap.Error(err), zap.Any("eventType", current)) - return nil, fmt.Errorf("deleting event type: %v", err) - } - } - // No current and no error. - return nil, nil - } - - if current != nil { - if equality.Semantic.DeepEqual(expected.Spec, current.Spec) { - return current, nil - } - // EventTypes are immutable, delete it and create it again. - if err = r.EventingClientSet.EventingV1alpha1().EventTypes(src.Namespace).Delete(current.Name, &metav1.DeleteOptions{}); err != nil { - logging.FromContext(ctx).Error("Error deleting existing event type", zap.Error(err), zap.Any("eventType", current)) - return nil, fmt.Errorf("deleting event type: %v", err) - } - } - - current, err = r.EventingClientSet.EventingV1alpha1().EventTypes(src.Namespace).Create(expected) - if err != nil { - logging.FromContext(ctx).Error("Error creating event type", zap.Error(err), zap.Any("eventType", expected)) - return nil, fmt.Errorf("creating event type: %v", err) - } - logging.FromContext(ctx).Debug("EventType created", zap.Any("eventType", current)) - return current, nil -} - -func (r *Reconciler) updateStatus(ctx context.Context, desired *v1alpha1.CronJobSource) (*v1alpha1.CronJobSource, error) { - cronjob, err := r.cronjobLister.CronJobSources(desired.Namespace).Get(desired.Name) - if err != nil { - return nil, err - } - - // If there's nothing to update, just return. - if reflect.DeepEqual(cronjob.Status, desired.Status) { - return cronjob, nil - } - - becomesReady := desired.Status.IsReady() && !cronjob.Status.IsReady() - - // Don't modify the informers copy. - existing := cronjob.DeepCopy() - existing.Status = desired.Status - - cj, err := r.LegacyClientSet.SourcesV1alpha1().CronJobSources(desired.Namespace).UpdateStatus(existing) - if err == nil && becomesReady { - duration := time.Since(cj.ObjectMeta.CreationTimestamp.Time) - logging.FromContext(ctx).Info("CronJobSource became ready after", zap.Duration("duration", duration)) - r.Recorder.Event(cronjob, corev1.EventTypeNormal, cronJobReadinessChanged, fmt.Sprintf("CronJobSource %q became ready", cronjob.Name)) - if recorderErr := r.StatsReporter.ReportReady("CronJobSource", cronjob.Namespace, cronjob.Name, duration); recorderErr != nil { - logging.FromContext(ctx).Error("Failed to record ready for CronJobSource", zap.Error(recorderErr)) - } - } - - return cj, err -} - -// TODO determine how to push the updated logging config to existing data plane Pods. -func (r *Reconciler) UpdateFromLoggingConfigMap(cfg *corev1.ConfigMap) { - if cfg != nil { - delete(cfg.Data, "_example") - } - - logcfg, err := pkgLogging.NewConfigFromConfigMap(cfg) - if err != nil { - logging.FromContext(r.loggingContext).Warn("failed to create logging config from configmap", zap.String("cfg.Name", cfg.Name)) - return - } - r.loggingConfig = logcfg - logging.FromContext(r.loggingContext).Info("Update from logging ConfigMap", zap.Any("ConfigMap", cfg)) -} - -// TODO determine how to push the updated metrics config to existing data plane Pods. -func (r *Reconciler) UpdateFromMetricsConfigMap(cfg *corev1.ConfigMap) { - if cfg != nil { - delete(cfg.Data, "_example") - } - - r.metricsConfig = &metrics.ExporterOptions{ - Domain: metrics.Domain(), - Component: component, - ConfigMap: cfg.Data, - } - logging.FromContext(r.loggingContext).Info("Update from metrics ConfigMap", zap.Any("ConfigMap", cfg)) -} diff --git a/pkg/reconciler/legacycronjobsource/cronjobsource_test.go b/pkg/reconciler/legacycronjobsource/cronjobsource_test.go deleted file mode 100644 index 883f29af1ec..00000000000 --- a/pkg/reconciler/legacycronjobsource/cronjobsource_test.go +++ /dev/null @@ -1,577 +0,0 @@ -/* -Copyright 2019 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 legacycronjobsource - -import ( - "context" - "fmt" - "testing" - - "knative.dev/pkg/apis" - "knative.dev/pkg/resolver" - - "knative.dev/pkg/configmap" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - clientgotesting "k8s.io/client-go/testing" - - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/client/injection/ducks/duck/v1/addressable" - _ "knative.dev/pkg/client/injection/ducks/duck/v1beta1/addressable/fake" - "knative.dev/pkg/controller" - - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/reconciler" - "knative.dev/eventing/pkg/reconciler/legacycronjobsource/resources" - "knative.dev/eventing/pkg/utils" - - logtesting "knative.dev/pkg/logging/testing" - . "knative.dev/pkg/reconciler/testing" - - . "knative.dev/eventing/pkg/reconciler/testing" -) - -var ( - trueVal = true - ownerRef = metav1.OwnerReference{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "CronJobSource", - Name: sourceName, - UID: sourceUID, - Controller: &trueVal, - BlockOwnerDeletion: &trueVal, - } - eventTypeName = fmt.Sprintf("dev.knative.cronjob.event-%s", sourceUID) - - sinkDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Channel", - APIVersion: "messaging.knative.dev/v1alpha1", - }, - } - sinkDestURI = duckv1beta1.Destination{ - URI: apis.HTTP(sinkDNS), - } - brokerDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Broker", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - } - sinkDNS = "sink.mynamespace.svc." + utils.GetClusterDomainName() - sinkURI = "http://" + sinkDNS - sinkURIReference = "/foo" - sinkTargetURI = sinkURI + sinkURIReference -) - -const ( - image = "github.com/knative/test/image" - sourceName = "test-cronjob-source" - sourceUID = "1234" - testNS = "testnamespace" - testSchedule = "*/2 * * * *" - testData = "data" - - sinkName = "testsink" - generation = 1 -) - -func init() { - // Add types to scheme - _ = appsv1.AddToScheme(scheme.Scheme) - _ = corev1.AddToScheme(scheme.Scheme) - _ = duckv1alpha1.AddToScheme(scheme.Scheme) -} - -func TestAllCases(t *testing.T) { - table := TableTest{ - { - Name: "bad workqueue key", - // Make sure Reconcile handles bad keys. - Key: "too/many/parts", - }, { - Name: "key not found", - // Make sure Reconcile handles good keys that don't exist. - Key: "foo/not-found", - }, { - Name: "invalid schedule", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: "invalid schedule", - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantEvents: []string{ - Eventf(corev1.EventTypeWarning, "CronJobSourceUpdateStatusFailed", - "Failed to update CronJobSource's status: invalid schedule: expected exactly 5 fields, found 2: [invalid schedule]"), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: "invalid schedule", - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithCronJobSourceStatusObservedGeneration(generation), - WithInvalidCronJobSourceSchedule, - WithCronJobSourceSink(sinkURI), - ), - }}, - }, { - Name: "missing sink", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - }, - Key: testNS + "/" + sourceName, - WantErr: true, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithCronJobSourceStatusObservedGeneration(generation), - WithCronJobSourceSinkNotFound, - ), - }}, - }, { - Name: "valid", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(sinkDest), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "CronJobSourceReadinessChanged", `CronJobSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - }, { - Name: "valid with sink URI", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDestURI, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(sinkDest), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "CronJobSourceReadinessChanged", `CronJobSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDestURI, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - }, { - Name: "valid with event type creation", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &brokerDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - NewBroker(sinkName, testNS, - WithInitBrokerConditions, - WithBrokerAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(brokerDest), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "CronJobSourceReadinessChanged", `CronJobSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &brokerDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceEventType, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - WantCreates: []runtime.Object{ - NewEventType(eventTypeName, testNS, - WithEventTypeLabels(resources.Labels(sourceName)), - WithEventTypeType(sourcesv1alpha1.CronJobEventType), - WithEventTypeSource(sourcesv1alpha1.CronJobEventSource(testNS, sourceName)), - WithEventTypeBroker(sinkName), - WithEventTypeOwnerReference(ownerRef)), - }, - }, { - Name: "valid with event type deletion and creation", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &brokerDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - NewBroker(sinkName, testNS, - WithInitBrokerConditions, - WithBrokerAddress(sinkDNS), - ), - NewEventType(eventTypeName, testNS, - WithEventTypeLabels(resources.Labels(sourceName)), - WithEventTypeType("type-1"), - WithEventTypeSource(sourcesv1alpha1.CronJobEventSource(testNS, sourceName)), - WithEventTypeBroker(sinkName), - WithEventTypeOwnerReference(ownerRef)), - makeAvailableReceiveAdapter(brokerDest), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "CronJobSourceReadinessChanged", `CronJobSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &brokerDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceEventType, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - WantDeletes: []clientgotesting.DeleteActionImpl{{ - Name: eventTypeName, - }}, - WantCreates: []runtime.Object{ - NewEventType(eventTypeName, testNS, - WithEventTypeLabels(resources.Labels(sourceName)), - WithEventTypeType(sourcesv1alpha1.CronJobEventType), - WithEventTypeSource(sourcesv1alpha1.CronJobEventSource(testNS, sourceName)), - WithEventTypeBroker(sinkName), - WithEventTypeOwnerReference(ownerRef)), - }, - }, { - Name: "valid, existing ra", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(sinkDest), - }, - Key: testNS + "/" + sourceName, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - Eventf(corev1.EventTypeNormal, "CronJobSourceReadinessChanged", `CronJobSource %q became ready`, sourceName), - }, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - }, { - Name: "valid, no change", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(sinkDest), - }, - Key: testNS + "/" + sourceName, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - }, - }, { - Name: "valid with event type deletion", - Objects: []runtime.Object{ - NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - ), - NewChannel(sinkName, testNS, - WithInitChannelConditions, - WithChannelAddress(sinkDNS), - ), - makeAvailableReceiveAdapter(sinkDest), - NewEventType(eventTypeName, testNS, - WithEventTypeLabels(resources.Labels(sourceName)), - WithEventTypeType(sourcesv1alpha1.CronJobEventType), - WithEventTypeSource(sourcesv1alpha1.CronJobEventSource(testNS, sourceName)), - WithEventTypeBroker(sinkName), - WithEventTypeOwnerReference(ownerRef)), - }, - Key: testNS + "/" + sourceName, - WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ - Object: NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &sinkDest, - }), - WithCronJobSourceUID(sourceUID), - WithCronJobSourceObjectMetaGeneration(generation), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithValidCronJobSourceResources, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - WithCronJobSourceEventType, - WithCronJobSourceStatusObservedGeneration(generation), - ), - }}, - WantEvents: []string{ - Eventf(corev1.EventTypeNormal, "CronJobSourceReconciled", `CronJobSource reconciled: "%s/%s"`, testNS, sourceName), - }, - WantDeletes: []clientgotesting.DeleteActionImpl{{ - Name: eventTypeName, - }}, - }, - } - - logger := logtesting.TestLogger(t) - table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler { - ctx = addressable.WithDuck(ctx) - r := &Reconciler{ - Base: reconciler.NewBase(ctx, controllerAgentName, cmw), - cronjobLister: listers.GetLegacyCronJobSourceLister(), - deploymentLister: listers.GetDeploymentLister(), - eventTypeLister: listers.GetEventTypeLister(), - receiveAdapterImage: image, - } - r.sinkResolver = resolver.NewURIResolver(ctx, func(types.NamespacedName) {}) - - return r - }, - true, - logger, - )) -} - -func makeAvailableReceiveAdapter(dest duckv1beta1.Destination) *appsv1.Deployment { - ra := makeReceiveAdapterWithSink(dest) - WithDeploymentAvailable()(ra) - return ra -} - -func makeReceiveAdapterWithSink(dest duckv1beta1.Destination) *appsv1.Deployment { - source := NewCronJobSource(sourceName, testNS, - WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: testSchedule, - Data: testData, - Sink: &dest, - }, - ), - WithCronJobSourceUID(sourceUID), - // Status Update: - WithInitCronJobSourceConditions, - WithValidCronJobSourceSchedule, - WithCronJobSourceDeployed, - WithCronJobSourceSink(sinkURI), - ) - - args := resources.ReceiveAdapterArgs{ - Image: image, - Source: source, - Labels: resources.Labels(sourceName), - SinkURI: sinkURI, - } - return resources.MakeReceiveAdapter(&args) -} diff --git a/pkg/reconciler/legacycronjobsource/doc.go b/pkg/reconciler/legacycronjobsource/doc.go deleted file mode 100644 index a07c56d4726..00000000000 --- a/pkg/reconciler/legacycronjobsource/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2019 The Knative 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 cronjobsource implements the CronJobSource controller. -package legacycronjobsource diff --git a/pkg/reconciler/legacycronjobsource/resources/eventtype.go b/pkg/reconciler/legacycronjobsource/resources/eventtype.go deleted file mode 100644 index 261a136b7ea..00000000000 --- a/pkg/reconciler/legacycronjobsource/resources/eventtype.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "knative.dev/pkg/kmeta" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - eventingv1alpha1 "knative.dev/eventing/pkg/apis/eventing/v1alpha1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/utils" -) - -// MakeEventType creates the in-memory representation of the EventType for the specified CronJobSource. -func MakeEventType(src *v1alpha1.CronJobSource) *eventingv1alpha1.EventType { - return &eventingv1alpha1.EventType{ - ObjectMeta: metav1.ObjectMeta{ - Name: utils.GenerateFixedName(src, utils.ToDNS1123Subdomain(v1alpha1.CronJobEventType)), - Labels: Labels(src.Name), - Namespace: src.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *kmeta.NewControllerRef(src), - }, - }, - Spec: eventingv1alpha1.EventTypeSpec{ - Type: v1alpha1.CronJobEventType, - Source: v1alpha1.CronJobEventSource(src.Namespace, src.Name), - Broker: src.Spec.Sink.GetRef().Name, - }, - } -} diff --git a/pkg/reconciler/legacycronjobsource/resources/labels.go b/pkg/reconciler/legacycronjobsource/resources/labels.go deleted file mode 100644 index b2bc3eb7101..00000000000 --- a/pkg/reconciler/legacycronjobsource/resources/labels.go +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -const ( - // controllerAgentName is the string used by this controller to identify - // itself when creating events. - controllerAgentName = "cronjob-source-controller" -) - -// Labels are the labels attached to all resources based on a CronJobSource. -func Labels(name string) map[string]string { - return map[string]string{ - "sources.eventing.knative.dev/cronJobSource": name, - "eventing.knative.dev/source": controllerAgentName, - } -} diff --git a/pkg/reconciler/legacycronjobsource/resources/receive_adapter.go b/pkg/reconciler/legacycronjobsource/resources/receive_adapter.go deleted file mode 100644 index af8006a23c9..00000000000 --- a/pkg/reconciler/legacycronjobsource/resources/receive_adapter.go +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "fmt" - - v1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/utils" - "knative.dev/pkg/kmeta" -) - -var ( - // one is a form of int32(1) that you can take the address of. - one = int32(1) -) - -// ReceiveAdapterArgs are the arguments needed to create a Cron Job Source Receive Adapter. Every -// field is required. -type ReceiveAdapterArgs struct { - Image string - Source *v1alpha1.CronJobSource - Labels map[string]string - SinkURI string - MetricsConfig string - LoggingConfig string -} - -// MakeReceiveAdapter generates (but does not insert into K8s) the Receive Adapter Deployment for -// Cron Job Sources. -func MakeReceiveAdapter(args *ReceiveAdapterArgs) *v1.Deployment { - name := args.Source.ObjectMeta.Name - RequestResourceCPU, err := resource.ParseQuantity(args.Source.Spec.Resources.Requests.ResourceCPU) - if err != nil { - RequestResourceCPU = resource.MustParse("250m") - } - RequestResourceMemory, err := resource.ParseQuantity(args.Source.Spec.Resources.Requests.ResourceMemory) - if err != nil { - RequestResourceMemory = resource.MustParse("512Mi") - } - LimitResourceCPU, err := resource.ParseQuantity(args.Source.Spec.Resources.Limits.ResourceCPU) - if err != nil { - LimitResourceCPU = resource.MustParse("250m") - } - LimitResourceMemory, err := resource.ParseQuantity(args.Source.Spec.Resources.Limits.ResourceMemory) - if err != nil { - LimitResourceMemory = resource.MustParse("512Mi") - } - - res := corev1.ResourceRequirements{ - Requests: corev1.ResourceList{ - corev1.ResourceCPU: RequestResourceCPU, - corev1.ResourceMemory: RequestResourceMemory, - }, - Limits: corev1.ResourceList{ - corev1.ResourceCPU: LimitResourceCPU, - corev1.ResourceMemory: LimitResourceMemory, - }, - } - - return &v1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: args.Source.Namespace, - Name: utils.GenerateFixedName(args.Source, fmt.Sprintf("cronjobsource-%s", name)), - Labels: args.Labels, - OwnerReferences: []metav1.OwnerReference{ - *kmeta.NewControllerRef(args.Source), - }, - }, - Spec: v1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: args.Labels, - }, - Replicas: &one, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: args.Labels, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: args.Source.Spec.ServiceAccountName, - Containers: []corev1.Container{ - { - Name: "receive-adapter", - Image: args.Image, - Ports: []corev1.ContainerPort{ - { - Name: "metrics", - ContainerPort: 9090, - }}, - Env: []corev1.EnvVar{ - { - Name: "SCHEDULE", - Value: args.Source.Spec.Schedule, - }, - { - Name: "DATA", - Value: args.Source.Spec.Data, - }, - { - Name: "SINK_URI", - Value: args.SinkURI, - }, - { - Name: "NAME", - Value: args.Source.Name, - }, - { - Name: "NAMESPACE", - Value: args.Source.Namespace, - }, { - Name: "METRICS_DOMAIN", - Value: "knative.dev/eventing", - }, { - Name: "K_METRICS_CONFIG", - Value: args.MetricsConfig, - }, { - Name: "K_LOGGING_CONFIG", - Value: args.LoggingConfig, - }, - }, - Resources: res, - }, - }, - }, - }, - }, - } -} diff --git a/pkg/reconciler/legacycronjobsource/resources/receive_adapter_test.go b/pkg/reconciler/legacycronjobsource/resources/receive_adapter_test.go deleted file mode 100644 index 95c970e28f3..00000000000 --- a/pkg/reconciler/legacycronjobsource/resources/receive_adapter_test.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2019 The Knative 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 resources - -import ( - "fmt" - "testing" - - v1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/pkg/kmp" -) - -func TestMakeReceiveAdapter(t *testing.T) { - src := &v1alpha1.CronJobSource{ - ObjectMeta: metav1.ObjectMeta{ - Name: "source-name", - Namespace: "source-namespace", - UID: "source-uid", - }, - Spec: v1alpha1.CronJobSourceSpec{ - ServiceAccountName: "source-svc-acct", - Schedule: "*/2 * * * *", - Data: "data", - }, - } - - got := MakeReceiveAdapter(&ReceiveAdapterArgs{ - Image: "test-image", - Source: src, - Labels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - SinkURI: "sink-uri", - }) - - one := int32(1) - yes := true - want := &v1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "source-namespace", - Name: fmt.Sprintf("cronjobsource-%s-%s", src.Name, src.UID), - Labels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: "sources.eventing.knative.dev/v1alpha1", - Kind: "CronJobSource", - Name: src.Name, - UID: src.UID, - Controller: &yes, - BlockOwnerDeletion: &yes, - }}, - }, - Spec: v1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - }, - Replicas: &one, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", - }, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: "source-svc-acct", - Containers: []corev1.Container{ - { - Name: "receive-adapter", - Image: "test-image", - Ports: []corev1.ContainerPort{{ - Name: "metrics", - ContainerPort: 9090, - }}, - Env: []corev1.EnvVar{ - { - Name: "SCHEDULE", - Value: "*/2 * * * *", - }, - { - Name: "DATA", - Value: "data", - }, - { - Name: "SINK_URI", - Value: "sink-uri", - }, - { - Name: "NAME", - Value: "source-name", - }, - { - Name: "NAMESPACE", - Value: "source-namespace", - }, - { - Name: "METRICS_DOMAIN", - Value: "knative.dev/eventing", - }, - { - Name: "K_METRICS_CONFIG", - Value: "", - }, - { - Name: "K_LOGGING_CONFIG", - Value: "", - }, - }, - Resources: corev1.ResourceRequirements{ - Limits: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse("250m"), - corev1.ResourceMemory: resource.MustParse("512Mi"), - }, - Requests: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse("250m"), - corev1.ResourceMemory: resource.MustParse("512Mi"), - }, - }, - }, - }, - }, - }, - }, - } - - if diff, err := kmp.SafeDiff(want, got); err != nil { - t.Errorf("unexpected cron job resources (-want, +got) = %v", err) - } else if diff != "" { - t.Errorf("Unexpected deployment (-want +got) = %v", diff) - } -} diff --git a/pkg/reconciler/legacysinkbinding/controller.go b/pkg/reconciler/legacysinkbinding/controller.go deleted file mode 100644 index 8249a608a5c..00000000000 --- a/pkg/reconciler/legacysinkbinding/controller.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2019 The Knative 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 legacysinkbinding - -import ( - "context" - - fbinformer "knative.dev/eventing/pkg/legacyclient/injection/informers/legacysources/v1alpha1/sinkbinding" - "knative.dev/pkg/client/injection/ducks/duck/v1/podspecable" - "knative.dev/pkg/resolver" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/record" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/pkg/apis/duck" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/injection/clients/dynamicclient" - "knative.dev/pkg/logging" - "knative.dev/pkg/tracker" - "knative.dev/pkg/webhook/psbinding" -) - -const ( - controllerAgentName = "legacysinkbinding-controller" -) - -// NewController returns a new SinkBinding reconciler. -func NewController( - ctx context.Context, - cmw configmap.Watcher, -) *controller.Impl { - logger := logging.FromContext(ctx) - - fbInformer := fbinformer.Get(ctx) - dc := dynamicclient.Get(ctx) - psInformerFactory := podspecable.Get(ctx) - - c := &psbinding.BaseReconciler{ - GVR: v1alpha1.SchemeGroupVersion.WithResource("sinkbindings"), - Get: func(namespace string, name string) (psbinding.Bindable, error) { - return fbInformer.Lister().SinkBindings(namespace).Get(name) - }, - DynamicClient: dc, - Recorder: record.NewBroadcaster().NewRecorder( - scheme.Scheme, corev1.EventSource{Component: controllerAgentName}), - } - impl := controller.NewImpl(c, logger, "SinkBindings") - - logger.Info("Setting up event handlers") - - fbInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) - - c.WithContext = WithContextFactory(ctx, impl.EnqueueKey) - c.Tracker = tracker.New(impl.EnqueueKey, controller.GetTrackerLease(ctx)) - c.Factory = &duck.CachedInformerFactory{ - Delegate: &duck.EnqueueInformerFactory{ - Delegate: psInformerFactory, - EventHandler: controller.HandleAll(c.Tracker.OnChanged), - }, - } - - return impl -} - -func ListAll(ctx context.Context, handler cache.ResourceEventHandler) psbinding.ListAll { - fbInformer := fbinformer.Get(ctx) - - // Whenever a SinkBinding changes our webhook programming might change. - fbInformer.Informer().AddEventHandler(handler) - - return func() ([]psbinding.Bindable, error) { - l, err := fbInformer.Lister().List(labels.Everything()) - if err != nil { - return nil, err - } - bl := make([]psbinding.Bindable, 0, len(l)) - for _, elt := range l { - bl = append(bl, elt) - } - return bl, nil - } - -} - -func WithContextFactory(ctx context.Context, handler func(types.NamespacedName)) psbinding.BindableContext { - r := resolver.NewURIResolver(ctx, handler) - - return func(ctx context.Context, b psbinding.Bindable) (context.Context, error) { - sb := b.(*v1alpha1.SinkBinding) - uri, err := r.URIFromDestinationV1(sb.Spec.Sink, sb) - if err != nil { - return nil, err - } - sb.Status.SinkURI = uri - return v1alpha1.WithSinkURI(ctx, sb.Status.SinkURI), nil - } -} diff --git a/pkg/reconciler/pingsource/resources/eventtype.go b/pkg/reconciler/pingsource/resources/eventtype.go index 973ee5c8abd..e9f04e16d38 100644 --- a/pkg/reconciler/pingsource/resources/eventtype.go +++ b/pkg/reconciler/pingsource/resources/eventtype.go @@ -25,7 +25,7 @@ import ( "knative.dev/eventing/pkg/utils" ) -// MakeEventType creates the in-memory representation of the EventType for the specified CronJobSource. +// MakeEventType creates the in-memory representation of the EventType for the specified PingSource. func MakeEventType(src *v1alpha1.PingSource) *eventingv1alpha1.EventType { return &eventingv1alpha1.EventType{ ObjectMeta: metav1.ObjectMeta{ diff --git a/pkg/reconciler/pingsource/resources/labels.go b/pkg/reconciler/pingsource/resources/labels.go index ed1c9733c53..4156045f137 100644 --- a/pkg/reconciler/pingsource/resources/labels.go +++ b/pkg/reconciler/pingsource/resources/labels.go @@ -22,7 +22,7 @@ const ( controllerAgentName = "ping-source-controller" ) -// Labels are the labels attached to all resources based on a CronJobSource. +// Labels are the labels attached to all resources based on a PingSource. func Labels(name string) map[string]string { return map[string]string{ "sources.knative.dev/pingSource": name, diff --git a/pkg/reconciler/reconciler.go b/pkg/reconciler/reconciler.go index a627453131c..a8cff223cfe 100644 --- a/pkg/reconciler/reconciler.go +++ b/pkg/reconciler/reconciler.go @@ -30,15 +30,12 @@ import ( "k8s.io/client-go/tools/record" clientset "knative.dev/eventing/pkg/client/clientset/versioned" eventingScheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" - legacyclientset "knative.dev/eventing/pkg/legacyclient/clientset/versioned" - legacyScheme "knative.dev/eventing/pkg/legacyclient/clientset/versioned/scheme" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" "knative.dev/pkg/logging" "knative.dev/pkg/logging/logkey" eventingclient "knative.dev/eventing/pkg/client/injection/client" - legacyclient "knative.dev/eventing/pkg/legacyclient/injection/client" kubeclient "knative.dev/pkg/client/injection/kube/client" "knative.dev/pkg/injection/clients/dynamicclient" ) @@ -51,9 +48,6 @@ type Base struct { // EventingClientSet allows us to configure Eventing objects EventingClientSet clientset.Interface - // LegacyClientSet allows us to configure Legacy Eventing objects - LegacyClientSet legacyclientset.Interface - // ApiExtensionsClientSet allows us to configure k8s API extension objects. ApiExtensionsClientSet apiextensionsclientset.Interface @@ -121,7 +115,6 @@ func NewBase(ctx context.Context, controllerAgentName string, cmw configmap.Watc base := &Base{ KubeClientSet: kubeClient, EventingClientSet: eventingclient.Get(ctx), - LegacyClientSet: legacyclient.Get(ctx), DynamicClientSet: dynamicclient.Get(ctx), ConfigMapWatcher: cmw, Recorder: recorder, @@ -136,5 +129,4 @@ func init() { // Add eventing types to the default Kubernetes Scheme so Events can be // logged for eventing types. eventingScheme.AddToScheme(scheme.Scheme) - legacyScheme.AddToScheme(scheme.Scheme) } diff --git a/pkg/reconciler/stats_reporter.go b/pkg/reconciler/stats_reporter.go index 356845bf381..17488506cf4 100644 --- a/pkg/reconciler/stats_reporter.go +++ b/pkg/reconciler/stats_reporter.go @@ -50,15 +50,10 @@ const ( // SubscriptionReadyLatencyN is the time it takes for a subscription to become ready since the resource is created. SubscriptionReadyLatencyN = "subscription_ready_latency" - // ContainerSourceReadyCountN is the number of container sources that have become ready. - ContainerSourceReadyCountN = "container_source_ready_count" - // ContainerSourceReadyLatencyN is the time it takes for a container source to become ready since the resource is created. - ContainerSourceReadyLatencyN = "container_source_ready_latency" - - // CronJobSourceReadyCountN is the number of cron job sources that have become ready. - CronJobSourceReadyCountN = "cron_job_source_ready_count" - // CronJobSourceReadyLatencyN is the time it takes for a cron job source to become ready since the resource is created. - CronJobSourceReadyLatencyN = "cron_job_source_ready_latency" + // PingSourceReadyCountN is the number of cron job sources that have become ready. + PingSourceReadyCountN = "ping_source_ready_count" + // PingSourceReadyLatencyN is the time it takes for a cron job source to become ready since the resource is created. + PingSourceReadyLatencyN = "ping_source_ready_latency" // ApiServerSourceReadyCountN is the number of api server sources that have become ready. ApiServerSourceReadyCountN = "api_server_source_ready_count" @@ -96,13 +91,9 @@ var ( ReadyCountKey: SubscriptionReadyCountN, }, // Sources - "ContainerSource": { - ReadyLatencyKey: ContainerSourceReadyLatencyN, - ReadyCountKey: ContainerSourceReadyCountN, - }, - "CronJobSource": { - ReadyLatencyKey: CronJobSourceReadyLatencyN, - ReadyCountKey: CronJobSourceReadyCountN, + "PingSource": { + ReadyLatencyKey: PingSourceReadyLatencyN, + ReadyCountKey: PingSourceReadyCountN, }, "ApiServerSource": { ReadyLatencyKey: ApiServerSourceReadyLatencyN, diff --git a/pkg/reconciler/testing/containersource.go b/pkg/reconciler/testing/containersource.go deleted file mode 100644 index c71305d72e1..00000000000 --- a/pkg/reconciler/testing/containersource.go +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright 2019 The Knative 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 testing - -import ( - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// ContainerSourceOption enables further configuration of a ContainerSource. -type ContainerSourceOption func(*legacysourcesv1alpha1.ContainerSource) - -// NewContainerSource creates a ContainerSource with ContainerSourceOptions -func NewContainerSource(name, namespace string, o ...ContainerSourceOption) *legacysourcesv1alpha1.ContainerSource { - c := &legacysourcesv1alpha1.ContainerSource{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - } - for _, opt := range o { - opt(c) - } - //c.SetDefaults(context.Background()) // TODO: We should add defaults and validation. - return c -} - -func WithContainerSourceUID(uid types.UID) ContainerSourceOption { - return func(s *legacysourcesv1alpha1.ContainerSource) { - s.UID = uid - } -} - -// WithInitContainerSourceConditions initializes the ContainerSource's conditions. -func WithInitContainerSourceConditions(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.InitializeConditions() - s.MarkDeprecated(&s.Status.Status, "ContainerSourceDeprecated", "containersources.sources.eventing.knative.dev are deprecated and will be removed in the future. Use a Deployment and SinkBinding.sources.knative.dev instead.") -} - -func WithContainerSourceSinkNotFound(msg string) ContainerSourceOption { - return func(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.MarkNoSink("NotFound", msg) - } -} - -func WithContainerSourceSinkMissing(msg string) ContainerSourceOption { - return func(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.MarkNoSink("Missing", msg) - } -} - -func WithContainerSourceSink(uri string) ContainerSourceOption { - return func(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.MarkSink(uri) - } -} - -func WithContainerSourceDeploying(msg string) ContainerSourceOption { - return func(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.MarkDeploying("DeploymentCreated", msg) - } -} - -func WithContainerSourceDeployFailed(msg string) ContainerSourceOption { - return func(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.MarkNotDeployed("DeploymentCreateFailed", msg) - } -} - -func WithContainerSourceDeployed(s *legacysourcesv1alpha1.ContainerSource) { - s.Status.MarkDeployed() -} - -func WithContainerSourceDeleted(c *legacysourcesv1alpha1.ContainerSource) { - t := metav1.NewTime(time.Unix(1e9, 0)) - c.ObjectMeta.SetDeletionTimestamp(&t) -} - -func WithContainerSourceSpec(spec legacysourcesv1alpha1.ContainerSourceSpec) ContainerSourceOption { - return func(c *legacysourcesv1alpha1.ContainerSource) { - c.Spec = spec - } -} - -func WithContainerSourceLabels(labels map[string]string) ContainerSourceOption { - return func(c *legacysourcesv1alpha1.ContainerSource) { - c.Labels = labels - } -} - -func WithContainerSourceAnnotations(annotations map[string]string) ContainerSourceOption { - return func(c *legacysourcesv1alpha1.ContainerSource) { - c.Annotations = annotations - } -} - -func WithContainerSourceStatusObservedGeneration(generation int64) ContainerSourceOption { - return func(c *legacysourcesv1alpha1.ContainerSource) { - c.Status.ObservedGeneration = generation - } -} - -func WithContainerSourceObjectMetaGeneration(generation int64) ContainerSourceOption { - return func(c *legacysourcesv1alpha1.ContainerSource) { - c.ObjectMeta.Generation = generation - } -} diff --git a/pkg/reconciler/testing/cronjobsource.go b/pkg/reconciler/testing/cronjobsource.go deleted file mode 100644 index 3efd5215ad5..00000000000 --- a/pkg/reconciler/testing/cronjobsource.go +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright 2019 The Knative 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 testing - -import ( - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" -) - -// CronJobSourceOption enables further configuration of a CronJob. -type CronJobSourceOption func(*v1alpha1.CronJobSource) - -// NewCronJobSource creates a CronJobSource with CronJobOptions. -func NewCronJobSource(name, namespace string, o ...CronJobSourceOption) *v1alpha1.CronJobSource { - c := &v1alpha1.CronJobSource{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - } - for _, opt := range o { - opt(c) - } - // c.SetDefaults(context.Background()) // TODO: We should add defaults and validation. - return c -} - -func WithCronJobSourceUID(uid string) CronJobSourceOption { - return func(c *v1alpha1.CronJobSource) { - c.UID = types.UID(uid) - } -} - -// WithInitCronJobSourceConditions initializes the CronJobSource's conditions. -func WithInitCronJobSourceConditions(s *v1alpha1.CronJobSource) { - s.Status.InitializeConditions() - s.MarkDeprecated(&s.Status.Status, "CronJobSourceDeprecated", "cronjobsources.sources.eventing.knative.dev are deprecated and will be removed in the future. Use a CronJob and SinkBinding.sources.knative.dev instead.") -} - -func WithValidCronJobSourceSchedule(s *v1alpha1.CronJobSource) { - s.Status.MarkSchedule() -} - -func WithInvalidCronJobSourceSchedule(s *v1alpha1.CronJobSource) { - s.Status.MarkInvalidSchedule("Invalid", "") -} - -func WithCronJobSourceSinkNotFound(s *v1alpha1.CronJobSource) { - s.Status.MarkNoSink("NotFound", "") -} - -func WithCronJobSourceSink(uri string) CronJobSourceOption { - return func(s *v1alpha1.CronJobSource) { - s.Status.MarkSink(uri) - } -} - -func WithCronJobSourceDeployed(s *v1alpha1.CronJobSource) { - s.Status.PropagateDeploymentAvailability(NewDeployment("any", "any", WithDeploymentAvailable())) -} - -func WithCronJobSourceEventType(s *v1alpha1.CronJobSource) { - s.Status.MarkEventType() -} - -func WithValidCronJobSourceResources(s *v1alpha1.CronJobSource) { - s.Status.MarkResourcesCorrect() -} - -func WithCronJobSourceDeleted(c *v1alpha1.CronJobSource) { - t := metav1.NewTime(time.Unix(1e9, 0)) - c.ObjectMeta.SetDeletionTimestamp(&t) -} - -func WithCronJobSourceSpec(spec v1alpha1.CronJobSourceSpec) CronJobSourceOption { - return func(c *v1alpha1.CronJobSource) { - c.Spec = spec - } -} - -func WithCronJobApiVersion(apiVersion string) CronJobSourceOption { - return func(c *v1alpha1.CronJobSource) { - c.APIVersion = apiVersion - } -} - -func WithCronJobSourceStatusObservedGeneration(generation int64) CronJobSourceOption { - return func(c *v1alpha1.CronJobSource) { - c.Status.ObservedGeneration = generation - } -} - -func WithCronJobSourceObjectMetaGeneration(generation int64) CronJobSourceOption { - return func(c *v1alpha1.CronJobSource) { - c.ObjectMeta.Generation = generation - } -} diff --git a/pkg/reconciler/testing/factory.go b/pkg/reconciler/testing/factory.go index 033fd389270..f1ae2d71396 100644 --- a/pkg/reconciler/testing/factory.go +++ b/pkg/reconciler/testing/factory.go @@ -35,7 +35,6 @@ import ( "knative.dev/pkg/controller" fakeeventingclient "knative.dev/eventing/pkg/client/injection/client/fake" - fakelegacyclient "knative.dev/eventing/pkg/legacyclient/injection/client/fake" fakekubeclient "knative.dev/pkg/client/injection/kube/client/fake" fakedynamicclient "knative.dev/pkg/injection/clients/dynamicclient/fake" @@ -61,7 +60,6 @@ func MakeFactory(ctor Ctor, unstructured bool, logger *zap.SugaredLogger) Factor ctx, kubeClient := fakekubeclient.With(ctx, ls.GetKubeObjects()...) ctx, client := fakeeventingclient.With(ctx, ls.GetEventingObjects()...) - ctx, legacy := fakelegacyclient.With(ctx, ls.GetLegacyObjects()...) ctx, dynamicClient := fakedynamicclient.With(ctx, NewScheme(), ToUnstructured(t, r.Objects)...) @@ -87,7 +85,6 @@ func MakeFactory(ctor Ctor, unstructured bool, logger *zap.SugaredLogger) Factor for _, reactor := range r.WithReactors { kubeClient.PrependReactor("*", "*", reactor) client.PrependReactor("*", "*", reactor) - legacy.PrependReactor("*", "*", reactor) dynamicClient.PrependReactor("*", "*", reactor) } @@ -99,15 +96,7 @@ func MakeFactory(ctor Ctor, unstructured bool, logger *zap.SugaredLogger) Factor return ValidateUpdates(ctx, action) }) - // Validate all Create operations through the legacy client. - legacy.PrependReactor("create", "*", func(action ktesting.Action) (handled bool, ret runtime.Object, err error) { - return ValidateCreates(ctx, action) - }) - legacy.PrependReactor("update", "*", func(action ktesting.Action) (handled bool, ret runtime.Object, err error) { - return ValidateUpdates(ctx, action) - }) - - actionRecorderList := ActionRecorderList{dynamicClient, client, kubeClient, legacy} + actionRecorderList := ActionRecorderList{dynamicClient, client, kubeClient} eventList := EventList{Recorder: eventRecorder} return c, actionRecorderList, eventList diff --git a/pkg/reconciler/testing/legacyapiserversource.go b/pkg/reconciler/testing/legacyapiserversource.go deleted file mode 100644 index b1d249eda24..00000000000 --- a/pkg/reconciler/testing/legacyapiserversource.go +++ /dev/null @@ -1,118 +0,0 @@ -/* -Copyright 2020 The Knative 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 testing - -import ( - "fmt" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/pkg/utils" -) - -// LegacyApiServerSourceOption enables further configuration of a Legacy ApiServerSource. -type LegacyApiServerSourceOption func(*v1alpha1.ApiServerSource) - -// NewLegacyApiServerSource creates a ApiServer with ApiServerOptions -func NewLegacyApiServerSource(name, namespace string, o ...LegacyApiServerSourceOption) *v1alpha1.ApiServerSource { - c := &v1alpha1.ApiServerSource{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - } - for _, opt := range o { - opt(c) - } - //c.SetDefaults(context.Background()) // TODO: We should add defaults and validation. - return c -} - -func WithLegacyApiServerSourceUID(uid string) LegacyApiServerSourceOption { - return func(a *v1alpha1.ApiServerSource) { - a.UID = types.UID(uid) - } -} - -// WithInitApiServerSourceConditions initializes the ApiServerSource's conditions. -func WithInitLegacyApiServerSourceConditions(s *v1alpha1.ApiServerSource) { - s.Status.InitializeConditions() - s.MarkDeprecated(&s.Status.Status, "ApiServerSourceDeprecated", "apiserversources.sources.eventing.knative.dev are deprecated and will be removed in the future. Use apiserversources.sources.knative.dev instead.") -} - -func WithLegacyApiServerSourceSinkNotFound(s *v1alpha1.ApiServerSource) { - s.Status.MarkNoSink("NotFound", "") -} - -func WithLegacyApiServerSourceSink(uri string) LegacyApiServerSourceOption { - return func(s *v1alpha1.ApiServerSource) { - s.Status.MarkSink(uri) - } -} - -func WithLegacyApiServerSourceSinkDepRef(uri string) LegacyApiServerSourceOption { - return func(s *v1alpha1.ApiServerSource) { - s.Status.MarkSinkWarnRefDeprecated(uri) - } -} - -func WithLegacyApiServerSourceDeploymentUnavailable(s *v1alpha1.ApiServerSource) { - // The Deployment uses GenerateName, so its name is empty. - name := utils.GenerateFixedName(s, fmt.Sprintf("apiserversource-%s", s.Name)) - s.Status.PropagateDeploymentAvailability(NewDeployment(name, "any")) -} - -func WithLegacyApiServerSourceDeployed(s *v1alpha1.ApiServerSource) { - s.Status.PropagateDeploymentAvailability(NewDeployment("any", "any", WithDeploymentAvailable())) -} - -func WithLegacyApiServerSourceEventTypes(s *v1alpha1.ApiServerSource) { - s.Status.MarkEventTypes() -} - -func WithLegacyApiServerSourceSufficientPermissions(s *v1alpha1.ApiServerSource) { - s.Status.MarkSufficientPermissions() -} - -func WithLegacyApiServerSourceNoSufficientPermissions(s *v1alpha1.ApiServerSource) { - s.Status.MarkNoSufficientPermissions("", `User system:serviceaccount:testnamespace:default cannot get, list, watch resource "namespaces" in API group ""`) -} - -func WithLegacyApiServerSourceDeleted(c *v1alpha1.ApiServerSource) { - t := metav1.NewTime(time.Unix(1e9, 0)) - c.ObjectMeta.SetDeletionTimestamp(&t) -} - -func WithLegacyApiServerSourceSpec(spec v1alpha1.ApiServerSourceSpec) LegacyApiServerSourceOption { - return func(c *v1alpha1.ApiServerSource) { - c.Spec = spec - } -} - -func WithLegacyApiServerSourceStatusObservedGeneration(generation int64) LegacyApiServerSourceOption { - return func(c *v1alpha1.ApiServerSource) { - c.Status.ObservedGeneration = generation - } -} - -func WithLegacyApiServerSourceObjectMetaGeneration(generation int64) LegacyApiServerSourceOption { - return func(c *v1alpha1.ApiServerSource) { - c.ObjectMeta.Generation = generation - } -} diff --git a/pkg/reconciler/testing/listers.go b/pkg/reconciler/testing/listers.go index ed2e2a6a974..f9a7c613c7c 100644 --- a/pkg/reconciler/testing/listers.go +++ b/pkg/reconciler/testing/listers.go @@ -34,7 +34,6 @@ import ( configsv1alpha1 "knative.dev/eventing/pkg/apis/configs/v1alpha1" eventingv1alpha1 "knative.dev/eventing/pkg/apis/eventing/v1alpha1" flowsv1alpha1 "knative.dev/eventing/pkg/apis/flows/v1alpha1" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" messagingv1alpha1 "knative.dev/eventing/pkg/apis/messaging/v1alpha1" sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" fakeeventingclientset "knative.dev/eventing/pkg/client/clientset/versioned/fake" @@ -43,8 +42,6 @@ import ( flowslisters "knative.dev/eventing/pkg/client/listers/flows/v1alpha1" messaginglisters "knative.dev/eventing/pkg/client/listers/messaging/v1alpha1" sourcelisters "knative.dev/eventing/pkg/client/listers/sources/v1alpha1" - fakelegacyclientset "knative.dev/eventing/pkg/legacyclient/clientset/versioned/fake" - legacysourcelisters "knative.dev/eventing/pkg/legacyclient/listers/legacysources/v1alpha1" "knative.dev/pkg/reconciler/testing" ) @@ -56,7 +53,6 @@ var subscriberAddToScheme = func(scheme *runtime.Scheme) error { var clientSetSchemes = []func(*runtime.Scheme) error{ fakekubeclientset.AddToScheme, fakeeventingclientset.AddToScheme, - fakelegacyclientset.AddToScheme, fakeapiextensionsclientset.AddToScheme, subscriberAddToScheme, } @@ -102,10 +98,6 @@ func (l *Listers) GetEventingObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakeeventingclientset.AddToScheme) } -func (l *Listers) GetLegacyObjects() []runtime.Object { - return l.sorter.ObjectsForSchemeFunc(fakelegacyclientset.AddToScheme) -} - func (l *Listers) GetSubscriberObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(subscriberAddToScheme) } @@ -113,7 +105,6 @@ func (l *Listers) GetSubscriberObjects() []runtime.Object { func (l *Listers) GetAllObjects() []runtime.Object { all := l.GetSubscriberObjects() all = append(all, l.GetEventingObjects()...) - all = append(all, l.GetLegacyObjects()...) all = append(all, l.GetKubeObjects()...) return all } @@ -158,18 +149,6 @@ func (l *Listers) GetPingSourceLister() sourcelisters.PingSourceLister { return sourcelisters.NewPingSourceLister(l.indexerFor(&sourcesv1alpha1.PingSource{})) } -func (l *Listers) GetLegacyCronJobSourceLister() legacysourcelisters.CronJobSourceLister { - return legacysourcelisters.NewCronJobSourceLister(l.indexerFor(&legacysourcesv1alpha1.CronJobSource{})) -} - -func (l *Listers) GetLegacyApiServerSourceLister() legacysourcelisters.ApiServerSourceLister { - return legacysourcelisters.NewApiServerSourceLister(l.indexerFor(&legacysourcesv1alpha1.ApiServerSource{})) -} - -func (l *Listers) GetLegacyContainerSourceLister() legacysourcelisters.ContainerSourceLister { - return legacysourcelisters.NewContainerSourceLister(l.indexerFor(&legacysourcesv1alpha1.ContainerSource{})) -} - func (l *Listers) GetDeploymentLister() appsv1listers.DeploymentLister { return appsv1listers.NewDeploymentLister(l.indexerFor(&appsv1.Deployment{})) } diff --git a/pkg/reconciler/testing/pingsource.go b/pkg/reconciler/testing/pingsource.go index 646f474b3c1..3e129a90f0c 100644 --- a/pkg/reconciler/testing/pingsource.go +++ b/pkg/reconciler/testing/pingsource.go @@ -76,10 +76,18 @@ func WithInitPingSourceConditions(s *v1alpha1.PingSource) { s.Status.InitializeConditions() } +func WithInitPingSourceV1A2Conditions(s *v1alpha2.PingSource) { + s.Status.InitializeConditions() +} + func WithValidPingSourceSchedule(s *v1alpha1.PingSource) { s.Status.MarkSchedule() } +func WithValidPingSourceV1A2Schedule(s *v1alpha2.PingSource) { + s.Status.MarkSchedule() +} + func WithInvalidPingSourceSchedule(s *v1alpha1.PingSource) { s.Status.MarkInvalidSchedule("Invalid", "") } @@ -88,24 +96,46 @@ func WithPingSourceSinkNotFound(s *v1alpha1.PingSource) { s.Status.MarkNoSink("NotFound", "") } +func WithPingSourceV1A2SinkNotFound(s *v1alpha2.PingSource) { + s.Status.MarkNoSink("NotFound", "") +} + func WithPingSourceSink(uri *apis.URL) PingSourceOption { return func(s *v1alpha1.PingSource) { s.Status.MarkSink(uri) } } +func WithPingSourceV1A2Sink(uri *apis.URL) PingSourceV1A2Option { + return func(s *v1alpha2.PingSource) { + s.Status.MarkSink(uri) + } +} + func WithPingSourceDeployed(s *v1alpha1.PingSource) { s.Status.PropagateDeploymentAvailability(NewDeployment("any", "any", WithDeploymentAvailable())) } +func WithPingSourceV1A2Deployed(s *v1alpha2.PingSource) { + s.Status.PropagateDeploymentAvailability(NewDeployment("any", "any", WithDeploymentAvailable())) +} + func WithPingSourceEventType(s *v1alpha1.PingSource) { s.Status.MarkEventType() } +func WithPingSourceV1A2EventType(s *v1alpha2.PingSource) { + s.Status.MarkEventType() +} + func WithValidPingSourceResources(s *v1alpha1.PingSource) { s.Status.MarkResourcesCorrect() } +func WithValidPingSourceV1A2Resources(s *v1alpha2.PingSource) { + s.Status.MarkResourcesCorrect() +} + func WithPingSourceDeleted(c *v1alpha1.PingSource) { t := metav1.NewTime(time.Unix(1e9, 0)) c.ObjectMeta.SetDeletionTimestamp(&t) diff --git a/pkg/reconciler/testing/sinkbinding.go b/pkg/reconciler/testing/sinkbinding.go index 818ae114e1b..6743de2e181 100644 --- a/pkg/reconciler/testing/sinkbinding.go +++ b/pkg/reconciler/testing/sinkbinding.go @@ -18,10 +18,9 @@ package testing import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - sourcesv1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" + sourcesv1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/tracker" ) @@ -32,24 +31,6 @@ type SinkBindingV1Alpha1Option func(*sourcesv1alpha1.SinkBinding) // SinkBindingV1Alpha2Option enables further configuration of a SinkBinding. type SinkBindingV1Alpha2Option func(*sourcesv1alpha2.SinkBinding) -// LegacySinkBindingOption enables further configuration of a SinkBinding. -type LegacySinkBindingOption func(*legacysourcesv1alpha1.SinkBinding) - -// NewLegacySinkBinding creates a SinkBinding with SinkBindingOptions -func NewLegacySinkBinding(name, namespace string, o ...LegacySinkBindingOption) *legacysourcesv1alpha1.SinkBinding { - c := &legacysourcesv1alpha1.SinkBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - } - for _, opt := range o { - opt(c) - } - //c.SetDefaults(context.Background()) // TODO: We should add defaults and validation. - return c -} - // NewSinkBindingV1Alpha1 creates a SinkBinding with SinkBindingOptions func NewSinkBindingV1Alpha1(name, namespace string, o ...SinkBindingV1Alpha1Option) *sourcesv1alpha1.SinkBinding { c := &sourcesv1alpha1.SinkBinding{ @@ -80,20 +61,6 @@ func NewSinkBindingV1Alpha2(name, namespace string, o ...SinkBindingV1Alpha2Opti return c } -// WithLegacySubject assigns the subject of the SinkBinding. -func WithLegacySubject(subject tracker.Reference) LegacySinkBindingOption { - return func(sb *legacysourcesv1alpha1.SinkBinding) { - sb.Spec.Subject = subject - } -} - -// WithLegacySink assigns the sink of the SinkBinding. -func WithLegacySink(sink duckv1.Destination) LegacySinkBindingOption { - return func(sb *legacysourcesv1alpha1.SinkBinding) { - sb.Spec.Sink = sink - } -} - // WithSubjectV1A1 assigns the subject of the SinkBinding. func WithSubjectV1A1(subject tracker.Reference) SinkBindingV1Alpha1Option { return func(sb *sourcesv1alpha1.SinkBinding) { diff --git a/pkg/reconciler/testing/trigger.go b/pkg/reconciler/testing/trigger.go index 33bfa3dbfe4..863e85be5d9 100644 --- a/pkg/reconciler/testing/trigger.go +++ b/pkg/reconciler/testing/trigger.go @@ -28,14 +28,6 @@ import ( duckv1 "knative.dev/pkg/apis/duck/v1" ) -const ( - unmarshalFailedDependencyAnnotation = "{" + - "\"kind\":{CronJobSource}, " + - "\"name\":\"test-cronjob-source\"," + - "\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"" + - "}" -) - // TriggerOption enables further configuration of a Trigger. type TriggerOption func(*v1alpha1.Trigger) @@ -161,15 +153,6 @@ func WithTriggerStatusSubscriberURI(uri string) TriggerOption { } } -func WithUnmarshalFailedDependencyAnnotation() TriggerOption { - return func(t *v1alpha1.Trigger) { - if t.Annotations == nil { - t.Annotations = make(map[string]string) - } - t.Annotations[v1alpha1.DependencyAnnotation] = unmarshalFailedDependencyAnnotation - } -} - func WithInjectionAnnotation(injectionAnnotation string) TriggerOption { return func(t *v1alpha1.Trigger) { if t.Annotations == nil { diff --git a/pkg/reconciler/trigger/trigger_test.go b/pkg/reconciler/trigger/trigger_test.go index d05f3055cfc..8d959fc98cd 100644 --- a/pkg/reconciler/trigger/trigger_test.go +++ b/pkg/reconciler/trigger/trigger_test.go @@ -33,49 +33,14 @@ import ( "knative.dev/eventing/pkg/apis/eventing/v1alpha1" "knative.dev/eventing/pkg/reconciler" + . "knative.dev/eventing/pkg/reconciler/testing" reconciletesting "knative.dev/eventing/pkg/reconciler/testing" - "knative.dev/eventing/pkg/utils" duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - - . "knative.dev/eventing/pkg/reconciler/testing" . "knative.dev/pkg/reconciler/testing" ) var ( - sinkRef = corev1.ObjectReference{ - Name: sinkName, - Kind: "Channel", - APIVersion: "messaging.knative.dev/v1alpha1", - } - - brokerRef = corev1.ObjectReference{ - Name: sinkName, - Kind: "Broker", - APIVersion: "eventing.knative.dev/v1alpha1", - } - brokerDest = duckv1beta1.Destination{ - Ref: &corev1.ObjectReference{ - Name: sinkName, - Kind: "Broker", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - } - sinkDNS = "sink.mynamespace.svc." + utils.GetClusterDomainName() - sinkURI = "http://" + sinkDNS - - subscriberGVK = metav1.GroupVersionKind{ - Group: subscriberGroup, - Version: subscriberVersion, - Kind: subscriberKind, - } subscriberAPIVersion = fmt.Sprintf("%s/%s", subscriberGroup, subscriberVersion) - - k8sServiceGVK = metav1.GroupVersionKind{ - Group: "", - Version: "v1", - Kind: "Service", - } ) const ( @@ -84,34 +49,13 @@ const ( triggerUID = "test-trigger-uid" brokerName = "test-broker" - subscriberGroup = "serving.knative.dev" - subscriberVersion = "v1" - subscriberKind = "Service" - subscriberName = "subscriber-name" - subscriberURI = "http://example.com/subscriber/" - subscriberURIReference = "foo" - subscriberResolvedTargetURI = "http://example.com/subscriber/foo" - - k8sServiceResolvedURI = "http://subscriber-name.test-namespace.svc.cluster.local/" - - dependencyAnnotation = "{\"kind\":\"CronJobSource\",\"name\":\"test-cronjob-source\",\"apiVersion\":\"sources.eventing.knative.dev/v1alpha1\"}" - cronJobSourceName = "test-cronjob-source" - cronJobSourceAPIVersion = "sources.eventing.knative.dev/v1alpha1" - testSchedule = "*/2 * * * *" - testData = "data" - sinkName = "testsink" + subscriberGroup = "serving.knative.dev" + subscriberVersion = "v1" + subscriberKind = "Service" + subscriberName = "subscriber-name" + subscriberURI = "http://example.com/subscriber/" injectionAnnotation = "enabled" - - currentGeneration = 1 - outdatedGeneration = 0 - triggerGeneration = 7 -) - -var ( - trueVal = true - - subscriptionName = fmt.Sprintf("%s-%s-%s", brokerName, triggerName, triggerUID) ) func init() { diff --git a/test/e2e/legacy_sinkbinding_test.go b/test/e2e/legacy_sinkbinding_test.go deleted file mode 100644 index 8a1b6061f54..00000000000 --- a/test/e2e/legacy_sinkbinding_test.go +++ /dev/null @@ -1,202 +0,0 @@ -// +build e2e - -/* -Copyright 2020 The Knative 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 e2e - -import ( - "fmt" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/uuid" - - appsv1 "k8s.io/api/apps/v1" - batchv1 "k8s.io/api/batch/v1" - batchv1beta1 "k8s.io/api/batch/v1beta1" - duckv1 "knative.dev/pkg/apis/duck/v1" - pkgTest "knative.dev/pkg/test" - "knative.dev/pkg/tracker" - - eventingtesting "knative.dev/eventing/pkg/reconciler/testing" - "knative.dev/eventing/test/lib" - "knative.dev/eventing/test/lib/resources" -) - -func TestLegacySinkBindingDeployment(t *testing.T) { - const ( - sinkBindingName = "e2e-sink-binding" - deploymentName = "e2e-sink-binding-deployment" - // the heartbeats image is built from test_images/heartbeats - imageName = "heartbeats" - - loggerPodName = "e2e-sink-binding-logger-pod" - ) - - client := setup(t, true) - defer tearDown(client) - - // create event logger pod and service - loggerPod := resources.EventLoggerPod(loggerPodName) - client.CreatePodOrFail(loggerPod, lib.WithService(loggerPodName)) - - // create sink binding - sinkBinding := eventingtesting.NewLegacySinkBinding( - sinkBindingName, - client.Namespace, - eventingtesting.WithLegacySink(duckv1.Destination{Ref: resources.KnativeRefForService(loggerPodName, client.Namespace)}), - eventingtesting.WithLegacySubject(tracker.Reference{ - APIVersion: "apps/v1", - Kind: "Deployment", - Namespace: client.Namespace, - Name: deploymentName, - }), - ) - client.CreateLegacySinkBindingOrFail(sinkBinding) - - data := fmt.Sprintf("TestSinkBindingDeployment%s", uuid.NewUUID()) - client.CreateDeploymentOrFail(&appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: client.Namespace, - Name: deploymentName, - }, - Spec: appsv1.DeploymentSpec{ - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "foo": "bar", - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: imageName, - Image: pkgTest.ImagePath(imageName), - ImagePullPolicy: corev1.PullAlways, - Args: []string{"--msg=" + data}, - Env: []corev1.EnvVar{{ - Name: "POD_NAME", - Value: deploymentName, - }, { - Name: "POD_NAMESPACE", - Value: client.Namespace, - }}, - }}, - }, - }, - }, - }) - - // wait for all test resources to be ready - client.WaitForAllTestResourcesReadyOrFail() - - // verify the logger service receives the event - expectedCount := 2 - if err := client.CheckLog(loggerPodName, lib.CheckerContainsAtLeast(data, expectedCount)); err != nil { - t.Fatalf("String %q does not appear at least %d times in logs of logger pod %q: %v", data, expectedCount, loggerPodName, err) - } -} - -func TestLegacySinkBindingCronJob(t *testing.T) { - const ( - sinkBindingName = "e2e-sink-binding" - deploymentName = "e2e-sink-binding-cronjob" - // the heartbeats image is built from test_images/heartbeats - imageName = "heartbeats" - - loggerPodName = "e2e-sink-binding-logger-pod" - ) - - client := setup(t, true) - defer tearDown(client) - - // create event logger pod and service - loggerPod := resources.EventLoggerPod(loggerPodName) - client.CreatePodOrFail(loggerPod, lib.WithService(loggerPodName)) - - // create sink binding - sinkBinding := eventingtesting.NewLegacySinkBinding( - sinkBindingName, - client.Namespace, - eventingtesting.WithLegacySink(duckv1.Destination{Ref: resources.KnativeRefForService(loggerPodName, client.Namespace)}), - eventingtesting.WithLegacySubject(tracker.Reference{ - APIVersion: "batch/v1", - Kind: "Job", - Namespace: client.Namespace, - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "foo": "bar", - }, - }, - }), - ) - client.CreateLegacySinkBindingOrFail(sinkBinding) - - data := fmt.Sprintf("TestSinkBindingCronJob%s", uuid.NewUUID()) - client.CreateCronJobOrFail(&batchv1beta1.CronJob{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: client.Namespace, - Name: deploymentName, - }, - Spec: batchv1beta1.CronJobSpec{ - Schedule: "* * * * *", - JobTemplate: batchv1beta1.JobTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: batchv1.JobSpec{ - Template: corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - RestartPolicy: corev1.RestartPolicyNever, - Containers: []corev1.Container{{ - Name: imageName, - Image: pkgTest.ImagePath(imageName), - ImagePullPolicy: corev1.PullAlways, - Args: []string{"--msg=" + data}, - Env: []corev1.EnvVar{{ - Name: "ONE_SHOT", - Value: "true", - }, { - Name: "POD_NAME", - Value: deploymentName, - }, { - Name: "POD_NAMESPACE", - Value: client.Namespace, - }}, - }}, - }, - }, - }, - }, - }, - }) - - // wait for all test resources to be ready - client.WaitForAllTestResourcesReadyOrFail() - - // verify the logger service receives the event - expectedCount := 2 - if err := client.CheckLog(loggerPodName, lib.CheckerContainsAtLeast(data, expectedCount)); err != nil { - t.Fatalf("String %q does not appear at least %d times in logs of logger pod %q: %v", data, expectedCount, loggerPodName, err) - } -} diff --git a/test/e2e/legacy_source_api_server_test.go b/test/e2e/legacy_source_api_server_test.go deleted file mode 100644 index 0dac614ea12..00000000000 --- a/test/e2e/legacy_source_api_server_test.go +++ /dev/null @@ -1,184 +0,0 @@ -// +build e2e - -/* -Copyright 2020 The Knative 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 e2e - -import ( - "fmt" - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - "knative.dev/eventing/test/lib" - "knative.dev/eventing/test/lib/resources" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - - eventingtesting "knative.dev/eventing/pkg/reconciler/testing" -) - -func TestLegacyApiServerSource(t *testing.T) { - const ( - baseApiServerSourceName = "e2e-api-server-source" - - roleName = "event-watcher-r" - serviceAccountName = "event-watcher-sa" - baseHelloworldPodName = "e2e-api-server-source-helloworld-pod" - baseLoggerPodName = "e2e-api-server-source-logger-pod" - ) - - mode := "Ref" - table := []struct { - name string - spec sourcesv1alpha1.ApiServerSourceSpec - pod func(name string) *corev1.Pod - expected string - }{ - { - name: "event-ref", - spec: sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "v1", - Kind: "Event", - }, - }, - Mode: mode, - ServiceAccountName: serviceAccountName, - }, - pod: func(name string) *corev1.Pod { return resources.HelloWorldPod(name) }, - expected: "Event", - }, - { - name: "event-ref-unmatch-label", - spec: sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "v1", - Kind: "Pod", - LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{"e2e": "testing"}}, - }, - }, - Mode: mode, - ServiceAccountName: serviceAccountName, - }, - pod: func(name string) *corev1.Pod { return resources.HelloWorldPod(name) }, - expected: "", - }, - { - name: "event-ref-match-label", - spec: sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "v1", - Kind: "Pod", - LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{"e2e": "testing"}}, - }, - }, - Mode: mode, - ServiceAccountName: serviceAccountName, - }, - pod: func(name string) *corev1.Pod { - return resources.HelloWorldPod(name, resources.WithLabelsForPod(map[string]string{"e2e": "testing"})) - }, - expected: "Pod", - }, - { - name: "event-ref-match-label-expr", - spec: sourcesv1alpha1.ApiServerSourceSpec{ - Resources: []sourcesv1alpha1.ApiServerResource{ - { - APIVersion: "v1", - Kind: "Pod", - LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{"e2e": "testing"}, - MatchExpressions: []metav1.LabelSelectorRequirement{ - {Key: "e2e", Operator: "Exists"}, - }, - }, - }, - }, - Mode: mode, - ServiceAccountName: serviceAccountName, - }, - pod: func(name string) *corev1.Pod { - return resources.HelloWorldPod(name, resources.WithLabelsForPod(map[string]string{"e2e": "testing"})) - }, - expected: "Pod", - }, - } - - client := setup(t, true) - defer tearDown(client) - - // creates ServiceAccount and RoleBinding with a role for reading pods and events - r := resources.Role(roleName, - resources.WithRuleForRole(&rbacv1.PolicyRule{ - APIGroups: []string{""}, - Resources: []string{"events", "pods"}, - Verbs: []string{"get", "list", "watch"}})) - client.CreateServiceAccountOrFail(serviceAccountName) - client.CreateRoleOrFail(r) - client.CreateRoleBindingOrFail( - serviceAccountName, - lib.RoleKind, - roleName, - fmt.Sprintf("%s-%s", serviceAccountName, roleName), - client.Namespace, - ) - - for _, tc := range table { - - // create event logger pod and service - loggerPodName := fmt.Sprintf("%s-%s", baseLoggerPodName, tc.name) - tc.spec.Sink = &duckv1beta1.Destination{Ref: resources.ServiceRef(loggerPodName)} - - loggerPod := resources.EventLoggerPod(loggerPodName) - client.CreatePodOrFail(loggerPod, lib.WithService(loggerPodName)) - - apiServerSource := eventingtesting.NewLegacyApiServerSource( - fmt.Sprintf("%s-%s", baseApiServerSourceName, tc.name), - client.Namespace, - eventingtesting.WithLegacyApiServerSourceSpec(tc.spec), - ) - - client.CreateLegacyApiServerSourceOrFail(apiServerSource) - - // wait for all test resources to be ready - client.WaitForAllTestResourcesReadyOrFail() - - helloworldPod := tc.pod(fmt.Sprintf("%s-%s", baseHelloworldPodName, tc.name)) - client.CreatePodOrFail(helloworldPod) - - // verify the logger service receives the event(s) - // TODO(Fredy-Z): right now it's only doing a very basic check by looking for the tc.data word, - // we can add a json matcher to improve it in the future. - - if tc.expected == "" { - if err := client.CheckLogEmpty(loggerPodName, 10*time.Second); err != nil { - t.Fatalf("Log is not empty in logger pod %q: %v", loggerPodName, err) - } - - } else { - if err := client.CheckLog(loggerPodName, lib.CheckerContains(tc.expected)); err != nil { - t.Fatalf("String %q does not appear in logs of logger pod %q: %v", tc.expected, loggerPodName, err) - } - } - } -} diff --git a/test/e2e/source_container_test.go b/test/e2e/source_container_test.go deleted file mode 100644 index 509fbc96fdd..00000000000 --- a/test/e2e/source_container_test.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build e2e - -/* -Copyright 2019 The Knative 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 e2e - -import ( - "fmt" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/uuid" - - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - pkgTest "knative.dev/pkg/test" - - "knative.dev/eventing/test/lib" - "knative.dev/eventing/test/lib/resources" - - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - eventingtesting "knative.dev/eventing/pkg/reconciler/testing" -) - -func TestContainerSource(t *testing.T) { - const ( - containerSourceName = "e2e-container-source" - templateName = "e2e-container-source-template" - // the heartbeats image is built from test_images/heartbeats - imageName = "heartbeats" - - loggerPodName = "e2e-container-source-logger-pod" - ) - - client := setup(t, true) - defer tearDown(client) - - // create event logger pod and service - loggerPod := resources.EventLoggerPod(loggerPodName) - client.CreatePodOrFail(loggerPod, lib.WithService(loggerPodName)) - - // create container source - data := fmt.Sprintf("TestContainerSource%s", uuid.NewUUID()) - // args are the arguments passing to the container, msg is used in the heartbeats image - args := []string{"--msg=" + data} - // envVars are the environment variables of the container - envVars := []corev1.EnvVar{{ - Name: "POD_NAME", - Value: templateName, - }, { - Name: "POD_NAMESPACE", - Value: client.Namespace, - }} - containerSource := eventingtesting.NewContainerSource( - containerSourceName, - client.Namespace, - eventingtesting.WithContainerSourceSpec(sourcesv1alpha1.ContainerSourceSpec{ - Template: &corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Name: templateName, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: imageName, - Image: pkgTest.ImagePath(imageName), - ImagePullPolicy: corev1.PullAlways, - Args: args, - Env: envVars, - }}, - }, - }, - Sink: &duckv1beta1.Destination{Ref: resources.ServiceRef(loggerPodName)}, - }), - ) - client.CreateLegacyContainerSourceOrFail(containerSource) - - // wait for all test resources to be ready - client.WaitForAllTestResourcesReadyOrFail() - - // verify the logger service receives the event - expectedCount := 2 - if err := client.CheckLog(loggerPodName, lib.CheckerContainsAtLeast(data, expectedCount)); err != nil { - t.Fatalf("String %q does not appear at least %d times in logs of logger pod %q: %v", data, expectedCount, loggerPodName, err) - } -} diff --git a/test/e2e/source_cron_job_test.go b/test/e2e/source_cron_job_test.go deleted file mode 100644 index 056f4a3be8a..00000000000 --- a/test/e2e/source_cron_job_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build e2e - -/* -Copyright 2019 The Knative 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 e2e - -import ( - "fmt" - "testing" - - "k8s.io/apimachinery/pkg/util/uuid" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - - "knative.dev/eventing/test/lib" - "knative.dev/eventing/test/lib/resources" - - sourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" - eventingtesting "knative.dev/eventing/pkg/reconciler/testing" -) - -func TestCronJobSource(t *testing.T) { - const ( - cronJobSourceName = "e2e-cron-job-source" - // Every 1 minute starting from now - schedule = "*/1 * * * *" - - loggerPodName = "e2e-cron-job-source-logger-pod" - ) - - client := setup(t, true) - defer tearDown(client) - - // create event logger pod and service - loggerPod := resources.EventLoggerPod(loggerPodName) - client.CreatePodOrFail(loggerPod, lib.WithService(loggerPodName)) - - // create cron job source - data := fmt.Sprintf("TestCronJobSource %s", uuid.NewUUID()) - cronJobSource := eventingtesting.NewCronJobSource( - cronJobSourceName, - client.Namespace, - eventingtesting.WithCronJobSourceSpec(sourcesv1alpha1.CronJobSourceSpec{ - Schedule: schedule, - Data: data, - Sink: &duckv1beta1.Destination{Ref: resources.ServiceRef(loggerPodName)}, - }), - ) - client.CreateLegacyCronJobSourceOrFail(cronJobSource) - - // wait for all test resources to be ready - client.WaitForAllTestResourcesReadyOrFail() - - // verify the logger service receives the event - if err := client.CheckLog(loggerPodName, lib.CheckerContains(data)); err != nil { - t.Fatalf("String %q not found in logs of logger pod %q: %v", data, loggerPodName, err) - } -} diff --git a/test/lib/client.go b/test/lib/client.go index 38c05ae1fe1..5572f6ab646 100644 --- a/test/lib/client.go +++ b/test/lib/client.go @@ -27,14 +27,12 @@ import ( "knative.dev/pkg/test" eventing "knative.dev/eventing/pkg/client/clientset/versioned" - legacy "knative.dev/eventing/pkg/legacyclient/clientset/versioned" ) // Client holds instances of interfaces for making requests to Knative. type Client struct { Kube *test.KubeClient Eventing *eventing.Clientset - Legacy *legacy.Clientset Dynamic dynamic.Interface Config *rest.Config @@ -65,11 +63,6 @@ func NewClient(configPath string, clusterName string, namespace string, t *testi return nil, err } - client.Legacy, err = legacy.NewForConfig(client.Config) - if err != nil { - return nil, err - } - client.Dynamic, err = dynamic.NewForConfig(client.Config) if err != nil { return nil, err diff --git a/test/lib/creation.go b/test/lib/creation.go index 59f946900ee..57612ad6895 100644 --- a/test/lib/creation.go +++ b/test/lib/creation.go @@ -32,7 +32,6 @@ import ( "knative.dev/eventing/pkg/apis/eventing/v1alpha1" "knative.dev/eventing/pkg/apis/eventing/v1beta1" flowsv1alpha1 "knative.dev/eventing/pkg/apis/flows/v1alpha1" - legacysourcesv1alpha1 "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" messagingv1alpha1 "knative.dev/eventing/pkg/apis/messaging/v1alpha1" sourcesv1alpha1 "knative.dev/eventing/pkg/apis/sources/v1alpha1" "knative.dev/eventing/pkg/utils" @@ -269,28 +268,6 @@ func (client *Client) CreateFlowsParallelOrFail(parallel *flowsv1alpha1.Parallel client.Tracker.AddObj(parallel) } -// CreateLegacyCronJobSourceOrFail will create a CronJobSource or fail the test if there is an error. -func (client *Client) CreateLegacyCronJobSourceOrFail(cronJobSource *legacysourcesv1alpha1.CronJobSource) { - client.T.Logf("Creating legacy cronjobsource %+v", cronJobSource) - cronJobSourceInterface := client.Legacy.SourcesV1alpha1().CronJobSources(client.Namespace) - _, err := cronJobSourceInterface.Create(cronJobSource) - if err != nil { - client.T.Fatalf("Failed to create cronjobsource %q: %v", cronJobSource.Name, err) - } - client.Tracker.AddObj(cronJobSource) -} - -// CreateLegacyContainerSourceOrFail will create a ContainerSource or fail the test if there is an error. -func (client *Client) CreateLegacyContainerSourceOrFail(containerSource *legacysourcesv1alpha1.ContainerSource) { - client.T.Logf("Creating legacy containersource %+v", containerSource) - containerSourceInterface := client.Legacy.SourcesV1alpha1().ContainerSources(client.Namespace) - _, err := containerSourceInterface.Create(containerSource) - if err != nil { - client.T.Fatalf("Failed to create containersource %q: %v", containerSource.Name, err) - } - client.Tracker.AddObj(containerSource) -} - // CreateSinkBindingV1Alpha1OrFail will create a SinkBinding or fail the test if there is an error. func (client *Client) CreateSinkBindingV1Alpha1OrFail(sb *sourcesv1alpha1.SinkBinding) { client.T.Logf("Creating sinkbinding %+v", sb) @@ -313,17 +290,6 @@ func (client *Client) CreateSinkBindingV1Alpha2OrFail(sb *sourcesv1alpha2.SinkBi client.Tracker.AddObj(sb) } -// CreateLegacySinkBindingOrFail will create a SinkBinding or fail the test if there is an error. -func (client *Client) CreateLegacySinkBindingOrFail(sb *legacysourcesv1alpha1.SinkBinding) { - client.T.Logf("Creating sinkbinding %+v", sb) - sbInterface := client.Legacy.SourcesV1alpha1().SinkBindings(client.Namespace) - _, err := sbInterface.Create(sb) - if err != nil { - client.T.Fatalf("Failed to create sinkbinding %q: %v", sb.Name, err) - } - client.Tracker.AddObj(sb) -} - // CreateApiServerSourceOrFail will create an ApiServerSource func (client *Client) CreateApiServerSourceOrFail(apiServerSource *sourcesv1alpha1.ApiServerSource) { client.T.Logf("Creating apiserversource %+v", apiServerSource) @@ -357,17 +323,6 @@ func (client *Client) CreatePingSourceV1Alpha2OrFail(pingSource *sourcesv1alpha2 client.Tracker.AddObj(pingSource) } -// CreateLegacyApiServerSourceOrFail will create an ApiServerSource -func (client *Client) CreateLegacyApiServerSourceOrFail(apiServerSource *legacysourcesv1alpha1.ApiServerSource) { - client.T.Logf("Creating apiserversource %+v", apiServerSource) - apiServerInterface := client.Legacy.SourcesV1alpha1().ApiServerSources(client.Namespace) - _, err := apiServerInterface.Create(apiServerSource) - if err != nil { - client.T.Fatalf("Failed to create apiserversource %q: %v", apiServerSource.Name, err) - } - client.Tracker.AddObj(apiServerSource) -} - func (client *Client) CreateServiceOrFail(svc *corev1.Service) *corev1.Service { client.T.Logf("Creating service %+v", svc) namespace := client.Namespace diff --git a/test/lib/resources/constants.go b/test/lib/resources/constants.go index d2303f64817..5e72af2d592 100644 --- a/test/lib/resources/constants.go +++ b/test/lib/resources/constants.go @@ -21,12 +21,11 @@ const SystemNamespace = "knative-eventing" // API versions for the resources. const ( - CoreAPIVersion = "v1" - EventingAPIVersion = "eventing.knative.dev/v1alpha1" - LegacySourcesAPIVersion = "sources.eventing.knative.dev/v1alpha1" - MessagingAPIVersion = "messaging.knative.dev/v1alpha1" - FlowsAPIVersion = "flows.knative.dev/v1alpha1" - ServingAPIVersion = "serving.knative.dev/v1" + CoreAPIVersion = "v1" + EventingAPIVersion = "eventing.knative.dev/v1alpha1" + MessagingAPIVersion = "messaging.knative.dev/v1alpha1" + FlowsAPIVersion = "flows.knative.dev/v1alpha1" + ServingAPIVersion = "serving.knative.dev/v1" ) // Kind for Knative resources. diff --git a/test/lib/typemeta.go b/test/lib/typemeta.go index f26d428afc7..f71dadf640f 100644 --- a/test/lib/typemeta.go +++ b/test/lib/typemeta.go @@ -39,23 +39,6 @@ func EventingTypeMeta(kind string) *metav1.TypeMeta { } } -// CronJobSourceTypeMeta is the TypeMeta ref for CronJobSource. -var CronJobSourceTypeMeta = LegacySourcesTypeMeta(resources.CronJobSourceKind) - -// ContainerSourceTypeMeta is the TypeMeta ref for ContainerSource. -var ContainerSourceTypeMeta = LegacySourcesTypeMeta(resources.ContainerSourceKind) - -// LegacyApiServerSourceTypeMeta is the TypeMeta ref for ApiServerSource. -var LegacyApiServerSourceTypeMeta = LegacySourcesTypeMeta(resources.ApiServerSourceKind) - -// LegacySourcesTypeMeta returns the TypeMeta ref for an eventing sources resource. -func LegacySourcesTypeMeta(kind string) *metav1.TypeMeta { - return &metav1.TypeMeta{ - Kind: kind, - APIVersion: resources.LegacySourcesAPIVersion, - } -} - // ChannelTypeMeta is the TypeMeta ref for Channel. var ChannelTypeMeta = MessagingTypeMeta(resources.ChannelKind)