diff --git a/docs/eventing-api.md b/docs/eventing-api.md index f4504edb0c1..44a6731e096 100644 --- a/docs/eventing-api.md +++ b/docs/eventing-api.md @@ -16,6 +16,9 @@ eventing.knative.dev/v1beta1
+
Package v1beta2 is the v1beta2 version of the API.
+ +Resource Types: ++
EventType represents a type of event that can be consumed from a Broker.
+ +Field | +Description | +||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+apiVersion +string |
+
+
+eventing.knative.dev/v1beta2
+
+ |
+||||||||||||
+kind +string + |
+EventType |
+||||||||||||
+metadata + + +Kubernetes meta/v1.ObjectMeta + + + |
+
+(Optional)
+Refer to the Kubernetes API documentation for the fields of the
+metadata field.
+ |
+||||||||||||
+spec + + +EventTypeSpec + + + |
+
+ Spec defines the desired state of the EventType. ++ +
|
+||||||||||||
+status + + +EventTypeStatus + + + |
+
+(Optional)
+ Status represents the current state of the EventType. +This data may be out of date. +TODO might be removed https://github.com/knative/eventing/issues/2750 + |
+
+(Appears on:EventType) +
++
+Field | +Description | +
---|---|
+type + +string + + |
+
+ Type represents the CloudEvents type. It is authoritative. + |
+
+source + + +knative.dev/pkg/apis.URL + + + |
+
+(Optional)
+ Source is a URI, it represents the CloudEvents source. + |
+
+schema + + +knative.dev/pkg/apis.URL + + + |
+
+(Optional)
+ Schema is a URI, it represents the CloudEvents schemaurl extension attribute. +It may be a JSON schema, a protobuf schema, etc. It is optional. + |
+
+schemaData + +string + + |
+
+(Optional)
+ SchemaData allows the CloudEvents schema to be stored directly in the +EventType. Content is dependent on the encoding. Optional attribute. +The contents are not validated or manipulated by the system. + |
+
+broker + +string + + |
+
+(Optional)
+ TODO remove https://github.com/knative/eventing/issues/2750 +Broker refers to the Broker that can provide the EventType. + |
+
+description + +string + + |
+
+(Optional)
+ Description is an optional field used to describe the EventType, in any meaningful way. + |
+
+(Appears on:EventType) +
++
EventTypeStatus represents the current state of a EventType.
+ +Field | +Description | +
---|---|
+Status + + +knative.dev/pkg/apis/duck/v1.Status + + + |
+
+
+(Members of inherits duck/v1 Status, which currently provides: +* ObservedGeneration - the ‘Generation’ of the Service that was last processed by the controller. +* Conditions - the latest available observations of a resource’s current state. + |
+
Package v1 is the v1 version of the API.
diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index 706a5974f03..c47dffe3ad0 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -38,7 +38,7 @@ group "Kubernetes Codegen" # instead of the $GOPATH directly. For normal projects this can be dropped. ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ knative.dev/eventing/pkg/client knative.dev/eventing/pkg/apis \ - "eventing:v1beta1 eventing:v1 messaging:v1 flows:v1 sources:v1beta2 sources:v1" \ + "eventing:v1beta1 eventing:v1beta2 eventing:v1 messaging:v1 flows:v1 sources:v1beta2 sources:v1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt # Deep copy config @@ -59,7 +59,7 @@ group "Knative Codegen" # Knative Injection ${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \ knative.dev/eventing/pkg/client knative.dev/eventing/pkg/apis \ - "eventing:v1beta1 eventing:v1 messaging:v1 flows:v1 sources:v1beta2 sources:v1 duck:v1beta1 duck:v1" \ + "eventing:v1beta1 eventing:v1beta2 eventing:v1 messaging:v1 flows:v1 sources:v1beta2 sources:v1 duck:v1beta1 duck:v1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt group "Generating API reference docs" diff --git a/pkg/apis/eventing/v1beta2/doc.go b/pkg/apis/eventing/v1beta2/doc.go new file mode 100644 index 00000000000..115faf55b37 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package v1beta2 is the v1beta2 version of the API. +// +k8s:deepcopy-gen=package +// +groupName=eventing.knative.dev +package v1beta2 diff --git a/pkg/apis/eventing/v1beta2/eventtype_conversion.go b/pkg/apis/eventing/v1beta2/eventtype_conversion.go new file mode 100644 index 00000000000..2bdd421a5c2 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_conversion.go @@ -0,0 +1,34 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +// ConvertTo implements apis.Convertible +func (source *EventType) ConvertTo(ctx context.Context, to apis.Convertible) error { + return fmt.Errorf("v1beta2 is the highest known version, got: %T", to) +} + +// ConvertFrom implements apis.Convertible +func (sink *EventType) ConvertFrom(ctx context.Context, from apis.Convertible) error { + return fmt.Errorf("v1beta2 is the highest known version, got: %T", from) +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_conversion_test.go b/pkg/apis/eventing/v1beta2/eventtype_conversion_test.go new file mode 100644 index 00000000000..a19802b478e --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_conversion_test.go @@ -0,0 +1,34 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "context" + "testing" +) + +func TestEventTypeConversionHighestVersion(t *testing.T) { + good, bad := &EventType{}, &EventType{} + + 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/eventing/v1beta2/eventtype_defaults.go b/pkg/apis/eventing/v1beta2/eventtype_defaults.go new file mode 100644 index 00000000000..67ae41c8854 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_defaults.go @@ -0,0 +1,29 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import "context" + +func (et *EventType) SetDefaults(ctx context.Context) { + et.Spec.SetDefaults(ctx) +} + +func (ets *EventTypeSpec) SetDefaults(ctx context.Context) { + if ets.Broker == "" { + ets.Broker = "default" + } +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_defaults_test.go b/pkg/apis/eventing/v1beta2/eventtype_defaults_test.go new file mode 100644 index 00000000000..41496fc2901 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_defaults_test.go @@ -0,0 +1,87 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + + "knative.dev/pkg/apis" +) + +func TestEventTypeDefaults(t *testing.T) { + testSource := apis.HTTP("test-source") + testSchema := apis.HTTP("test-schema") + testCases := map[string]struct { + initial EventType + expected EventType + }{ + "nil spec": { + initial: EventType{}, + expected: EventType{ + Spec: EventTypeSpec{ + Broker: "default", + }, + }, + }, + "broker empty": { + initial: EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "", + Schema: testSchema, + }, + }, + expected: EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "default", + Schema: testSchema, + }, + }, + }, + "broker not set": { + initial: EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Schema: testSchema, + }, + }, + expected: EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "default", + Schema: testSchema, + }, + }, + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + tc.initial.SetDefaults(context.TODO()) + if diff := cmp.Diff(tc.expected, tc.initial); diff != "" { + t.Fatal("Unexpected defaults (-want, +got):", diff) + } + }) + } +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_lifecycle.go b/pkg/apis/eventing/v1beta2/eventtype_lifecycle.go new file mode 100644 index 00000000000..a8e1bfe8460 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_lifecycle.go @@ -0,0 +1,104 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + corev1 "k8s.io/api/core/v1" + + eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" + "knative.dev/pkg/apis" +) + +var eventTypeCondSet = apis.NewLivingConditionSet(EventTypeConditionBrokerExists, EventTypeConditionBrokerReady) + +const ( + EventTypeConditionReady = apis.ConditionReady + EventTypeConditionBrokerExists apis.ConditionType = "BrokerExists" + EventTypeConditionBrokerReady apis.ConditionType = "BrokerReady" +) + +// GetConditionSet retrieves the condition set for this resource. Implements the KRShaped interface. +func (*EventType) GetConditionSet() apis.ConditionSet { + return eventTypeCondSet +} + +// GetCondition returns the condition currently associated with the given type, or nil. +func (et *EventTypeStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return eventTypeCondSet.Manage(et).GetCondition(t) +} + +// IsReady returns true if the resource is ready overall. +func (et *EventTypeStatus) IsReady() bool { + return eventTypeCondSet.Manage(et).IsHappy() +} + +// GetTopLevelCondition returns the top level Condition. +func (et *EventTypeStatus) GetTopLevelCondition() *apis.Condition { + return eventTypeCondSet.Manage(et).GetTopLevelCondition() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (et *EventTypeStatus) InitializeConditions() { + eventTypeCondSet.Manage(et).InitializeConditions() +} + +func (et *EventTypeStatus) MarkBrokerExists() { + eventTypeCondSet.Manage(et).MarkTrue(EventTypeConditionBrokerExists) +} + +func (et *EventTypeStatus) MarkBrokerDoesNotExist() { + eventTypeCondSet.Manage(et).MarkFalse(EventTypeConditionBrokerExists, "BrokerDoesNotExist", "Broker does not exist") +} + +func (et *EventTypeStatus) MarkBrokerExistsUnknown(reason, messageFormat string, messageA ...interface{}) { + eventTypeCondSet.Manage(et).MarkUnknown(EventTypeConditionBrokerExists, reason, messageFormat, messageA...) +} + +func (et *EventTypeStatus) MarkBrokerReady() { + eventTypeCondSet.Manage(et).MarkTrue(EventTypeConditionBrokerReady) +} + +func (et *EventTypeStatus) MarkBrokerFailed(reason, messageFormat string, messageA ...interface{}) { + eventTypeCondSet.Manage(et).MarkFalse(EventTypeConditionBrokerReady, reason, messageFormat, messageA...) +} + +func (et *EventTypeStatus) MarkBrokerUnknown(reason, messageFormat string, messageA ...interface{}) { + eventTypeCondSet.Manage(et).MarkUnknown(EventTypeConditionBrokerReady, reason, messageFormat, messageA...) +} + +func (et *EventTypeStatus) MarkBrokerNotConfigured() { + eventTypeCondSet.Manage(et).MarkUnknown(EventTypeConditionBrokerReady, + "BrokerNotConfigured", "Broker has not yet been reconciled.") +} + +func (et *EventTypeStatus) PropagateBrokerStatus(bs *eventingv1.BrokerStatus) { + bc := bs.GetConditionSet().Manage(bs).GetTopLevelCondition() + if bc == nil { + et.MarkBrokerNotConfigured() + return + } + switch { + case bc.Status == corev1.ConditionUnknown: + et.MarkBrokerUnknown(bc.Reason, bc.Message) + case bc.Status == corev1.ConditionTrue: + eventTypeCondSet.Manage(et).MarkTrue(EventTypeConditionBrokerReady) + case bc.Status == corev1.ConditionFalse: + et.MarkBrokerFailed(bc.Reason, bc.Message) + default: + et.MarkBrokerUnknown("BrokerUnknown", "The status of Broker is invalid: %v", bc.Status) + } +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_lifecycle_test.go b/pkg/apis/eventing/v1beta2/eventtype_lifecycle_test.go new file mode 100644 index 00000000000..9775ecb0176 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_lifecycle_test.go @@ -0,0 +1,267 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + + corev1 "k8s.io/api/core/v1" + eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +var ( + trueValue = true + falseValue = false + + eventTypeConditionReady = apis.Condition{ + Type: EventTypeConditionReady, + Status: corev1.ConditionTrue, + } + + eventTypeConditionBrokerExists = apis.Condition{ + Type: EventTypeConditionBrokerExists, + Status: corev1.ConditionTrue, + } + + eventTypeConditionBrokerReady = apis.Condition{ + Type: EventTypeConditionBrokerReady, + Status: corev1.ConditionTrue, + } + + ignoreAllButTypeAndStatus = cmpopts.IgnoreFields( + apis.Condition{}, + "LastTransitionTime", "Message", "Reason", "Severity") +) + +func TestEventTypeGetConditionSet(t *testing.T) { + r := &EventType{} + + if got, want := r.GetConditionSet().GetTopLevelConditionType(), apis.ConditionReady; got != want { + t.Errorf("GetTopLevelCondition=%v, want=%v", got, want) + } +} + +func TestEventTypeGetCondition(t *testing.T) { + tests := []struct { + name string + ets *EventTypeStatus + condQuery apis.ConditionType + want *apis.Condition + }{{ + name: "single condition", + ets: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{ + eventTypeConditionReady, + }, + }, + }, + condQuery: apis.ConditionReady, + want: &eventTypeConditionReady, + }, { + name: "broker exists condition", + ets: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{ + eventTypeConditionBrokerExists, + }, + }, + }, + condQuery: EventTypeConditionBrokerExists, + want: &eventTypeConditionBrokerExists, + }, { + name: "multiple conditions, condition true", + ets: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{ + eventTypeConditionBrokerExists, + eventTypeConditionBrokerReady, + }, + }, + }, + condQuery: EventTypeConditionBrokerReady, + want: &eventTypeConditionBrokerReady, + }, { + name: "unknown condition", + ets: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{ + eventTypeConditionBrokerReady, + eventTypeConditionReady, + }, + }, + }, + condQuery: apis.ConditionType("foo"), + want: nil, + }} + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := test.ets.GetCondition(test.condQuery) + if diff := cmp.Diff(test.want, got); diff != "" { + t.Error("unexpected condition (-want, +got) =", diff) + } + }) + } +} + +func TestEventTypeInitializeConditions(t *testing.T) { + tests := []struct { + name string + ets *EventTypeStatus + want *EventTypeStatus + }{{ + name: "empty", + ets: &EventTypeStatus{}, + want: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{{ + Type: EventTypeConditionBrokerExists, + Status: corev1.ConditionUnknown, + }, { + Type: EventTypeConditionBrokerReady, + Status: corev1.ConditionUnknown, + }, { + Type: EventTypeConditionReady, + Status: corev1.ConditionUnknown, + }, + }, + }, + }, + }, { + name: "one false", + ets: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{{ + Type: EventTypeConditionBrokerExists, + Status: corev1.ConditionFalse, + }}, + }, + }, + want: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{{ + Type: EventTypeConditionBrokerExists, + Status: corev1.ConditionFalse, + }, { + Type: EventTypeConditionBrokerReady, + Status: corev1.ConditionUnknown, + }, { + Type: EventTypeConditionReady, + Status: corev1.ConditionUnknown, + }}, + }, + }, + }, { + name: "one true", + ets: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{{ + Type: EventTypeConditionBrokerReady, + Status: corev1.ConditionTrue, + }}, + }, + }, + want: &EventTypeStatus{ + Status: duckv1.Status{ + Conditions: []apis.Condition{{ + Type: EventTypeConditionBrokerExists, + Status: corev1.ConditionUnknown, + }, { + Type: EventTypeConditionBrokerReady, + Status: corev1.ConditionTrue, + }, { + Type: EventTypeConditionReady, + Status: corev1.ConditionUnknown, + }}, + }, + }}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + test.ets.InitializeConditions() + if diff := cmp.Diff(test.want, test.ets, ignoreAllButTypeAndStatus); diff != "" { + t.Error("unexpected conditions (-want, +got) =", diff) + } + }) + } +} + +func TestEventTypeConditionStatus(t *testing.T) { + tests := []struct { + name string + markBrokerExists *bool + brokerStatus *eventingv1.BrokerStatus + wantConditionStatus corev1.ConditionStatus + }{{ + name: "all happy", + markBrokerExists: &trueValue, + brokerStatus: eventingv1.TestHelper.ReadyBrokerStatus(), + wantConditionStatus: corev1.ConditionTrue, + }, { + name: "all happy, dls not configured", + markBrokerExists: &trueValue, + brokerStatus: eventingv1.TestHelper.ReadyBrokerStatusWithoutDLS(), + wantConditionStatus: corev1.ConditionTrue, + }, { + name: "broker exist sad", + markBrokerExists: &falseValue, + brokerStatus: nil, + wantConditionStatus: corev1.ConditionFalse, + }, { + name: "broker ready sad", + markBrokerExists: &trueValue, + brokerStatus: eventingv1.TestHelper.FalseBrokerStatus(), + wantConditionStatus: corev1.ConditionFalse, + }, { + name: "broker ready unknown", + markBrokerExists: &trueValue, + brokerStatus: eventingv1.TestHelper.UnknownBrokerStatus(), + wantConditionStatus: corev1.ConditionUnknown, + }, { + name: "all sad", + markBrokerExists: &falseValue, + brokerStatus: nil, + wantConditionStatus: corev1.ConditionFalse, + }} + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ets := &EventTypeStatus{} + if test.markBrokerExists != nil { + if *test.markBrokerExists { + ets.MarkBrokerExists() + } else { + ets.MarkBrokerDoesNotExist() + } + } + if test.brokerStatus != nil { + ets.PropagateBrokerStatus(test.brokerStatus) + } + + got := ets.GetTopLevelCondition().Status + if test.wantConditionStatus != got { + t.Errorf("unexpected readiness: want %v, got %v", test.wantConditionStatus, got) + } + }) + } +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_types.go b/pkg/apis/eventing/v1beta2/eventtype_types.go new file mode 100644 index 00000000000..e182e2d8134 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_types.go @@ -0,0 +1,120 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + "knative.dev/pkg/kmeta" +) + +// +genclient +// +genreconciler +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// EventType represents a type of event that can be consumed from a Broker. +type EventType struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec defines the desired state of the EventType. + Spec EventTypeSpec `json:"spec,omitempty"` + + // Status represents the current state of the EventType. + // This data may be out of date. + // +optional + // TODO might be removed https://github.com/knative/eventing/issues/2750 + Status EventTypeStatus `json:"status,omitempty"` +} + +var ( + // Check that EventType can be validated, can be defaulted, and has immutable fields. + _ apis.Validatable = (*EventType)(nil) + _ apis.Defaultable = (*EventType)(nil) + + // Check that EventType can return its spec untyped. + _ apis.HasSpec = (*EventType)(nil) + + _ runtime.Object = (*EventType)(nil) + + // Check that we can create OwnerReferences to an EventType. + _ kmeta.OwnerRefable = (*EventType)(nil) + + // Check that the type conforms to the duck Knative Resource shape. + _ duckv1.KRShaped = (*EventType)(nil) +) + +type EventTypeSpec struct { + // Type represents the CloudEvents type. It is authoritative. + Type string `json:"type"` + // Source is a URI, it represents the CloudEvents source. + // +optional + Source *apis.URL `json:"source,omitempty"` + // Schema is a URI, it represents the CloudEvents schemaurl extension attribute. + // It may be a JSON schema, a protobuf schema, etc. It is optional. + // +optional + Schema *apis.URL `json:"schema,omitempty"` + // SchemaData allows the CloudEvents schema to be stored directly in the + // EventType. Content is dependent on the encoding. Optional attribute. + // The contents are not validated or manipulated by the system. + // +optional + SchemaData string `json:"schemaData,omitempty"` + // TODO remove https://github.com/knative/eventing/issues/2750 + // Broker refers to the Broker that can provide the EventType. + // +optional + Broker string `json:"broker,omitempty"` + // Description is an optional field used to describe the EventType, in any meaningful way. + // +optional + Description string `json:"description,omitempty"` +} + +// EventTypeStatus represents the current state of a EventType. +type EventTypeStatus struct { + // inherits duck/v1 Status, which currently provides: + // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. + // * Conditions - the latest available observations of a resource's current state. + duckv1.Status `json:",inline"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// EventTypeList is a collection of EventTypes. +type EventTypeList struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + Items []EventType `json:"items"` +} + +// GetGroupVersionKind returns GroupVersionKind for EventType +func (p *EventType) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("EventType") +} + +// GetUntypedSpec returns the spec of the EventType. +func (e *EventType) GetUntypedSpec() interface{} { + return e.Spec +} + +// GetStatus retrieves the status of the EventType. Implements the KRShaped interface. +func (t *EventType) GetStatus() *duckv1.Status { + return &t.Status.Status +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_types_test.go b/pkg/apis/eventing/v1beta2/eventtype_types_test.go new file mode 100644 index 00000000000..56e4a416877 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_types_test.go @@ -0,0 +1,39 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "testing" +) + +func TestEventTypeGetStatus(t *testing.T) { + r := &EventType{ + Status: EventTypeStatus{}, + } + if got, want := r.GetStatus(), &r.Status.Status; got != want { + t.Errorf("GetStatus=%v, want=%v", got, want) + } +} + +func TestEventType_GetGroupVersionKind(t *testing.T) { + src := EventType{} + gvk := src.GetGroupVersionKind() + + if gvk.Kind != "EventType" { + t.Errorf("Should be EventType.") + } +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_validation.go b/pkg/apis/eventing/v1beta2/eventtype_validation.go new file mode 100644 index 00000000000..5e610aad936 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_validation.go @@ -0,0 +1,62 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "context" + + "knative.dev/pkg/apis" + "knative.dev/pkg/kmp" +) + +func (et *EventType) Validate(ctx context.Context) *apis.FieldError { + return et.Spec.Validate(ctx).ViaField("spec") +} + +func (ets *EventTypeSpec) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if ets.Type == "" { + fe := apis.ErrMissingField("type") + errs = errs.Also(fe) + } + // TODO validate Source is a valid URI. + // TODO validate Schema is a valid URI. + // There is no validation of the SchemaData, it is application specific data. + return errs +} + +func (et *EventType) CheckImmutableFields(ctx context.Context, original *EventType) *apis.FieldError { + if original == nil { + return nil + } + + // All fields are immutable. + if diff, err := kmp.ShortDiff(original.Spec, et.Spec); err != nil { + return &apis.FieldError{ + Message: "Failed to diff EventType", + Paths: []string{"spec"}, + Details: err.Error(), + } + } else if diff != "" { + return &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: diff, + } + } + return nil +} diff --git a/pkg/apis/eventing/v1beta2/eventtype_validation_test.go b/pkg/apis/eventing/v1beta2/eventtype_validation_test.go new file mode 100644 index 00000000000..03c5d7f889f --- /dev/null +++ b/pkg/apis/eventing/v1beta2/eventtype_validation_test.go @@ -0,0 +1,258 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "knative.dev/pkg/apis" +) + +func TestEventTypeValidation(t *testing.T) { + name := "invalid type" + et := &EventType{Spec: EventTypeSpec{}} + + want := &apis.FieldError{ + Paths: []string{"spec.type"}, + Message: "missing field(s)", + } + + t.Run(name, func(t *testing.T) { + got := et.Validate(context.TODO()) + if diff := cmp.Diff(want.Error(), got.Error()); diff != "" { + t.Error("EventType.Validate (-want, +got) =", diff) + } + }) +} + +func TestEventTypeSpecValidation(t *testing.T) { + testSource := apis.HTTP("test-source") + tests := []struct { + name string + ets *EventTypeSpec + want *apis.FieldError + }{{ + name: "invalid eventtype type", + ets: &EventTypeSpec{}, + want: func() *apis.FieldError { + fe := apis.ErrMissingField("type") + return fe + }(), + }, { + name: "valid eventtype", + ets: &EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := test.ets.Validate(context.TODO()) + if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { + t.Errorf("%s: Validate EventTypeSpec (-want, +got) = %v", test.name, diff) + } + }) + } +} + +func TestEventTypeImmutableFields(t *testing.T) { + differentSource := apis.HTTP("original-source") + testSource := apis.HTTP("test-source") + testSchema := apis.HTTP("test-schema") + testSchemaData := `{"data": "awesome"}` + differentSchema := apis.HTTP("original-schema") + tests := []struct { + name string + current *EventType + original *EventType + want *apis.FieldError + }{{ + name: "good (no change)", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: testSchema, + SchemaData: testSchemaData, + }, + }, + original: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: testSchema, + SchemaData: testSchemaData, + }, + }, + want: nil, + }, { + name: "new nil is ok", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: testSchema, + }, + }, + original: nil, + want: nil, + }, { + name: "bad (broker change)", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + }, + }, + original: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "original-broker", + }, + }, + want: &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: `{v1beta2.EventTypeSpec}.Broker: + -: "original-broker" + +: "test-broker" +`, + }, + }, { + name: "bad (type change)", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + }, + }, + original: &EventType{ + Spec: EventTypeSpec{ + Type: "original-type", + Source: testSource, + Broker: "test-broker", + }, + }, + want: &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: `{v1beta2.EventTypeSpec}.Type: + -: "original-type" + +: "test-type" +`, + }, + }, { + name: "bad (source change)", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + }, + }, + original: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: differentSource, + Broker: "test-broker", + }, + }, + want: &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: `{v1beta2.EventTypeSpec}.Source.Host: + -: "original-source" + +: "test-source" +`, + }, + }, { + name: "bad (schema change)", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: testSchema, + }, + }, + original: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: differentSchema, + }, + }, + want: &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: `{v1beta2.EventTypeSpec}.Schema.Host: + -: "original-schema" + +: "test-schema" +`, + }, + }, { + name: "bad (description change)", + current: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: testSchema, + Description: "test-description", + }, + }, + original: &EventType{ + Spec: EventTypeSpec{ + Type: "test-type", + Source: testSource, + Broker: "test-broker", + Schema: testSchema, + Description: "original-description", + }, + }, + want: &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: `{v1beta2.EventTypeSpec}.Description: + -: "original-description" + +: "test-description" +`, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := test.current.CheckImmutableFields(context.TODO(), test.original) + if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { + t.Error("CheckImmutableFields (-want, +got) =", diff) + } + }) + } +} diff --git a/pkg/apis/eventing/v1beta2/register.go b/pkg/apis/eventing/v1beta2/register.go new file mode 100644 index 00000000000..ef8f01caa2c --- /dev/null +++ b/pkg/apis/eventing/v1beta2/register.go @@ -0,0 +1,53 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "knative.dev/eventing/pkg/apis/eventing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: eventing.GroupName, Version: "v1beta2"} + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) schema.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &EventType{}, + &EventTypeList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/pkg/apis/eventing/v1beta2/register_test.go b/pkg/apis/eventing/v1beta2/register_test.go new file mode 100644 index 00000000000..eb4e12381c0 --- /dev/null +++ b/pkg/apis/eventing/v1beta2/register_test.go @@ -0,0 +1,52 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1beta2 + +import ( + "testing" + + "k8s.io/apimachinery/pkg/runtime" +) + +func TestKind(t *testing.T) { + schemaGroupKind := Kind("EventType") + if schemaGroupKind.Kind != "EventType" || schemaGroupKind.Group != "eventing.knative.dev" { + t.Errorf("Unexpected GroupKind: %+v", schemaGroupKind) + } +} + +func TestResource(t *testing.T) { + schemaGroupResource := Resource("EventType") + if schemaGroupResource.Group != "eventing.knative.dev" || schemaGroupResource.Resource != "EventType" { + t.Errorf("Unexpected GroupResource: %+v", schemaGroupResource) + } +} + +func TestKnownTypes(t *testing.T) { + scheme := runtime.NewScheme() + addKnownTypes(scheme) + types := scheme.KnownTypes(SchemeGroupVersion) + + for _, name := range []string{ + "EventType", + "EventTypeList", + } { + if _, ok := types[name]; !ok { + t.Errorf("Did not find %q as registered type", name) + } + } +} diff --git a/pkg/apis/eventing/v1beta2/zz_generated.deepcopy.go b/pkg/apis/eventing/v1beta2/zz_generated.deepcopy.go new file mode 100644 index 00000000000..3163151d70a --- /dev/null +++ b/pkg/apis/eventing/v1beta2/zz_generated.deepcopy.go @@ -0,0 +1,131 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1beta2 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" + apis "knative.dev/pkg/apis" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EventType) DeepCopyInto(out *EventType) { + *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 EventType. +func (in *EventType) DeepCopy() *EventType { + if in == nil { + return nil + } + out := new(EventType) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EventType) 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 *EventTypeList) DeepCopyInto(out *EventTypeList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]EventType, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTypeList. +func (in *EventTypeList) DeepCopy() *EventTypeList { + if in == nil { + return nil + } + out := new(EventTypeList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *EventTypeList) 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 *EventTypeSpec) DeepCopyInto(out *EventTypeSpec) { + *out = *in + if in.Source != nil { + in, out := &in.Source, &out.Source + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + if in.Schema != nil { + in, out := &in.Schema, &out.Schema + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTypeSpec. +func (in *EventTypeSpec) DeepCopy() *EventTypeSpec { + if in == nil { + return nil + } + out := new(EventTypeSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *EventTypeStatus) DeepCopyInto(out *EventTypeStatus) { + *out = *in + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTypeStatus. +func (in *EventTypeStatus) DeepCopy() *EventTypeStatus { + if in == nil { + return nil + } + out := new(EventTypeStatus) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index 0a807519087..029b89efdc9 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -27,6 +27,7 @@ import ( flowcontrol "k8s.io/client-go/util/flowcontrol" eventingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1" eventingv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta1" + eventingv1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2" flowsv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/flows/v1" messagingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" sourcesv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" @@ -36,6 +37,7 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface EventingV1beta1() eventingv1beta1.EventingV1beta1Interface + EventingV1beta2() eventingv1beta2.EventingV1beta2Interface EventingV1() eventingv1.EventingV1Interface FlowsV1() flowsv1.FlowsV1Interface MessagingV1() messagingv1.MessagingV1Interface @@ -48,6 +50,7 @@ type Interface interface { type Clientset struct { *discovery.DiscoveryClient eventingV1beta1 *eventingv1beta1.EventingV1beta1Client + eventingV1beta2 *eventingv1beta2.EventingV1beta2Client eventingV1 *eventingv1.EventingV1Client flowsV1 *flowsv1.FlowsV1Client messagingV1 *messagingv1.MessagingV1Client @@ -60,6 +63,11 @@ func (c *Clientset) EventingV1beta1() eventingv1beta1.EventingV1beta1Interface { return c.eventingV1beta1 } +// EventingV1beta2 retrieves the EventingV1beta2Client +func (c *Clientset) EventingV1beta2() eventingv1beta2.EventingV1beta2Interface { + return c.eventingV1beta2 +} + // EventingV1 retrieves the EventingV1Client func (c *Clientset) EventingV1() eventingv1.EventingV1Interface { return c.eventingV1 @@ -133,6 +141,10 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, if err != nil { return nil, err } + cs.eventingV1beta2, err = eventingv1beta2.NewForConfigAndClient(&configShallowCopy, httpClient) + if err != nil { + return nil, err + } cs.eventingV1, err = eventingv1.NewForConfigAndClient(&configShallowCopy, httpClient) if err != nil { return nil, err @@ -175,6 +187,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { func New(c rest.Interface) *Clientset { var cs Clientset cs.eventingV1beta1 = eventingv1beta1.New(c) + cs.eventingV1beta2 = eventingv1beta2.New(c) cs.eventingV1 = eventingv1.New(c) cs.flowsV1 = flowsv1.New(c) cs.messagingV1 = messagingv1.New(c) diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 5a81e7fe133..01ff7244eab 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -29,6 +29,8 @@ import ( fakeeventingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1/fake" eventingv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta1" fakeeventingv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta1/fake" + eventingv1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2" + fakeeventingv1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake" flowsv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/flows/v1" fakeflowsv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/flows/v1/fake" messagingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" @@ -94,6 +96,11 @@ func (c *Clientset) EventingV1beta1() eventingv1beta1.EventingV1beta1Interface { return &fakeeventingv1beta1.FakeEventingV1beta1{Fake: &c.Fake} } +// EventingV1beta2 retrieves the EventingV1beta2Client +func (c *Clientset) EventingV1beta2() eventingv1beta2.EventingV1beta2Interface { + return &fakeeventingv1beta2.FakeEventingV1beta2{Fake: &c.Fake} +} + // EventingV1 retrieves the EventingV1Client func (c *Clientset) EventingV1() eventingv1.EventingV1Interface { return &fakeeventingv1.FakeEventingV1{Fake: &c.Fake} diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index 5feb41ac8e0..88a24b5e8a9 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -26,6 +26,7 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" eventingv1beta1 "knative.dev/eventing/pkg/apis/eventing/v1beta1" + eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" flowsv1 "knative.dev/eventing/pkg/apis/flows/v1" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" @@ -37,6 +38,7 @@ var codecs = serializer.NewCodecFactory(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ eventingv1beta1.AddToScheme, + eventingv1beta2.AddToScheme, eventingv1.AddToScheme, flowsv1.AddToScheme, messagingv1.AddToScheme, diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index 710aacfe441..f763a6688ba 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -26,6 +26,7 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" eventingv1beta1 "knative.dev/eventing/pkg/apis/eventing/v1beta1" + eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" flowsv1 "knative.dev/eventing/pkg/apis/flows/v1" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" @@ -37,6 +38,7 @@ var Codecs = serializer.NewCodecFactory(Scheme) var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ eventingv1beta1.AddToScheme, + eventingv1beta2.AddToScheme, eventingv1.AddToScheme, flowsv1.AddToScheme, messagingv1.AddToScheme, diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/doc.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/doc.go new file mode 100644 index 00000000000..07add715ef5 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1beta2 diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/eventing_client.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/eventing_client.go new file mode 100644 index 00000000000..ced74363128 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/eventing_client.go @@ -0,0 +1,107 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + "net/http" + + rest "k8s.io/client-go/rest" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + "knative.dev/eventing/pkg/client/clientset/versioned/scheme" +) + +type EventingV1beta2Interface interface { + RESTClient() rest.Interface + EventTypesGetter +} + +// EventingV1beta2Client is used to interact with features provided by the eventing.knative.dev group. +type EventingV1beta2Client struct { + restClient rest.Interface +} + +func (c *EventingV1beta2Client) EventTypes(namespace string) EventTypeInterface { + return newEventTypes(c, namespace) +} + +// NewForConfig creates a new EventingV1beta2Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). +func NewForConfig(c *rest.Config) (*EventingV1beta2Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new EventingV1beta2Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventingV1beta2Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientForConfigAndClient(&config, h) + if err != nil { + return nil, err + } + return &EventingV1beta2Client{client}, nil +} + +// NewForConfigOrDie creates a new EventingV1beta2Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *EventingV1beta2Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new EventingV1beta2Client for the given RESTClient. +func New(c rest.Interface) *EventingV1beta2Client { + return &EventingV1beta2Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1beta2.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *EventingV1beta2Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/eventtype.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/eventtype.go new file mode 100644 index 00000000000..95ba787325f --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/eventtype.go @@ -0,0 +1,195 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +import ( + "context" + "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" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + scheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" +) + +// EventTypesGetter has a method to return a EventTypeInterface. +// A group's client should implement this interface. +type EventTypesGetter interface { + EventTypes(namespace string) EventTypeInterface +} + +// EventTypeInterface has methods to work with EventType resources. +type EventTypeInterface interface { + Create(ctx context.Context, eventType *v1beta2.EventType, opts v1.CreateOptions) (*v1beta2.EventType, error) + Update(ctx context.Context, eventType *v1beta2.EventType, opts v1.UpdateOptions) (*v1beta2.EventType, error) + UpdateStatus(ctx context.Context, eventType *v1beta2.EventType, opts v1.UpdateOptions) (*v1beta2.EventType, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta2.EventType, error) + List(ctx context.Context, opts v1.ListOptions) (*v1beta2.EventTypeList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.EventType, err error) + EventTypeExpansion +} + +// eventTypes implements EventTypeInterface +type eventTypes struct { + client rest.Interface + ns string +} + +// newEventTypes returns a EventTypes +func newEventTypes(c *EventingV1beta2Client, namespace string) *eventTypes { + return &eventTypes{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the eventType, and returns the corresponding eventType object, and an error if there is any. +func (c *eventTypes) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.EventType, err error) { + result = &v1beta2.EventType{} + err = c.client.Get(). + Namespace(c.ns). + Resource("eventtypes"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of EventTypes that match those selectors. +func (c *eventTypes) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.EventTypeList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1beta2.EventTypeList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("eventtypes"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested eventTypes. +func (c *eventTypes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("eventtypes"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a eventType and creates it. Returns the server's representation of the eventType, and an error, if there is any. +func (c *eventTypes) Create(ctx context.Context, eventType *v1beta2.EventType, opts v1.CreateOptions) (result *v1beta2.EventType, err error) { + result = &v1beta2.EventType{} + err = c.client.Post(). + Namespace(c.ns). + Resource("eventtypes"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(eventType). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a eventType and updates it. Returns the server's representation of the eventType, and an error, if there is any. +func (c *eventTypes) Update(ctx context.Context, eventType *v1beta2.EventType, opts v1.UpdateOptions) (result *v1beta2.EventType, err error) { + result = &v1beta2.EventType{} + err = c.client.Put(). + Namespace(c.ns). + Resource("eventtypes"). + Name(eventType.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(eventType). + Do(ctx). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *eventTypes) UpdateStatus(ctx context.Context, eventType *v1beta2.EventType, opts v1.UpdateOptions) (result *v1beta2.EventType, err error) { + result = &v1beta2.EventType{} + err = c.client.Put(). + Namespace(c.ns). + Resource("eventtypes"). + Name(eventType.Name). + SubResource("status"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(eventType). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the eventType and deletes it. Returns an error if one occurs. +func (c *eventTypes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("eventtypes"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *eventTypes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("eventtypes"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched eventType. +func (c *eventTypes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.EventType, err error) { + result = &v1beta2.EventType{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("eventtypes"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/doc.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/doc.go new file mode 100644 index 00000000000..40528db3a52 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/fake_eventing_client.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/fake_eventing_client.go new file mode 100644 index 00000000000..784f0a65a08 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/fake_eventing_client.go @@ -0,0 +1,40 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" + v1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2" +) + +type FakeEventingV1beta2 struct { + *testing.Fake +} + +func (c *FakeEventingV1beta2) EventTypes(namespace string) v1beta2.EventTypeInterface { + return &FakeEventTypes{c, namespace} +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeEventingV1beta2) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/fake_eventtype.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/fake_eventtype.go new file mode 100644 index 00000000000..d348f36a5e4 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/fake/fake_eventtype.go @@ -0,0 +1,142 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" +) + +// FakeEventTypes implements EventTypeInterface +type FakeEventTypes struct { + Fake *FakeEventingV1beta2 + ns string +} + +var eventtypesResource = schema.GroupVersionResource{Group: "eventing.knative.dev", Version: "v1beta2", Resource: "eventtypes"} + +var eventtypesKind = schema.GroupVersionKind{Group: "eventing.knative.dev", Version: "v1beta2", Kind: "EventType"} + +// Get takes name of the eventType, and returns the corresponding eventType object, and an error if there is any. +func (c *FakeEventTypes) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.EventType, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(eventtypesResource, c.ns, name), &v1beta2.EventType{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta2.EventType), err +} + +// List takes label and field selectors, and returns the list of EventTypes that match those selectors. +func (c *FakeEventTypes) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.EventTypeList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(eventtypesResource, eventtypesKind, c.ns, opts), &v1beta2.EventTypeList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1beta2.EventTypeList{ListMeta: obj.(*v1beta2.EventTypeList).ListMeta} + for _, item := range obj.(*v1beta2.EventTypeList).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 eventTypes. +func (c *FakeEventTypes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(eventtypesResource, c.ns, opts)) + +} + +// Create takes the representation of a eventType and creates it. Returns the server's representation of the eventType, and an error, if there is any. +func (c *FakeEventTypes) Create(ctx context.Context, eventType *v1beta2.EventType, opts v1.CreateOptions) (result *v1beta2.EventType, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(eventtypesResource, c.ns, eventType), &v1beta2.EventType{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta2.EventType), err +} + +// Update takes the representation of a eventType and updates it. Returns the server's representation of the eventType, and an error, if there is any. +func (c *FakeEventTypes) Update(ctx context.Context, eventType *v1beta2.EventType, opts v1.UpdateOptions) (result *v1beta2.EventType, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(eventtypesResource, c.ns, eventType), &v1beta2.EventType{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta2.EventType), 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 *FakeEventTypes) UpdateStatus(ctx context.Context, eventType *v1beta2.EventType, opts v1.UpdateOptions) (*v1beta2.EventType, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(eventtypesResource, "status", c.ns, eventType), &v1beta2.EventType{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta2.EventType), err +} + +// Delete takes name of the eventType and deletes it. Returns an error if one occurs. +func (c *FakeEventTypes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteActionWithOptions(eventtypesResource, c.ns, name, opts), &v1beta2.EventType{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeEventTypes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(eventtypesResource, c.ns, listOpts) + + _, err := c.Fake.Invokes(action, &v1beta2.EventTypeList{}) + return err +} + +// Patch applies the patch and returns the patched eventType. +func (c *FakeEventTypes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.EventType, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(eventtypesResource, c.ns, name, pt, data, subresources...), &v1beta2.EventType{}) + + if obj == nil { + return nil, err + } + return obj.(*v1beta2.EventType), err +} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1beta2/generated_expansion.go b/pkg/client/clientset/versioned/typed/eventing/v1beta2/generated_expansion.go new file mode 100644 index 00000000000..18a7ab381cd --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1beta2/generated_expansion.go @@ -0,0 +1,21 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta2 + +type EventTypeExpansion interface{} diff --git a/pkg/client/informers/externalversions/eventing/interface.go b/pkg/client/informers/externalversions/eventing/interface.go index efb6b138691..a71a3365ff7 100644 --- a/pkg/client/informers/externalversions/eventing/interface.go +++ b/pkg/client/informers/externalversions/eventing/interface.go @@ -21,6 +21,7 @@ package eventing import ( v1 "knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1" v1beta1 "knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1beta1" + v1beta2 "knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1beta2" internalinterfaces "knative.dev/eventing/pkg/client/informers/externalversions/internalinterfaces" ) @@ -28,6 +29,8 @@ import ( type Interface interface { // V1beta1 provides access to shared informers for resources in V1beta1. V1beta1() v1beta1.Interface + // V1beta2 provides access to shared informers for resources in V1beta2. + V1beta2() v1beta2.Interface // V1 provides access to shared informers for resources in V1. V1() v1.Interface } @@ -48,6 +51,11 @@ func (g *group) V1beta1() v1beta1.Interface { return v1beta1.New(g.factory, g.namespace, g.tweakListOptions) } +// V1beta2 returns a new v1beta2.Interface. +func (g *group) V1beta2() v1beta2.Interface { + return v1beta2.New(g.factory, g.namespace, g.tweakListOptions) +} + // V1 returns a new v1.Interface. func (g *group) V1() v1.Interface { return v1.New(g.factory, g.namespace, g.tweakListOptions) diff --git a/pkg/client/informers/externalversions/eventing/v1beta2/eventtype.go b/pkg/client/informers/externalversions/eventing/v1beta2/eventtype.go new file mode 100644 index 00000000000..9a4c6525522 --- /dev/null +++ b/pkg/client/informers/externalversions/eventing/v1beta2/eventtype.go @@ -0,0 +1,90 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + "context" + 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" + eventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + internalinterfaces "knative.dev/eventing/pkg/client/informers/externalversions/internalinterfaces" + v1beta2 "knative.dev/eventing/pkg/client/listers/eventing/v1beta2" +) + +// EventTypeInformer provides access to a shared informer and lister for +// EventTypes. +type EventTypeInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1beta2.EventTypeLister +} + +type eventTypeInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewEventTypeInformer constructs a new informer for EventType 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 NewEventTypeInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredEventTypeInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredEventTypeInformer constructs a new informer for EventType 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 NewFilteredEventTypeInformer(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.EventingV1beta2().EventTypes(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.EventingV1beta2().EventTypes(namespace).Watch(context.TODO(), options) + }, + }, + &eventingv1beta2.EventType{}, + resyncPeriod, + indexers, + ) +} + +func (f *eventTypeInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredEventTypeInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *eventTypeInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&eventingv1beta2.EventType{}, f.defaultInformer) +} + +func (f *eventTypeInformer) Lister() v1beta2.EventTypeLister { + return v1beta2.NewEventTypeLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/eventing/v1beta2/interface.go b/pkg/client/informers/externalversions/eventing/v1beta2/interface.go new file mode 100644 index 00000000000..98f69b73ee8 --- /dev/null +++ b/pkg/client/informers/externalversions/eventing/v1beta2/interface.go @@ -0,0 +1,45 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta2 + +import ( + internalinterfaces "knative.dev/eventing/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // EventTypes returns a EventTypeInformer. + EventTypes() EventTypeInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// EventTypes returns a EventTypeInformer. +func (v *version) EventTypes() EventTypeInformer { + return &eventTypeInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index a265d0ce6f0..3ed3888349d 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -25,10 +25,11 @@ import ( cache "k8s.io/client-go/tools/cache" v1 "knative.dev/eventing/pkg/apis/eventing/v1" v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1beta1" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" flowsv1 "knative.dev/eventing/pkg/apis/flows/v1" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" - v1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" + sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" ) // GenericInformer is type of SharedIndexInformer which will locate and delegate to other @@ -67,6 +68,10 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case v1beta1.SchemeGroupVersion.WithResource("eventtypes"): return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1beta1().EventTypes().Informer()}, nil + // Group=eventing.knative.dev, Version=v1beta2 + case v1beta2.SchemeGroupVersion.WithResource("eventtypes"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1beta2().EventTypes().Informer()}, nil + // Group=flows.knative.dev, Version=v1 case flowsv1.SchemeGroupVersion.WithResource("parallels"): return &genericInformer{resource: resource.GroupResource(), informer: f.Flows().V1().Parallels().Informer()}, nil @@ -92,7 +97,7 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1().SinkBindings().Informer()}, nil // Group=sources.knative.dev, Version=v1beta2 - case v1beta2.SchemeGroupVersion.WithResource("pingsources"): + case sourcesv1beta2.SchemeGroupVersion.WithResource("pingsources"): return &genericInformer{resource: resource.GroupResource(), informer: f.Sources().V1beta2().PingSources().Informer()}, nil } diff --git a/pkg/client/injection/client/client.go b/pkg/client/injection/client/client.go index ad79c3ffd60..f24f55dfd8e 100644 --- a/pkg/client/injection/client/client.go +++ b/pkg/client/injection/client/client.go @@ -35,13 +35,15 @@ import ( rest "k8s.io/client-go/rest" eventingv1 "knative.dev/eventing/pkg/apis/eventing/v1" v1beta1 "knative.dev/eventing/pkg/apis/eventing/v1beta1" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" flowsv1 "knative.dev/eventing/pkg/apis/flows/v1" messagingv1 "knative.dev/eventing/pkg/apis/messaging/v1" sourcesv1 "knative.dev/eventing/pkg/apis/sources/v1" - v1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" + sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" versioned "knative.dev/eventing/pkg/client/clientset/versioned" typedeventingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1" typedeventingv1beta1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta1" + typedeventingv1beta2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1beta2" typedflowsv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/flows/v1" typedmessagingv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/messaging/v1" typedsourcesv1 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1" @@ -252,6 +254,152 @@ func (w *wrapEventingV1beta1EventTypeImpl) Watch(ctx context.Context, opts v1.Li return nil, errors.New("NYI: Watch") } +// EventingV1beta2 retrieves the EventingV1beta2Client +func (w *wrapClient) EventingV1beta2() typedeventingv1beta2.EventingV1beta2Interface { + return &wrapEventingV1beta2{ + dyn: w.dyn, + } +} + +type wrapEventingV1beta2 struct { + dyn dynamic.Interface +} + +func (w *wrapEventingV1beta2) RESTClient() rest.Interface { + panic("RESTClient called on dynamic client!") +} + +func (w *wrapEventingV1beta2) EventTypes(namespace string) typedeventingv1beta2.EventTypeInterface { + return &wrapEventingV1beta2EventTypeImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "eventing.knative.dev", + Version: "v1beta2", + Resource: "eventtypes", + }), + + namespace: namespace, + } +} + +type wrapEventingV1beta2EventTypeImpl struct { + dyn dynamic.NamespaceableResourceInterface + + namespace string +} + +var _ typedeventingv1beta2.EventTypeInterface = (*wrapEventingV1beta2EventTypeImpl)(nil) + +func (w *wrapEventingV1beta2EventTypeImpl) Create(ctx context.Context, in *v1beta2.EventType, opts v1.CreateOptions) (*v1beta2.EventType, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "eventing.knative.dev", + Version: "v1beta2", + Kind: "EventType", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta2.EventType{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapEventingV1beta2EventTypeImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Namespace(w.namespace).Delete(ctx, name, opts) +} + +func (w *wrapEventingV1beta2EventTypeImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapEventingV1beta2EventTypeImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta2.EventType, error) { + uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &v1beta2.EventType{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapEventingV1beta2EventTypeImpl) List(ctx context.Context, opts v1.ListOptions) (*v1beta2.EventTypeList, error) { + uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) + if err != nil { + return nil, err + } + out := &v1beta2.EventTypeList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapEventingV1beta2EventTypeImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.EventType, err error) { + uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &v1beta2.EventType{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapEventingV1beta2EventTypeImpl) Update(ctx context.Context, in *v1beta2.EventType, opts v1.UpdateOptions) (*v1beta2.EventType, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "eventing.knative.dev", + Version: "v1beta2", + Kind: "EventType", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta2.EventType{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapEventingV1beta2EventTypeImpl) UpdateStatus(ctx context.Context, in *v1beta2.EventType, opts v1.UpdateOptions) (*v1beta2.EventType, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "eventing.knative.dev", + Version: "v1beta2", + Kind: "EventType", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Namespace(w.namespace).UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta2.EventType{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapEventingV1beta2EventTypeImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} + // EventingV1 retrieves the EventingV1Client func (w *wrapClient) EventingV1() typedeventingv1.EventingV1Interface { return &wrapEventingV1{ @@ -1249,7 +1397,7 @@ type wrapSourcesV1beta2PingSourceImpl struct { var _ typedsourcesv1beta2.PingSourceInterface = (*wrapSourcesV1beta2PingSourceImpl)(nil) -func (w *wrapSourcesV1beta2PingSourceImpl) Create(ctx context.Context, in *v1beta2.PingSource, opts v1.CreateOptions) (*v1beta2.PingSource, error) { +func (w *wrapSourcesV1beta2PingSourceImpl) Create(ctx context.Context, in *sourcesv1beta2.PingSource, opts v1.CreateOptions) (*sourcesv1beta2.PingSource, error) { in.SetGroupVersionKind(schema.GroupVersionKind{ Group: "sources.knative.dev", Version: "v1beta2", @@ -1263,7 +1411,7 @@ func (w *wrapSourcesV1beta2PingSourceImpl) Create(ctx context.Context, in *v1bet if err != nil { return nil, err } - out := &v1beta2.PingSource{} + out := &sourcesv1beta2.PingSource{} if err := convert(uo, out); err != nil { return nil, err } @@ -1278,43 +1426,43 @@ func (w *wrapSourcesV1beta2PingSourceImpl) DeleteCollection(ctx context.Context, return w.dyn.Namespace(w.namespace).DeleteCollection(ctx, opts, listOpts) } -func (w *wrapSourcesV1beta2PingSourceImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta2.PingSource, error) { +func (w *wrapSourcesV1beta2PingSourceImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*sourcesv1beta2.PingSource, error) { uo, err := w.dyn.Namespace(w.namespace).Get(ctx, name, opts) if err != nil { return nil, err } - out := &v1beta2.PingSource{} + out := &sourcesv1beta2.PingSource{} if err := convert(uo, out); err != nil { return nil, err } return out, nil } -func (w *wrapSourcesV1beta2PingSourceImpl) List(ctx context.Context, opts v1.ListOptions) (*v1beta2.PingSourceList, error) { +func (w *wrapSourcesV1beta2PingSourceImpl) List(ctx context.Context, opts v1.ListOptions) (*sourcesv1beta2.PingSourceList, error) { uo, err := w.dyn.Namespace(w.namespace).List(ctx, opts) if err != nil { return nil, err } - out := &v1beta2.PingSourceList{} + out := &sourcesv1beta2.PingSourceList{} if err := convert(uo, out); err != nil { return nil, err } return out, nil } -func (w *wrapSourcesV1beta2PingSourceImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.PingSource, err error) { +func (w *wrapSourcesV1beta2PingSourceImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *sourcesv1beta2.PingSource, err error) { uo, err := w.dyn.Namespace(w.namespace).Patch(ctx, name, pt, data, opts) if err != nil { return nil, err } - out := &v1beta2.PingSource{} + out := &sourcesv1beta2.PingSource{} if err := convert(uo, out); err != nil { return nil, err } return out, nil } -func (w *wrapSourcesV1beta2PingSourceImpl) Update(ctx context.Context, in *v1beta2.PingSource, opts v1.UpdateOptions) (*v1beta2.PingSource, error) { +func (w *wrapSourcesV1beta2PingSourceImpl) Update(ctx context.Context, in *sourcesv1beta2.PingSource, opts v1.UpdateOptions) (*sourcesv1beta2.PingSource, error) { in.SetGroupVersionKind(schema.GroupVersionKind{ Group: "sources.knative.dev", Version: "v1beta2", @@ -1328,14 +1476,14 @@ func (w *wrapSourcesV1beta2PingSourceImpl) Update(ctx context.Context, in *v1bet if err != nil { return nil, err } - out := &v1beta2.PingSource{} + out := &sourcesv1beta2.PingSource{} if err := convert(uo, out); err != nil { return nil, err } return out, nil } -func (w *wrapSourcesV1beta2PingSourceImpl) UpdateStatus(ctx context.Context, in *v1beta2.PingSource, opts v1.UpdateOptions) (*v1beta2.PingSource, error) { +func (w *wrapSourcesV1beta2PingSourceImpl) UpdateStatus(ctx context.Context, in *sourcesv1beta2.PingSource, opts v1.UpdateOptions) (*sourcesv1beta2.PingSource, error) { in.SetGroupVersionKind(schema.GroupVersionKind{ Group: "sources.knative.dev", Version: "v1beta2", @@ -1349,7 +1497,7 @@ func (w *wrapSourcesV1beta2PingSourceImpl) UpdateStatus(ctx context.Context, in if err != nil { return nil, err } - out := &v1beta2.PingSource{} + out := &sourcesv1beta2.PingSource{} if err := convert(uo, out); err != nil { return nil, err } diff --git a/pkg/client/injection/informers/eventing/v1beta2/eventtype/eventtype.go b/pkg/client/injection/informers/eventing/v1beta2/eventtype/eventtype.go new file mode 100644 index 00000000000..061eedc7fd5 --- /dev/null +++ b/pkg/client/injection/informers/eventing/v1beta2/eventtype/eventtype.go @@ -0,0 +1,116 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package eventtype + +import ( + context "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + cache "k8s.io/client-go/tools/cache" + apiseventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + v1beta2 "knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1beta2" + client "knative.dev/eventing/pkg/client/injection/client" + factory "knative.dev/eventing/pkg/client/injection/informers/factory" + eventingv1beta2 "knative.dev/eventing/pkg/client/listers/eventing/v1beta2" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +func init() { + injection.Default.RegisterInformer(withInformer) + injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct{} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := factory.Get(ctx) + inf := f.Eventing().V1beta2().EventTypes() + return context.WithValue(ctx, Key{}, inf), inf.Informer() +} + +func withDynamicInformer(ctx context.Context) context.Context { + inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} + return context.WithValue(ctx, Key{}, inf) +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context) v1beta2.EventTypeInformer { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1beta2.EventTypeInformer from context.") + } + return untyped.(v1beta2.EventTypeInformer) +} + +type wrapper struct { + client versioned.Interface + + namespace string + + resourceVersion string +} + +var _ v1beta2.EventTypeInformer = (*wrapper)(nil) +var _ eventingv1beta2.EventTypeLister = (*wrapper)(nil) + +func (w *wrapper) Informer() cache.SharedIndexInformer { + return cache.NewSharedIndexInformer(nil, &apiseventingv1beta2.EventType{}, 0, nil) +} + +func (w *wrapper) Lister() eventingv1beta2.EventTypeLister { + return w +} + +func (w *wrapper) EventTypes(namespace string) eventingv1beta2.EventTypeNamespaceLister { + return &wrapper{client: w.client, namespace: namespace, resourceVersion: w.resourceVersion} +} + +// SetResourceVersion allows consumers to adjust the minimum resourceVersion +// used by the underlying client. It is not accessible via the standard +// lister interface, but can be accessed through a user-defined interface and +// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) +func (w *wrapper) SetResourceVersion(resourceVersion string) { + w.resourceVersion = resourceVersion +} + +func (w *wrapper) List(selector labels.Selector) (ret []*apiseventingv1beta2.EventType, err error) { + lo, err := w.client.EventingV1beta2().EventTypes(w.namespace).List(context.TODO(), v1.ListOptions{ + LabelSelector: selector.String(), + ResourceVersion: w.resourceVersion, + }) + if err != nil { + return nil, err + } + for idx := range lo.Items { + ret = append(ret, &lo.Items[idx]) + } + return ret, nil +} + +func (w *wrapper) Get(name string) (*apiseventingv1beta2.EventType, error) { + return w.client.EventingV1beta2().EventTypes(w.namespace).Get(context.TODO(), name, v1.GetOptions{ + ResourceVersion: w.resourceVersion, + }) +} diff --git a/pkg/client/injection/informers/eventing/v1beta2/eventtype/fake/fake.go b/pkg/client/injection/informers/eventing/v1beta2/eventtype/fake/fake.go new file mode 100644 index 00000000000..d5f3bccae75 --- /dev/null +++ b/pkg/client/injection/informers/eventing/v1beta2/eventtype/fake/fake.go @@ -0,0 +1,40 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package fake + +import ( + context "context" + + eventtype "knative.dev/eventing/pkg/client/injection/informers/eventing/v1beta2/eventtype" + fake "knative.dev/eventing/pkg/client/injection/informers/factory/fake" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" +) + +var Get = eventtype.Get + +func init() { + injection.Fake.RegisterInformer(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := fake.Get(ctx) + inf := f.Eventing().V1beta2().EventTypes() + return context.WithValue(ctx, eventtype.Key{}, inf), inf.Informer() +} diff --git a/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered/eventtype.go b/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered/eventtype.go new file mode 100644 index 00000000000..1730865891a --- /dev/null +++ b/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered/eventtype.go @@ -0,0 +1,136 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package filtered + +import ( + context "context" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + cache "k8s.io/client-go/tools/cache" + apiseventingv1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + v1beta2 "knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1beta2" + client "knative.dev/eventing/pkg/client/injection/client" + filtered "knative.dev/eventing/pkg/client/injection/informers/factory/filtered" + eventingv1beta2 "knative.dev/eventing/pkg/client/listers/eventing/v1beta2" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +func init() { + injection.Default.RegisterFilteredInformers(withInformer) + injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct { + Selector string +} + +func withInformer(ctx context.Context) (context.Context, []controller.Informer) { + untyped := ctx.Value(filtered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + infs := []controller.Informer{} + for _, selector := range labelSelectors { + f := filtered.Get(ctx, selector) + inf := f.Eventing().V1beta2().EventTypes() + ctx = context.WithValue(ctx, Key{Selector: selector}, inf) + infs = append(infs, inf.Informer()) + } + return ctx, infs +} + +func withDynamicInformer(ctx context.Context) context.Context { + untyped := ctx.Value(filtered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + for _, selector := range labelSelectors { + inf := &wrapper{client: client.Get(ctx), selector: selector} + ctx = context.WithValue(ctx, Key{Selector: selector}, inf) + } + return ctx +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context, selector string) v1beta2.EventTypeInformer { + untyped := ctx.Value(Key{Selector: selector}) + if untyped == nil { + logging.FromContext(ctx).Panicf( + "Unable to fetch knative.dev/eventing/pkg/client/informers/externalversions/eventing/v1beta2.EventTypeInformer with selector %s from context.", selector) + } + return untyped.(v1beta2.EventTypeInformer) +} + +type wrapper struct { + client versioned.Interface + + namespace string + + selector string +} + +var _ v1beta2.EventTypeInformer = (*wrapper)(nil) +var _ eventingv1beta2.EventTypeLister = (*wrapper)(nil) + +func (w *wrapper) Informer() cache.SharedIndexInformer { + return cache.NewSharedIndexInformer(nil, &apiseventingv1beta2.EventType{}, 0, nil) +} + +func (w *wrapper) Lister() eventingv1beta2.EventTypeLister { + return w +} + +func (w *wrapper) EventTypes(namespace string) eventingv1beta2.EventTypeNamespaceLister { + return &wrapper{client: w.client, namespace: namespace, selector: w.selector} +} + +func (w *wrapper) List(selector labels.Selector) (ret []*apiseventingv1beta2.EventType, err error) { + reqs, err := labels.ParseToRequirements(w.selector) + if err != nil { + return nil, err + } + selector = selector.Add(reqs...) + lo, err := w.client.EventingV1beta2().EventTypes(w.namespace).List(context.TODO(), v1.ListOptions{ + LabelSelector: selector.String(), + // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. + }) + if err != nil { + return nil, err + } + for idx := range lo.Items { + ret = append(ret, &lo.Items[idx]) + } + return ret, nil +} + +func (w *wrapper) Get(name string) (*apiseventingv1beta2.EventType, error) { + // TODO(mattmoor): Check that the fetched object matches the selector. + return w.client.EventingV1beta2().EventTypes(w.namespace).Get(context.TODO(), name, v1.GetOptions{ + // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. + }) +} diff --git a/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered/fake/fake.go b/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered/fake/fake.go new file mode 100644 index 00000000000..2c947d737a8 --- /dev/null +++ b/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered/fake/fake.go @@ -0,0 +1,52 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package fake + +import ( + context "context" + + filtered "knative.dev/eventing/pkg/client/injection/informers/eventing/v1beta2/eventtype/filtered" + factoryfiltered "knative.dev/eventing/pkg/client/injection/informers/factory/filtered" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +var Get = filtered.Get + +func init() { + injection.Fake.RegisterFilteredInformers(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, []controller.Informer) { + untyped := ctx.Value(factoryfiltered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + infs := []controller.Informer{} + for _, selector := range labelSelectors { + f := factoryfiltered.Get(ctx, selector) + inf := f.Eventing().V1beta2().EventTypes() + ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) + infs = append(infs, inf.Informer()) + } + return ctx, infs +} diff --git a/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/controller.go b/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/controller.go new file mode 100644 index 00000000000..650be5f2e87 --- /dev/null +++ b/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/controller.go @@ -0,0 +1,170 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package eventtype + +import ( + context "context" + fmt "fmt" + reflect "reflect" + strings "strings" + + zap "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + scheme "k8s.io/client-go/kubernetes/scheme" + v1 "k8s.io/client-go/kubernetes/typed/core/v1" + record "k8s.io/client-go/tools/record" + versionedscheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" + client "knative.dev/eventing/pkg/client/injection/client" + eventtype "knative.dev/eventing/pkg/client/injection/informers/eventing/v1beta2/eventtype" + kubeclient "knative.dev/pkg/client/injection/kube/client" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + logkey "knative.dev/pkg/logging/logkey" + reconciler "knative.dev/pkg/reconciler" +) + +const ( + defaultControllerAgentName = "eventtype-controller" + defaultFinalizerName = "eventtypes.eventing.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.ControllerOptions to be used by the internal reconciler. +func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { + logger := logging.FromContext(ctx) + + // Check the options function input. It should be 0 or 1. + if len(optionsFns) > 1 { + logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) + } + + eventtypeInformer := eventtype.Get(ctx) + + lister := eventtypeInformer.Lister() + + var promoteFilterFunc func(obj interface{}) bool + var promoteFunc = func(bkt reconciler.Bucket) {} + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + + // Signal promotion event + promoteFunc(bkt) + + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + if promoteFilterFunc != nil { + if ok := promoteFilterFunc(elt); !ok { + continue + } + } + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client.Get(ctx), + Lister: lister, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + ctrType := reflect.TypeOf(r).Elem() + ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) + ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") + + logger = logger.With( + zap.String(logkey.ControllerType, ctrTypeName), + zap.String(logkey.Kind, "eventing.knative.dev.EventType"), + ) + + impl := controller.NewContext(ctx, rec, controller.ControllerOptions{WorkQueueName: ctrTypeName, Logger: logger}) + agentName := defaultControllerAgentName + + // Pass impl to the options. Save any optional results. + for _, fn := range optionsFns { + opts := fn(impl) + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.AgentName != "" { + agentName = opts.AgentName + } + if opts.SkipStatusUpdates { + rec.skipStatusUpdates = true + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + if opts.PromoteFilterFunc != nil { + promoteFilterFunc = opts.PromoteFilterFunc + } + if opts.PromoteFunc != nil { + promoteFunc = opts.PromoteFunc + } + } + + 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/eventing/v1beta2/eventtype/reconciler.go b/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/reconciler.go new file mode 100644 index 00000000000..51b9478189f --- /dev/null +++ b/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/reconciler.go @@ -0,0 +1,440 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package eventtype + +import ( + context "context" + json "encoding/json" + fmt "fmt" + + zap "go.uber.org/zap" + "go.uber.org/zap/zapcore" + 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" + record "k8s.io/client-go/tools/record" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + versioned "knative.dev/eventing/pkg/client/clientset/versioned" + eventingv1beta2 "knative.dev/eventing/pkg/client/listers/eventing/v1beta2" + controller "knative.dev/pkg/controller" + kmp "knative.dev/pkg/kmp" + logging "knative.dev/pkg/logging" + reconciler "knative.dev/pkg/reconciler" +) + +// Interface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1beta2.EventType. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1beta2.EventType. 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 *v1beta2.EventType) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1beta2.EventType. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1beta2.EventType. 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 *v1beta2.EventType) reconciler.Event +} + +// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1beta2.EventType if they want to process resources for which +// they are not the leader. +type ReadOnlyInterface interface { + // ObserveKind implements logic to observe v1beta2.EventType. + // This method should not write to the API. + ObserveKind(ctx context.Context, o *v1beta2.EventType) reconciler.Event +} + +type doReconcile func(ctx context.Context, o *v1beta2.EventType) reconciler.Event + +// reconcilerImpl implements controller.Reconciler for v1beta2.EventType 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 eventingv1beta2.EventTypeLister + + // 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 eventingv1beta2.EventTypeLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { + // Check the options function input. It should be 0 or 1. + if len(options) > 1 { + logger.Fatal("Up to one options struct is supported, found: ", len(options)) + } + + // Fail fast when users inadvertently implement the other LeaderAware interface. + // For the typed reconcilers, Promote shouldn't take any arguments. + if _, ok := r.(reconciler.LeaderAware); ok { + logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) + } + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + // TODO: Consider letting users specify a filter in options. + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client, + Lister: lister, + Recorder: recorder, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + for _, opts := range options { + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.SkipStatusUpdates { + rec.skipStatusUpdates = true + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // Initialize the reconciler state. This will convert the namespace/name + // string into a distinct namespace and name, determine if this instance of + // the reconciler is the leader, and any additional interfaces implemented + // by the reconciler. Returns an error is the resource key is invalid. + s, err := newState(key, r) + if err != nil { + logger.Error("Invalid resource key: ", key) + return nil + } + + // If we are not the leader, and we don't implement either ReadOnly + // observer interfaces, then take a fast-path out. + if s.isNotLeaderNorObserver() { + return controller.NewSkipKey(key) + } + + // If configStore is set, attach the frozen configuration to the context. + if r.configStore != nil { + ctx = r.configStore.ToContext(ctx) + } + + // Add the recorder to context. + ctx = controller.WithEventRecorder(ctx, r.Recorder) + + // Get the resource with this namespace/name. + + getter := r.Lister.EventTypes(s.namespace) + + original, err := getter.Get(s.name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing and call + // the ObserveDeletion handler if appropriate. + logger.Debugf("Resource %q no longer exists", key) + if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { + return del.ObserveDeletion(ctx, types.NamespacedName{ + Namespace: s.namespace, + Name: s.name, + }) + } + return nil + } else if err != nil { + return err + } + + // Don't modify the informers copy. + resource := original.DeepCopy() + + var reconcileEvent reconciler.Event + + name, do := s.reconcileMethodFor(resource) + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", name)) + switch name { + case reconciler.DoReconcileKind: + // Set and update the finalizer on resource if r.reconciler + // implements Finalizer. + if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { + return fmt.Errorf("failed to set finalizers: %w", err) + } + + if !r.skipStatusUpdates { + reconciler.PreProcessReconcile(ctx, resource) + } + + // Reconcile this copy of the resource and then write back any status + // updates regardless of whether the reconciliation errored out. + reconcileEvent = do(ctx, resource) + + if !r.skipStatusUpdates { + reconciler.PostProcessReconcile(ctx, resource, original) + } + + case reconciler.DoFinalizeKind: + // For finalizing reconcilers, if this resource being marked for deletion + // and reconciled cleanly (nil or normal event), remove the finalizer. + reconcileEvent = do(ctx, resource) + + if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { + return fmt.Errorf("failed to clear finalizers: %w", err) + } + + case reconciler.DoObserveKind: + // Observe any changes to this resource, since we are not the leader. + reconcileEvent = do(ctx, resource) + + } + + // Synchronize the status. + switch { + case r.skipStatusUpdates: + // This reconciler implementation is configured to skip resource updates. + // This may mean this reconciler does not observe spec, but reconciles external changes. + case equality.Semantic.DeepEqual(original.Status, resource.Status): + // If we didn't change anything then don't call updateStatus. + // This is important because the copy we loaded from the injectionInformer's + // cache may be stale and we don't want to overwrite a prior update + // to status with this stale state. + case !s.isLeader: + // High-availability reconcilers may have many replicas watching the resource, but only + // the elected leader is expected to write modifications. + logger.Warn("Saw status changes when we aren't the leader!") + default: + if err = r.updateStatus(ctx, logger, 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.Event(resource, event.EventType, event.Reason, event.Error()) + + // the event was wrapped inside an error, consider the reconciliation as failed + if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { + return reconcileEvent + } + return nil + } + + if controller.IsSkipKey(reconcileEvent) { + // This is a wrapped error, don't emit an event. + } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { + // This is a wrapped error, don't emit an event. + } else { + 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(ctx context.Context, logger *zap.SugaredLogger, existing *v1beta2.EventType, desired *v1beta2.EventType) 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.EventingV1beta2().EventTypes(desired.Namespace) + + existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) + if err != nil { + return err + } + } + + // If there's nothing to update, just return. + if equality.Semantic.DeepEqual(existing.Status, desired.Status) { + return nil + } + + if logger.Desugar().Core().Enabled(zapcore.DebugLevel) { + if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { + logger.Debug("Updating status with: ", diff) + } + } + + existing.Status = desired.Status + + updater := r.Client.EventingV1beta2().EventTypes(existing.Namespace) + + _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) + return err + }) +} + +// updateFinalizersFiltered will update the Finalizers of the resource. +// TODO: this method could be generic and sync all finalizers. For now it only +// updates defaultFinalizerName or its override. +func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1beta2.EventType, desiredFinalizers sets.String) (*v1beta2.EventType, error) { + // Don't modify the informers copy. + existing := resource.DeepCopy() + + var finalizers []string + + // If there's nothing to update, just return. + existingFinalizers := sets.NewString(existing.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.EventingV1beta2().EventTypes(resource.Namespace) + + resourceName := resource.Name + updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) + if err != nil { + r.Recorder.Eventf(existing, v1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resourceName, err) + } else { + r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return updated, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1beta2.EventType) (*v1beta2.EventType, 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) + } + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource, finalizers) +} + +func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1beta2.EventType, reconcileEvent reconciler.Event) (*v1beta2.EventType, 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) + } + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource, finalizers) +} diff --git a/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/state.go b/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/state.go new file mode 100644 index 00000000000..13a36fc2a81 --- /dev/null +++ b/pkg/client/injection/reconciler/eventing/v1beta2/eventtype/state.go @@ -0,0 +1,97 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by injection-gen. DO NOT EDIT. + +package eventtype + +import ( + fmt "fmt" + + types "k8s.io/apimachinery/pkg/types" + cache "k8s.io/client-go/tools/cache" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" + reconciler "knative.dev/pkg/reconciler" +) + +// state is used to track the state of a reconciler in a single run. +type state struct { + // key is the original reconciliation key from the queue. + key string + // namespace is the namespace split from the reconciliation key. + namespace string + // name is the name split from the reconciliation key. + name string + // reconciler is the reconciler. + reconciler Interface + // roi is the read only interface cast of the reconciler. + roi ReadOnlyInterface + // isROI (Read Only Interface) the reconciler only observes reconciliation. + isROI bool + // isLeader the instance of the reconciler is the elected leader. + isLeader bool +} + +func newState(key string, r *reconcilerImpl) (*state, error) { + // Convert the namespace/name string into a distinct namespace and name. + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return nil, fmt.Errorf("invalid resource key: %s", key) + } + + roi, isROI := r.reconciler.(ReadOnlyInterface) + + isLeader := r.IsLeaderFor(types.NamespacedName{ + Namespace: namespace, + Name: name, + }) + + return &state{ + key: key, + namespace: namespace, + name: name, + reconciler: r.reconciler, + roi: roi, + isROI: isROI, + isLeader: isLeader, + }, nil +} + +// isNotLeaderNorObserver checks to see if this reconciler with the current +// state is enabled to do any work or not. +// isNotLeaderNorObserver returns true when there is no work possible for the +// reconciler. +func (s *state) isNotLeaderNorObserver() bool { + if !s.isLeader && !s.isROI { + // If we are not the leader, and we don't implement the ReadOnly + // interface, then take a fast-path out. + return true + } + return false +} + +func (s *state) reconcileMethodFor(o *v1beta2.EventType) (string, doReconcile) { + if o.GetDeletionTimestamp().IsZero() { + if s.isLeader { + return reconciler.DoReconcileKind, s.reconciler.ReconcileKind + } else if s.isROI { + return reconciler.DoObserveKind, s.roi.ObserveKind + } + } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { + return reconciler.DoFinalizeKind, fin.FinalizeKind + } + return "unknown", nil +} diff --git a/pkg/client/listers/eventing/v1beta2/eventtype.go b/pkg/client/listers/eventing/v1beta2/eventtype.go new file mode 100644 index 00000000000..4f84cd9245d --- /dev/null +++ b/pkg/client/listers/eventing/v1beta2/eventtype.go @@ -0,0 +1,99 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +import ( + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" + v1beta2 "knative.dev/eventing/pkg/apis/eventing/v1beta2" +) + +// EventTypeLister helps list EventTypes. +// All objects returned here must be treated as read-only. +type EventTypeLister interface { + // List lists all EventTypes in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1beta2.EventType, err error) + // EventTypes returns an object that can list and get EventTypes. + EventTypes(namespace string) EventTypeNamespaceLister + EventTypeListerExpansion +} + +// eventTypeLister implements the EventTypeLister interface. +type eventTypeLister struct { + indexer cache.Indexer +} + +// NewEventTypeLister returns a new EventTypeLister. +func NewEventTypeLister(indexer cache.Indexer) EventTypeLister { + return &eventTypeLister{indexer: indexer} +} + +// List lists all EventTypes in the indexer. +func (s *eventTypeLister) List(selector labels.Selector) (ret []*v1beta2.EventType, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta2.EventType)) + }) + return ret, err +} + +// EventTypes returns an object that can list and get EventTypes. +func (s *eventTypeLister) EventTypes(namespace string) EventTypeNamespaceLister { + return eventTypeNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// EventTypeNamespaceLister helps list and get EventTypes. +// All objects returned here must be treated as read-only. +type EventTypeNamespaceLister interface { + // List lists all EventTypes in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1beta2.EventType, err error) + // Get retrieves the EventType from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1beta2.EventType, error) + EventTypeNamespaceListerExpansion +} + +// eventTypeNamespaceLister implements the EventTypeNamespaceLister +// interface. +type eventTypeNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all EventTypes in the indexer for a given namespace. +func (s eventTypeNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.EventType, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta2.EventType)) + }) + return ret, err +} + +// Get retrieves the EventType from the indexer for a given namespace and name. +func (s eventTypeNamespaceLister) Get(name string) (*v1beta2.EventType, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1beta2.Resource("eventtype"), name) + } + return obj.(*v1beta2.EventType), nil +} diff --git a/pkg/client/listers/eventing/v1beta2/expansion_generated.go b/pkg/client/listers/eventing/v1beta2/expansion_generated.go new file mode 100644 index 00000000000..4363c014067 --- /dev/null +++ b/pkg/client/listers/eventing/v1beta2/expansion_generated.go @@ -0,0 +1,27 @@ +/* +Copyright 2021 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta2 + +// EventTypeListerExpansion allows custom methods to be added to +// EventTypeLister. +type EventTypeListerExpansion interface{} + +// EventTypeNamespaceListerExpansion allows custom methods to be added to +// EventTypeNamespaceLister. +type EventTypeNamespaceListerExpansion interface{}