diff --git a/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go b/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go index a9dcf8c3239..fba140a7e9a 100644 --- a/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go +++ b/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go @@ -126,7 +126,7 @@ func (s *ApiServerSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deploy } } if !deploymentAvailableFound { - PingSourceCondSet.Manage(s).MarkUnknown(PingSourceConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + apiserverCondSet.Manage(s).MarkUnknown(ApiServerConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) } } diff --git a/pkg/apis/sources/v1alpha2/apiserver_defaults_test.go b/pkg/apis/sources/v1alpha2/apiserver_defaults_test.go index d5710386718..32f7ed1a746 100644 --- a/pkg/apis/sources/v1alpha2/apiserver_defaults_test.go +++ b/pkg/apis/sources/v1alpha2/apiserver_defaults_test.go @@ -19,10 +19,118 @@ package v1alpha2 import ( "context" "testing" + + "github.com/google/go-cmp/cmp" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + duckv1 "knative.dev/pkg/apis/duck/v1" ) -// No-op test because method does nothing. -func TestAPIServerSourceDefaults(t *testing.T) { - s := ApiServerSource{} - s.SetDefaults(context.TODO()) +func TestApiServerSourceDefaults(t *testing.T) { + testCases := map[string]struct { + initial ApiServerSource + expected ApiServerSource + }{ + "no EventMode": { + initial: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + ServiceAccountName: "default", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + expected: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + EventMode: ReferenceMode, + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + ServiceAccountName: "default", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + }, + "no ServiceAccountName": { + initial: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + EventMode: ReferenceMode, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + expected: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + EventMode: ReferenceMode, + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + ServiceAccountName: "default", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + tc.initial.SetDefaults(context.Background()) + if diff := cmp.Diff(tc.expected, tc.initial); diff != "" { + t.Fatalf("Unexpected defaults (-want, +got): %s", diff) + } + }) + } } diff --git a/pkg/apis/sources/v1alpha2/apiserver_lifecycle.go b/pkg/apis/sources/v1alpha2/apiserver_lifecycle.go index d5c2b88eec2..4404a3d5699 100644 --- a/pkg/apis/sources/v1alpha2/apiserver_lifecycle.go +++ b/pkg/apis/sources/v1alpha2/apiserver_lifecycle.go @@ -36,9 +36,6 @@ const ( // ApiServerConditionSufficientPermissions has status True when the ApiServerSource has sufficient permissions to access resources. ApiServerConditionSufficientPermissions apis.ConditionType = "SufficientPermissions" - - // ApiServerConditionEventTypeProvided has status True when the ApiServerSource has been configured with its event types. - ApiServerConditionEventTypeProvided apis.ConditionType = "EventTypesProvided" ) var apiserverCondSet = apis.NewLivingConditionSet( @@ -109,20 +106,10 @@ func (s *ApiServerSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deploy } } if !deploymentAvailableFound { - PingSourceCondSet.Manage(s).MarkUnknown(PingSourceConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + apiserverCondSet.Manage(s).MarkUnknown(ApiServerConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) } } -// MarkEventTypes sets the condition that the source has set its event type. -func (s *ApiServerSourceStatus) MarkEventTypes() { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionEventTypeProvided) -} - -// MarkNoEventTypes sets the condition that the source does not its event type configured. -func (s *ApiServerSourceStatus) MarkNoEventTypes(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionEventTypeProvided, reason, messageFormat, messageA...) -} - // MarkSufficientPermissions sets the condition that the source has enough permissions to access the resources. func (s *ApiServerSourceStatus) MarkSufficientPermissions() { apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSufficientPermissions) diff --git a/pkg/apis/sources/v1alpha2/apiserver_lifecycle_test.go b/pkg/apis/sources/v1alpha2/apiserver_lifecycle_test.go index 2c0ab66d7a0..1beddbae88b 100644 --- a/pkg/apis/sources/v1alpha2/apiserver_lifecycle_test.go +++ b/pkg/apis/sources/v1alpha2/apiserver_lifecycle_test.go @@ -104,7 +104,6 @@ func TestApiServerSourceStatusIsReady(t *testing.T) { s: func() *ApiServerSourceStatus { s := &ApiServerSourceStatus{} s.InitializeConditions() - s.MarkEventTypes() return s }(), wantConditionStatus: corev1.ConditionUnknown, @@ -158,14 +157,13 @@ func TestApiServerSourceStatusIsReady(t *testing.T) { wantConditionStatus: corev1.ConditionUnknown, want: false, }, { - name: "mark sink and sufficient permissions and deployed and event types", + name: "mark sink and sufficient permissions and deployed", s: func() *ApiServerSourceStatus { s := &ApiServerSourceStatus{} s.InitializeConditions() s.MarkSink(sink) s.MarkSufficientPermissions() s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) - s.MarkEventTypes() return s }(), wantConditionStatus: corev1.ConditionTrue, @@ -273,7 +271,6 @@ func TestApiServerSourceStatusGetCondition(t *testing.T) { s.MarkSink(sink) s.MarkSufficientPermissions() s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) - s.MarkEventTypes() return s }(), condQuery: ApiServerConditionReady, @@ -289,7 +286,6 @@ func TestApiServerSourceStatusGetCondition(t *testing.T) { s.MarkSink(nil) s.MarkSufficientPermissions() s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) - s.MarkEventTypes() return s }(), condQuery: ApiServerConditionReady, diff --git a/pkg/apis/sources/v1beta1/apiserver_conversion.go b/pkg/apis/sources/v1beta1/apiserver_conversion.go new file mode 100644 index 00000000000..9003c4c6299 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_conversion.go @@ -0,0 +1,34 @@ +/* +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 v1beta1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +func (source *ApiServerSource) ConvertTo(ctx context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +func (sink *ApiServerSource) ConvertFrom(ctx context.Context, source apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest known version, got: %T", source) +} diff --git a/pkg/apis/sources/v1beta1/apiserver_conversion_test.go b/pkg/apis/sources/v1beta1/apiserver_conversion_test.go new file mode 100644 index 00000000000..6a60fb1f048 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_conversion_test.go @@ -0,0 +1,34 @@ +/* +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 v1beta1 + +import ( + "context" + "testing" +) + +func TestApiServerConversionBadType(t *testing.T) { + good, bad := &ApiServerSource{}, &ApiServerSource{} + + 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/v1beta1/apiserver_defaults.go b/pkg/apis/sources/v1beta1/apiserver_defaults.go new file mode 100644 index 00000000000..31fcba4bcbc --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_defaults.go @@ -0,0 +1,36 @@ +/* +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 v1beta1 + +import ( + "context" +) + +func (s *ApiServerSource) SetDefaults(ctx context.Context) { + s.Spec.SetDefaults(ctx) +} + +func (ss *ApiServerSourceSpec) SetDefaults(ctx context.Context) { + + if ss.EventMode == "" { + ss.EventMode = ReferenceMode + } + + if ss.ServiceAccountName == "" { + ss.ServiceAccountName = "default" + } +} diff --git a/pkg/apis/sources/v1beta1/apiserver_defaults_test.go b/pkg/apis/sources/v1beta1/apiserver_defaults_test.go new file mode 100644 index 00000000000..c8a237e8ad7 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_defaults_test.go @@ -0,0 +1,136 @@ +/* +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 v1beta1 + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +func TestApiServerSourceDefaults(t *testing.T) { + testCases := map[string]struct { + initial ApiServerSource + expected ApiServerSource + }{ + "no EventMode": { + initial: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + ServiceAccountName: "default", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + expected: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + EventMode: ReferenceMode, + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + ServiceAccountName: "default", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + }, + "no ServiceAccountName": { + initial: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + EventMode: ReferenceMode, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + expected: ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + Spec: ApiServerSourceSpec{ + EventMode: ReferenceMode, + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + ServiceAccountName: "default", + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + }, + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + tc.initial.SetDefaults(context.Background()) + if diff := cmp.Diff(tc.expected, tc.initial); diff != "" { + t.Fatalf("Unexpected defaults (-want, +got): %s", diff) + } + }) + } +} diff --git a/pkg/apis/sources/v1beta1/apiserver_lifecycle.go b/pkg/apis/sources/v1beta1/apiserver_lifecycle.go new file mode 100644 index 00000000000..1990cabec5e --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_lifecycle.go @@ -0,0 +1,126 @@ +/* +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 v1beta1 + +import ( + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" +) + +const ( + // ApiServerConditionReady has status True when the ApiServerSource is ready to send events. + ApiServerConditionReady = apis.ConditionReady + + // ApiServerConditionSinkProvided has status True when the ApiServerSource has been configured with a sink target. + ApiServerConditionSinkProvided apis.ConditionType = "SinkProvided" + + // ApiServerConditionDeployed has status True when the ApiServerSource has had it's deployment created. + ApiServerConditionDeployed apis.ConditionType = "Deployed" + + // ApiServerConditionSufficientPermissions has status True when the ApiServerSource has sufficient permissions to access resources. + ApiServerConditionSufficientPermissions apis.ConditionType = "SufficientPermissions" +) + +var apiserverCondSet = apis.NewLivingConditionSet( + ApiServerConditionSinkProvided, + ApiServerConditionDeployed, + ApiServerConditionSufficientPermissions, +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*ApiServerSource) GetConditionSet() apis.ConditionSet { + return apiserverCondSet +} + +// GetGroupVersionKind returns the GroupVersionKind. +func (*ApiServerSource) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("ApiServerSource") +} + +// GetUntypedSpec returns the spec of the ApiServerSource. +func (s *ApiServerSource) GetUntypedSpec() interface{} { + return s.Spec +} + +// GetCondition returns the condition currently associated with the given type, or nil. +func (s *ApiServerSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return apiserverCondSet.Manage(s).GetCondition(t) +} + +// GetTopLevelCondition returns the top level condition. +func (s *ApiServerSourceStatus) GetTopLevelCondition() *apis.Condition { + return apiserverCondSet.Manage(s).GetTopLevelCondition() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (s *ApiServerSourceStatus) InitializeConditions() { + apiserverCondSet.Manage(s).InitializeConditions() +} + +// MarkSink sets the condition that the source has a sink configured. +func (s *ApiServerSourceStatus) MarkSink(uri *apis.URL) { + s.SinkURI = uri + if uri != nil { + apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSinkProvided) + } else { + apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") + } +} + +// MarkNoSink sets the condition that the source does not have a sink configured. +func (s *ApiServerSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { + apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSinkProvided, reason, messageFormat, messageA...) +} + +// PropagateDeploymentAvailability uses the availability of the provided Deployment to determine if +// ApiServerConditionDeployed should be marked as true or false. +func (s *ApiServerSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) { + deploymentAvailableFound := false + for _, cond := range d.Status.Conditions { + if cond.Type == appsv1.DeploymentAvailable { + deploymentAvailableFound = true + if cond.Status == corev1.ConditionTrue { + apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionDeployed) + } else if cond.Status == corev1.ConditionFalse { + apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionDeployed, cond.Reason, cond.Message) + } else if cond.Status == corev1.ConditionUnknown { + apiserverCondSet.Manage(s).MarkUnknown(ApiServerConditionDeployed, cond.Reason, cond.Message) + } + } + } + if !deploymentAvailableFound { + apiserverCondSet.Manage(s).MarkUnknown(ApiServerConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + } +} + +// MarkSufficientPermissions sets the condition that the source has enough permissions to access the resources. +func (s *ApiServerSourceStatus) MarkSufficientPermissions() { + apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSufficientPermissions) +} + +// MarkNoSufficientPermissions sets the condition that the source does not have enough permissions to access the resources +func (s *ApiServerSourceStatus) MarkNoSufficientPermissions(reason, messageFormat string, messageA ...interface{}) { + apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSufficientPermissions, reason, messageFormat, messageA...) +} + +// IsReady returns true if the resource is ready overall. +func (s *ApiServerSourceStatus) IsReady() bool { + return apiserverCondSet.Manage(s).IsHappy() +} diff --git a/pkg/apis/sources/v1beta1/apiserver_lifecycle_test.go b/pkg/apis/sources/v1beta1/apiserver_lifecycle_test.go new file mode 100644 index 00000000000..49aabee5c56 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_lifecycle_test.go @@ -0,0 +1,322 @@ +/* +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 v1beta1 + +import ( + "reflect" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" +) + +func TestApiServerSourceGetConditionSet(t *testing.T) { + r := &ApiServerSource{} + + if got, want := r.GetConditionSet().GetTopLevelConditionType(), apis.ConditionReady; got != want { + t.Errorf("GetTopLevelCondition=%v, want=%v", got, want) + } +} + +func TestApiServerSourceGetGroupVersionKind(t *testing.T) { + r := &ApiServerSource{} + want := schema.GroupVersionKind{ + Group: "sources.knative.dev", + Version: "v1beta1", + Kind: "ApiServerSource", + } + if got := r.GetGroupVersionKind(); got != want { + t.Errorf("got: %v, want: %v", got, want) + } +} + +func TestApiServerSourceStatusIsReady(t *testing.T) { + sink, _ := apis.ParseURL("uri://example") + + tests := []struct { + name string + s *ApiServerSourceStatus + wantConditionStatus corev1.ConditionStatus + want bool + }{{ + name: "uninitialized", + s: &ApiServerSourceStatus{}, + want: false, + }, { + name: "initialized", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark deployed", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sink", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sufficient permissions", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSufficientPermissions() + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark event types", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sink and sufficient permissions and deployed", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + wantConditionStatus: corev1.ConditionTrue, + want: true, + }, { + name: "mark sink and sufficient permissions and unavailable deployment", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.UnavailableDeployment()) + return s + }(), + wantConditionStatus: corev1.ConditionFalse, + want: false, + }, { + name: "mark sink and sufficient permissions and unknown deployment", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.UnknownDeployment()) + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sink and sufficient permissions and not deployed", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(&appsv1.Deployment{}) + return s + }(), + wantConditionStatus: corev1.ConditionUnknown, + want: false, + }, { + name: "mark sink and sufficient permissions and deployed", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + wantConditionStatus: corev1.ConditionTrue, + want: true, + }, { + name: "mark sink and not enough permissions", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkNoSufficientPermissions("areason", "amessage") + return s + }(), + wantConditionStatus: corev1.ConditionFalse, + want: false, + }} + + 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 TestApiServerSourceStatusGetCondition(t *testing.T) { + sink, _ := apis.ParseURL("uri://example") + + tests := []struct { + name string + s *ApiServerSourceStatus + condQuery apis.ConditionType + want *apis.Condition + }{{ + name: "uninitialized", + s: &ApiServerSourceStatus{}, + condQuery: ApiServerConditionReady, + want: nil, + }, { + name: "initialized", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + return s + }(), + condQuery: ApiServerConditionReady, + want: &apis.Condition{ + Type: ApiServerConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark deployed", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + condQuery: ApiServerConditionReady, + want: &apis.Condition{ + Type: ApiServerConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark sink", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + return s + }(), + condQuery: ApiServerConditionReady, + want: &apis.Condition{ + Type: ApiServerConditionReady, + Status: corev1.ConditionUnknown, + }, + }, { + name: "mark sink and enough permissions and deployed", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + condQuery: ApiServerConditionReady, + want: &apis.Condition{ + Type: ApiServerConditionReady, + Status: corev1.ConditionTrue, + }, + }, { + name: "mark sink and enough permissions and deployed and event types", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(sink) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + condQuery: ApiServerConditionReady, + want: &apis.Condition{ + Type: ApiServerConditionReady, + Status: corev1.ConditionTrue, + }, + }, { + name: "mark sink empty and enough permissions and deployed and event types", + s: func() *ApiServerSourceStatus { + s := &ApiServerSourceStatus{} + s.InitializeConditions() + s.MarkSink(nil) + s.MarkSufficientPermissions() + s.PropagateDeploymentAvailability(TestHelper.AvailableDeployment()) + return s + }(), + condQuery: ApiServerConditionReady, + want: &apis.Condition{ + Type: ApiServerConditionReady, + Status: corev1.ConditionFalse, + Reason: "SinkEmpty", + Message: "Sink has resolved to empty.", + }, + }} + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := test.s.GetCondition(test.condQuery) + ignoreTime := cmpopts.IgnoreFields(apis.Condition{}, + "LastTransitionTime", "Severity") + if diff := cmp.Diff(test.want, got, ignoreTime); diff != "" { + t.Errorf("unexpected condition (-want, +got) = %v", diff) + } + }) + } +} + +func TestApiServerSourceGetters(t *testing.T) { + r := &ApiServerSource{ + Spec: ApiServerSourceSpec{ + ServiceAccountName: "test", + EventMode: "test", + }, + } + if got, want := r.GetUntypedSpec(), r.Spec; !reflect.DeepEqual(got, want) { + t.Errorf("GetUntypedSpec() = %v, want: %v", got, want) + } +} diff --git a/pkg/apis/sources/v1beta1/apiserver_types.go b/pkg/apis/sources/v1beta1/apiserver_types.go new file mode 100644 index 00000000000..7e338903096 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_types.go @@ -0,0 +1,161 @@ +/* +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 v1beta1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +k8s:defaulter-gen=true + +// ApiServerSource is the Schema for the apiserversources API +type ApiServerSource struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ApiServerSourceSpec `json:"spec,omitempty"` + Status ApiServerSourceStatus `json:"status,omitempty"` +} + +// Check the interfaces that ApiServerSource should be implementing. +var ( + _ runtime.Object = (*ApiServerSource)(nil) + _ kmeta.OwnerRefable = (*ApiServerSource)(nil) + _ apis.Validatable = (*ApiServerSource)(nil) + _ apis.Defaultable = (*ApiServerSource)(nil) + _ apis.HasSpec = (*ApiServerSource)(nil) + _ duckv1.KRShaped = (*ApiServerSource)(nil) +) + +const ( + // ApiServerSourceAddEventType is the ApiServerSource CloudEvent type for adds. + ApiServerSourceAddEventType = "dev.knative.apiserver.resource.add" + // ApiServerSourceUpdateEventType is the ApiServerSource CloudEvent type for updates. + ApiServerSourceUpdateEventType = "dev.knative.apiserver.resource.update" + // ApiServerSourceDeleteEventType is the ApiServerSource CloudEvent type for deletions. + ApiServerSourceDeleteEventType = "dev.knative.apiserver.resource.delete" + + // ApiServerSourceAddRefEventType is the ApiServerSource CloudEvent type for ref adds. + ApiServerSourceAddRefEventType = "dev.knative.apiserver.ref.add" + // ApiServerSourceUpdateRefEventType is the ApiServerSource CloudEvent type for ref updates. + ApiServerSourceUpdateRefEventType = "dev.knative.apiserver.ref.update" + // ApiServerSourceDeleteRefEventType is the ApiServerSource CloudEvent type for ref deletions. + ApiServerSourceDeleteRefEventType = "dev.knative.apiserver.ref.delete" +) + +// ApiServerSourceEventTypes is the list of CloudEvent types the ApiServerSource emits. +var ApiServerSourceEventTypes = []string{ + ApiServerSourceAddEventType, + ApiServerSourceDeleteEventType, + ApiServerSourceUpdateEventType, + ApiServerSourceAddRefEventType, + ApiServerSourceDeleteRefEventType, + ApiServerSourceUpdateRefEventType, +} + +// ApiServerSourceSpec defines the desired state of ApiServerSource +type ApiServerSourceSpec 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"` + + // Resource are the resources this source will track and send related + // lifecycle events from the Kubernetes ApiServer, with an optional label + // selector to help filter. + // +required + Resources []APIVersionKindSelector `json:"resources,omitempty"` + + // ResourceOwner is an additional filter to only track resources that are + // owned by a specific resource type. If ResourceOwner matches Resources[n] + // then Resources[n] is allowed to pass the ResourceOwner filter. + // +optional + ResourceOwner *APIVersionKind `json:"owner,omitempty"` + + // EventMode controls the format of the event. + // `Reference` sends a dataref event type for the resource under watch. + // `Resource` send the full resource lifecycle event. + // Defaults to `Reference` + // +optional + EventMode string `json:"mode,omitempty"` + + // ServiceAccountName is the name of the ServiceAccount to use to run this + // source. Defaults to default if not set. + // +optional + ServiceAccountName string `json:"serviceAccountName,omitempty"` +} + +// ApiServerSourceStatus defines the observed state of ApiServerSource +type ApiServerSourceStatus 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"` +} + +// APIVersionKind is an APIVersion and Kind tuple. +type APIVersionKind struct { + // APIVersion - the API version of the resource to watch. + APIVersion string `json:"apiVersion"` + + // Kind of the resource to watch. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + Kind string `json:"kind"` +} + +// APIVersionKindSelector is an APIVersion Kind tuple with a LabelSelector. +type APIVersionKindSelector struct { + // APIVersion - the API version of the resource to watch. + APIVersion string `json:"apiVersion"` + + // Kind of the resource to watch. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + Kind string `json:"kind"` + + // LabelSelector filters this source to objects to those resources pass the + // label selector. + // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + // +optional + LabelSelector *metav1.LabelSelector `json:"selector,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ApiServerSourceList contains a list of ApiServerSource +type ApiServerSourceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ApiServerSource `json:"items"` +} + +// GetStatus retrieves the status of the ApiServerSource . Implements the KRShaped interface. +func (a *ApiServerSource) GetStatus() *duckv1.Status { + return &a.Status.Status +} diff --git a/pkg/apis/sources/v1beta1/apiserver_types_test.go b/pkg/apis/sources/v1beta1/apiserver_types_test.go new file mode 100644 index 00000000000..5ec67585b1f --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_types_test.go @@ -0,0 +1,36 @@ +/* +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 v1beta1 + +import "testing" + +func TestApiServerSource_GetStatus(t *testing.T) { + r := &ApiServerSource{ + Status: ApiServerSourceStatus{}, + } + if got, want := r.GetStatus(), &r.Status.Status; got != want { + t.Errorf("GetStatus=%v, want=%v", got, want) + } +} + +func TestApiServerSource_GetGroupVersionKind(t *testing.T) { + ass := ApiServerSource{} + gvk := ass.GetGroupVersionKind() + if gvk.Kind != "ApiServerSource" { + t.Errorf("Should be ApiServerSource.") + } +} diff --git a/pkg/apis/sources/v1beta1/apiserver_validation.go b/pkg/apis/sources/v1beta1/apiserver_validation.go new file mode 100644 index 00000000000..97cb1d35d82 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_validation.go @@ -0,0 +1,77 @@ +/* +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 v1beta1 + +import ( + "context" + "strings" + + "k8s.io/apimachinery/pkg/runtime/schema" + + "knative.dev/pkg/apis" +) + +const ( + // ReferenceMode produces payloads of ObjectReference + ReferenceMode = "Reference" + // ResourceMode produces payloads of ResourceEvent + ResourceMode = "Resource" +) + +func (c *ApiServerSource) Validate(ctx context.Context) *apis.FieldError { + return c.Spec.Validate(ctx).ViaField("spec") +} + +func (cs *ApiServerSourceSpec) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + + // Validate mode, if can be empty or set as certain value + switch cs.EventMode { + case ReferenceMode, ResourceMode: + // EventMode is valid. + default: + errs = errs.Also(apis.ErrInvalidValue(cs.EventMode, "mode")) + } + + // Validate sink + errs = errs.Also(cs.Sink.Validate(ctx).ViaField("sink")) + + if len(cs.Resources) == 0 { + errs = errs.Also(apis.ErrMissingField("resources")) + } + for i, res := range cs.Resources { + _, err := schema.ParseGroupVersion(res.APIVersion) + if err != nil { + errs = errs.Also(apis.ErrInvalidValue(res.APIVersion, "apiVersion").ViaFieldIndex("resources", i)) + } + if strings.TrimSpace(res.Kind) == "" { + errs = errs.Also(apis.ErrMissingField("kind").ViaFieldIndex("resources", i)) + } + } + + if cs.ResourceOwner != nil { + _, err := schema.ParseGroupVersion(cs.ResourceOwner.APIVersion) + if err != nil { + errs = errs.Also(apis.ErrInvalidValue(cs.ResourceOwner.APIVersion, "apiVersion").ViaField("owner")) + } + if strings.TrimSpace(cs.ResourceOwner.Kind) == "" { + errs = errs.Also(apis.ErrMissingField("kind").ViaField("owner")) + } + } + + return errs +} diff --git a/pkg/apis/sources/v1beta1/apiserver_validation_test.go b/pkg/apis/sources/v1beta1/apiserver_validation_test.go new file mode 100644 index 00000000000..03ed0bcb589 --- /dev/null +++ b/pkg/apis/sources/v1beta1/apiserver_validation_test.go @@ -0,0 +1,187 @@ +/* +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 v1beta1 + +import ( + "context" + "errors" + "testing" + + duckv1 "knative.dev/pkg/apis/duck/v1" + + "github.com/google/go-cmp/cmp" + "knative.dev/pkg/apis" +) + +func TestAPIServerValidation(t *testing.T) { + tests := []struct { + name string + spec ApiServerSourceSpec + want error + }{{ + name: "valid spec", + spec: ApiServerSourceSpec{ + EventMode: "Resource", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + want: nil, + }, { + name: "empty sink", + spec: ApiServerSourceSpec{ + EventMode: "Resource", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + errs = errs.Also(apis.ErrGeneric("expected at least one, got none", "ref", "uri").ViaField("sink")) + return errs + }(), + }, { + name: "invalid mode", + spec: ApiServerSourceSpec{ + EventMode: "Test", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Foo", + }}, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + want: func() *apis.FieldError { + var errs *apis.FieldError + errs = errs.Also(apis.ErrInvalidValue("Test", "mode")) + return errs + }(), + }, { + name: "invalid apiVersion", + spec: ApiServerSourceSpec{ + EventMode: "Resource", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1/v2/v3", + Kind: "Foo", + }}, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + want: errors.New("invalid value: v1/v2/v3: resources[0].apiVersion"), + }, { + name: "missing kind", + spec: ApiServerSourceSpec{ + EventMode: "Resource", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + }}, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + }, + want: errors.New("missing field(s): resources[0].kind"), + }, { + name: "owner - invalid apiVersion", + spec: ApiServerSourceSpec{ + EventMode: "Resource", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Bar", + }}, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + ResourceOwner: &APIVersionKind{ + APIVersion: "v1/v2/v3", + Kind: "Foo", + }, + }, + want: errors.New("invalid value: v1/v2/v3: owner.apiVersion"), + }, { + name: "missing kind", + spec: ApiServerSourceSpec{ + EventMode: "Resource", + Resources: []APIVersionKindSelector{{ + APIVersion: "v1", + Kind: "Bar", + }}, + SourceSpec: duckv1.SourceSpec{ + Sink: duckv1.Destination{ + Ref: &duckv1.KReference{ + APIVersion: "v1alpha1", + Kind: "broker", + Name: "default", + }, + }, + }, + ResourceOwner: &APIVersionKind{ + APIVersion: "v1", + }, + }, + want: errors.New("missing field(s): owner.kind"), + }} + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := test.spec.Validate(context.TODO()) + if test.want != nil { + if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { + t.Errorf("APIServerSourceSpec.Validate (-want, +got) = %v", diff) + } + } else if got != nil { + t.Errorf("APIServerSourceSpec.Validate wanted nil, got = %v", got.Error()) + } + }) + } +} diff --git a/pkg/apis/sources/v1beta1/implements_test.go b/pkg/apis/sources/v1beta1/implements_test.go index ec618cf26f1..9e9f8209e6a 100644 --- a/pkg/apis/sources/v1beta1/implements_test.go +++ b/pkg/apis/sources/v1beta1/implements_test.go @@ -35,6 +35,9 @@ func TestTypesImplements(t *testing.T) { {instance: &SinkBinding{}, iface: &duckv1.Conditions{}}, {instance: &SinkBinding{}, iface: &duckv1.Source{}}, {instance: &SinkBinding{}, iface: &duckv1beta1.Binding{}}, + // ApiServerSource + {instance: &ApiServerSource{}, iface: &duckv1.Conditions{}}, + {instance: &ApiServerSource{}, iface: &duckv1.Source{}}, } for _, tc := range testCases { if err := duck.VerifyType(tc.instance, tc.iface); err != nil { diff --git a/pkg/apis/sources/v1beta1/register.go b/pkg/apis/sources/v1beta1/register.go index a4f6c6009e9..2fdbf9ccc58 100644 --- a/pkg/apis/sources/v1beta1/register.go +++ b/pkg/apis/sources/v1beta1/register.go @@ -45,6 +45,8 @@ var ( // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, + &ApiServerSource{}, + &ApiServerSourceList{}, &SinkBinding{}, &SinkBindingList{}, &ContainerSource{}, diff --git a/pkg/apis/sources/v1beta1/register_test.go b/pkg/apis/sources/v1beta1/register_test.go index cda3500e823..7a5790f453a 100644 --- a/pkg/apis/sources/v1beta1/register_test.go +++ b/pkg/apis/sources/v1beta1/register_test.go @@ -60,6 +60,8 @@ func TestKnownTypes(t *testing.T) { types := scheme.KnownTypes(SchemeGroupVersion) for _, name := range []string{ + "ApiServerSource", + "ApiServerSourceList", "SinkBinding", "SinkBindingList", "ContainerSource", diff --git a/pkg/apis/sources/v1beta1/zz_generated.deepcopy.go b/pkg/apis/sources/v1beta1/zz_generated.deepcopy.go index 22fa2c6ae8c..74fd3d497f3 100644 --- a/pkg/apis/sources/v1beta1/zz_generated.deepcopy.go +++ b/pkg/apis/sources/v1beta1/zz_generated.deepcopy.go @@ -21,9 +21,154 @@ limitations under the License. package v1beta1 import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIVersionKind) DeepCopyInto(out *APIVersionKind) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIVersionKind. +func (in *APIVersionKind) DeepCopy() *APIVersionKind { + if in == nil { + return nil + } + out := new(APIVersionKind) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIVersionKindSelector) DeepCopyInto(out *APIVersionKindSelector) { + *out = *in + if in.LabelSelector != nil { + in, out := &in.LabelSelector, &out.LabelSelector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIVersionKindSelector. +func (in *APIVersionKindSelector) DeepCopy() *APIVersionKindSelector { + if in == nil { + return nil + } + out := new(APIVersionKindSelector) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApiServerSource) DeepCopyInto(out *ApiServerSource) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSource. +func (in *ApiServerSource) DeepCopy() *ApiServerSource { + if in == nil { + return nil + } + out := new(ApiServerSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ApiServerSource) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApiServerSourceList) DeepCopyInto(out *ApiServerSourceList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ApiServerSource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceList. +func (in *ApiServerSourceList) DeepCopy() *ApiServerSourceList { + if in == nil { + return nil + } + out := new(ApiServerSourceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ApiServerSourceList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApiServerSourceSpec) DeepCopyInto(out *ApiServerSourceSpec) { + *out = *in + in.SourceSpec.DeepCopyInto(&out.SourceSpec) + if in.Resources != nil { + in, out := &in.Resources, &out.Resources + *out = make([]APIVersionKindSelector, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ResourceOwner != nil { + in, out := &in.ResourceOwner, &out.ResourceOwner + *out = new(APIVersionKind) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceSpec. +func (in *ApiServerSourceSpec) DeepCopy() *ApiServerSourceSpec { + if in == nil { + return nil + } + out := new(ApiServerSourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ApiServerSourceStatus) DeepCopyInto(out *ApiServerSourceStatus) { + *out = *in + in.SourceStatus.DeepCopyInto(&out.SourceStatus) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceStatus. +func (in *ApiServerSourceStatus) DeepCopy() *ApiServerSourceStatus { + if in == nil { + return nil + } + out := new(ApiServerSourceStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ContainerSource) DeepCopyInto(out *ContainerSource) { *out = *in diff --git a/pkg/client/clientset/versioned/typed/sources/v1beta1/apiserversource.go b/pkg/client/clientset/versioned/typed/sources/v1beta1/apiserversource.go new file mode 100644 index 00000000000..929886e32d3 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/sources/v1beta1/apiserversource.go @@ -0,0 +1,191 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1beta1 "knative.dev/eventing/pkg/apis/sources/v1beta1" + scheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" +) + +// ApiServerSourcesGetter has a method to return a ApiServerSourceInterface. +// A group's client should implement this interface. +type ApiServerSourcesGetter interface { + ApiServerSources(namespace string) ApiServerSourceInterface +} + +// ApiServerSourceInterface has methods to work with ApiServerSource resources. +type ApiServerSourceInterface interface { + Create(*v1beta1.ApiServerSource) (*v1beta1.ApiServerSource, error) + Update(*v1beta1.ApiServerSource) (*v1beta1.ApiServerSource, error) + UpdateStatus(*v1beta1.ApiServerSource) (*v1beta1.ApiServerSource, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1beta1.ApiServerSource, error) + List(opts v1.ListOptions) (*v1beta1.ApiServerSourceList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.ApiServerSource, err error) + ApiServerSourceExpansion +} + +// apiServerSources implements ApiServerSourceInterface +type apiServerSources struct { + client rest.Interface + ns string +} + +// newApiServerSources returns a ApiServerSources +func newApiServerSources(c *SourcesV1beta1Client, namespace string) *apiServerSources { + return &apiServerSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the apiServerSource, and returns the corresponding apiServerSource object, and an error if there is any. +func (c *apiServerSources) Get(name string, options v1.GetOptions) (result *v1beta1.ApiServerSource, err error) { + result = &v1beta1.ApiServerSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("apiserversources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ApiServerSources that match those selectors. +func (c *apiServerSources) List(opts v1.ListOptions) (result *v1beta1.ApiServerSourceList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1beta1.ApiServerSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("apiserversources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested apiServerSources. +func (c *apiServerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("apiserversources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch() +} + +// Create takes the representation of a apiServerSource and creates it. Returns the server's representation of the apiServerSource, and an error, if there is any. +func (c *apiServerSources) Create(apiServerSource *v1beta1.ApiServerSource) (result *v1beta1.ApiServerSource, err error) { + result = &v1beta1.ApiServerSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("apiserversources"). + Body(apiServerSource). + Do(). + Into(result) + return +} + +// Update takes the representation of a apiServerSource and updates it. Returns the server's representation of the apiServerSource, and an error, if there is any. +func (c *apiServerSources) Update(apiServerSource *v1beta1.ApiServerSource) (result *v1beta1.ApiServerSource, err error) { + result = &v1beta1.ApiServerSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("apiserversources"). + Name(apiServerSource.Name). + Body(apiServerSource). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *apiServerSources) UpdateStatus(apiServerSource *v1beta1.ApiServerSource) (result *v1beta1.ApiServerSource, err error) { + result = &v1beta1.ApiServerSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("apiserversources"). + Name(apiServerSource.Name). + SubResource("status"). + Body(apiServerSource). + Do(). + Into(result) + return +} + +// Delete takes name of the apiServerSource and deletes it. Returns an error if one occurs. +func (c *apiServerSources) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("apiserversources"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *apiServerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("apiserversources"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched apiServerSource. +func (c *apiServerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.ApiServerSource, err error) { + result = &v1beta1.ApiServerSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("apiserversources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_apiserversource.go b/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_apiserversource.go new file mode 100644 index 00000000000..eebb4bda47b --- /dev/null +++ b/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_apiserversource.go @@ -0,0 +1,140 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + v1beta1 "knative.dev/eventing/pkg/apis/sources/v1beta1" +) + +// FakeApiServerSources implements ApiServerSourceInterface +type FakeApiServerSources struct { + Fake *FakeSourcesV1beta1 + ns string +} + +var apiserversourcesResource = schema.GroupVersionResource{Group: "sources.knative.dev", Version: "v1beta1", Resource: "apiserversources"} + +var apiserversourcesKind = schema.GroupVersionKind{Group: "sources.knative.dev", Version: "v1beta1", Kind: "ApiServerSource"} + +// Get takes name of the apiServerSource, and returns the corresponding apiServerSource object, and an error if there is any. +func (c *FakeApiServerSources) Get(name string, options v1.GetOptions) (result *v1beta1.ApiServerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(apiserversourcesResource, c.ns, name), &v1beta1.ApiServerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ApiServerSource), err +} + +// List takes label and field selectors, and returns the list of ApiServerSources that match those selectors. +func (c *FakeApiServerSources) List(opts v1.ListOptions) (result *v1beta1.ApiServerSourceList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(apiserversourcesResource, apiserversourcesKind, c.ns, opts), &v1beta1.ApiServerSourceList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1beta1.ApiServerSourceList{ListMeta: obj.(*v1beta1.ApiServerSourceList).ListMeta} + for _, item := range obj.(*v1beta1.ApiServerSourceList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested apiServerSources. +func (c *FakeApiServerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(apiserversourcesResource, c.ns, opts)) + +} + +// Create takes the representation of a apiServerSource and creates it. Returns the server's representation of the apiServerSource, and an error, if there is any. +func (c *FakeApiServerSources) Create(apiServerSource *v1beta1.ApiServerSource) (result *v1beta1.ApiServerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(apiserversourcesResource, c.ns, apiServerSource), &v1beta1.ApiServerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ApiServerSource), err +} + +// Update takes the representation of a apiServerSource and updates it. Returns the server's representation of the apiServerSource, and an error, if there is any. +func (c *FakeApiServerSources) Update(apiServerSource *v1beta1.ApiServerSource) (result *v1beta1.ApiServerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(apiserversourcesResource, c.ns, apiServerSource), &v1beta1.ApiServerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ApiServerSource), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeApiServerSources) UpdateStatus(apiServerSource *v1beta1.ApiServerSource) (*v1beta1.ApiServerSource, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(apiserversourcesResource, "status", c.ns, apiServerSource), &v1beta1.ApiServerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ApiServerSource), err +} + +// Delete takes name of the apiServerSource and deletes it. Returns an error if one occurs. +func (c *FakeApiServerSources) Delete(name string, options *v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(apiserversourcesResource, c.ns, name), &v1beta1.ApiServerSource{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeApiServerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(apiserversourcesResource, c.ns, listOptions) + + _, err := c.Fake.Invokes(action, &v1beta1.ApiServerSourceList{}) + return err +} + +// Patch applies the patch and returns the patched apiServerSource. +func (c *FakeApiServerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.ApiServerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(apiserversourcesResource, c.ns, name, pt, data, subresources...), &v1beta1.ApiServerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ApiServerSource), err +} diff --git a/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_sources_client.go b/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_sources_client.go index bcae6657420..9ea481b5db5 100644 --- a/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_sources_client.go +++ b/pkg/client/clientset/versioned/typed/sources/v1beta1/fake/fake_sources_client.go @@ -28,6 +28,10 @@ type FakeSourcesV1beta1 struct { *testing.Fake } +func (c *FakeSourcesV1beta1) ApiServerSources(namespace string) v1beta1.ApiServerSourceInterface { + return &FakeApiServerSources{c, namespace} +} + func (c *FakeSourcesV1beta1) ContainerSources(namespace string) v1beta1.ContainerSourceInterface { return &FakeContainerSources{c, namespace} } diff --git a/pkg/client/clientset/versioned/typed/sources/v1beta1/generated_expansion.go b/pkg/client/clientset/versioned/typed/sources/v1beta1/generated_expansion.go index 3f1743bd045..e42f4bcb3df 100644 --- a/pkg/client/clientset/versioned/typed/sources/v1beta1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/sources/v1beta1/generated_expansion.go @@ -18,6 +18,8 @@ limitations under the License. package v1beta1 +type ApiServerSourceExpansion interface{} + type ContainerSourceExpansion interface{} type SinkBindingExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/sources/v1beta1/sources_client.go b/pkg/client/clientset/versioned/typed/sources/v1beta1/sources_client.go index a38c2341a51..576f4d5b6cd 100644 --- a/pkg/client/clientset/versioned/typed/sources/v1beta1/sources_client.go +++ b/pkg/client/clientset/versioned/typed/sources/v1beta1/sources_client.go @@ -26,6 +26,7 @@ import ( type SourcesV1beta1Interface interface { RESTClient() rest.Interface + ApiServerSourcesGetter ContainerSourcesGetter SinkBindingsGetter } @@ -35,6 +36,10 @@ type SourcesV1beta1Client struct { restClient rest.Interface } +func (c *SourcesV1beta1Client) ApiServerSources(namespace string) ApiServerSourceInterface { + return newApiServerSources(c, namespace) +} + func (c *SourcesV1beta1Client) ContainerSources(namespace string) ContainerSourceInterface { return newContainerSources(c, namespace) } diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index dd7913ca0b5..e969775f8bc 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -126,6 +126,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1alpha2().SinkBindings().Informer()}, nil // Group=sources.knative.dev, Version=v1beta1 + case sourcesv1beta1.SchemeGroupVersion.WithResource("apiserversources"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1beta1().ApiServerSources().Informer()}, nil case sourcesv1beta1.SchemeGroupVersion.WithResource("containersources"): return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1beta1().ContainerSources().Informer()}, nil case sourcesv1beta1.SchemeGroupVersion.WithResource("sinkbindings"): diff --git a/pkg/client/informers/externalversions/sources/v1beta1/apiserversource.go b/pkg/client/informers/externalversions/sources/v1beta1/apiserversource.go new file mode 100644 index 00000000000..05e8febc2e4 --- /dev/null +++ b/pkg/client/informers/externalversions/sources/v1beta1/apiserversource.go @@ -0,0 +1,89 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + time "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" + sourcesv1beta1 "knative.dev/eventing/pkg/apis/sources/v1beta1" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/eventing/pkg/client/informers/externalversions/internalinterfaces" + v1beta1 "knative.dev/eventing/pkg/client/listers/sources/v1beta1" +) + +// ApiServerSourceInformer provides access to a shared informer and lister for +// ApiServerSources. +type ApiServerSourceInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1beta1.ApiServerSourceLister +} + +type apiServerSourceInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewApiServerSourceInformer constructs a new informer for ApiServerSource type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewApiServerSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredApiServerSourceInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredApiServerSourceInformer constructs a new informer for ApiServerSource type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredApiServerSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SourcesV1beta1().ApiServerSources(namespace).List(options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.SourcesV1beta1().ApiServerSources(namespace).Watch(options) + }, + }, + &sourcesv1beta1.ApiServerSource{}, + resyncPeriod, + indexers, + ) +} + +func (f *apiServerSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredApiServerSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *apiServerSourceInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&sourcesv1beta1.ApiServerSource{}, f.defaultInformer) +} + +func (f *apiServerSourceInformer) Lister() v1beta1.ApiServerSourceLister { + return v1beta1.NewApiServerSourceLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/sources/v1beta1/interface.go b/pkg/client/informers/externalversions/sources/v1beta1/interface.go index b6867f102b9..90247203d83 100644 --- a/pkg/client/informers/externalversions/sources/v1beta1/interface.go +++ b/pkg/client/informers/externalversions/sources/v1beta1/interface.go @@ -24,6 +24,8 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { + // ApiServerSources returns a ApiServerSourceInformer. + ApiServerSources() ApiServerSourceInformer // ContainerSources returns a ContainerSourceInformer. ContainerSources() ContainerSourceInformer // SinkBindings returns a SinkBindingInformer. @@ -41,6 +43,11 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// ApiServerSources returns a ApiServerSourceInformer. +func (v *version) ApiServerSources() ApiServerSourceInformer { + return &apiServerSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + // ContainerSources returns a ContainerSourceInformer. func (v *version) ContainerSources() ContainerSourceInformer { return &containerSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/pkg/client/injection/informers/sources/v1beta1/apiserversource/apiserversource.go b/pkg/client/injection/informers/sources/v1beta1/apiserversource/apiserversource.go new file mode 100644 index 00000000000..f39cd81053d --- /dev/null +++ b/pkg/client/injection/informers/sources/v1beta1/apiserversource/apiserversource.go @@ -0,0 +1,52 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package apiserversource + +import ( + context "context" + + v1beta1 "knative.dev/eventing/pkg/client/informers/externalversions/sources/v1beta1" + 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().V1beta1().ApiServerSources() + return context.WithValue(ctx, Key{}, inf), inf.Informer() +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context) v1beta1.ApiServerSourceInformer { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/eventing/pkg/client/informers/externalversions/sources/v1beta1.ApiServerSourceInformer from context.") + } + return untyped.(v1beta1.ApiServerSourceInformer) +} diff --git a/pkg/client/injection/informers/sources/v1beta1/apiserversource/fake/fake.go b/pkg/client/injection/informers/sources/v1beta1/apiserversource/fake/fake.go new file mode 100644 index 00000000000..cd678ab7200 --- /dev/null +++ b/pkg/client/injection/informers/sources/v1beta1/apiserversource/fake/fake.go @@ -0,0 +1,40 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package fake + +import ( + context "context" + + fake "knative.dev/eventing/pkg/client/injection/informers/factory/fake" + apiserversource "knative.dev/eventing/pkg/client/injection/informers/sources/v1beta1/apiserversource" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" +) + +var Get = apiserversource.Get + +func init() { + injection.Fake.RegisterInformer(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := fake.Get(ctx) + inf := f.Sources().V1beta1().ApiServerSources() + return context.WithValue(ctx, apiserversource.Key{}, inf), inf.Informer() +} diff --git a/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/controller.go b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/controller.go new file mode 100644 index 00000000000..5bf729d06ab --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/controller.go @@ -0,0 +1,142 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package apiserversource + +import ( + context "context" + fmt "fmt" + reflect "reflect" + strings "strings" + + 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" + apiserversource "knative.dev/eventing/pkg/client/injection/informers/sources/v1beta1/apiserversource" + kubeclient "knative.dev/pkg/client/injection/kube/client" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + reconciler "knative.dev/pkg/reconciler" +) + +const ( + defaultControllerAgentName = "apiserversource-controller" + defaultFinalizerName = "apiserversources.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 but 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.Fatalf("up to one options function is supported, found %d", len(optionsFns)) + } + + apiserversourceInformer := apiserversource.Get(ctx) + + lister := apiserversourceInformer.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, + } + + t := reflect.TypeOf(r).Elem() + queueName := fmt.Sprintf("%s.%s", strings.ReplaceAll(t.PkgPath(), "/", "-"), t.Name()) + + impl := controller.NewImpl(rec, logger, queueName) + 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 + } + } + + 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/v1beta1/apiserversource/reconciler.go b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/reconciler.go new file mode 100644 index 00000000000..02f4e325599 --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/reconciler.go @@ -0,0 +1,448 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package apiserversource + +import ( + context "context" + json "encoding/json" + fmt "fmt" + reflect "reflect" + + zap "go.uber.org/zap" + v1 "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" + cache "k8s.io/client-go/tools/cache" + record "k8s.io/client-go/tools/record" + v1beta1 "knative.dev/eventing/pkg/apis/sources/v1beta1" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + sourcesv1beta1 "knative.dev/eventing/pkg/client/listers/sources/v1beta1" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + reconciler "knative.dev/pkg/reconciler" +) + +// Interface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1beta1.ApiServerSource. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1beta1.ApiServerSource. 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 *v1beta1.ApiServerSource) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1beta1.ApiServerSource. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1beta1.ApiServerSource. 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 *v1beta1.ApiServerSource) reconciler.Event +} + +// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1beta1.ApiServerSource if they want to process resources for which +// they are not the leader. +type ReadOnlyInterface interface { + // ObserveKind implements logic to observe v1beta1.ApiServerSource. + // This method should not write to the API. + ObserveKind(ctx context.Context, o *v1beta1.ApiServerSource) reconciler.Event +} + +// ReadOnlyFinalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1beta1.ApiServerSource 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 v1beta1.ApiServerSource. + // This method should not write to the API. + ObserveFinalizeKind(ctx context.Context, o *v1beta1.ApiServerSource) reconciler.Event +} + +// reconcilerImpl implements controller.Reconciler for v1beta1.ApiServerSource 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 sourcesv1beta1.ApiServerSourceLister + + // 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 sourcesv1beta1.ApiServerSourceLister, 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.Fatalf("up to one options struct is supported, found %d", 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 + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // Convert the namespace/name string into a distinct namespace and name + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + logger.Errorf("invalid resource key: %s", key) + return nil + } + // Establish whether we are the leader for use below. + isLeader := r.IsLeaderFor(types.NamespacedName{ + Namespace: namespace, + Name: name, + }) + roi, isROI := r.reconciler.(ReadOnlyInterface) + rof, isROF := r.reconciler.(ReadOnlyFinalizer) + if !isLeader && !isROI && !isROF { + // If we are not the leader, and we don't implement either ReadOnly + // interface, then take a fast-path out. + return nil + } + + // 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.ApiServerSources(namespace) + + original, err := getter.Get(name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing. + logger.Debugf("resource %q no longer exists", key) + return nil + } else if err != nil { + return err + } + + // Don't modify the informers copy. + resource := original.DeepCopy() + + var reconcileEvent reconciler.Event + if resource.GetDeletionTimestamp().IsZero() { + if isLeader { + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", "ReconcileKind")) + + // 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) + } + + 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 = r.reconciler.ReconcileKind(ctx, resource) + + reconciler.PostProcessReconcile(ctx, resource, original) + + } else if isROI { + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", "ObserveKind")) + + // Observe any changes to this resource, since we are not the leader. + reconcileEvent = roi.ObserveKind(ctx, resource) + } + } else if fin, ok := r.reconciler.(Finalizer); isLeader && ok { + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", "FinalizeKind")) + + // For finalizing reconcilers, if this resource being marked for deletion + // and reconciled cleanly (nil or normal event), remove the finalizer. + reconcileEvent = fin.FinalizeKind(ctx, resource) + if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { + return fmt.Errorf("failed to clear finalizers: %w", err) + } + } else if !isLeader && isROF { + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", "ObserveFinalizeKind")) + + // For finalizing reconcilers, just observe when we aren't the leader. + reconcileEvent = rof.ObserveFinalizeKind(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 !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(original, resource); err != nil { + logger.Warnw("Failed to update resource status", zap.Error(err)) + r.Recorder.Eventf(resource, v1.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.Eventf(resource, event.EventType, event.Reason, event.Format, event.Args...) + + // 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, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) + return reconcileEvent + } + + return nil +} + +func (r *reconcilerImpl) updateStatus(existing *v1beta1.ApiServerSource, desired *v1beta1.ApiServerSource) 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.SourcesV1beta1().ApiServerSources(desired.Namespace) + + existing, err = getter.Get(desired.Name, metav1.GetOptions{}) + if err != nil { + return err + } + } + + // If there's nothing to update, just return. + if reflect.DeepEqual(existing.Status, desired.Status) { + return nil + } + + existing.Status = desired.Status + + updater := r.Client.SourcesV1beta1().ApiServerSources(existing.Namespace) + + _, err = updater.UpdateStatus(existing) + 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 *v1beta1.ApiServerSource) (*v1beta1.ApiServerSource, error) { + + getter := r.Lister.ApiServerSources(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.SourcesV1beta1().ApiServerSources(resource.Namespace) + + resourceName := resource.Name + resource, err = patcher.Patch(resourceName, types.MergePatchType, patch) + if err != nil { + r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resourceName, err) + } else { + r.Recorder.Eventf(resource, v1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return resource, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1beta1.ApiServerSource) (*v1beta1.ApiServerSource, 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 *v1beta1.ApiServerSource, reconcileEvent reconciler.Event) (*v1beta1.ApiServerSource, 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 == v1.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/v1beta1/apiserversource/stub/controller.go b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/stub/controller.go new file mode 100644 index 00000000000..530527250d9 --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/stub/controller.go @@ -0,0 +1,54 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package apiserversource + +import ( + context "context" + + apiserversource "knative.dev/eventing/pkg/client/injection/informers/sources/v1beta1/apiserversource" + v1beta1apiserversource "knative.dev/eventing/pkg/client/injection/reconciler/sources/v1beta1/apiserversource" + configmap "knative.dev/pkg/configmap" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" +) + +// TODO: PLEASE COPY AND MODIFY THIS FILE AS A STARTING POINT + +// NewController creates a Reconciler for ApiServerSource and returns the result of NewImpl. +func NewController( + ctx context.Context, + cmw configmap.Watcher, +) *controller.Impl { + logger := logging.FromContext(ctx) + + apiserversourceInformer := apiserversource.Get(ctx) + + // TODO: setup additional informers here. + + r := &Reconciler{} + impl := v1beta1apiserversource.NewImpl(ctx, r) + + logger.Info("Setting up event handlers.") + + apiserversourceInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)) + + // TODO: add additional informer event handlers here. + + return impl +} diff --git a/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/stub/reconciler.go b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/stub/reconciler.go new file mode 100644 index 00000000000..78aa620a8de --- /dev/null +++ b/pkg/client/injection/reconciler/sources/v1beta1/apiserversource/stub/reconciler.go @@ -0,0 +1,87 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package apiserversource + +import ( + context "context" + + v1 "k8s.io/api/core/v1" + v1beta1 "knative.dev/eventing/pkg/apis/sources/v1beta1" + apiserversource "knative.dev/eventing/pkg/client/injection/reconciler/sources/v1beta1/apiserversource" + reconciler "knative.dev/pkg/reconciler" +) + +// TODO: PLEASE COPY AND MODIFY THIS FILE AS A STARTING POINT + +// newReconciledNormal makes a new reconciler event with event type Normal, and +// reason ApiServerSourceReconciled. +func newReconciledNormal(namespace, name string) reconciler.Event { + return reconciler.NewEvent(v1.EventTypeNormal, "ApiServerSourceReconciled", "ApiServerSource reconciled: \"%s/%s\"", namespace, name) +} + +// Reconciler implements controller.Reconciler for ApiServerSource resources. +type Reconciler struct { + // TODO: add additional requirements here. +} + +// Check that our Reconciler implements Interface +var _ apiserversource.Interface = (*Reconciler)(nil) + +// Optionally check that our Reconciler implements Finalizer +//var _ apiserversource.Finalizer = (*Reconciler)(nil) + +// Optionally check that our Reconciler implements ReadOnlyInterface +// Implement this to observe resources even when we are not the leader. +//var _ apiserversource.ReadOnlyInterface = (*Reconciler)(nil) + +// Optionally check that our Reconciler implements ReadOnlyFinalizer +// Implement this to observe tombstoned resources even when we are not +// the leader (best effort). +//var _ apiserversource.ReadOnlyFinalizer = (*Reconciler)(nil) + +// ReconcileKind implements Interface.ReconcileKind. +func (r *Reconciler) ReconcileKind(ctx context.Context, o *v1beta1.ApiServerSource) reconciler.Event { + // TODO: use this if the resource implements InitializeConditions. + // o.Status.InitializeConditions() + + // TODO: add custom reconciliation logic here. + + // TODO: use this if the object has .status.ObservedGeneration. + // o.Status.ObservedGeneration = o.Generation + return newReconciledNormal(o.Namespace, o.Name) +} + +// Optionally, use FinalizeKind to add finalizers. FinalizeKind will be called +// when the resource is deleted. +//func (r *Reconciler) FinalizeKind(ctx context.Context, o *v1beta1.ApiServerSource) reconciler.Event { +// // TODO: add custom finalization logic here. +// return nil +//} + +// Optionally, use ObserveKind to observe the resource when we are not the leader. +// func (r *Reconciler) ObserveKind(ctx context.Context, o *v1beta1.ApiServerSource) reconciler.Event { +// // TODO: add custom observation logic here. +// return nil +// } + +// Optionally, use ObserveFinalizeKind to observe resources being finalized when we are no the leader. +//func (r *Reconciler) ObserveFinalizeKind(ctx context.Context, o *v1beta1.ApiServerSource) reconciler.Event { +// // TODO: add custom observation logic here. +// return nil +//} diff --git a/pkg/client/listers/sources/v1beta1/apiserversource.go b/pkg/client/listers/sources/v1beta1/apiserversource.go new file mode 100644 index 00000000000..1366b46db35 --- /dev/null +++ b/pkg/client/listers/sources/v1beta1/apiserversource.go @@ -0,0 +1,94 @@ +/* +Copyright 2020 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta1 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1beta1 "knative.dev/eventing/pkg/apis/sources/v1beta1" +) + +// ApiServerSourceLister helps list ApiServerSources. +type ApiServerSourceLister interface { + // List lists all ApiServerSources in the indexer. + List(selector labels.Selector) (ret []*v1beta1.ApiServerSource, err error) + // ApiServerSources returns an object that can list and get ApiServerSources. + ApiServerSources(namespace string) ApiServerSourceNamespaceLister + ApiServerSourceListerExpansion +} + +// apiServerSourceLister implements the ApiServerSourceLister interface. +type apiServerSourceLister struct { + indexer cache.Indexer +} + +// NewApiServerSourceLister returns a new ApiServerSourceLister. +func NewApiServerSourceLister(indexer cache.Indexer) ApiServerSourceLister { + return &apiServerSourceLister{indexer: indexer} +} + +// List lists all ApiServerSources in the indexer. +func (s *apiServerSourceLister) List(selector labels.Selector) (ret []*v1beta1.ApiServerSource, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta1.ApiServerSource)) + }) + return ret, err +} + +// ApiServerSources returns an object that can list and get ApiServerSources. +func (s *apiServerSourceLister) ApiServerSources(namespace string) ApiServerSourceNamespaceLister { + return apiServerSourceNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// ApiServerSourceNamespaceLister helps list and get ApiServerSources. +type ApiServerSourceNamespaceLister interface { + // List lists all ApiServerSources in the indexer for a given namespace. + List(selector labels.Selector) (ret []*v1beta1.ApiServerSource, err error) + // Get retrieves the ApiServerSource from the indexer for a given namespace and name. + Get(name string) (*v1beta1.ApiServerSource, error) + ApiServerSourceNamespaceListerExpansion +} + +// apiServerSourceNamespaceLister implements the ApiServerSourceNamespaceLister +// interface. +type apiServerSourceNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all ApiServerSources in the indexer for a given namespace. +func (s apiServerSourceNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ApiServerSource, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta1.ApiServerSource)) + }) + return ret, err +} + +// Get retrieves the ApiServerSource from the indexer for a given namespace and name. +func (s apiServerSourceNamespaceLister) Get(name string) (*v1beta1.ApiServerSource, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1beta1.Resource("apiserversource"), name) + } + return obj.(*v1beta1.ApiServerSource), nil +} diff --git a/pkg/client/listers/sources/v1beta1/expansion_generated.go b/pkg/client/listers/sources/v1beta1/expansion_generated.go index d1e6b925954..f36739de82b 100644 --- a/pkg/client/listers/sources/v1beta1/expansion_generated.go +++ b/pkg/client/listers/sources/v1beta1/expansion_generated.go @@ -18,6 +18,14 @@ limitations under the License. package v1beta1 +// ApiServerSourceListerExpansion allows custom methods to be added to +// ApiServerSourceLister. +type ApiServerSourceListerExpansion interface{} + +// ApiServerSourceNamespaceListerExpansion allows custom methods to be added to +// ApiServerSourceNamespaceLister. +type ApiServerSourceNamespaceListerExpansion interface{} + // ContainerSourceListerExpansion allows custom methods to be added to // ContainerSourceLister. type ContainerSourceListerExpansion interface{}