From f3de6dc973bf39ab54955cdbb45c5b3b1bb3073b Mon Sep 17 00:00:00 2001 From: Lionel Villard Date: Mon, 26 Apr 2021 13:41:03 -0400 Subject: [PATCH] Add PingSource v1 API --- cmd/webhook/main.go | 4 +- config/core/resources/pingsource.yaml | 8 +- pkg/apis/sources/v1/implements_test.go | 3 + pkg/apis/sources/v1/ping_conversion.go | 36 ++ pkg/apis/sources/v1/ping_conversion_test.go | 34 ++ pkg/apis/sources/v1/ping_defaults.go | 35 ++ pkg/apis/sources/v1/ping_defaults_test.go | 67 +++ pkg/apis/sources/v1/ping_lifecycle.go | 122 +++++ pkg/apis/sources/v1/ping_lifecycle_test.go | 260 ++++++++++ pkg/apis/sources/v1/ping_types.go | 110 +++++ pkg/apis/sources/v1/ping_types_test.go | 28 ++ pkg/apis/sources/v1/ping_validation.go | 100 ++++ pkg/apis/sources/v1/ping_validation_test.go | 390 +++++++++++++++ pkg/apis/sources/v1/register.go | 2 + pkg/apis/sources/v1/register_test.go | 2 + pkg/apis/sources/v1/roundtrip_test.go | 9 + pkg/apis/sources/v1/zz_generated.deepcopy.go | 95 ++++ pkg/apis/sources/v1beta2/ping_conversion.go | 48 +- .../sources/v1beta2/ping_conversion_test.go | 2 +- .../typed/sources/v1/fake/fake_pingsource.go | 142 ++++++ .../sources/v1/fake/fake_sources_client.go | 4 + .../typed/sources/v1/generated_expansion.go | 2 + .../versioned/typed/sources/v1/pingsource.go | 195 ++++++++ .../typed/sources/v1/sources_client.go | 5 + .../informers/externalversions/generic.go | 2 + .../externalversions/sources/v1/interface.go | 7 + .../externalversions/sources/v1/pingsource.go | 90 ++++ .../sources/v1/pingsource/fake/fake.go | 40 ++ .../v1/pingsource/filtered/fake/fake.go | 52 ++ .../v1/pingsource/filtered/pingsource.go | 65 +++ .../sources/v1/pingsource/pingsource.go | 52 ++ .../sources/v1/pingsource/controller.go | 153 ++++++ .../sources/v1/pingsource/reconciler.go | 455 ++++++++++++++++++ .../reconciler/sources/v1/pingsource/state.go | 106 ++++ .../listers/sources/v1/expansion_generated.go | 8 + pkg/client/listers/sources/v1/pingsource.go | 99 ++++ pkg/reconciler/testing/v1/pingsource.go | 109 +++++ test/e2e/source_ping_v1_test.go | 135 ++++++ test/lib/creation.go | 17 + 39 files changed, 3085 insertions(+), 8 deletions(-) create mode 100644 pkg/apis/sources/v1/ping_conversion.go create mode 100644 pkg/apis/sources/v1/ping_conversion_test.go create mode 100644 pkg/apis/sources/v1/ping_defaults.go create mode 100644 pkg/apis/sources/v1/ping_defaults_test.go create mode 100644 pkg/apis/sources/v1/ping_lifecycle.go create mode 100644 pkg/apis/sources/v1/ping_lifecycle_test.go create mode 100644 pkg/apis/sources/v1/ping_types.go create mode 100644 pkg/apis/sources/v1/ping_types_test.go create mode 100644 pkg/apis/sources/v1/ping_validation.go create mode 100644 pkg/apis/sources/v1/ping_validation_test.go create mode 100644 pkg/client/clientset/versioned/typed/sources/v1/fake/fake_pingsource.go create mode 100644 pkg/client/clientset/versioned/typed/sources/v1/pingsource.go create mode 100644 pkg/client/informers/externalversions/sources/v1/pingsource.go create mode 100644 pkg/client/injection/informers/sources/v1/pingsource/fake/fake.go create mode 100644 pkg/client/injection/informers/sources/v1/pingsource/filtered/fake/fake.go create mode 100644 pkg/client/injection/informers/sources/v1/pingsource/filtered/pingsource.go create mode 100644 pkg/client/injection/informers/sources/v1/pingsource/pingsource.go create mode 100644 pkg/client/injection/reconciler/sources/v1/pingsource/controller.go create mode 100644 pkg/client/injection/reconciler/sources/v1/pingsource/reconciler.go create mode 100644 pkg/client/injection/reconciler/sources/v1/pingsource/state.go create mode 100644 pkg/client/listers/sources/v1/pingsource.go create mode 100644 pkg/reconciler/testing/v1/pingsource.go create mode 100644 test/e2e/source_ping_v1_test.go diff --git a/cmd/webhook/main.go b/cmd/webhook/main.go index 3b9bff03935..d177616ab20 100644 --- a/cmd/webhook/main.go +++ b/cmd/webhook/main.go @@ -72,6 +72,7 @@ var ourTypes = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ sourcesv1beta2.SchemeGroupVersion.WithKind("PingSource"): &sourcesv1beta2.PingSource{}, // v1 sourcesv1.SchemeGroupVersion.WithKind("ApiServerSource"): &sourcesv1.ApiServerSource{}, + sourcesv1.SchemeGroupVersion.WithKind("PingSource"): &sourcesv1.PingSource{}, sourcesv1.SchemeGroupVersion.WithKind("SinkBinding"): &sourcesv1.SinkBinding{}, sourcesv1.SchemeGroupVersion.WithKind("ContainerSource"): &sourcesv1.ContainerSource{}, @@ -225,11 +226,12 @@ func NewConversionController(ctx context.Context, cmw configmap.Watcher) *contro sourcesv1_: &sourcesv1.ApiServerSource{}, }, }, - sourcesv1beta2.Kind("PingSource"): { + sourcesv1.Kind("PingSource"): { DefinitionName: sources.PingSourceResource.String(), HubVersion: sourcesv1beta2_, Zygotes: map[string]conversion.ConvertibleObject{ sourcesv1beta2_: &sourcesv1beta2.PingSource{}, + sourcesv1_: &sourcesv1.PingSource{}, }, }, sourcesv1.Kind("SinkBinding"): { diff --git a/config/core/resources/pingsource.yaml b/config/core/resources/pingsource.yaml index af7d1a60acd..d10af857d6f 100644 --- a/config/core/resources/pingsource.yaml +++ b/config/core/resources/pingsource.yaml @@ -30,7 +30,8 @@ metadata: spec: group: sources.knative.dev versions: - - name: v1beta2 + - &version + name: v1beta2 served: true storage: true subresources: @@ -192,6 +193,11 @@ spec: - name: Reason type: string jsonPath: ".status.conditions[?(@.type=='Ready')].reason" + - <<: *version + name: v1 + served: true + storage: false + # v1 schema is identical to the v1beta2 schema names: categories: - all diff --git a/pkg/apis/sources/v1/implements_test.go b/pkg/apis/sources/v1/implements_test.go index 9a2f0e46cde..dbacc73426f 100644 --- a/pkg/apis/sources/v1/implements_test.go +++ b/pkg/apis/sources/v1/implements_test.go @@ -31,6 +31,9 @@ func TestTypesImplements(t *testing.T) { // ApiServerSource {instance: &ApiServerSource{}, iface: &duckv1.Conditions{}}, {instance: &ApiServerSource{}, iface: &duckv1.Source{}}, + // PingSourceSource + {instance: &PingSource{}, iface: &duckv1.Conditions{}}, + {instance: &PingSource{}, iface: &duckv1.Source{}}, // SinkBinding {instance: &SinkBinding{}, iface: &duckv1.Conditions{}}, {instance: &SinkBinding{}, iface: &duckv1.Source{}}, diff --git a/pkg/apis/sources/v1/ping_conversion.go b/pkg/apis/sources/v1/ping_conversion.go new file mode 100644 index 00000000000..12afe722e40 --- /dev/null +++ b/pkg/apis/sources/v1/ping_conversion.go @@ -0,0 +1,36 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +// Converts source from v1.PingSource into a higher version. +func (source *PingSource) ConvertTo(ctx context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +// Converts source from a higher version into v1.PingSource +func (sink *PingSource) ConvertFrom(ctx context.Context, source apis.Convertible) error { + return fmt.Errorf("v1 is the highest known version, got: %T", source) +} diff --git a/pkg/apis/sources/v1/ping_conversion_test.go b/pkg/apis/sources/v1/ping_conversion_test.go new file mode 100644 index 00000000000..446e2883ce4 --- /dev/null +++ b/pkg/apis/sources/v1/ping_conversion_test.go @@ -0,0 +1,34 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + "testing" +) + +func TestPingSourceConversionBadType(t *testing.T) { + good, bad := &PingSource{}, &testObject{} + + if err := good.ConvertTo(context.Background(), bad); err == nil { + t.Errorf("ConvertTo() = %#v, wanted error", bad) + } + + if err := good.ConvertFrom(context.Background(), bad); err == nil { + t.Errorf("ConvertFrom() = %#v, wanted error", good) + } +} diff --git a/pkg/apis/sources/v1/ping_defaults.go b/pkg/apis/sources/v1/ping_defaults.go new file mode 100644 index 00000000000..efe8db64f1c --- /dev/null +++ b/pkg/apis/sources/v1/ping_defaults.go @@ -0,0 +1,35 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" +) + +const ( + defaultSchedule = "* * * * *" +) + +func (s *PingSource) SetDefaults(ctx context.Context) { + s.Spec.SetDefaults(ctx) +} + +func (ss *PingSourceSpec) SetDefaults(ctx context.Context) { + if ss.Schedule == "" { + ss.Schedule = defaultSchedule + } +} diff --git a/pkg/apis/sources/v1/ping_defaults_test.go b/pkg/apis/sources/v1/ping_defaults_test.go new file mode 100644 index 00000000000..32fe44f3ce1 --- /dev/null +++ b/pkg/apis/sources/v1/ping_defaults_test.go @@ -0,0 +1,67 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestPingSourceSetDefaults(t *testing.T) { + testCases := map[string]struct { + initial PingSource + expected PingSource + }{ + "nil": { + expected: PingSource{ + Spec: PingSourceSpec{ + Schedule: defaultSchedule, + }, + }, + }, + "empty": { + initial: PingSource{}, + expected: PingSource{ + Spec: PingSourceSpec{ + Schedule: defaultSchedule, + }, + }, + }, + "with schedule": { + initial: PingSource{ + Spec: PingSourceSpec{ + Schedule: "1 2 3 4 5", + }, + }, + expected: PingSource{ + Spec: PingSourceSpec{ + Schedule: "1 2 3 4 5", + }, + }, + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + tc.initial.SetDefaults(context.TODO()) + if diff := cmp.Diff(tc.expected, tc.initial); diff != "" { + t.Fatal("Unexpected defaults (-want, +got):", diff) + } + }) + } +} diff --git a/pkg/apis/sources/v1/ping_lifecycle.go b/pkg/apis/sources/v1/ping_lifecycle.go new file mode 100644 index 00000000000..a7a0bb90805 --- /dev/null +++ b/pkg/apis/sources/v1/ping_lifecycle.go @@ -0,0 +1,122 @@ +/* +Copyright 2021 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 v1 + +import ( + "fmt" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" +) + +const ( + // PingSourceConditionReady has status True when the PingSource is ready to send events. + PingSourceConditionReady = apis.ConditionReady + + // PingSourceConditionSinkProvided has status True when the PingSource has been configured with a sink target. + PingSourceConditionSinkProvided apis.ConditionType = "SinkProvided" + + // PingSourceConditionDeployed has status True when the PingSource has had it's receive adapter deployment created. + PingSourceConditionDeployed apis.ConditionType = "Deployed" +) + +var PingSourceCondSet = apis.NewLivingConditionSet( + PingSourceConditionSinkProvided, + PingSourceConditionDeployed) + +const ( + // PingSourceEventType is the default PingSource CloudEvent type. + PingSourceEventType = "dev.knative.sources.ping" +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*PingSource) GetConditionSet() apis.ConditionSet { + return PingSourceCondSet +} + +// PingSourceSource returns the PingSource CloudEvent source. +func PingSourceSource(namespace, name string) string { + return fmt.Sprintf("/apis/v1/namespaces/%s/pingsources/%s", namespace, name) +} + +// GetUntypedSpec returns the spec of the PingSource. +func (s *PingSource) GetUntypedSpec() interface{} { + return s.Spec +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (s *PingSource) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("PingSource") +} + +// GetCondition returns the condition currently associated with the given type, or nil. +func (s *PingSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return PingSourceCondSet.Manage(s).GetCondition(t) +} + +// GetTopLevelCondition returns the top level Condition. +func (ps *PingSourceStatus) GetTopLevelCondition() *apis.Condition { + return PingSourceCondSet.Manage(ps).GetTopLevelCondition() +} + +// IsReady returns true if the resource is ready overall. +func (s *PingSourceStatus) IsReady() bool { + return PingSourceCondSet.Manage(s).IsHappy() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (s *PingSourceStatus) InitializeConditions() { + PingSourceCondSet.Manage(s).InitializeConditions() +} + +// MarkSink sets the condition that the source has a sink configured. +func (s *PingSourceStatus) MarkSink(uri *apis.URL) { + s.SinkURI = uri + if uri != nil { + PingSourceCondSet.Manage(s).MarkTrue(PingSourceConditionSinkProvided) + } else { + PingSourceCondSet.Manage(s).MarkFalse(PingSourceConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.") + } +} + +// MarkNoSink sets the condition that the source does not have a sink configured. +func (s *PingSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { + PingSourceCondSet.Manage(s).MarkFalse(PingSourceConditionSinkProvided, reason, messageFormat, messageA...) +} + +// PropagateDeploymentAvailability uses the availability of the provided Deployment to determine if +// PingSourceConditionDeployed should be marked as true or false. +func (s *PingSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) { + deploymentAvailableFound := false + for _, cond := range d.Status.Conditions { + if cond.Type == appsv1.DeploymentAvailable { + deploymentAvailableFound = true + if cond.Status == corev1.ConditionTrue { + PingSourceCondSet.Manage(s).MarkTrue(PingSourceConditionDeployed) + } else if cond.Status == corev1.ConditionFalse { + PingSourceCondSet.Manage(s).MarkFalse(PingSourceConditionDeployed, cond.Reason, cond.Message) + } else if cond.Status == corev1.ConditionUnknown { + PingSourceCondSet.Manage(s).MarkUnknown(PingSourceConditionDeployed, cond.Reason, cond.Message) + } + } + } + if !deploymentAvailableFound { + PingSourceCondSet.Manage(s).MarkUnknown(PingSourceConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + } +} diff --git a/pkg/apis/sources/v1/ping_lifecycle_test.go b/pkg/apis/sources/v1/ping_lifecycle_test.go new file mode 100644 index 00000000000..4061b30b165 --- /dev/null +++ b/pkg/apis/sources/v1/ping_lifecycle_test.go @@ -0,0 +1,260 @@ +/* +Copyright 2021 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 v1 + +import ( + "testing" + + corev1 "k8s.io/api/core/v1" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "knative.dev/pkg/apis" +) + +func TestPingSourceGetConditionSet(t *testing.T) { + r := &PingSource{} + + if got, want := r.GetConditionSet().GetTopLevelConditionType(), apis.ConditionReady; got != want { + t.Errorf("GetTopLevelCondition=%v, want=%v", got, want) + } +} + +func TestPingSource_GetGroupVersionKind(t *testing.T) { + src := PingSource{} + gvk := src.GetGroupVersionKind() + + if gvk.Kind != "PingSource" { + t.Error("Should be PingSource.") + } +} + +func TestPingSource_PingSourceSource(t *testing.T) { + cePingSource := PingSourceSource("ns1", "job1") + + if cePingSource != "/apis/v1/namespaces/ns1/pingsources/job1" { + t.Error("Should be '/apis/v1/namespaces/ns1/pingsources/job1'") + } +} + +func TestPingSourceStatusIsReady(t *testing.T) { + exampleUri, _ := apis.ParseURL("uri://example") + + tests := []struct { + name string + s *PingSourceStatus + wantConditionStatus corev1.ConditionStatus + want bool + }{{ + name: "uninitialized", + s: &PingSourceStatus{}, + want: false, + }, { + name: "initialized", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark deployed", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.PropagateDeploymentAvailability(availableDeployment) + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sink", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + + s.MarkSink(exampleUri) + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sink and deployed", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.MarkSink(exampleUri) + s.PropagateDeploymentAvailability(availableDeployment) + return s + }(), + wantConditionStatus: corev1.ConditionTrue, + want: true, + }} + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.wantConditionStatus != "" { + gotConditionStatus := test.s.GetTopLevelCondition().Status + if gotConditionStatus != test.wantConditionStatus { + t.Errorf("unexpected condition status: want %v, got %v", test.wantConditionStatus, gotConditionStatus) + } + } + got := test.s.IsReady() + if got != test.want { + t.Errorf("unexpected readiness: want %v, got %v", test.want, got) + } + }) + } +} + +func TestPingSourceStatusGetTopLevelCondition(t *testing.T) { + exampleUri, _ := apis.ParseURL("uri://example") + + tests := []struct { + name string + s *PingSourceStatus + want *apis.Condition + }{{ + name: "uninitialized", + s: &PingSourceStatus{}, + want: nil, + }, { + name: "initialized", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + return s + }(), + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark deployed", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.PropagateDeploymentAvailability(availableDeployment) + return s + }(), + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark sink", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.MarkSink(exampleUri) + return s + }(), + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark sink and deployed", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.MarkSink(exampleUri) + s.PropagateDeploymentAvailability(availableDeployment) + return s + }(), + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionTrue, + }, + }} + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := test.s.GetTopLevelCondition() + ignoreTime := cmpopts.IgnoreFields(apis.Condition{}, + "LastTransitionTime", "Severity") + if diff := cmp.Diff(test.want, got, ignoreTime); diff != "" { + t.Error("unexpected condition (-want, +got) =", diff) + } + }) + } +} + +func TestPingSourceStatusGetCondition(t *testing.T) { + exampleUri, _ := apis.ParseURL("uri://example") + tests := []struct { + name string + s *PingSourceStatus + condQuery apis.ConditionType + want *apis.Condition + }{{ + name: "uninitialized", + s: &PingSourceStatus{}, + condQuery: PingSourceConditionReady, + want: nil, + }, { + name: "initialized", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + return s + }(), + condQuery: PingSourceConditionReady, + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark deployed", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.PropagateDeploymentAvailability(availableDeployment) + return s + }(), + condQuery: PingSourceConditionReady, + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark sink", + s: func() *PingSourceStatus { + s := &PingSourceStatus{} + s.InitializeConditions() + s.MarkSink(exampleUri) + return s + }(), + condQuery: PingSourceConditionReady, + want: &apis.Condition{ + Type: PingSourceConditionReady, + Status: corev1.ConditionUnknown, + }, + }} + + 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.Error("unexpected condition (-want, +got) =", diff) + } + }) + } +} diff --git a/pkg/apis/sources/v1/ping_types.go b/pkg/apis/sources/v1/ping_types.go new file mode 100644 index 00000000000..5390fc288ff --- /dev/null +++ b/pkg/apis/sources/v1/ping_types.go @@ -0,0 +1,110 @@ +/* +Copyright 2021 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 v1 + +import ( + "knative.dev/pkg/apis" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:defaulter-gen=true + +// PingSource is the Schema for the PingSources API. +type PingSource struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec PingSourceSpec `json:"spec,omitempty"` + Status PingSourceStatus `json:"status,omitempty"` +} + +// Check the interfaces that PingSource should be implementing. +var ( + _ runtime.Object = (*PingSource)(nil) + _ kmeta.OwnerRefable = (*PingSource)(nil) + _ apis.Validatable = (*PingSource)(nil) + _ apis.Defaultable = (*PingSource)(nil) + _ apis.HasSpec = (*PingSource)(nil) + _ duckv1.KRShaped = (*PingSource)(nil) +) + +// PingSourceSpec defines the desired state of the PingSource. +type PingSourceSpec struct { + // inherits duck/v1 SourceSpec, which currently provides: + // * Sink - a reference to an object that will resolve to a domain name or + // a URI directly to use as the sink. + // * CloudEventOverrides - defines overrides to control the output format + // and modifications of the event sent to the sink. + duckv1.SourceSpec `json:",inline"` + + // Schedule is the cron schedule. Defaults to `* * * * *`. + // +optional + Schedule string `json:"schedule,omitempty"` + + // Timezone modifies the actual time relative to the specified timezone. + // Defaults to the system time zone. + // More general information about time zones: https://www.iana.org/time-zones + // List of valid timezone values: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + Timezone string `json:"timezone,omitempty"` + + // ContentType is the media type of Data or DataBase64. Default is empty. + // +optional + ContentType string `json:"contentType,omitempty"` + + // Data is data used as the body of the event posted to the sink. Default is empty. + // Mutually exclusive with DataBase64. + // +optional + Data string `json:"data,omitempty"` + + // DataBase64 is the base64-encoded string of the actual event's body posted to the sink. Default is empty. + // Mutually exclusive with Data. + // +optional + DataBase64 string `json:"dataBase64,omitempty"` +} + +// PingSourceStatus defines the observed state of PingSource. +type PingSourceStatus struct { + // inherits duck/v1 SourceStatus, 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. + // * SinkURI - the current active sink URI that has been configured for the + // Source. + duckv1.SourceStatus `json:",inline"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PingSourceList contains a list of PingSources. +type PingSourceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []PingSource `json:"items"` +} + +// GetStatus retrieves the status of the PingSource. Implements the KRShaped interface. +func (p *PingSource) GetStatus() *duckv1.Status { + return &p.Status.Status +} diff --git a/pkg/apis/sources/v1/ping_types_test.go b/pkg/apis/sources/v1/ping_types_test.go new file mode 100644 index 00000000000..b2a7d54b95f --- /dev/null +++ b/pkg/apis/sources/v1/ping_types_test.go @@ -0,0 +1,28 @@ +/* +Copyright 2021 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 v1 + +import "testing" + +func TestPingSource_GetStatus(t *testing.T) { + p := &PingSource{ + Status: PingSourceStatus{}, + } + if got, want := p.GetStatus(), &p.Status.Status; got != want { + t.Errorf("GetStatus=%v, want=%v", got, want) + } +} diff --git a/pkg/apis/sources/v1/ping_validation.go b/pkg/apis/sources/v1/ping_validation.go new file mode 100644 index 00000000000..d8648974700 --- /dev/null +++ b/pkg/apis/sources/v1/ping_validation.go @@ -0,0 +1,100 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "strings" + + cloudevents "github.com/cloudevents/sdk-go/v2" + + "github.com/robfig/cron/v3" + "knative.dev/pkg/apis" + + "knative.dev/eventing/pkg/apis/sources/config" +) + +func (c *PingSource) Validate(ctx context.Context) *apis.FieldError { + return c.Spec.Validate(ctx).ViaField("spec") +} + +func (cs *PingSourceSpec) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + + schedule := cs.Schedule + if cs.Timezone != "" { + schedule = "CRON_TZ=" + cs.Timezone + " " + schedule + } + + if _, err := cron.ParseStandard(schedule); err != nil { + if strings.HasPrefix(err.Error(), "provided bad location") { + fe := apis.ErrInvalidValue(err, "timezone") + errs = errs.Also(fe) + } else { + fe := apis.ErrInvalidValue(err, "schedule") + errs = errs.Also(fe) + } + } + + pingConfig := config.FromContextOrDefaults(ctx) + pingDefaults := pingConfig.PingDefaults.GetPingConfig() + + if fe := cs.Sink.Validate(ctx); fe != nil { + errs = errs.Also(fe.ViaField("sink")) + } + + if cs.Data != "" && cs.DataBase64 != "" { + errs = errs.Also(apis.ErrMultipleOneOf("data", "dataBase64")) + } else if cs.DataBase64 != "" { + if bsize := int64(len(cs.DataBase64)); pingDefaults.DataMaxSize > -1 && bsize > pingDefaults.DataMaxSize { + fe := apis.ErrInvalidValue(fmt.Sprintf("the dataBase64 length of %d bytes exceeds limit set at %d.", bsize, pingDefaults.DataMaxSize), "dataBase64") + errs = errs.Also(fe) + } + decoded, err := base64.StdEncoding.DecodeString(cs.DataBase64) + // invalid base64 string + if err != nil { + errs = errs.Also(apis.ErrInvalidValue(err, "dataBase64")) + } else { + // validate if the decoded base64 string is valid JSON + if cs.ContentType == cloudevents.ApplicationJSON { + if err := validateJSON(string(decoded)); err != nil { + errs = errs.Also(apis.ErrInvalidValue(err, "dataBase64")) + } + } + } + } else if cs.Data != "" { + if bsize := int64(len(cs.Data)); pingDefaults.DataMaxSize > -1 && bsize > pingDefaults.DataMaxSize { + fe := apis.ErrInvalidValue(fmt.Sprintf("the data length of %d bytes exceeds limit set at %d.", bsize, pingDefaults.DataMaxSize), "data") + errs = errs.Also(fe) + } + if cs.ContentType == cloudevents.ApplicationJSON { + // validate if data is valid JSON + if err := validateJSON(cs.Data); err != nil { + errs = errs.Also(apis.ErrInvalidValue(err, "data")) + } + } + } + return errs +} + +func validateJSON(str string) error { + var objmap map[string]interface{} + return json.Unmarshal([]byte(str), &objmap) +} diff --git a/pkg/apis/sources/v1/ping_validation_test.go b/pkg/apis/sources/v1/ping_validation_test.go new file mode 100644 index 00000000000..f06e399883e --- /dev/null +++ b/pkg/apis/sources/v1/ping_validation_test.go @@ -0,0 +1,390 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + "encoding/base64" + "strings" + "testing" + + cloudevents "github.com/cloudevents/sdk-go/v2" + + duckv1 "knative.dev/pkg/apis/duck/v1" + + "github.com/google/go-cmp/cmp" + "knative.dev/pkg/apis" + + "knative.dev/eventing/pkg/apis/sources/config" +) + +func TestPingSourceValidation(t *testing.T) { + tests := []struct { + name string + source PingSource + ctx func(ctx context.Context) context.Context + want *apis.FieldError + }{ + { + name: "valid spec", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: nil, + }, { + name: "valid spec with timezone", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + Timezone: "Europe/Paris", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: nil, + }, { + name: "valid spec with invalid timezone", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + Timezone: "Knative/Land", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("provided bad location Knative/Land: unknown time zone Knative/Land", "spec.timezone") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "empty sink", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + }, + }, + want: func() *apis.FieldError { + return apis.ErrGeneric("expected at least one, got none", "ref", "uri").ViaField("spec.sink") + }(), + }, { + name: "invalid schedule", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "2", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("expected exactly 5 fields, found 1: [2]", "spec.schedule") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "valid spec with data", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: "application/json", + Data: `{"msg": "Hello World"}`, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: nil, + }, { + name: "valid spec with dataBase64", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + DataBase64: "SGVsbG8gV29ybGQu", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: nil, + }, { + name: "invalid spec with data and dataBase64 both set", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + Data: "Hello world", + DataBase64: "SGVsbG8gV29ybGQu", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrMultipleOneOf("spec.data", "spec.dataBase64") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "invalid spec: dataBase64 is invalid base64 string", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + DataBase64: "$$$ invalid base64 string $$$", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("illegal base64 data at input byte 0", "spec.dataBase64") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "invalid spec: contentType=application/json, data is invalid JSON format", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.ApplicationJSON, + Data: "Invalid JSON", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("invalid character 'I' looking for beginning of value", "spec.data") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "invalid spec: contentType=application/json, decoded dataBase64 is invalid JSON format", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.ApplicationJSON, + DataBase64: base64.StdEncoding.EncodeToString([]byte("Invalid JSON")), + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("invalid character 'I' looking for beginning of value", "spec.dataBase64") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "invalid DataBase64 is to big ", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + DataBase64: base64.StdEncoding.EncodeToString([]byte(bigString())), + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + ctx: func(ctx context.Context) context.Context { + return config.ToContext(ctx, &config.Config{PingDefaults: &config.PingDefaults{DataMaxSize: 4096}}) + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("the dataBase64 length of 6668 bytes exceeds limit set at 4096.", "spec.dataBase64") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "invalid Data is to big ", + source: PingSource{ + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + Data: bigString(), + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + ctx: func(ctx context.Context) context.Context { + + return config.ToContext(ctx, &config.Config{PingDefaults: &config.PingDefaults{DataMaxSize: 4096}}) + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + fe := apis.ErrInvalidValue("the data length of 5000 bytes exceeds limit set at 4096.", "spec.data") + errs = errs.Also(fe) + return errs + }(), + }, { + name: "big data ok ", + source: PingSource{ + + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + Data: bigString(), + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + ctx: func(ctx context.Context) context.Context { + return config.ToContext(ctx, &config.Config{PingDefaults: &config.PingDefaults{DataMaxSize: -1}}) + }, + want: nil, + }, { + name: "big data still ok ", + source: PingSource{ + + Spec: PingSourceSpec{ + Schedule: "*/2 * * * *", + ContentType: cloudevents.TextPlain, + Data: bigString(), + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + want: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ctx := context.TODO() + if test.ctx != nil { + ctx = test.ctx(ctx) + } + got := test.source.Validate(ctx) + if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { + t.Error("PingSourceSpec.Validate (-want, +got) =", diff) + } + }) + } +} +func bigString() string { + var b strings.Builder + b.Grow(5000) + b.WriteString("\"") + for i := 0; i < 4998; i++ { + b.WriteString("a") + } + b.WriteString("\"") + return b.String() +} diff --git a/pkg/apis/sources/v1/register.go b/pkg/apis/sources/v1/register.go index f0e2c198672..45260f42c27 100644 --- a/pkg/apis/sources/v1/register.go +++ b/pkg/apis/sources/v1/register.go @@ -51,6 +51,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { &SinkBindingList{}, &ContainerSource{}, &ContainerSourceList{}, + &PingSource{}, + &PingSourceList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/pkg/apis/sources/v1/register_test.go b/pkg/apis/sources/v1/register_test.go index 411870b3543..49489149d12 100644 --- a/pkg/apis/sources/v1/register_test.go +++ b/pkg/apis/sources/v1/register_test.go @@ -62,6 +62,8 @@ func TestKnownTypes(t *testing.T) { for _, name := range []string{ "ApiServerSource", "ApiServerSourceList", + "PingSource", + "PingSourceList", "SinkBinding", "SinkBindingList", "ContainerSource", diff --git a/pkg/apis/sources/v1/roundtrip_test.go b/pkg/apis/sources/v1/roundtrip_test.go index aa9aeb4f6bf..a18af0e75ab 100644 --- a/pkg/apis/sources/v1/roundtrip_test.go +++ b/pkg/apis/sources/v1/roundtrip_test.go @@ -45,6 +45,15 @@ var FuzzerFuncs = fuzzer.MergeFuzzerFuncs( source.Status.InitializeConditions() pkgfuzzer.FuzzConditions(&source.Status, c) }, + func(source *PingSource, c fuzz.Continue) { + c.FuzzNoCustom(source) // fuzz the source + // Clear the random fuzzed condition + source.Status.SetConditions(nil) + + // Fuzz the known conditions except their type value + source.Status.InitializeConditions() + pkgfuzzer.FuzzConditions(&source.Status, c) + }, func(source *ContainerSource, c fuzz.Continue) { c.FuzzNoCustom(source) // fuzz the source // Clear the random fuzzed condition diff --git a/pkg/apis/sources/v1/zz_generated.deepcopy.go b/pkg/apis/sources/v1/zz_generated.deepcopy.go index 93a61b4cd02..62c83377820 100644 --- a/pkg/apis/sources/v1/zz_generated.deepcopy.go +++ b/pkg/apis/sources/v1/zz_generated.deepcopy.go @@ -265,6 +265,101 @@ func (in *ContainerSourceStatus) DeepCopy() *ContainerSourceStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PingSource) DeepCopyInto(out *PingSource) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PingSource. +func (in *PingSource) DeepCopy() *PingSource { + if in == nil { + return nil + } + out := new(PingSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PingSource) 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 *PingSourceList) DeepCopyInto(out *PingSourceList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PingSource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PingSourceList. +func (in *PingSourceList) DeepCopy() *PingSourceList { + if in == nil { + return nil + } + out := new(PingSourceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PingSourceList) 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 *PingSourceSpec) DeepCopyInto(out *PingSourceSpec) { + *out = *in + in.SourceSpec.DeepCopyInto(&out.SourceSpec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PingSourceSpec. +func (in *PingSourceSpec) DeepCopy() *PingSourceSpec { + if in == nil { + return nil + } + out := new(PingSourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PingSourceStatus) DeepCopyInto(out *PingSourceStatus) { + *out = *in + in.SourceStatus.DeepCopyInto(&out.SourceStatus) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PingSourceStatus. +func (in *PingSourceStatus) DeepCopy() *PingSourceStatus { + if in == nil { + return nil + } + out := new(PingSourceStatus) + 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 diff --git a/pkg/apis/sources/v1beta2/ping_conversion.go b/pkg/apis/sources/v1beta2/ping_conversion.go index 17fb38b6208..fd0ece828ac 100644 --- a/pkg/apis/sources/v1beta2/ping_conversion.go +++ b/pkg/apis/sources/v1beta2/ping_conversion.go @@ -18,19 +18,57 @@ package v1beta2 import ( "context" - "fmt" "knative.dev/pkg/apis" + + v1 "knative.dev/eventing/pkg/apis/sources/v1" ) // ConvertTo implements apis.Convertible // Converts source from v1beta2.PingSource into a higher version. -func (source *PingSource) ConvertTo(ctx context.Context, sink apis.Convertible) error { - return fmt.Errorf("v1beta2 is the highest known version, got: %T", sink) +func (source *PingSource) ConvertTo(ctx context.Context, obj apis.Convertible) error { + switch sink := obj.(type) { + case *v1.PingSource: + sink.ObjectMeta = source.ObjectMeta + sink.Status = v1.PingSourceStatus{ + SourceStatus: source.Status.SourceStatus, + } + sink.Spec = v1.PingSourceSpec{ + SourceSpec: source.Spec.SourceSpec, + Schedule: source.Spec.Schedule, + Timezone: source.Spec.Timezone, + ContentType: source.Spec.ContentType, + Data: source.Spec.Data, + DataBase64: source.Spec.DataBase64, + } + + return nil + default: + return apis.ConvertToViaProxy(ctx, source, &v1.PingSource{}, sink) + } } // ConvertFrom implements apis.Convertible // Converts source from a higher version into v1beta2.PingSource -func (sink *PingSource) ConvertFrom(ctx context.Context, source apis.Convertible) error { - return fmt.Errorf("v1beta2 is the highest known version, got: %T", source) +func (sink *PingSource) ConvertFrom(ctx context.Context, obj apis.Convertible) error { + switch source := obj.(type) { + case *v1.PingSource: + sink.ObjectMeta = source.ObjectMeta + sink.Status = PingSourceStatus{ + SourceStatus: source.Status.SourceStatus, + } + + sink.Spec = PingSourceSpec{ + SourceSpec: source.Spec.SourceSpec, + Schedule: source.Spec.Schedule, + Timezone: source.Spec.Timezone, + ContentType: source.Spec.ContentType, + Data: source.Spec.Data, + DataBase64: source.Spec.DataBase64, + } + + return nil + default: + return apis.ConvertFromViaProxy(ctx, source, &v1.PingSource{}, sink) + } } diff --git a/pkg/apis/sources/v1beta2/ping_conversion_test.go b/pkg/apis/sources/v1beta2/ping_conversion_test.go index 10ae86a11e8..1c93bc8acf1 100644 --- a/pkg/apis/sources/v1beta2/ping_conversion_test.go +++ b/pkg/apis/sources/v1beta2/ping_conversion_test.go @@ -1,5 +1,5 @@ /* -Copyright 2020 The Knative Authors +Copyright 2021 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. diff --git a/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_pingsource.go b/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_pingsource.go new file mode 100644 index 00000000000..a6e9ea27480 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_pingsource.go @@ -0,0 +1,142 @@ +/* +Copyright 2021 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 ( + "context" + + 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" + sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" +) + +// FakePingSources implements PingSourceInterface +type FakePingSources struct { + Fake *FakeSourcesV1 + ns string +} + +var pingsourcesResource = schema.GroupVersionResource{Group: "sources.knative.dev", Version: "v1", Resource: "pingsources"} + +var pingsourcesKind = schema.GroupVersionKind{Group: "sources.knative.dev", Version: "v1", Kind: "PingSource"} + +// Get takes name of the pingSource, and returns the corresponding pingSource object, and an error if there is any. +func (c *FakePingSources) Get(ctx context.Context, name string, options v1.GetOptions) (result *sourcesv1.PingSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(pingsourcesResource, c.ns, name), &sourcesv1.PingSource{}) + + if obj == nil { + return nil, err + } + return obj.(*sourcesv1.PingSource), err +} + +// List takes label and field selectors, and returns the list of PingSources that match those selectors. +func (c *FakePingSources) List(ctx context.Context, opts v1.ListOptions) (result *sourcesv1.PingSourceList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(pingsourcesResource, pingsourcesKind, c.ns, opts), &sourcesv1.PingSourceList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &sourcesv1.PingSourceList{ListMeta: obj.(*sourcesv1.PingSourceList).ListMeta} + for _, item := range obj.(*sourcesv1.PingSourceList).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 pingSources. +func (c *FakePingSources) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(pingsourcesResource, c.ns, opts)) + +} + +// Create takes the representation of a pingSource and creates it. Returns the server's representation of the pingSource, and an error, if there is any. +func (c *FakePingSources) Create(ctx context.Context, pingSource *sourcesv1.PingSource, opts v1.CreateOptions) (result *sourcesv1.PingSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(pingsourcesResource, c.ns, pingSource), &sourcesv1.PingSource{}) + + if obj == nil { + return nil, err + } + return obj.(*sourcesv1.PingSource), err +} + +// Update takes the representation of a pingSource and updates it. Returns the server's representation of the pingSource, and an error, if there is any. +func (c *FakePingSources) Update(ctx context.Context, pingSource *sourcesv1.PingSource, opts v1.UpdateOptions) (result *sourcesv1.PingSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(pingsourcesResource, c.ns, pingSource), &sourcesv1.PingSource{}) + + if obj == nil { + return nil, err + } + return obj.(*sourcesv1.PingSource), 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 *FakePingSources) UpdateStatus(ctx context.Context, pingSource *sourcesv1.PingSource, opts v1.UpdateOptions) (*sourcesv1.PingSource, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(pingsourcesResource, "status", c.ns, pingSource), &sourcesv1.PingSource{}) + + if obj == nil { + return nil, err + } + return obj.(*sourcesv1.PingSource), err +} + +// Delete takes name of the pingSource and deletes it. Returns an error if one occurs. +func (c *FakePingSources) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(pingsourcesResource, c.ns, name), &sourcesv1.PingSource{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakePingSources) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(pingsourcesResource, c.ns, listOpts) + + _, err := c.Fake.Invokes(action, &sourcesv1.PingSourceList{}) + return err +} + +// Patch applies the patch and returns the patched pingSource. +func (c *FakePingSources) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *sourcesv1.PingSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(pingsourcesResource, c.ns, name, pt, data, subresources...), &sourcesv1.PingSource{}) + + if obj == nil { + return nil, err + } + return obj.(*sourcesv1.PingSource), err +} diff --git a/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_sources_client.go b/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_sources_client.go index 74abcb9f64a..f53e0758d39 100644 --- a/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_sources_client.go +++ b/pkg/client/clientset/versioned/typed/sources/v1/fake/fake_sources_client.go @@ -36,6 +36,10 @@ func (c *FakeSourcesV1) ContainerSources(namespace string) v1.ContainerSourceInt return &FakeContainerSources{c, namespace} } +func (c *FakeSourcesV1) PingSources(namespace string) v1.PingSourceInterface { + return &FakePingSources{c, namespace} +} + func (c *FakeSourcesV1) SinkBindings(namespace string) v1.SinkBindingInterface { return &FakeSinkBindings{c, namespace} } diff --git a/pkg/client/clientset/versioned/typed/sources/v1/generated_expansion.go b/pkg/client/clientset/versioned/typed/sources/v1/generated_expansion.go index f328e512bff..22bdb65a52b 100644 --- a/pkg/client/clientset/versioned/typed/sources/v1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/sources/v1/generated_expansion.go @@ -22,4 +22,6 @@ type ApiServerSourceExpansion interface{} type ContainerSourceExpansion interface{} +type PingSourceExpansion interface{} + type SinkBindingExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/sources/v1/pingsource.go b/pkg/client/clientset/versioned/typed/sources/v1/pingsource.go new file mode 100644 index 00000000000..489b463c29c --- /dev/null +++ b/pkg/client/clientset/versioned/typed/sources/v1/pingsource.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + "time" + + metav1 "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" + v1 "knative.dev/eventing/pkg/apis/sources/v1" + scheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" +) + +// PingSourcesGetter has a method to return a PingSourceInterface. +// A group's client should implement this interface. +type PingSourcesGetter interface { + PingSources(namespace string) PingSourceInterface +} + +// PingSourceInterface has methods to work with PingSource resources. +type PingSourceInterface interface { + Create(ctx context.Context, pingSource *v1.PingSource, opts metav1.CreateOptions) (*v1.PingSource, error) + Update(ctx context.Context, pingSource *v1.PingSource, opts metav1.UpdateOptions) (*v1.PingSource, error) + UpdateStatus(ctx context.Context, pingSource *v1.PingSource, opts metav1.UpdateOptions) (*v1.PingSource, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.PingSource, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.PingSourceList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PingSource, err error) + PingSourceExpansion +} + +// pingSources implements PingSourceInterface +type pingSources struct { + client rest.Interface + ns string +} + +// newPingSources returns a PingSources +func newPingSources(c *SourcesV1Client, namespace string) *pingSources { + return &pingSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the pingSource, and returns the corresponding pingSource object, and an error if there is any. +func (c *pingSources) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PingSource, err error) { + result = &v1.PingSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("pingsources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of PingSources that match those selectors. +func (c *pingSources) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PingSourceList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.PingSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("pingsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested pingSources. +func (c *pingSources) Watch(ctx context.Context, opts metav1.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("pingsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a pingSource and creates it. Returns the server's representation of the pingSource, and an error, if there is any. +func (c *pingSources) Create(ctx context.Context, pingSource *v1.PingSource, opts metav1.CreateOptions) (result *v1.PingSource, err error) { + result = &v1.PingSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("pingsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(pingSource). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a pingSource and updates it. Returns the server's representation of the pingSource, and an error, if there is any. +func (c *pingSources) Update(ctx context.Context, pingSource *v1.PingSource, opts metav1.UpdateOptions) (result *v1.PingSource, err error) { + result = &v1.PingSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("pingsources"). + Name(pingSource.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(pingSource). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *pingSources) UpdateStatus(ctx context.Context, pingSource *v1.PingSource, opts metav1.UpdateOptions) (result *v1.PingSource, err error) { + result = &v1.PingSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("pingsources"). + Name(pingSource.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(pingSource). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the pingSource and deletes it. Returns an error if one occurs. +func (c *pingSources) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("pingsources"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *pingSources) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("pingsources"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched pingSource. +func (c *pingSources) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PingSource, err error) { + result = &v1.PingSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("pingsources"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/sources/v1/sources_client.go b/pkg/client/clientset/versioned/typed/sources/v1/sources_client.go index 4860b0db3dd..54ee28b2915 100644 --- a/pkg/client/clientset/versioned/typed/sources/v1/sources_client.go +++ b/pkg/client/clientset/versioned/typed/sources/v1/sources_client.go @@ -28,6 +28,7 @@ type SourcesV1Interface interface { RESTClient() rest.Interface ApiServerSourcesGetter ContainerSourcesGetter + PingSourcesGetter SinkBindingsGetter } @@ -44,6 +45,10 @@ func (c *SourcesV1Client) ContainerSources(namespace string) ContainerSourceInte return newContainerSources(c, namespace) } +func (c *SourcesV1Client) PingSources(namespace string) PingSourceInterface { + return newPingSources(c, namespace) +} + func (c *SourcesV1Client) SinkBindings(namespace string) SinkBindingInterface { return newSinkBindings(c, namespace) } diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 71d09b3ee49..94b41212161 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -86,6 +86,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1().ApiServerSources().Informer()}, nil case sourcesv1.SchemeGroupVersion.WithResource("containersources"): return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1().ContainerSources().Informer()}, nil + case sourcesv1.SchemeGroupVersion.WithResource("pingsources"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1().PingSources().Informer()}, nil case sourcesv1.SchemeGroupVersion.WithResource("sinkbindings"): return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1().SinkBindings().Informer()}, nil diff --git a/pkg/client/informers/externalversions/sources/v1/interface.go b/pkg/client/informers/externalversions/sources/v1/interface.go index baf6916fba9..490ec63d10d 100644 --- a/pkg/client/informers/externalversions/sources/v1/interface.go +++ b/pkg/client/informers/externalversions/sources/v1/interface.go @@ -28,6 +28,8 @@ type Interface interface { ApiServerSources() ApiServerSourceInformer // ContainerSources returns a ContainerSourceInformer. ContainerSources() ContainerSourceInformer + // PingSources returns a PingSourceInformer. + PingSources() PingSourceInformer // SinkBindings returns a SinkBindingInformer. SinkBindings() SinkBindingInformer } @@ -53,6 +55,11 @@ func (v *version) ContainerSources() ContainerSourceInformer { return &containerSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } +// PingSources returns a PingSourceInformer. +func (v *version) PingSources() PingSourceInformer { + return &pingSourceInformer{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/client/informers/externalversions/sources/v1/pingsource.go b/pkg/client/informers/externalversions/sources/v1/pingsource.go new file mode 100644 index 00000000000..f741f06d3e8 --- /dev/null +++ b/pkg/client/informers/externalversions/sources/v1/pingsource.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 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 v1 + +import ( + "context" + time "time" + + metav1 "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" + sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/eventing/pkg/client/informers/externalversions/internalinterfaces" + v1 "knative.dev/eventing/pkg/client/listers/sources/v1" +) + +// PingSourceInformer provides access to a shared informer and lister for +// PingSources. +type PingSourceInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.PingSourceLister +} + +type pingSourceInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewPingSourceInformer constructs a new informer for PingSource 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 NewPingSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredPingSourceInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredPingSourceInformer constructs a new informer for PingSource 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 NewFilteredPingSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SourcesV1().PingSources(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SourcesV1().PingSources(namespace).Watch(context.TODO(), options) + }, + }, + &sourcesv1.PingSource{}, + resyncPeriod, + indexers, + ) +} + +func (f *pingSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredPingSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *pingSourceInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&sourcesv1.PingSource{}, f.defaultInformer) +} + +func (f *pingSourceInformer) Lister() v1.PingSourceLister { + return v1.NewPingSourceLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/injection/informers/sources/v1/pingsource/fake/fake.go b/pkg/client/injection/informers/sources/v1/pingsource/fake/fake.go new file mode 100644 index 00000000000..d48188bfda3 --- /dev/null +++ b/pkg/client/injection/informers/sources/v1/pingsource/fake/fake.go @@ -0,0 +1,40 @@ +/* +Copyright 2021 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/client/injection/informers/factory/fake" + pingsource "knative.dev/eventing/pkg/client/injection/informers/sources/v1/pingsource" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" +) + +var Get = pingsource.Get + +func init() { + injection.Fake.RegisterInformer(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := fake.Get(ctx) + inf := f.Sources().V1().PingSources() + return context.WithValue(ctx, pingsource.Key{}, inf), inf.Informer() +} diff --git a/pkg/client/injection/informers/sources/v1/pingsource/filtered/fake/fake.go b/pkg/client/injection/informers/sources/v1/pingsource/filtered/fake/fake.go new file mode 100644 index 00000000000..90e4414f29b --- /dev/null +++ b/pkg/client/injection/informers/sources/v1/pingsource/filtered/fake/fake.go @@ -0,0 +1,52 @@ +/* +Copyright 2021 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" + + factoryfiltered "knative.dev/eventing/pkg/client/injection/informers/factory/filtered" + filtered "knative.dev/eventing/pkg/client/injection/informers/sources/v1/pingsource/filtered" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +var Get = filtered.Get + +func init() { + injection.Fake.RegisterFilteredInformers(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, []controller.Informer) { + untyped := ctx.Value(factoryfiltered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + infs := []controller.Informer{} + for _, selector := range labelSelectors { + f := factoryfiltered.Get(ctx, selector) + inf := f.Sources().V1().PingSources() + ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) + infs = append(infs, inf.Informer()) + } + return ctx, infs +} diff --git a/pkg/client/injection/informers/sources/v1/pingsource/filtered/pingsource.go b/pkg/client/injection/informers/sources/v1/pingsource/filtered/pingsource.go new file mode 100644 index 00000000000..3e88483aaa4 --- /dev/null +++ b/pkg/client/injection/informers/sources/v1/pingsource/filtered/pingsource.go @@ -0,0 +1,65 @@ +/* +Copyright 2021 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 filtered + +import ( + context "context" + + v1 "knative.dev/eventing/pkg/client/informers/externalversions/sources/v1" + filtered "knative.dev/eventing/pkg/client/injection/informers/factory/filtered" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +func init() { + injection.Default.RegisterFilteredInformers(withInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct { + Selector string +} + +func withInformer(ctx context.Context) (context.Context, []controller.Informer) { + untyped := ctx.Value(filtered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + infs := []controller.Informer{} + for _, selector := range labelSelectors { + f := filtered.Get(ctx, selector) + inf := f.Sources().V1().PingSources() + ctx = context.WithValue(ctx, Key{Selector: selector}, inf) + infs = append(infs, inf.Informer()) + } + return ctx, infs +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context, selector string) v1.PingSourceInformer { + untyped := ctx.Value(Key{Selector: selector}) + if untyped == nil { + logging.FromContext(ctx).Panicf( + "Unable to fetch knative.dev/eventing/pkg/client/informers/externalversions/sources/v1.PingSourceInformer with selector %s from context.", selector) + } + return untyped.(v1.PingSourceInformer) +} diff --git a/pkg/client/injection/informers/sources/v1/pingsource/pingsource.go b/pkg/client/injection/informers/sources/v1/pingsource/pingsource.go new file mode 100644 index 00000000000..5bbe75ad590 --- /dev/null +++ b/pkg/client/injection/informers/sources/v1/pingsource/pingsource.go @@ -0,0 +1,52 @@ +/* +Copyright 2021 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 pingsource + +import ( + context "context" + + v1 "knative.dev/eventing/pkg/client/informers/externalversions/sources/v1" + factory "knative.dev/eventing/pkg/client/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().V1().PingSources() + return context.WithValue(ctx, Key{}, inf), inf.Informer() +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context) v1.PingSourceInformer { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/eventing/pkg/client/informers/externalversions/sources/v1.PingSourceInformer from context.") + } + return untyped.(v1.PingSourceInformer) +} diff --git a/pkg/client/injection/reconciler/sources/v1/pingsource/controller.go b/pkg/client/injection/reconciler/sources/v1/pingsource/controller.go new file mode 100644 index 00000000000..9eac17ef768 --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1/pingsource/controller.go @@ -0,0 +1,153 @@ +/* +Copyright 2021 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 pingsource + +import ( + context "context" + fmt "fmt" + reflect "reflect" + strings "strings" + + zap "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + scheme "k8s.io/client-go/kubernetes/scheme" + v1 "k8s.io/client-go/kubernetes/typed/core/v1" + record "k8s.io/client-go/tools/record" + versionedscheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" + client "knative.dev/eventing/pkg/client/injection/client" + pingsource "knative.dev/eventing/pkg/client/injection/informers/sources/v1/pingsource" + kubeclient "knative.dev/pkg/client/injection/kube/client" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + logkey "knative.dev/pkg/logging/logkey" + reconciler "knative.dev/pkg/reconciler" +) + +const ( + defaultControllerAgentName = "pingsource-controller" + defaultFinalizerName = "pingsources.sources.knative.dev" +) + +// NewImpl returns a controller.Impl that handles queuing and feeding work from +// the queue through an implementation of controller.Reconciler, delegating to +// the provided Interface and optional Finalizer methods. OptionsFn is used to return +// controller.Options to be used by the internal reconciler. +func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { + logger := logging.FromContext(ctx) + + // Check the options function input. It should be 0 or 1. + if len(optionsFns) > 1 { + logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) + } + + pingsourceInformer := pingsource.Get(ctx) + + lister := pingsourceInformer.Lister() + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + // TODO: Consider letting users specify a filter in options. + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client.Get(ctx), + Lister: lister, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + ctrType := reflect.TypeOf(r).Elem() + ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) + ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") + + logger = logger.With( + zap.String(logkey.ControllerType, ctrTypeName), + zap.String(logkey.Kind, "sources.knative.dev.PingSource"), + ) + + impl := controller.NewImpl(rec, logger, ctrTypeName) + agentName := defaultControllerAgentName + + // Pass impl to the options. Save any optional results. + for _, fn := range optionsFns { + opts := fn(impl) + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.AgentName != "" { + agentName = opts.AgentName + } + if opts.SkipStatusUpdates { + rec.skipStatusUpdates = true + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + } + + rec.Recorder = createRecorder(ctx, agentName) + + return impl +} + +func createRecorder(ctx context.Context, agentName string) record.EventRecorder { + logger := logging.FromContext(ctx) + + recorder := controller.GetEventRecorder(ctx) + if recorder == nil { + // Create event broadcaster + logger.Debug("Creating event broadcaster") + eventBroadcaster := record.NewBroadcaster() + watches := []watch.Interface{ + eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof), + eventBroadcaster.StartRecordingToSink( + &v1.EventSinkImpl{Interface: kubeclient.Get(ctx).CoreV1().Events("")}), + } + recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName}) + go func() { + <-ctx.Done() + for _, w := range watches { + w.Stop() + } + }() + } + + return recorder +} + +func init() { + versionedscheme.AddToScheme(scheme.Scheme) +} diff --git a/pkg/client/injection/reconciler/sources/v1/pingsource/reconciler.go b/pkg/client/injection/reconciler/sources/v1/pingsource/reconciler.go new file mode 100644 index 00000000000..51cac64d349 --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1/pingsource/reconciler.go @@ -0,0 +1,455 @@ +/* +Copyright 2021 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 pingsource + +import ( + context "context" + json "encoding/json" + fmt "fmt" + + zap "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + equality "k8s.io/apimachinery/pkg/api/equality" + errors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + record "k8s.io/client-go/tools/record" + v1 "knative.dev/eventing/pkg/apis/sources/v1" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + sourcesv1 "knative.dev/eventing/pkg/client/listers/sources/v1" + controller "knative.dev/pkg/controller" + kmp "knative.dev/pkg/kmp" + logging "knative.dev/pkg/logging" + reconciler "knative.dev/pkg/reconciler" +) + +// Interface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1.PingSource. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1.PingSource. Any changes + // to the objects .Status or .Finalizers will be propagated to the stored + // object. It is recommended that implementors do not call any update calls + // for the Kind inside of ReconcileKind, it is the responsibility of the calling + // controller to propagate those properties. The resource passed to ReconcileKind + // will always have an empty deletion timestamp. + ReconcileKind(ctx context.Context, o *v1.PingSource) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1.PingSource. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1.PingSource. Any changes + // to the objects .Status or .Finalizers will be ignored. Returning a nil or + // Normal type reconciler.Event will allow the finalizer to be deleted on + // the resource. The resource passed to FinalizeKind will always have a set + // deletion timestamp. + FinalizeKind(ctx context.Context, o *v1.PingSource) reconciler.Event +} + +// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1.PingSource if they want to process resources for which +// they are not the leader. +type ReadOnlyInterface interface { + // ObserveKind implements logic to observe v1.PingSource. + // This method should not write to the API. + ObserveKind(ctx context.Context, o *v1.PingSource) reconciler.Event +} + +// ReadOnlyFinalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1.PingSource if they want to process tombstoned resources +// even when they are not the leader. Due to the nature of how finalizers are handled +// there are no guarantees that this will be called. +type ReadOnlyFinalizer interface { + // ObserveFinalizeKind implements custom logic to observe the final state of v1.PingSource. + // This method should not write to the API. + ObserveFinalizeKind(ctx context.Context, o *v1.PingSource) reconciler.Event +} + +type doReconcile func(ctx context.Context, o *v1.PingSource) reconciler.Event + +// reconcilerImpl implements controller.Reconciler for v1.PingSource resources. +type reconcilerImpl struct { + // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. + reconciler.LeaderAwareFuncs + + // Client is used to write back status updates. + Client versioned.Interface + + // Listers index properties about resources. + Lister sourcesv1.PingSourceLister + + // Recorder is an event recorder for recording Event resources to the + // Kubernetes API. + Recorder record.EventRecorder + + // configStore allows for decorating a context with config maps. + // +optional + configStore reconciler.ConfigStore + + // reconciler is the implementation of the business logic of the resource. + reconciler Interface + + // finalizerName is the name of the finalizer to reconcile. + finalizerName string + + // skipStatusUpdates configures whether or not this reconciler automatically updates + // the status of the reconciled resource. + skipStatusUpdates bool +} + +// Check that our Reconciler implements controller.Reconciler. +var _ controller.Reconciler = (*reconcilerImpl)(nil) + +// Check that our generated Reconciler is always LeaderAware. +var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) + +func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister sourcesv1.PingSourceLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { + // Check the options function input. It should be 0 or 1. + if len(options) > 1 { + logger.Fatal("Up to one options struct is supported, found: ", len(options)) + } + + // Fail fast when users inadvertently implement the other LeaderAware interface. + // For the typed reconcilers, Promote shouldn't take any arguments. + if _, ok := r.(reconciler.LeaderAware); ok { + logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) + } + // TODO: Consider validating when folks implement ReadOnlyFinalizer, but not Finalizer. + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + // TODO: Consider letting users specify a filter in options. + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client, + Lister: lister, + Recorder: recorder, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + for _, opts := range options { + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.SkipStatusUpdates { + rec.skipStatusUpdates = true + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // Initialize the reconciler state. This will convert the namespace/name + // string into a distinct namespace and name, determine if this instance of + // the reconciler is the leader, and any additional interfaces implemented + // by the reconciler. Returns an error is the resource key is invalid. + s, err := newState(key, r) + if err != nil { + logger.Error("Invalid resource key: ", key) + return nil + } + + // If we are not the leader, and we don't implement either ReadOnly + // observer interfaces, then take a fast-path out. + if s.isNotLeaderNorObserver() { + return controller.NewSkipKey(key) + } + + // If configStore is set, attach the frozen configuration to the context. + if r.configStore != nil { + ctx = r.configStore.ToContext(ctx) + } + + // Add the recorder to context. + ctx = controller.WithEventRecorder(ctx, r.Recorder) + + // Get the resource with this namespace/name. + + getter := r.Lister.PingSources(s.namespace) + + original, err := getter.Get(s.name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing and call + // the ObserveDeletion handler if appropriate. + logger.Debugf("Resource %q no longer exists", key) + if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { + return del.ObserveDeletion(ctx, types.NamespacedName{ + Namespace: s.namespace, + Name: s.name, + }) + } + return nil + } else if err != nil { + return err + } + + // Don't modify the informers copy. + resource := original.DeepCopy() + + var reconcileEvent reconciler.Event + + name, do := s.reconcileMethodFor(resource) + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", name)) + switch name { + case reconciler.DoReconcileKind: + // Set and update the finalizer on resource if r.reconciler + // implements Finalizer. + if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { + return fmt.Errorf("failed to set finalizers: %w", err) + } + + if !r.skipStatusUpdates { + reconciler.PreProcessReconcile(ctx, resource) + } + + // Reconcile this copy of the resource and then write back any status + // updates regardless of whether the reconciliation errored out. + reconcileEvent = do(ctx, resource) + + if !r.skipStatusUpdates { + reconciler.PostProcessReconcile(ctx, resource, original) + } + + case reconciler.DoFinalizeKind: + // For finalizing reconcilers, if this resource being marked for deletion + // and reconciled cleanly (nil or normal event), remove the finalizer. + reconcileEvent = do(ctx, resource) + + if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { + return fmt.Errorf("failed to clear finalizers: %w", err) + } + + case reconciler.DoObserveKind, reconciler.DoObserveFinalizeKind: + // Observe any changes to this resource, since we are not the leader. + reconcileEvent = do(ctx, resource) + + } + + // Synchronize the status. + switch { + case r.skipStatusUpdates: + // This reconciler implementation is configured to skip resource updates. + // This may mean this reconciler does not observe spec, but reconciles external changes. + case equality.Semantic.DeepEqual(original.Status, resource.Status): + // If we didn't change anything then don't call updateStatus. + // This is important because the copy we loaded from the injectionInformer's + // cache may be stale and we don't want to overwrite a prior update + // to status with this stale state. + case !s.isLeader: + // High-availability reconcilers may have many replicas watching the resource, but only + // the elected leader is expected to write modifications. + logger.Warn("Saw status changes when we aren't the leader!") + default: + if err = r.updateStatus(ctx, original, resource); err != nil { + logger.Warnw("Failed to update resource status", zap.Error(err)) + r.Recorder.Eventf(resource, corev1.EventTypeWarning, "UpdateFailed", + "Failed to update status for %q: %v", resource.Name, err) + return err + } + } + + // Report the reconciler event, if any. + if reconcileEvent != nil { + var event *reconciler.ReconcilerEvent + if reconciler.EventAs(reconcileEvent, &event) { + logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) + r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) + + // the event was wrapped inside an error, consider the reconciliation as failed + if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { + return reconcileEvent + } + return nil + } + + logger.Errorw("Returned an error", zap.Error(reconcileEvent)) + r.Recorder.Event(resource, corev1.EventTypeWarning, "InternalError", reconcileEvent.Error()) + return reconcileEvent + } + + return nil +} + +func (r *reconcilerImpl) updateStatus(ctx context.Context, existing *v1.PingSource, desired *v1.PingSource) error { + existing = existing.DeepCopy() + return reconciler.RetryUpdateConflicts(func(attempts int) (err error) { + // The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API. + if attempts > 0 { + + getter := r.Client.SourcesV1().PingSources(desired.Namespace) + + existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) + if err != nil { + return err + } + } + + // If there's nothing to update, just return. + if equality.Semantic.DeepEqual(existing.Status, desired.Status) { + return nil + } + + if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { + logging.FromContext(ctx).Debug("Updating status with: ", diff) + } + + existing.Status = desired.Status + + updater := r.Client.SourcesV1().PingSources(existing.Namespace) + + _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) + return err + }) +} + +// updateFinalizersFiltered will update the Finalizers of the resource. +// TODO: this method could be generic and sync all finalizers. For now it only +// updates defaultFinalizerName or its override. +func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1.PingSource) (*v1.PingSource, error) { + + getter := r.Lister.PingSources(resource.Namespace) + + actual, err := getter.Get(resource.Name) + if err != nil { + return resource, err + } + + // Don't modify the informers copy. + existing := actual.DeepCopy() + + var finalizers []string + + // If there's nothing to update, just return. + existingFinalizers := sets.NewString(existing.Finalizers...) + desiredFinalizers := sets.NewString(resource.Finalizers...) + + if desiredFinalizers.Has(r.finalizerName) { + if existingFinalizers.Has(r.finalizerName) { + // Nothing to do. + return resource, nil + } + // Add the finalizer. + finalizers = append(existing.Finalizers, r.finalizerName) + } else { + if !existingFinalizers.Has(r.finalizerName) { + // Nothing to do. + return resource, nil + } + // Remove the finalizer. + existingFinalizers.Delete(r.finalizerName) + finalizers = existingFinalizers.List() + } + + mergePatch := map[string]interface{}{ + "metadata": map[string]interface{}{ + "finalizers": finalizers, + "resourceVersion": existing.ResourceVersion, + }, + } + + patch, err := json.Marshal(mergePatch) + if err != nil { + return resource, err + } + + patcher := r.Client.SourcesV1().PingSources(resource.Namespace) + + resourceName := resource.Name + updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) + if err != nil { + r.Recorder.Eventf(existing, corev1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resourceName, err) + } else { + r.Recorder.Eventf(updated, corev1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return updated, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1.PingSource) (*v1.PingSource, error) { + if _, ok := r.reconciler.(Finalizer); !ok { + return resource, nil + } + + finalizers := sets.NewString(resource.Finalizers...) + + // If this resource is not being deleted, mark the finalizer. + if resource.GetDeletionTimestamp().IsZero() { + finalizers.Insert(r.finalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} + +func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1.PingSource, reconcileEvent reconciler.Event) (*v1.PingSource, error) { + if _, ok := r.reconciler.(Finalizer); !ok { + return resource, nil + } + if resource.GetDeletionTimestamp().IsZero() { + return resource, nil + } + + finalizers := sets.NewString(resource.Finalizers...) + + if reconcileEvent != nil { + var event *reconciler.ReconcilerEvent + if reconciler.EventAs(reconcileEvent, &event) { + if event.EventType == corev1.EventTypeNormal { + finalizers.Delete(r.finalizerName) + } + } + } else { + finalizers.Delete(r.finalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} diff --git a/pkg/client/injection/reconciler/sources/v1/pingsource/state.go b/pkg/client/injection/reconciler/sources/v1/pingsource/state.go new file mode 100644 index 00000000000..a71dcebddcb --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1/pingsource/state.go @@ -0,0 +1,106 @@ +/* +Copyright 2021 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 pingsource + +import ( + fmt "fmt" + + types "k8s.io/apimachinery/pkg/types" + cache "k8s.io/client-go/tools/cache" + v1 "knative.dev/eventing/pkg/apis/sources/v1" + reconciler "knative.dev/pkg/reconciler" +) + +// state is used to track the state of a reconciler in a single run. +type state struct { + // key is the original reconciliation key from the queue. + key string + // namespace is the namespace split from the reconciliation key. + namespace string + // name is the name split from the reconciliation key. + name string + // reconciler is the reconciler. + reconciler Interface + // roi is the read only interface cast of the reconciler. + roi ReadOnlyInterface + // isROI (Read Only Interface) the reconciler only observes reconciliation. + isROI bool + // rof is the read only finalizer cast of the reconciler. + rof ReadOnlyFinalizer + // isROF (Read Only Finalizer) the reconciler only observes finalize. + isROF bool + // isLeader the instance of the reconciler is the elected leader. + isLeader bool +} + +func newState(key string, r *reconcilerImpl) (*state, error) { + // Convert the namespace/name string into a distinct namespace and name. + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return nil, fmt.Errorf("invalid resource key: %s", key) + } + + roi, isROI := r.reconciler.(ReadOnlyInterface) + rof, isROF := r.reconciler.(ReadOnlyFinalizer) + + isLeader := r.IsLeaderFor(types.NamespacedName{ + Namespace: namespace, + Name: name, + }) + + return &state{ + key: key, + namespace: namespace, + name: name, + reconciler: r.reconciler, + roi: roi, + isROI: isROI, + rof: rof, + isROF: isROF, + isLeader: isLeader, + }, nil +} + +// isNotLeaderNorObserver checks to see if this reconciler with the current +// state is enabled to do any work or not. +// isNotLeaderNorObserver returns true when there is no work possible for the +// reconciler. +func (s *state) isNotLeaderNorObserver() bool { + if !s.isLeader && !s.isROI && !s.isROF { + // If we are not the leader, and we don't implement either ReadOnly + // interface, then take a fast-path out. + return true + } + return false +} + +func (s *state) reconcileMethodFor(o *v1.PingSource) (string, doReconcile) { + if o.GetDeletionTimestamp().IsZero() { + if s.isLeader { + return reconciler.DoReconcileKind, s.reconciler.ReconcileKind + } else if s.isROI { + return reconciler.DoObserveKind, s.roi.ObserveKind + } + } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { + return reconciler.DoFinalizeKind, fin.FinalizeKind + } else if !s.isLeader && s.isROF { + return reconciler.DoObserveFinalizeKind, s.rof.ObserveFinalizeKind + } + return "unknown", nil +} diff --git a/pkg/client/listers/sources/v1/expansion_generated.go b/pkg/client/listers/sources/v1/expansion_generated.go index 4f3d7a8137f..cfa0aaae756 100644 --- a/pkg/client/listers/sources/v1/expansion_generated.go +++ b/pkg/client/listers/sources/v1/expansion_generated.go @@ -34,6 +34,14 @@ type ContainerSourceListerExpansion interface{} // ContainerSourceNamespaceLister. type ContainerSourceNamespaceListerExpansion interface{} +// PingSourceListerExpansion allows custom methods to be added to +// PingSourceLister. +type PingSourceListerExpansion interface{} + +// PingSourceNamespaceListerExpansion allows custom methods to be added to +// PingSourceNamespaceLister. +type PingSourceNamespaceListerExpansion interface{} + // SinkBindingListerExpansion allows custom methods to be added to // SinkBindingLister. type SinkBindingListerExpansion interface{} diff --git a/pkg/client/listers/sources/v1/pingsource.go b/pkg/client/listers/sources/v1/pingsource.go new file mode 100644 index 00000000000..15be67add96 --- /dev/null +++ b/pkg/client/listers/sources/v1/pingsource.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 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 v1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1 "knative.dev/eventing/pkg/apis/sources/v1" +) + +// PingSourceLister helps list PingSources. +// All objects returned here must be treated as read-only. +type PingSourceLister interface { + // List lists all PingSources in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.PingSource, err error) + // PingSources returns an object that can list and get PingSources. + PingSources(namespace string) PingSourceNamespaceLister + PingSourceListerExpansion +} + +// pingSourceLister implements the PingSourceLister interface. +type pingSourceLister struct { + indexer cache.Indexer +} + +// NewPingSourceLister returns a new PingSourceLister. +func NewPingSourceLister(indexer cache.Indexer) PingSourceLister { + return &pingSourceLister{indexer: indexer} +} + +// List lists all PingSources in the indexer. +func (s *pingSourceLister) List(selector labels.Selector) (ret []*v1.PingSource, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.PingSource)) + }) + return ret, err +} + +// PingSources returns an object that can list and get PingSources. +func (s *pingSourceLister) PingSources(namespace string) PingSourceNamespaceLister { + return pingSourceNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// PingSourceNamespaceLister helps list and get PingSources. +// All objects returned here must be treated as read-only. +type PingSourceNamespaceLister interface { + // List lists all PingSources in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.PingSource, err error) + // Get retrieves the PingSource from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.PingSource, error) + PingSourceNamespaceListerExpansion +} + +// pingSourceNamespaceLister implements the PingSourceNamespaceLister +// interface. +type pingSourceNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all PingSources in the indexer for a given namespace. +func (s pingSourceNamespaceLister) List(selector labels.Selector) (ret []*v1.PingSource, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.PingSource)) + }) + return ret, err +} + +// Get retrieves the PingSource from the indexer for a given namespace and name. +func (s pingSourceNamespaceLister) Get(name string) (*v1.PingSource, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("pingsource"), name) + } + return obj.(*v1.PingSource), nil +} diff --git a/pkg/reconciler/testing/v1/pingsource.go b/pkg/reconciler/testing/v1/pingsource.go new file mode 100644 index 00000000000..7111523295d --- /dev/null +++ b/pkg/reconciler/testing/v1/pingsource.go @@ -0,0 +1,109 @@ +/* +Copyright 2021 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 ( + "context" + "time" + + "knative.dev/eventing/pkg/reconciler/testing" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + v1 "knative.dev/eventing/pkg/apis/sources/v1" +) + +// PingSourceOption enables further configuration of a CronJob. +type PingSourceOption func(*v1.PingSource) + +// NewPingSource creates a PingSource with PingSourceOption. +func NewPingSource(name, namespace string, o ...PingSourceOption) *v1.PingSource { + c := &v1.PingSource{ + 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 WithPingSource(uid string) PingSourceOption { + return func(c *v1.PingSource) { + c.UID = types.UID(uid) + } +} + +func WithInitPingSourceConditions(s *v1.PingSource) { + s.Status.InitializeConditions() +} + +func WithPingSourceSinkNotFound(s *v1.PingSource) { + s.Status.MarkNoSink("NotFound", "") +} + +func WithPingSourceSink(uri *apis.URL) PingSourceOption { + return func(s *v1.PingSource) { + s.Status.MarkSink(uri) + } +} + +func WithPingSourceDeployed(s *v1.PingSource) { + s.Status.PropagateDeploymentAvailability(testing.NewDeployment("any", "any", testing.WithDeploymentAvailable())) +} + +func WithPingSourceCloudEventAttributes(s *v1.PingSource) { + s.Status.CloudEventAttributes = []duckv1.CloudEventAttributes{{ + Type: v1.PingSourceEventType, + Source: v1.PingSourceSource(s.Namespace, s.Name), + }} +} + +func WithPingSourceSpec(spec v1.PingSourceSpec) PingSourceOption { + return func(c *v1.PingSource) { + c.Spec = spec + } +} + +func WithPingSourceStatusObservedGeneration(generation int64) PingSourceOption { + return func(c *v1.PingSource) { + c.Status.ObservedGeneration = generation + } +} + +func WithPingSourceObjectMetaGeneration(generation int64) PingSourceOption { + return func(c *v1.PingSource) { + c.ObjectMeta.Generation = generation + } +} + +func WithPingSourceFinalizers(finalizers ...string) PingSourceOption { + return func(c *v1.PingSource) { + c.Finalizers = finalizers + } +} + +func WithPingSourceDeleted(c *v1.PingSource) { + t := metav1.NewTime(time.Unix(1e9, 0)) + c.SetDeletionTimestamp(&t) +} diff --git a/test/e2e/source_ping_v1_test.go b/test/e2e/source_ping_v1_test.go new file mode 100644 index 00000000000..d17aa84e2e1 --- /dev/null +++ b/test/e2e/source_ping_v1_test.go @@ -0,0 +1,135 @@ +// +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 ( + "context" + "fmt" + "testing" + + cloudevents "github.com/cloudevents/sdk-go/v2" + + "knative.dev/eventing/pkg/reconciler/sugar" + + sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" + sugarresources "knative.dev/eventing/pkg/reconciler/sugar/resources" + "knative.dev/eventing/test/lib/recordevents" + + . "github.com/cloudevents/sdk-go/v2/test" + "k8s.io/apimachinery/pkg/util/uuid" + + duckv1 "knative.dev/pkg/apis/duck/v1" + + testlib "knative.dev/eventing/test/lib" + "knative.dev/eventing/test/lib/resources" + + rttestingv1 "knative.dev/eventing/pkg/reconciler/testing/v1" +) + +func TestPingSourceV1(t *testing.T) { + const ( + sourceName = "e2e-ping-source" + // Every 1 minute starting from now + + recordEventPodName = "e2e-ping-source-logger-pod-v1" + ) + + client := setup(t, true) + defer tearDown(client) + + ctx := context.Background() + + // create event logger pod and service + eventTracker, _ := recordevents.StartEventRecordOrFail(ctx, client, recordEventPodName) + // create cron job source + data := fmt.Sprintf(`{"msg":"TestPingSource %s"}`, uuid.NewUUID()) + source := rttestingv1.NewPingSource( + sourceName, + client.Namespace, + rttestingv1.WithPingSourceSpec(sourcesv1.PingSourceSpec{ + ContentType: cloudevents.ApplicationJSON, + Data: data, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: resources.KnativeRefForService(recordEventPodName, client.Namespace), + }, + }, + }), + ) + client.CreatePingSourceV1OrFail(source) + + // wait for all test resources to be ready + client.WaitForAllTestResourcesReadyOrFail(ctx) + + // verify the logger service receives the event and only once + eventTracker.AssertExact(1, recordevents.MatchEvent( + HasSource(sourcesv1.PingSourceSource(client.Namespace, sourceName)), + HasData([]byte(data)), + )) +} + +func TestPingSourceV1EventTypes(t *testing.T) { + const ( + sourceName = "e2e-ping-source-eventtype" + ) + + client := setup(t, true) + defer tearDown(client) + + ctx := context.Background() + + // Label namespace so that it creates the default broker. + if err := client.LabelNamespace(map[string]string{sugar.InjectionLabelKey: sugar.InjectionEnabledLabelValue}); err != nil { + t.Fatal("Error annotating namespace:", err) + } + + // Wait for default broker ready. + client.WaitForResourceReadyOrFail(sugarresources.DefaultBrokerName, testlib.BrokerTypeMeta) + + // Create ping source + source := rttestingv1.NewPingSource( + sourceName, + client.Namespace, + rttestingv1.WithPingSourceSpec(sourcesv1.PingSourceSpec{ + ContentType: cloudevents.ApplicationJSON, + Data: fmt.Sprintf(`{"msg":"TestPingSource %s"}`, uuid.NewUUID()), + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + // TODO change sink to be a non-Broker one once we revisit EventType https://github.com/knative/eventing/issues/2750 + Ref: resources.KnativeRefForBroker(sugarresources.DefaultBrokerName, client.Namespace), + }, + }, + }), + ) + client.CreatePingSourceV1OrFail(source) + + // wait for all test resources to be ready + client.WaitForAllTestResourcesReadyOrFail(ctx) + + // Verify that an EventType was created. + eventTypes, err := waitForEventTypes(ctx, client, 1) + if err != nil { + t.Fatal("Waiting for EventTypes:", err) + } + et := eventTypes[0] + if et.Spec.Type != sourcesv1.PingSourceEventType && et.Spec.Source.String() != sourcesv1.PingSourceSource(client.Namespace, sourceName) { + t.Fatalf("Invalid spec.type and/or spec.source for PingSource EventType, expected: type=%s source=%s, got: type=%s source=%s", + sourcesv1.PingSourceEventType, sourcesv1.PingSourceSource(client.Namespace, sourceName), et.Spec.Type, et.Spec.Source) + } +} diff --git a/test/lib/creation.go b/test/lib/creation.go index 44a0a6b9394..18f96722fc0 100644 --- a/test/lib/creation.go +++ b/test/lib/creation.go @@ -387,6 +387,23 @@ func (c *Client) CreatePingSourceV1Beta2OrFail(pingSource *sourcesv1beta2.PingSo c.Tracker.AddObj(pingSource) } +// CreatePingSourceV1OrFail will create a PingSource +func (c *Client) CreatePingSourceV1OrFail(pingSource *sourcesv1.PingSource) { + c.T.Logf("Creating pingsource %+v", pingSource) + pingInterface := c.Eventing.SourcesV1().PingSources(c.Namespace) + err := c.RetryWebhookErrors(func(attempts int) (err error) { + _, e := pingInterface.Create(context.Background(), pingSource, metav1.CreateOptions{}) + if e != nil { + c.T.Logf("Failed to create pingsource %q: %v", pingSource.Name, e) + } + return e + }) + if err != nil && !errors.IsAlreadyExists(err) { + c.T.Fatalf("Failed to create pingsource %q: %v", pingSource.Name, err) + } + c.Tracker.AddObj(pingSource) +} + func (c *Client) CreateServiceOrFail(svc *corev1.Service) *corev1.Service { c.T.Logf("Creating service %+v", svc) namespace := c.Namespace