diff --git a/Makefile b/Makefile index d86c06740..1a16f9633 100644 --- a/Makefile +++ b/Makefile @@ -316,7 +316,7 @@ CONTROLLER_TOOLS_VERSION ?= v0.17.1 ENVTEST_VERSION ?= release-0.22 GOLANGCI_LINT_VERSION ?= v2.5.0 KAL_VERSION ?= v0.0.0-20250924094418-502783c08f9d -MOCKGEN_VERSION ?= v0.5.0 +MOCKGEN_VERSION ?= v0.6.0 KUTTL_VERSION ?= v0.23.0 GOVULNCHECK_VERSION ?= v1.1.4 OPERATOR_SDK_VERSION ?= v1.41.1 diff --git a/PROJECT b/PROJECT index 051929385..9d26dc4be 100644 --- a/PROJECT +++ b/PROJECT @@ -112,6 +112,14 @@ resources: kind: Subnet path: github.com/k-orc/openstack-resource-controller/api/v1alpha1 version: v1alpha1 +- api: + crdVersion: v1 + namespaced: true + domain: k-orc.cloud + group: openstack + kind: Trunk + path: github.com/k-orc/openstack-resource-controller/api/v1alpha1 + version: v1alpha1 - api: crdVersion: v1 namespaced: true diff --git a/README.md b/README.md index 098e54676..5db46e540 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ kubectl delete -f $ORC_RELEASE | server | | ◐ | ◐ | | server group | | ✔ | ✔ | | subnet | | ◐ | ◐ | +| trunk | | ✔ | ✔ | | volume | | ◐ | ◐ | | volume type | | ◐ | ◐ | | domain | | ✔ | ✔ | diff --git a/api/v1alpha1/trunk_type.go b/api/v1alpha1/trunk_type.go new file mode 100644 index 000000000..883394be7 --- /dev/null +++ b/api/v1alpha1/trunk_type.go @@ -0,0 +1,158 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +// TrunkFilter specifies a filter to select a trunk. At least one parameter must be specified. +// +kubebuilder:validation:MinProperties:=1 +type TrunkFilter struct { + // name of the existing resource + // +optional + Name *OpenStackName `json:"name,omitempty"` + + // description of the existing resource + // +optional + Description *NeutronDescription `json:"description,omitempty"` + + // portRef is a reference to the ORC Port which this trunk is associated with. + // +optional + PortRef *KubernetesNameRef `json:"portRef,omitempty"` + + // projectRef is a reference to the ORC Project this resource is associated with. + // Typically, only used by admin. + // +optional + ProjectRef *KubernetesNameRef `json:"projectRef,omitempty"` + + FilterByNeutronTags `json:",inline"` +} + +// Subport represents a subport that will be attached to a trunk. +type Subport struct { + // portRef is a reference to the ORC Port which will be used as a subport. + // +required + PortRef KubernetesNameRef `json:"portRef"` + + // segmentationType is the type of segmentation to use (e.g., "vlan"). + // +required + // +kubebuilder:validation:MaxLength=64 + SegmentationType string `json:"segmentationType"` + + // segmentationID is the segmentation identifier (e.g., VLAN ID). + // +required + SegmentationID int32 `json:"segmentationID"` +} + +// SubportStatus represents the observed state of a subport. +type SubportStatus struct { + // portID is the ID of the port used as a subport. + // +kubebuilder:validation:MaxLength=1024 + // +optional + PortID string `json:"portID,omitempty"` + + // segmentationType is the type of segmentation used. + // +kubebuilder:validation:MaxLength=1024 + // +optional + SegmentationType string `json:"segmentationType,omitempty"` + + // segmentationID is the segmentation identifier. + // +optional + SegmentationID *int32 `json:"segmentationID,omitempty"` +} + +// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="portRef is immutable" +type TrunkResourceSpec struct { + // name is a human-readable name of the trunk. If not set, the object's name will be used. + // +optional + Name *OpenStackName `json:"name,omitempty"` + + // description is a human-readable description for the resource. + // +optional + Description *NeutronDescription `json:"description,omitempty"` + + // portRef is a reference to the ORC Port which will be used as the parent port for this trunk. + // +required + PortRef KubernetesNameRef `json:"portRef"` + + // tags is a list of tags which will be applied to the trunk. + // +kubebuilder:validation:MaxItems:=64 + // +listType=set + // +optional + Tags []NeutronTag `json:"tags,omitempty"` + + // adminStateUp is the administrative state of the trunk, which is up (true) or down (false). + // +optional + AdminStateUp *bool `json:"adminStateUp,omitempty"` + + // subports are the subports that will be attached to this trunk. + // +kubebuilder:validation:MaxItems:=128 + // +listType=atomic + // +optional + Subports []Subport `json:"subports,omitempty"` + + // projectRef is a reference to the ORC Project this resource is associated with. + // Typically, only used by admin. + // +optional + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="projectRef is immutable" + ProjectRef *KubernetesNameRef `json:"projectRef,omitempty"` +} + +type TrunkResourceStatus struct { + // name is the human-readable name of the resource. Might not be unique. + // +kubebuilder:validation:MaxLength=1024 + // +optional + Name string `json:"name,omitempty"` + + // description is a human-readable description for the resource. + // +kubebuilder:validation:MaxLength=1024 + // +optional + Description string `json:"description,omitempty"` + + // portID is the ID of the parent port. + // +kubebuilder:validation:MaxLength=1024 + // +optional + PortID string `json:"portID,omitempty"` + + // projectID is the project owner of the resource. + // +kubebuilder:validation:MaxLength=1024 + // +optional + ProjectID string `json:"projectID,omitempty"` + + // status indicates the current status of the resource. + // +kubebuilder:validation:MaxLength=1024 + // +optional + Status string `json:"status,omitempty"` + + // tags is the list of tags on the resource. + // +kubebuilder:validation:MaxItems=64 + // +kubebuilder:validation:items:MaxLength=1024 + // +listType=atomic + // +optional + Tags []string `json:"tags,omitempty"` + + // adminStateUp is the administrative state of the trunk, + // which is up (true) or down (false). + // +optional + AdminStateUp *bool `json:"adminStateUp,omitempty"` + + // subports is a list of subports attached to this trunk. + // +kubebuilder:validation:MaxItems=128 + // +listType=atomic + // +optional + Subports []SubportStatus `json:"subports,omitempty"` + + NeutronStatusMetadata `json:",inline"` +} + diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 01364e658..0f23ae9d7 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -4091,6 +4091,302 @@ func (in *SubnetStatus) DeepCopy() *SubnetStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Subport) DeepCopyInto(out *Subport) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subport. +func (in *Subport) DeepCopy() *Subport { + if in == nil { + return nil + } + out := new(Subport) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SubportStatus) DeepCopyInto(out *SubportStatus) { + *out = *in + if in.SegmentationID != nil { + in, out := &in.SegmentationID, &out.SegmentationID + *out = new(int32) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubportStatus. +func (in *SubportStatus) DeepCopy() *SubportStatus { + if in == nil { + return nil + } + out := new(SubportStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Trunk) DeepCopyInto(out *Trunk) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Trunk. +func (in *Trunk) DeepCopy() *Trunk { + if in == nil { + return nil + } + out := new(Trunk) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Trunk) 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 *TrunkFilter) DeepCopyInto(out *TrunkFilter) { + *out = *in + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(OpenStackName) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(NeutronDescription) + **out = **in + } + if in.PortRef != nil { + in, out := &in.PortRef, &out.PortRef + *out = new(KubernetesNameRef) + **out = **in + } + if in.ProjectRef != nil { + in, out := &in.ProjectRef, &out.ProjectRef + *out = new(KubernetesNameRef) + **out = **in + } + in.FilterByNeutronTags.DeepCopyInto(&out.FilterByNeutronTags) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkFilter. +func (in *TrunkFilter) DeepCopy() *TrunkFilter { + if in == nil { + return nil + } + out := new(TrunkFilter) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TrunkImport) DeepCopyInto(out *TrunkImport) { + *out = *in + if in.ID != nil { + in, out := &in.ID, &out.ID + *out = new(string) + **out = **in + } + if in.Filter != nil { + in, out := &in.Filter, &out.Filter + *out = new(TrunkFilter) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkImport. +func (in *TrunkImport) DeepCopy() *TrunkImport { + if in == nil { + return nil + } + out := new(TrunkImport) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TrunkList) DeepCopyInto(out *TrunkList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Trunk, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkList. +func (in *TrunkList) DeepCopy() *TrunkList { + if in == nil { + return nil + } + out := new(TrunkList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *TrunkList) 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 *TrunkResourceSpec) DeepCopyInto(out *TrunkResourceSpec) { + *out = *in + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(OpenStackName) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(NeutronDescription) + **out = **in + } + if in.Tags != nil { + in, out := &in.Tags, &out.Tags + *out = make([]NeutronTag, len(*in)) + copy(*out, *in) + } + if in.AdminStateUp != nil { + in, out := &in.AdminStateUp, &out.AdminStateUp + *out = new(bool) + **out = **in + } + if in.Subports != nil { + in, out := &in.Subports, &out.Subports + *out = make([]Subport, len(*in)) + copy(*out, *in) + } + if in.ProjectRef != nil { + in, out := &in.ProjectRef, &out.ProjectRef + *out = new(KubernetesNameRef) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkResourceSpec. +func (in *TrunkResourceSpec) DeepCopy() *TrunkResourceSpec { + if in == nil { + return nil + } + out := new(TrunkResourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TrunkResourceStatus) DeepCopyInto(out *TrunkResourceStatus) { + *out = *in + if in.Tags != nil { + in, out := &in.Tags, &out.Tags + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.AdminStateUp != nil { + in, out := &in.AdminStateUp, &out.AdminStateUp + *out = new(bool) + **out = **in + } + if in.Subports != nil { + in, out := &in.Subports, &out.Subports + *out = make([]SubportStatus, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + in.NeutronStatusMetadata.DeepCopyInto(&out.NeutronStatusMetadata) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkResourceStatus. +func (in *TrunkResourceStatus) DeepCopy() *TrunkResourceStatus { + if in == nil { + return nil + } + out := new(TrunkResourceStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TrunkSpec) DeepCopyInto(out *TrunkSpec) { + *out = *in + if in.Import != nil { + in, out := &in.Import, &out.Import + *out = new(TrunkImport) + (*in).DeepCopyInto(*out) + } + if in.Resource != nil { + in, out := &in.Resource, &out.Resource + *out = new(TrunkResourceSpec) + (*in).DeepCopyInto(*out) + } + if in.ManagedOptions != nil { + in, out := &in.ManagedOptions, &out.ManagedOptions + *out = new(ManagedOptions) + **out = **in + } + out.CloudCredentialsRef = in.CloudCredentialsRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkSpec. +func (in *TrunkSpec) DeepCopy() *TrunkSpec { + if in == nil { + return nil + } + out := new(TrunkSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TrunkStatus) DeepCopyInto(out *TrunkStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.ID != nil { + in, out := &in.ID, &out.ID + *out = new(string) + **out = **in + } + if in.Resource != nil { + in, out := &in.Resource, &out.Resource + *out = new(TrunkResourceStatus) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TrunkStatus. +func (in *TrunkStatus) DeepCopy() *TrunkStatus { + if in == nil { + return nil + } + out := new(TrunkStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *UserDataSpec) DeepCopyInto(out *UserDataSpec) { *out = *in diff --git a/api/v1alpha1/zz_generated.trunk-resource.go b/api/v1alpha1/zz_generated.trunk-resource.go new file mode 100644 index 000000000..c92b7e118 --- /dev/null +++ b/api/v1alpha1/zz_generated.trunk-resource.go @@ -0,0 +1,177 @@ +// Code generated by resource-generator. DO NOT EDIT. +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// TrunkImport specifies an existing resource which will be imported instead of +// creating a new one +// +kubebuilder:validation:MinProperties:=1 +// +kubebuilder:validation:MaxProperties:=1 +type TrunkImport struct { + // id contains the unique identifier of an existing OpenStack resource. Note + // that when specifying an import by ID, the resource MUST already exist. + // The ORC object will enter an error state if the resource does not exist. + // +optional + // +kubebuilder:validation:Format:=uuid + ID *string `json:"id,omitempty"` + + // filter contains a resource query which is expected to return a single + // result. The controller will continue to retry if filter returns no + // results. If filter returns multiple results the controller will set an + // error state and will not continue to retry. + // +optional + Filter *TrunkFilter `json:"filter,omitempty"` +} + +// TrunkSpec defines the desired state of an ORC object. +// +kubebuilder:validation:XValidation:rule="self.managementPolicy == 'managed' ? has(self.resource) : true",message="resource must be specified when policy is managed" +// +kubebuilder:validation:XValidation:rule="self.managementPolicy == 'managed' ? !has(self.__import__) : true",message="import may not be specified when policy is managed" +// +kubebuilder:validation:XValidation:rule="self.managementPolicy == 'unmanaged' ? !has(self.resource) : true",message="resource may not be specified when policy is unmanaged" +// +kubebuilder:validation:XValidation:rule="self.managementPolicy == 'unmanaged' ? has(self.__import__) : true",message="import must be specified when policy is unmanaged" +// +kubebuilder:validation:XValidation:rule="has(self.managedOptions) ? self.managementPolicy == 'managed' : true",message="managedOptions may only be provided when policy is managed" +type TrunkSpec struct { + // import refers to an existing OpenStack resource which will be imported instead of + // creating a new one. + // +optional + Import *TrunkImport `json:"import,omitempty"` + + // resource specifies the desired state of the resource. + // + // resource may not be specified if the management policy is `unmanaged`. + // + // resource must be specified if the management policy is `managed`. + // +optional + Resource *TrunkResourceSpec `json:"resource,omitempty"` + + // managementPolicy defines how ORC will treat the object. Valid values are + // `managed`: ORC will create, update, and delete the resource; `unmanaged`: + // ORC will import an existing resource, and will not apply updates to it or + // delete it. + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="managementPolicy is immutable" + // +kubebuilder:default:=managed + // +optional + ManagementPolicy ManagementPolicy `json:"managementPolicy,omitempty"` + + // managedOptions specifies options which may be applied to managed objects. + // +optional + ManagedOptions *ManagedOptions `json:"managedOptions,omitempty"` + + // cloudCredentialsRef points to a secret containing OpenStack credentials + // +required + CloudCredentialsRef CloudCredentialsReference `json:"cloudCredentialsRef"` +} + +// TrunkStatus defines the observed state of an ORC resource. +type TrunkStatus struct { + // conditions represents the observed status of the object. + // Known .status.conditions.type are: "Available", "Progressing" + // + // Available represents the availability of the OpenStack resource. If it is + // true then the resource is ready for use. + // + // Progressing indicates whether the controller is still attempting to + // reconcile the current state of the OpenStack resource to the desired + // state. Progressing will be False either because the desired state has + // been achieved, or because some terminal error prevents it from ever being + // achieved and the controller is no longer attempting to reconcile. If + // Progressing is True, an observer waiting on the resource should continue + // to wait. + // + // +kubebuilder:validation:MaxItems:=32 + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + // +optional + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` + + // id is the unique identifier of the OpenStack resource. + // +optional + ID *string `json:"id,omitempty"` + + // resource contains the observed state of the OpenStack resource. + // +optional + Resource *TrunkResourceStatus `json:"resource,omitempty"` +} + +var _ ObjectWithConditions = &Trunk{} + +func (i *Trunk) GetConditions() []metav1.Condition { + return i.Status.Conditions +} + +// +genclient +// +kubebuilder:object:root=true +// +kubebuilder:resource:categories=openstack +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="ID",type="string",JSONPath=".status.id",description="Resource ID" +// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=".status.conditions[?(@.type=='Available')].status",description="Availability status of resource" +// +kubebuilder:printcolumn:name="Message",type="string",JSONPath=".status.conditions[?(@.type=='Progressing')].message",description="Message describing current progress status" + +// Trunk is the Schema for an ORC resource. +type Trunk struct { + metav1.TypeMeta `json:",inline"` + + // metadata contains the object metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // spec specifies the desired state of the resource. + // +optional + Spec TrunkSpec `json:"spec,omitempty"` + + // status defines the observed state of the resource. + // +optional + Status TrunkStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// TrunkList contains a list of Trunk. +type TrunkList struct { + metav1.TypeMeta `json:",inline"` + + // metadata contains the list metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // items contains a list of Trunk. + // +required + Items []Trunk `json:"items"` +} + +func (l *TrunkList) GetItems() []Trunk { + return l.Items +} + +func init() { + SchemeBuilder.Register(&Trunk{}, &TrunkList{}) +} + +func (i *Trunk) GetCloudCredentialsRef() (*string, *CloudCredentialsReference) { + if i == nil { + return nil, nil + } + + return &i.Namespace, &i.Spec.CloudCredentialsRef +} + +var _ CloudCredentialsRefProvider = &Trunk{} diff --git a/cmd/manager/main.go b/cmd/manager/main.go index 13a82ff4a..71d264780 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -41,6 +41,7 @@ import ( "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/server" "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/servergroup" "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/subnet" + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/trunk" "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/volume" "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/volumetype" internalmanager "github.com/k-orc/openstack-resource-controller/v2/internal/manager" @@ -109,6 +110,7 @@ func main() { router.New(scopeFactory), routerinterface.New(scopeFactory), port.New(scopeFactory), + trunk.New(scopeFactory), floatingip.New(scopeFactory), flavor.New(scopeFactory), securitygroup.New(scopeFactory), diff --git a/cmd/models-schema/zz_generated.openapi.go b/cmd/models-schema/zz_generated.openapi.go index b61a6fa23..7f9b61511 100644 --- a/cmd/models-schema/zz_generated.openapi.go +++ b/cmd/models-schema/zz_generated.openapi.go @@ -167,6 +167,16 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.SubnetResourceStatus": schema_openstack_resource_controller_v2_api_v1alpha1_SubnetResourceStatus(ref), "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.SubnetSpec": schema_openstack_resource_controller_v2_api_v1alpha1_SubnetSpec(ref), "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.SubnetStatus": schema_openstack_resource_controller_v2_api_v1alpha1_SubnetStatus(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Subport": schema_openstack_resource_controller_v2_api_v1alpha1_Subport(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.SubportStatus": schema_openstack_resource_controller_v2_api_v1alpha1_SubportStatus(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Trunk": schema_openstack_resource_controller_v2_api_v1alpha1_Trunk(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkFilter": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkFilter(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkImport": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkImport(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkList": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkList(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkResourceSpec": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkResourceSpec(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkResourceStatus": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkResourceStatus(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkSpec": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkSpec(ref), + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkStatus": schema_openstack_resource_controller_v2_api_v1alpha1_TrunkStatus(ref), "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.UserDataSpec": schema_openstack_resource_controller_v2_api_v1alpha1_UserDataSpec(ref), "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Volume": schema_openstack_resource_controller_v2_api_v1alpha1_Volume(ref), "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.VolumeAttachmentStatus": schema_openstack_resource_controller_v2_api_v1alpha1_VolumeAttachmentStatus(ref), @@ -8239,6 +8249,632 @@ func schema_openstack_resource_controller_v2_api_v1alpha1_SubnetStatus(ref commo } } +func schema_openstack_resource_controller_v2_api_v1alpha1_Subport(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Subport represents a subport that will be attached to a trunk.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "portRef": { + SchemaProps: spec.SchemaProps{ + Description: "portRef is a reference to the ORC Port which will be used as a subport.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "segmentationType": { + SchemaProps: spec.SchemaProps{ + Description: "segmentationType is the type of segmentation to use (e.g., \"vlan\").", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "segmentationID": { + SchemaProps: spec.SchemaProps{ + Description: "segmentationID is the segmentation identifier (e.g., VLAN ID).", + Default: 0, + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + Required: []string{"portRef", "segmentationType", "segmentationID"}, + }, + }, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_SubportStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SubportStatus represents the observed state of a subport.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "portID": { + SchemaProps: spec.SchemaProps{ + Description: "portID is the ID of the port used as a subport.", + Type: []string{"string"}, + Format: "", + }, + }, + "segmentationType": { + SchemaProps: spec.SchemaProps{ + Description: "segmentationType is the type of segmentation used.", + Type: []string{"string"}, + Format: "", + }, + }, + "segmentationID": { + SchemaProps: spec.SchemaProps{ + Description: "segmentationID is the segmentation identifier.", + Type: []string{"integer"}, + Format: "int32", + }, + }, + }, + }, + }, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_Trunk(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Trunk is the Schema for an ORC resource.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata contains the object metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Description: "spec specifies the desired state of the resource.", + Default: map[string]interface{}{}, + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status defines the observed state of the resource.", + Default: map[string]interface{}{}, + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkSpec", "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkFilter(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "TrunkFilter specifies a filter to select a trunk. At least one parameter must be specified.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name of the existing resource", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Description: "description of the existing resource", + Type: []string{"string"}, + Format: "", + }, + }, + "portRef": { + SchemaProps: spec.SchemaProps{ + Description: "portRef is a reference to the ORC Port which this trunk is associated with.", + Type: []string{"string"}, + Format: "", + }, + }, + "projectRef": { + SchemaProps: spec.SchemaProps{ + Description: "projectRef is a reference to the ORC Project this resource is associated with. Typically, only used by admin.", + Type: []string{"string"}, + Format: "", + }, + }, + "tags": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "set", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "tags is a list of tags to filter by. If specified, the resource must have all of the tags specified to be included in the result.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "tagsAny": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "set", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "tagsAny is a list of tags to filter by. If specified, the resource must have at least one of the tags specified to be included in the result.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "notTags": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "set", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "notTags is a list of tags to filter by. If specified, resources which contain all of the given tags will be excluded from the result.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "notTagsAny": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "set", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "notTagsAny is a list of tags to filter by. If specified, resources which contain any of the given tags will be excluded from the result.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkImport(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "TrunkImport specifies an existing resource which will be imported instead of creating a new one", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "id": { + SchemaProps: spec.SchemaProps{ + Description: "id contains the unique identifier of an existing OpenStack resource. Note that when specifying an import by ID, the resource MUST already exist. The ORC object will enter an error state if the resource does not exist.", + Type: []string{"string"}, + Format: "", + }, + }, + "filter": { + SchemaProps: spec.SchemaProps{ + Description: "filter contains a resource query which is expected to return a single result. The controller will continue to retry if filter returns no results. If filter returns multiple results the controller will set an error state and will not continue to retry.", + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkFilter"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkFilter"}, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "TrunkList contains a list of Trunk.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Description: "metadata contains the list metadata", + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Description: "items contains a list of Trunk.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Trunk"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Trunk", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkResourceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is a human-readable name of the trunk. If not set, the object's name will be used.", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Description: "description is a human-readable description for the resource.", + Type: []string{"string"}, + Format: "", + }, + }, + "portRef": { + SchemaProps: spec.SchemaProps{ + Description: "portRef is a reference to the ORC Port which will be used as the parent port for this trunk.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "tags": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "set", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "tags is a list of tags which will be applied to the trunk.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "adminStateUp": { + SchemaProps: spec.SchemaProps{ + Description: "adminStateUp is the administrative state of the trunk, which is up (true) or down (false).", + Type: []string{"boolean"}, + Format: "", + }, + }, + "subports": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "subports are the subports that will be attached to this trunk.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Subport"), + }, + }, + }, + }, + }, + "projectRef": { + SchemaProps: spec.SchemaProps{ + Description: "projectRef is a reference to the ORC Project this resource is associated with. Typically, only used by admin.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"portRef"}, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.Subport"}, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkResourceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "name is the human-readable name of the resource. Might not be unique.", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Description: "description is a human-readable description for the resource.", + Type: []string{"string"}, + Format: "", + }, + }, + "portID": { + SchemaProps: spec.SchemaProps{ + Description: "portID is the ID of the parent port.", + Type: []string{"string"}, + Format: "", + }, + }, + "projectID": { + SchemaProps: spec.SchemaProps{ + Description: "projectID is the project owner of the resource.", + Type: []string{"string"}, + Format: "", + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Description: "status indicates the current status of the resource.", + Type: []string{"string"}, + Format: "", + }, + }, + "tags": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "tags is the list of tags on the resource.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + "adminStateUp": { + SchemaProps: spec.SchemaProps{ + Description: "adminStateUp is the administrative state of the trunk, which is up (true) or down (false).", + Type: []string{"boolean"}, + Format: "", + }, + }, + "subports": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "subports is a list of subports attached to this trunk.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.SubportStatus"), + }, + }, + }, + }, + }, + "createdAt": { + SchemaProps: spec.SchemaProps{ + Description: "createdAt shows the date and time when the resource was created. The date and time stamp format is ISO 8601", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "updatedAt": { + SchemaProps: spec.SchemaProps{ + Description: "updatedAt shows the date and time when the resource was updated. The date and time stamp format is ISO 8601", + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), + }, + }, + "revisionNumber": { + SchemaProps: spec.SchemaProps{ + Description: "revisionNumber optionally set via extensions/standard-attr-revisions", + Type: []string{"integer"}, + Format: "int64", + }, + }, + }, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.SubportStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "TrunkSpec defines the desired state of an ORC object.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "import": { + SchemaProps: spec.SchemaProps{ + Description: "import refers to an existing OpenStack resource which will be imported instead of creating a new one.", + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkImport"), + }, + }, + "resource": { + SchemaProps: spec.SchemaProps{ + Description: "resource specifies the desired state of the resource.\n\nresource may not be specified if the management policy is `unmanaged`.\n\nresource must be specified if the management policy is `managed`.", + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkResourceSpec"), + }, + }, + "managementPolicy": { + SchemaProps: spec.SchemaProps{ + Description: "managementPolicy defines how ORC will treat the object. Valid values are `managed`: ORC will create, update, and delete the resource; `unmanaged`: ORC will import an existing resource, and will not apply updates to it or delete it.", + Type: []string{"string"}, + Format: "", + }, + }, + "managedOptions": { + SchemaProps: spec.SchemaProps{ + Description: "managedOptions specifies options which may be applied to managed objects.", + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.ManagedOptions"), + }, + }, + "cloudCredentialsRef": { + SchemaProps: spec.SchemaProps{ + Description: "cloudCredentialsRef points to a secret containing OpenStack credentials", + Default: map[string]interface{}{}, + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.CloudCredentialsReference"), + }, + }, + }, + Required: []string{"cloudCredentialsRef"}, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.CloudCredentialsReference", "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.ManagedOptions", "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkImport", "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkResourceSpec"}, + } +} + +func schema_openstack_resource_controller_v2_api_v1alpha1_TrunkStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "TrunkStatus defines the observed state of an ORC resource.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "conditions": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-map-keys": []interface{}{ + "type", + }, + "x-kubernetes-list-type": "map", + "x-kubernetes-patch-merge-key": "type", + "x-kubernetes-patch-strategy": "merge", + }, + }, + SchemaProps: spec.SchemaProps{ + Description: "conditions represents the observed status of the object. Known .status.conditions.type are: \"Available\", \"Progressing\"\n\nAvailable represents the availability of the OpenStack resource. If it is true then the resource is ready for use.\n\nProgressing indicates whether the controller is still attempting to reconcile the current state of the OpenStack resource to the desired state. Progressing will be False either because the desired state has been achieved, or because some terminal error prevents it from ever being achieved and the controller is no longer attempting to reconcile. If Progressing is True, an observer waiting on the resource should continue to wait.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), + }, + }, + }, + }, + }, + "id": { + SchemaProps: spec.SchemaProps{ + Description: "id is the unique identifier of the OpenStack resource.", + Type: []string{"string"}, + Format: "", + }, + }, + "resource": { + SchemaProps: spec.SchemaProps{ + Description: "resource contains the observed state of the OpenStack resource.", + Ref: ref("github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkResourceStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1.TrunkResourceStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.Condition"}, + } +} + func schema_openstack_resource_controller_v2_api_v1alpha1_UserDataSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ diff --git a/cmd/resource-generator/main.go b/cmd/resource-generator/main.go index b40288feb..6f0e0ebdc 100644 --- a/cmd/resource-generator/main.go +++ b/cmd/resource-generator/main.go @@ -139,6 +139,10 @@ var resources []templateFields = []templateFields{ Name: "Subnet", ExistingOSClient: true, }, + { + Name: "Trunk", + ExistingOSClient: true, + }, { Name: "Volume", }, diff --git a/config/crd/bases/openstack.k-orc.cloud_trunks.yaml b/config/crd/bases/openstack.k-orc.cloud_trunks.yaml new file mode 100644 index 000000000..5daf493e7 --- /dev/null +++ b/config/crd/bases/openstack.k-orc.cloud_trunks.yaml @@ -0,0 +1,485 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.1 + name: trunks.openstack.k-orc.cloud +spec: + group: openstack.k-orc.cloud + names: + categories: + - openstack + kind: Trunk + listKind: TrunkList + plural: trunks + singular: trunk + scope: Namespaced + versions: + - additionalPrinterColumns: + - description: Resource ID + jsonPath: .status.id + name: ID + type: string + - description: Availability status of resource + jsonPath: .status.conditions[?(@.type=='Available')].status + name: Available + type: string + - description: Message describing current progress status + jsonPath: .status.conditions[?(@.type=='Progressing')].message + name: Message + type: string + name: v1alpha1 + schema: + openAPIV3Schema: + description: Trunk is the Schema for an ORC resource. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: spec specifies the desired state of the resource. + properties: + cloudCredentialsRef: + description: cloudCredentialsRef points to a secret containing OpenStack + credentials + properties: + cloudName: + description: cloudName specifies the name of the entry in the + clouds.yaml file to use. + maxLength: 256 + minLength: 1 + type: string + secretName: + description: |- + secretName is the name of a secret in the same namespace as the resource being provisioned. + The secret must contain a key named `clouds.yaml` which contains an OpenStack clouds.yaml file. + The secret may optionally contain a key named `cacert` containing a PEM-encoded CA certificate. + maxLength: 253 + minLength: 1 + type: string + required: + - cloudName + - secretName + type: object + import: + description: |- + import refers to an existing OpenStack resource which will be imported instead of + creating a new one. + maxProperties: 1 + minProperties: 1 + properties: + filter: + description: |- + filter contains a resource query which is expected to return a single + result. The controller will continue to retry if filter returns no + results. If filter returns multiple results the controller will set an + error state and will not continue to retry. + minProperties: 1 + properties: + description: + description: description of the existing resource + maxLength: 255 + minLength: 1 + type: string + name: + description: name of the existing resource + maxLength: 255 + minLength: 1 + pattern: ^[^,]+$ + type: string + notTags: + description: |- + notTags is a list of tags to filter by. If specified, resources which + contain all of the given tags will be excluded from the result. + items: + description: |- + NeutronTag represents a tag on a Neutron resource. + It may not be empty and may not contain commas. + maxLength: 255 + minLength: 1 + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: set + notTagsAny: + description: |- + notTagsAny is a list of tags to filter by. If specified, resources + which contain any of the given tags will be excluded from the result. + items: + description: |- + NeutronTag represents a tag on a Neutron resource. + It may not be empty and may not contain commas. + maxLength: 255 + minLength: 1 + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: set + portRef: + description: portRef is a reference to the ORC Port which + this trunk is associated with. + maxLength: 253 + minLength: 1 + type: string + projectRef: + description: |- + projectRef is a reference to the ORC Project this resource is associated with. + Typically, only used by admin. + maxLength: 253 + minLength: 1 + type: string + tags: + description: |- + tags is a list of tags to filter by. If specified, the resource must + have all of the tags specified to be included in the result. + items: + description: |- + NeutronTag represents a tag on a Neutron resource. + It may not be empty and may not contain commas. + maxLength: 255 + minLength: 1 + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: set + tagsAny: + description: |- + tagsAny is a list of tags to filter by. If specified, the resource + must have at least one of the tags specified to be included in the + result. + items: + description: |- + NeutronTag represents a tag on a Neutron resource. + It may not be empty and may not contain commas. + maxLength: 255 + minLength: 1 + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: set + type: object + id: + description: |- + id contains the unique identifier of an existing OpenStack resource. Note + that when specifying an import by ID, the resource MUST already exist. + The ORC object will enter an error state if the resource does not exist. + format: uuid + type: string + type: object + managedOptions: + description: managedOptions specifies options which may be applied + to managed objects. + properties: + onDelete: + default: delete + description: |- + onDelete specifies the behaviour of the controller when the ORC + object is deleted. Options are `delete` - delete the OpenStack resource; + `detach` - do not delete the OpenStack resource. If not specified, the + default is `delete`. + enum: + - delete + - detach + type: string + type: object + managementPolicy: + default: managed + description: |- + managementPolicy defines how ORC will treat the object. Valid values are + `managed`: ORC will create, update, and delete the resource; `unmanaged`: + ORC will import an existing resource, and will not apply updates to it or + delete it. + enum: + - managed + - unmanaged + type: string + x-kubernetes-validations: + - message: managementPolicy is immutable + rule: self == oldSelf + resource: + description: |- + resource specifies the desired state of the resource. + + resource may not be specified if the management policy is `unmanaged`. + + resource must be specified if the management policy is `managed`. + properties: + adminStateUp: + description: adminStateUp is the administrative state of the trunk, + which is up (true) or down (false). + type: boolean + description: + description: description is a human-readable description for the + resource. + maxLength: 255 + minLength: 1 + type: string + name: + description: name is a human-readable name of the trunk. If not + set, the object's name will be used. + maxLength: 255 + minLength: 1 + pattern: ^[^,]+$ + type: string + portRef: + description: portRef is a reference to the ORC Port which will + be used as the parent port for this trunk. + maxLength: 253 + minLength: 1 + type: string + projectRef: + description: |- + projectRef is a reference to the ORC Project this resource is associated with. + Typically, only used by admin. + maxLength: 253 + minLength: 1 + type: string + x-kubernetes-validations: + - message: projectRef is immutable + rule: self == oldSelf + subports: + description: subports are the subports that will be attached to + this trunk. + items: + description: Subport represents a subport that will be attached + to a trunk. + properties: + portRef: + description: portRef is a reference to the ORC Port which + will be used as a subport. + maxLength: 253 + minLength: 1 + type: string + segmentationID: + description: segmentationID is the segmentation identifier + (e.g., VLAN ID). + format: int32 + type: integer + segmentationType: + description: segmentationType is the type of segmentation + to use (e.g., "vlan"). + maxLength: 64 + type: string + required: + - portRef + - segmentationID + - segmentationType + type: object + maxItems: 128 + type: array + x-kubernetes-list-type: atomic + tags: + description: tags is a list of tags which will be applied to the + trunk. + items: + description: |- + NeutronTag represents a tag on a Neutron resource. + It may not be empty and may not contain commas. + maxLength: 255 + minLength: 1 + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: set + required: + - portRef + type: object + x-kubernetes-validations: + - message: portRef is immutable + rule: self == oldSelf + required: + - cloudCredentialsRef + type: object + x-kubernetes-validations: + - message: resource must be specified when policy is managed + rule: 'self.managementPolicy == ''managed'' ? has(self.resource) : true' + - message: import may not be specified when policy is managed + rule: 'self.managementPolicy == ''managed'' ? !has(self.__import__) + : true' + - message: resource may not be specified when policy is unmanaged + rule: 'self.managementPolicy == ''unmanaged'' ? !has(self.resource) + : true' + - message: import must be specified when policy is unmanaged + rule: 'self.managementPolicy == ''unmanaged'' ? has(self.__import__) + : true' + - message: managedOptions may only be provided when policy is managed + rule: 'has(self.managedOptions) ? self.managementPolicy == ''managed'' + : true' + status: + description: status defines the observed state of the resource. + properties: + conditions: + description: |- + conditions represents the observed status of the object. + Known .status.conditions.type are: "Available", "Progressing" + + Available represents the availability of the OpenStack resource. If it is + true then the resource is ready for use. + + Progressing indicates whether the controller is still attempting to + reconcile the current state of the OpenStack resource to the desired + state. Progressing will be False either because the desired state has + been achieved, or because some terminal error prevents it from ever being + achieved and the controller is no longer attempting to reconcile. If + Progressing is True, an observer waiting on the resource should continue + to wait. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + maxItems: 32 + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + id: + description: id is the unique identifier of the OpenStack resource. + type: string + resource: + description: resource contains the observed state of the OpenStack + resource. + properties: + adminStateUp: + description: |- + adminStateUp is the administrative state of the trunk, + which is up (true) or down (false). + type: boolean + createdAt: + description: createdAt shows the date and time when the resource + was created. The date and time stamp format is ISO 8601 + format: date-time + type: string + description: + description: description is a human-readable description for the + resource. + maxLength: 1024 + type: string + name: + description: name is the human-readable name of the resource. + Might not be unique. + maxLength: 1024 + type: string + portID: + description: portID is the ID of the parent port. + maxLength: 1024 + type: string + projectID: + description: projectID is the project owner of the resource. + maxLength: 1024 + type: string + revisionNumber: + description: revisionNumber optionally set via extensions/standard-attr-revisions + format: int64 + type: integer + status: + description: status indicates the current status of the resource. + maxLength: 1024 + type: string + subports: + description: subports is a list of subports attached to this trunk. + items: + description: SubportStatus represents the observed state of + a subport. + properties: + portID: + description: portID is the ID of the port used as a subport. + maxLength: 1024 + type: string + segmentationID: + description: segmentationID is the segmentation identifier. + format: int32 + type: integer + segmentationType: + description: segmentationType is the type of segmentation + used. + maxLength: 1024 + type: string + type: object + maxItems: 128 + type: array + x-kubernetes-list-type: atomic + tags: + description: tags is the list of tags on the resource. + items: + maxLength: 1024 + type: string + maxItems: 64 + type: array + x-kubernetes-list-type: atomic + updatedAt: + description: updatedAt shows the date and time when the resource + was updated. The date and time stamp format is ISO 8601 + format: date-time + type: string + type: object + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index 43188a70b..0e63a9087 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -16,6 +16,7 @@ resources: - bases/openstack.k-orc.cloud_servers.yaml - bases/openstack.k-orc.cloud_servergroups.yaml - bases/openstack.k-orc.cloud_subnets.yaml +- bases/openstack.k-orc.cloud_trunks.yaml - bases/openstack.k-orc.cloud_volumes.yaml - bases/openstack.k-orc.cloud_volumetypes.yaml # +kubebuilder:scaffold:crdkustomizeresource diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 4c2ae9b14..f13784e88 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -30,6 +30,7 @@ rules: - servergroups - servers - subnets + - trunks - volumes - volumetypes verbs: @@ -56,6 +57,7 @@ rules: - servergroups/status - servers/status - subnets/status + - trunks/status - volumes/status - volumetypes/status verbs: diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml index db5abb1b4..bb0da845e 100644 --- a/config/samples/kustomization.yaml +++ b/config/samples/kustomization.yaml @@ -14,6 +14,7 @@ resources: - openstack_v1alpha1_server.yaml - openstack_v1alpha1_servergroup.yaml - openstack_v1alpha1_subnet.yaml +- openstack_v1alpha1_trunk.yaml - openstack_v1alpha1_volume.yaml - openstack_v1alpha1_volumetype.yaml # +kubebuilder:scaffold:manifestskustomizesamples diff --git a/config/samples/openstack_v1alpha1_trunk.yaml b/config/samples/openstack_v1alpha1_trunk.yaml new file mode 100644 index 000000000..1b77e9e02 --- /dev/null +++ b/config/samples/openstack_v1alpha1_trunk.yaml @@ -0,0 +1,26 @@ +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-sample +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-sample + description: Sample Trunk + portRef: port-sample + tags: + - tag1 + - tag2 + adminStateUp: true + subports: + - portRef: port-sample-subport1 + segmentationType: vlan + segmentationID: 100 + - portRef: port-sample-subport2 + segmentationType: vlan + segmentationID: 200 + projectRef: project-sample + diff --git a/examples/components/kustomizeconfig/kustomizeconfig.yaml b/examples/components/kustomizeconfig/kustomizeconfig.yaml index c043f7b19..fa1ace123 100644 --- a/examples/components/kustomizeconfig/kustomizeconfig.yaml +++ b/examples/components/kustomizeconfig/kustomizeconfig.yaml @@ -23,6 +23,8 @@ nameReference: kind: Server - path: spec/cloudCredentialsRef/secretName kind: Subnet + - path: spec/cloudCredentialsRef/secretName + kind: Trunk - kind: Network fieldSpecs: @@ -70,6 +72,12 @@ nameReference: kind: FloatingIP - path: spec/resource/ports[]/portRef kind: Server + - path: spec/resource/portRef + kind: Trunk + - path: spec/resource/subports[]/portRef + kind: Trunk + - path: spec/import/filter/portRef + kind: Trunk - kind: Project fieldSpecs: @@ -83,3 +91,7 @@ nameReference: kind: Port - path: spec/resource/projectRef kind: SecurityGroup + - path: spec/resource/projectRef + kind: Trunk + - path: spec/import/filter/projectRef + kind: Trunk diff --git a/internal/controllers/trunk/actuator.go b/internal/controllers/trunk/actuator.go new file mode 100644 index 000000000..f607c07df --- /dev/null +++ b/internal/controllers/trunk/actuator.go @@ -0,0 +1,467 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 trunk + +import ( + "context" + "fmt" + "iter" + + "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/trunks" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + orcv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/interfaces" + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/progress" + "github.com/k-orc/openstack-resource-controller/v2/internal/logging" + osclients "github.com/k-orc/openstack-resource-controller/v2/internal/osclients" + orcerrors "github.com/k-orc/openstack-resource-controller/v2/internal/util/errors" + "github.com/k-orc/openstack-resource-controller/v2/internal/util/tags" +) + +type ( + osResourceT = trunks.Trunk + + createResourceActuator = interfaces.CreateResourceActuator[orcObjectPT, orcObjectT, filterT, osResourceT] + deleteResourceActuator = interfaces.DeleteResourceActuator[orcObjectPT, orcObjectT, osResourceT] + reconcileResourceActuator = interfaces.ReconcileResourceActuator[orcObjectPT, osResourceT] + resourceReconciler = interfaces.ResourceReconciler[orcObjectPT, osResourceT] + helperFactory = interfaces.ResourceHelperFactory[orcObjectPT, orcObjectT, resourceSpecT, filterT, osResourceT] + trunkIterator = iter.Seq2[*osResourceT, error] +) + +type trunkActuator struct { + osClient osclients.NetworkClient + k8sClient client.Client +} + +var _ createResourceActuator = trunkActuator{} +var _ deleteResourceActuator = trunkActuator{} + +func (trunkActuator) GetResourceID(osResource *osResourceT) string { + return osResource.ID +} + +func (actuator trunkActuator) GetOSResourceByID(ctx context.Context, id string) (*osResourceT, progress.ReconcileStatus) { + trunk, err := actuator.osClient.GetTrunk(ctx, id) + if err != nil { + return nil, progress.WrapError(err) + } + return trunk, nil +} + +func (actuator trunkActuator) ListOSResourcesForAdoption(ctx context.Context, obj *orcv1alpha1.Trunk) (trunkIterator, bool) { + if obj.Spec.Resource == nil { + return nil, false + } + + listOpts := trunks.ListOpts{Name: getResourceName(obj)} + trunks, err := actuator.osClient.ListTrunk(ctx, listOpts) + if err != nil { + return func(yield func(*osResourceT, error) bool) { + yield(nil, err) + }, true + } + return func(yield func(*osResourceT, error) bool) { + for i := range trunks { + if !yield(&trunks[i], nil) { + return + } + } + }, true +} + +func (actuator trunkActuator) ListOSResourcesForImport(ctx context.Context, obj orcObjectPT, filter filterT) (iter.Seq2[*osResourceT, error], progress.ReconcileStatus) { + var reconcileStatus progress.ReconcileStatus + + port := &orcv1alpha1.Port{} + if filter.PortRef != nil { + portKey := client.ObjectKey{Name: string(*filter.PortRef), Namespace: obj.Namespace} + if err := actuator.k8sClient.Get(ctx, portKey, port); err != nil { + if apierrors.IsNotFound(err) { + reconcileStatus = reconcileStatus.WithReconcileStatus( + progress.WaitingOnObject("Port", portKey.Name, progress.WaitingOnCreation)) + } else { + reconcileStatus = reconcileStatus.WithReconcileStatus( + progress.WrapError(fmt.Errorf("fetching port %s: %w", portKey.Name, err))) + } + } else { + if !orcv1alpha1.IsAvailable(port) || port.Status.ID == nil { + reconcileStatus = reconcileStatus.WithReconcileStatus( + progress.WaitingOnObject("Port", portKey.Name, progress.WaitingOnReady)) + } + } + } + + project := &orcv1alpha1.Project{} + if filter.ProjectRef != nil { + projectKey := client.ObjectKey{Name: string(*filter.ProjectRef), Namespace: obj.Namespace} + if err := actuator.k8sClient.Get(ctx, projectKey, project); err != nil { + if apierrors.IsNotFound(err) { + reconcileStatus = reconcileStatus.WithReconcileStatus( + progress.WaitingOnObject("Project", projectKey.Name, progress.WaitingOnCreation)) + } else { + reconcileStatus = reconcileStatus.WithReconcileStatus( + progress.WrapError(fmt.Errorf("fetching project %s: %w", projectKey.Name, err))) + } + } else { + if !orcv1alpha1.IsAvailable(project) || project.Status.ID == nil { + reconcileStatus = reconcileStatus.WithReconcileStatus( + progress.WaitingOnObject("Project", projectKey.Name, progress.WaitingOnReady)) + } + } + } + + if needsReschedule, _ := reconcileStatus.NeedsReschedule(); needsReschedule { + return nil, reconcileStatus + } + + listOpts := trunks.ListOpts{ + Name: string(ptr.Deref(filter.Name, "")), + Description: string(ptr.Deref(filter.Description, "")), + PortID: ptr.Deref(port.Status.ID, ""), + ProjectID: ptr.Deref(project.Status.ID, ""), + Tags: tags.Join(filter.Tags), + TagsAny: tags.Join(filter.TagsAny), + NotTags: tags.Join(filter.NotTags), + NotTagsAny: tags.Join(filter.NotTagsAny), + } + + trunksList, err := actuator.osClient.ListTrunk(ctx, listOpts) + if err != nil { + return func(yield func(*osResourceT, error) bool) { + yield(nil, err) + }, nil + } + return func(yield func(*osResourceT, error) bool) { + for i := range trunksList { + if !yield(&trunksList[i], nil) { + return + } + } + }, nil +} + +func (actuator trunkActuator) CreateResource(ctx context.Context, obj *orcv1alpha1.Trunk) (*osResourceT, progress.ReconcileStatus) { + resource := obj.Spec.Resource + if resource == nil { + // Should have been caught by API validation + return nil, progress.WrapError(orcerrors.Terminal(orcv1alpha1.ConditionReasonInvalidConfiguration, "Creation requested, but spec.resource is not set")) + } + + // Fetch all dependencies and ensure they have our finalizer + port, portDepRS := portDependency.GetDependency( + ctx, actuator.k8sClient, obj, func(dep *orcv1alpha1.Port) bool { + return orcv1alpha1.IsAvailable(dep) && dep.Status.ID != nil + }, + ) + portMap, subportDepRS := subportDependency.GetDependencies( + ctx, actuator.k8sClient, obj, func(dep *orcv1alpha1.Port) bool { + return orcv1alpha1.IsAvailable(dep) && dep.Status.ID != nil + }, + ) + reconcileStatus := progress.NewReconcileStatus(). + WithReconcileStatus(portDepRS). + WithReconcileStatus(subportDepRS) + + var projectID string + if resource.ProjectRef != nil { + project, projectDepRS := projectDependency.GetDependency( + ctx, actuator.k8sClient, obj, func(dep *orcv1alpha1.Project) bool { + return orcv1alpha1.IsAvailable(dep) && dep.Status.ID != nil + }, + ) + reconcileStatus = reconcileStatus.WithReconcileStatus(projectDepRS) + if project != nil { + projectID = ptr.Deref(project.Status.ID, "") + } + } + + if needsReschedule, _ := reconcileStatus.NeedsReschedule(); needsReschedule { + return nil, reconcileStatus + } + + createOpts := trunks.CreateOpts{ + PortID: *port.Status.ID, + Name: getResourceName(obj), + Description: string(ptr.Deref(resource.Description, "")), + AdminStateUp: resource.AdminStateUp, + ProjectID: projectID, + } + + // Convert subports from spec to OpenStack format + if len(resource.Subports) > 0 { + createOpts.Subports = make([]trunks.Subport, len(resource.Subports)) + for i := range resource.Subports { + portName := string(resource.Subports[i].PortRef) + subportPort, ok := portMap[portName] + if !ok { + // Programming error + return nil, progress.WrapError(fmt.Errorf("subport port %s was not returned by GetDependencies", portName)) + } + createOpts.Subports[i] = trunks.Subport{ + PortID: *subportPort.Status.ID, + SegmentationType: resource.Subports[i].SegmentationType, + SegmentationID: int(resource.Subports[i].SegmentationID), + } + } + } + + osResource, err := actuator.osClient.CreateTrunk(ctx, createOpts) + if err != nil { + // We should require the spec to be updated before retrying a create which returned a conflict + if orcerrors.IsConflict(err) { + err = orcerrors.Terminal(orcv1alpha1.ConditionReasonInvalidConfiguration, "invalid configuration creating resource: "+err.Error(), err) + } + return nil, progress.WrapError(err) + } + + return osResource, nil +} + +func (actuator trunkActuator) DeleteResource(ctx context.Context, _ *orcv1alpha1.Trunk, osResource *osResourceT) progress.ReconcileStatus { + return progress.WrapError(actuator.osClient.DeleteTrunk(ctx, osResource.ID)) +} + +var _ reconcileResourceActuator = trunkActuator{} + +func (actuator trunkActuator) GetResourceReconcilers(ctx context.Context, orcObject orcObjectPT, osResource *osResourceT, controller interfaces.ResourceController) ([]resourceReconciler, progress.ReconcileStatus) { + return []resourceReconciler{ + tags.ReconcileTags[orcObjectPT, osResourceT](orcObject.Spec.Resource.Tags, osResource.Tags, tags.NewNeutronTagReplacer(actuator.osClient, "trunks", osResource.ID)), + actuator.updateResource, + actuator.reconcileSubports, + }, nil +} + +func (actuator trunkActuator) updateResource(ctx context.Context, obj orcObjectPT, osResource *osResourceT) progress.ReconcileStatus { + log := ctrl.LoggerFrom(ctx) + resource := obj.Spec.Resource + if resource == nil { + return progress.WrapError( + orcerrors.Terminal(orcv1alpha1.ConditionReasonInvalidConfiguration, "Update requested, but spec.resource is not set")) + } + + var updateOpts trunks.UpdateOpts + needsUpdate := false + + // Handle name update + name := getResourceName(obj) + if osResource.Name != name { + updateOpts.Name = &name + needsUpdate = true + } + + // Handle description update + description := string(ptr.Deref(resource.Description, "")) + if osResource.Description != description { + updateOpts.Description = &description + needsUpdate = true + } + + // Handle adminStateUp update + if resource.AdminStateUp != nil && *resource.AdminStateUp != osResource.AdminStateUp { + updateOpts.AdminStateUp = resource.AdminStateUp + needsUpdate = true + } + + if !needsUpdate { + log.V(logging.Debug).Info("No changes") + return nil + } + + updateOpts.RevisionNumber = &osResource.RevisionNumber + + _, err := actuator.osClient.UpdateTrunk(ctx, osResource.ID, updateOpts) + + // We should require the spec to be updated before retrying an update which returned a conflict + if orcerrors.IsConflict(err) { + err = orcerrors.Terminal(orcv1alpha1.ConditionReasonInvalidConfiguration, "invalid configuration updating resource: "+err.Error(), err) + } + + if err != nil { + return progress.WrapError(err) + } + + // Refresh is needed to get the updated resource state from OpenStack after modifications. + // This ensures the status accurately reflects the current state before the next reconciliation cycle. + return progress.NeedsRefresh() +} + +// reconcileSubports ensures the trunk's subports match the desired state from the spec. +// It handles adding new subports, removing deleted ones, and updating existing subports. +// Note: OpenStack trunk API does not support in-place updates of subport segmentation, +// so changes require removing and re-adding the subport, which may cause brief network interruption. +func (actuator trunkActuator) reconcileSubports(ctx context.Context, obj orcObjectPT, osResource *osResourceT) progress.ReconcileStatus { + log := ctrl.LoggerFrom(ctx) + resource := obj.Spec.Resource + if resource == nil { + return nil + } + + // Get current subports from OpenStack + currentSubports, err := actuator.osClient.ListTrunkSubports(ctx, osResource.ID) + if err != nil { + return progress.WrapError(fmt.Errorf("failed to list trunk subports: %w", err)) + } + + // Get desired subports from spec + portMap, subportDepRS := subportDependency.GetDependencies( + ctx, actuator.k8sClient, obj, func(dep *orcv1alpha1.Port) bool { + return orcv1alpha1.IsAvailable(dep) && dep.Status.ID != nil + }, + ) + if needsReschedule, _ := subportDepRS.NeedsReschedule(); needsReschedule { + return subportDepRS + } + + desiredSubports := make([]trunks.Subport, 0, len(resource.Subports)) + for i := range resource.Subports { + portName := string(resource.Subports[i].PortRef) + subportPort, ok := portMap[portName] + if !ok { + // Port not ready yet, will be retried + log.V(logging.Debug).Info("Skipping subport: port not ready", "portRef", portName) + continue + } + desiredSubports = append(desiredSubports, trunks.Subport{ + PortID: *subportPort.Status.ID, + SegmentationType: resource.Subports[i].SegmentationType, + SegmentationID: int(resource.Subports[i].SegmentationID), + }) + } + + // Build maps for comparison (keyed by PortID for efficient lookup) + currentMap := buildSubportMap(currentSubports) + desiredMap := buildSubportMap(desiredSubports) + + // Find subports to add + // Note: OpenStack trunk API does not support in-place updates of subport segmentation. + // When segmentation type or ID changes, we must remove the old subport and add it back + // with the new segmentation. This may cause a brief network interruption for that subport. + toAdd := []trunks.Subport{} + for portID, desired := range desiredMap { + if current, exists := currentMap[portID]; !exists { + toAdd = append(toAdd, desired) + } else if subportNeedsUpdate(current, desired) { + // Subport exists but with different segmentation, need to remove and re-add + // First remove the old one + removeOpts := trunks.RemoveSubportsOpts{ + Subports: []trunks.RemoveSubport{{PortID: portID}}, + } + if err := actuator.osClient.RemoveSubports(ctx, osResource.ID, removeOpts); err != nil { + return progress.WrapError(fmt.Errorf("failed to remove subport %s: %w", portID, err)) + } + toAdd = append(toAdd, desired) + } + } + + // Find subports to remove + toRemove := []trunks.RemoveSubport{} + for portID := range currentMap { + if _, exists := desiredMap[portID]; !exists { + toRemove = append(toRemove, trunks.RemoveSubport{PortID: portID}) + } + } + + // Apply changes + if len(toRemove) > 0 { + removeOpts := trunks.RemoveSubportsOpts{Subports: toRemove} + if err := actuator.osClient.RemoveSubports(ctx, osResource.ID, removeOpts); err != nil { + return progress.WrapError(fmt.Errorf("failed to remove subports: %w", err)) + } + log.V(logging.Debug).Info("Removed subports", "count", len(toRemove)) + } + + if len(toAdd) > 0 { + addOpts := trunks.AddSubportsOpts{Subports: toAdd} + if _, err := actuator.osClient.AddSubports(ctx, osResource.ID, addOpts); err != nil { + return progress.WrapError(fmt.Errorf("failed to add subports: %w", err)) + } + log.V(logging.Debug).Info("Added subports", "count", len(toAdd)) + } + + if len(toAdd) > 0 || len(toRemove) > 0 { + // Refresh is needed to get the updated subport list from OpenStack after modifications. + // This ensures the status accurately reflects the current state before the next reconciliation. + return progress.NeedsRefresh() + } + + return nil +} + +// buildSubportMap creates a map of subports keyed by PortID for efficient comparison. +func buildSubportMap(subports []trunks.Subport) map[string]trunks.Subport { + result := make(map[string]trunks.Subport, len(subports)) + for _, subport := range subports { + result[subport.PortID] = subport + } + return result +} + +// subportNeedsUpdate checks if a subport needs to be updated by comparing segmentation parameters. +// OpenStack trunk API does not support in-place updates, so any change requires remove+re-add. +func subportNeedsUpdate(current, desired trunks.Subport) bool { + return current.SegmentationType != desired.SegmentationType || current.SegmentationID != desired.SegmentationID +} + +type trunkHelperFactory struct{} + +var _ helperFactory = trunkHelperFactory{} + +func (trunkHelperFactory) NewAPIObjectAdapter(obj orcObjectPT) adapterI { + return trunkAdapter{obj} +} + +func (trunkHelperFactory) NewCreateActuator(ctx context.Context, orcObject orcObjectPT, controller interfaces.ResourceController) (createResourceActuator, progress.ReconcileStatus) { + return newActuator(ctx, controller, orcObject) +} + +func (trunkHelperFactory) NewDeleteActuator(ctx context.Context, orcObject orcObjectPT, controller interfaces.ResourceController) (deleteResourceActuator, progress.ReconcileStatus) { + return newActuator(ctx, controller, orcObject) +} + +func newActuator(ctx context.Context, controller interfaces.ResourceController, orcObject *orcv1alpha1.Trunk) (trunkActuator, progress.ReconcileStatus) { + if orcObject == nil { + return trunkActuator{}, progress.WrapError(fmt.Errorf("orcObject may not be nil")) + } + + // Ensure credential secrets exist and have our finalizer + _, reconcileStatus := credentialsDependency.GetDependencies(ctx, controller.GetK8sClient(), orcObject, func(*corev1.Secret) bool { return true }) + if needsReschedule, _ := reconcileStatus.NeedsReschedule(); needsReschedule { + return trunkActuator{}, reconcileStatus + } + + log := ctrl.LoggerFrom(ctx) + clientScope, err := controller.GetScopeFactory().NewClientScopeFromObject(ctx, controller.GetK8sClient(), log, orcObject) + if err != nil { + return trunkActuator{}, progress.WrapError(err) + } + osClient, err := clientScope.NewNetworkClient() + if err != nil { + return trunkActuator{}, progress.WrapError(err) + } + + return trunkActuator{ + osClient: osClient, + k8sClient: controller.GetK8sClient(), + }, nil +} + diff --git a/internal/controllers/trunk/actuator_test.go b/internal/controllers/trunk/actuator_test.go new file mode 100644 index 000000000..91ccc9420 --- /dev/null +++ b/internal/controllers/trunk/actuator_test.go @@ -0,0 +1,681 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 trunk + +import ( + "context" + "errors" + "testing" + + "github.com/gophercloud/gophercloud/v2" + "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/trunks" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + orcv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + osclientsmock "github.com/k-orc/openstack-resource-controller/v2/internal/osclients/mock" + orcerrors "github.com/k-orc/openstack-resource-controller/v2/internal/util/errors" + "go.uber.org/mock/gomock" +) + +func TestNeedsUpdate(t *testing.T) { + testCases := []struct { + name string + updateOpts trunks.UpdateOpts + expectChange bool + }{ + { + name: "Empty base opts", + updateOpts: trunks.UpdateOpts{}, + expectChange: false, + }, + { + name: "Empty base opts with revision number", + updateOpts: trunks.UpdateOpts{RevisionNumber: ptr.To(4)}, + expectChange: false, + }, + { + name: "Updated opts with name", + updateOpts: trunks.UpdateOpts{Name: ptr.To("updated")}, + expectChange: true, + }, + { + name: "Updated opts with description", + updateOpts: trunks.UpdateOpts{Description: ptr.To("new description")}, + expectChange: true, + }, + { + name: "Updated opts with adminStateUp", + updateOpts: trunks.UpdateOpts{AdminStateUp: ptr.To(false)}, + expectChange: true, + }, + } + + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + got := needsUpdate(tt.updateOpts) + if got != tt.expectChange { + t.Errorf("Expected change: %v, got: %v", tt.expectChange, got) + } + }) + } +} + +func TestHandleNameUpdate(t *testing.T) { + ptrToName := ptr.To[orcv1alpha1.OpenStackName] + testCases := []struct { + name string + newValue *orcv1alpha1.OpenStackName + existingValue string + expectChange bool + }{ + {name: "Identical", newValue: ptrToName("name"), existingValue: "name", expectChange: false}, + {name: "Different", newValue: ptrToName("new-name"), existingValue: "name", expectChange: true}, + {name: "No value provided, existing is identical to object name", newValue: nil, existingValue: "object-name", expectChange: false}, + {name: "No value provided, existing is different from object name", newValue: nil, existingValue: "different-from-object-name", expectChange: true}, + } + + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + resource := &orcv1alpha1.Trunk{} + resource.Name = "object-name" + resource.Spec = orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{Name: tt.newValue}, + } + osResource := &trunks.Trunk{Name: tt.existingValue} + + updateOpts := trunks.UpdateOpts{} + handleNameUpdate(&updateOpts, resource, osResource) + + got := needsUpdate(updateOpts) + if got != tt.expectChange { + t.Errorf("Expected change: %v, got: %v", tt.expectChange, got) + } + }) + } +} + +func TestHandleDescriptionUpdate(t *testing.T) { + ptrToDescription := ptr.To[orcv1alpha1.NeutronDescription] + testCases := []struct { + name string + newValue *orcv1alpha1.NeutronDescription + existingValue string + expectChange bool + }{ + {name: "Identical", newValue: ptrToDescription("desc"), existingValue: "desc", expectChange: false}, + {name: "Different", newValue: ptrToDescription("new-desc"), existingValue: "desc", expectChange: true}, + {name: "No value provided, existing is set", newValue: nil, existingValue: "desc", expectChange: true}, + {name: "No value provided, existing is empty", newValue: nil, existingValue: "", expectChange: false}, + } + + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + resource := &orcv1alpha1.TrunkResourceSpec{Description: tt.newValue} + osResource := &trunks.Trunk{Description: tt.existingValue} + + updateOpts := trunks.UpdateOpts{} + handleDescriptionUpdate(&updateOpts, resource, osResource) + + got := needsUpdate(updateOpts) + if got != tt.expectChange { + t.Errorf("Expected change: %v, got: %v", tt.expectChange, got) + } + }) + } +} + +func TestHandleAdminStateUpUpdate(t *testing.T) { + ptrToBool := ptr.To[bool] + testCases := []struct { + name string + newValue *bool + existingValue bool + expectChange bool + }{ + {name: "Identical", newValue: ptrToBool(true), existingValue: true, expectChange: false}, + {name: "Different", newValue: ptrToBool(true), existingValue: false, expectChange: true}, + {name: "No value provided, existing is set", newValue: nil, existingValue: false, expectChange: false}, + {name: "No value provided, existing is default", newValue: nil, existingValue: true, expectChange: false}, + {name: "False when already false", newValue: ptrToBool(false), existingValue: false, expectChange: false}, + {name: "False when was true", newValue: ptrToBool(false), existingValue: true, expectChange: true}, + } + + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + resource := &orcv1alpha1.TrunkResourceSpec{AdminStateUp: tt.newValue} + osResource := &trunks.Trunk{AdminStateUp: tt.existingValue} + + updateOpts := trunks.UpdateOpts{} + handleAdminStateUpUpdate(&updateOpts, resource, osResource) + + got := needsUpdate(updateOpts) + if got != tt.expectChange { + t.Errorf("Expected change: %v, got: %v", tt.expectChange, got) + } + }) + } +} + +// needsUpdate checks if the updateOpts contains any changes that require an update +func needsUpdate(updateOpts trunks.UpdateOpts) bool { + return updateOpts.Name != nil || updateOpts.Description != nil || updateOpts.AdminStateUp != nil +} + +// handleNameUpdate updates the updateOpts if the name needs to be changed +func handleNameUpdate(updateOpts *trunks.UpdateOpts, resource *orcv1alpha1.Trunk, osResource *trunks.Trunk) { + name := getResourceName(resource) + if osResource.Name != name { + updateOpts.Name = &name + } +} + +// handleDescriptionUpdate updates the updateOpts if the description needs to be changed +func handleDescriptionUpdate(updateOpts *trunks.UpdateOpts, resource *orcv1alpha1.TrunkResourceSpec, osResource *trunks.Trunk) { + description := string(ptr.Deref(resource.Description, "")) + if osResource.Description != description { + updateOpts.Description = &description + } +} + +// handleAdminStateUpUpdate updates the updateOpts if the adminStateUp needs to be changed +func handleAdminStateUpUpdate(updateOpts *trunks.UpdateOpts, resource *orcv1alpha1.TrunkResourceSpec, osResource *trunks.Trunk) { + if resource.AdminStateUp != nil && *resource.AdminStateUp != osResource.AdminStateUp { + updateOpts.AdminStateUp = resource.AdminStateUp + } +} + +func TestGetResourceID(t *testing.T) { + actuator := trunkActuator{} + osResource := &trunks.Trunk{ID: "test-id-123"} + + got := actuator.GetResourceID(osResource) + if got != "test-id-123" { + t.Errorf("Expected ID 'test-id-123', got '%s'", got) + } +} + +func TestGetOSResourceByID(t *testing.T) { + ctx := context.Background() + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + mockClient := osclientsmock.NewMockNetworkClient(mockCtrl) + actuator := trunkActuator{osClient: mockClient} + + t.Run("success", func(t *testing.T) { + expectedTrunk := &trunks.Trunk{ID: "test-id", Name: "test-trunk"} + mockClient.EXPECT().GetTrunk(ctx, "test-id").Return(expectedTrunk, nil) + + got, status := actuator.GetOSResourceByID(ctx, "test-id") + if status != nil { + t.Errorf("Expected nil status, got %v", status) + } + if got.ID != expectedTrunk.ID { + t.Errorf("Expected ID '%s', got '%s'", expectedTrunk.ID, got.ID) + } + }) + + t.Run("error", func(t *testing.T) { + expectedErr := errors.New("not found") + mockClient.EXPECT().GetTrunk(ctx, "test-id").Return(nil, expectedErr) + + got, status := actuator.GetOSResourceByID(ctx, "test-id") + if got != nil { + t.Errorf("Expected nil, got %v", got) + } + if status == nil { + t.Fatal("Expected non-nil status") + } + needsReschedule, err := status.NeedsReschedule() + if !needsReschedule { + t.Error("Expected needsReschedule to be true") + } + if err == nil { + t.Error("Expected error in status") + } + }) +} + +func TestListOSResourcesForAdoption(t *testing.T) { + ctx := context.Background() + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + mockClient := osclientsmock.NewMockNetworkClient(mockCtrl) + actuator := trunkActuator{osClient: mockClient} + + t.Run("no resource spec", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + Spec: orcv1alpha1.TrunkSpec{Resource: nil}, + } + iter, ok := actuator.ListOSResourcesForAdoption(ctx, obj) + if ok { + t.Error("Expected ok to be false when resource spec is nil") + } + if iter != nil { + t.Error("Expected nil iterator when resource spec is nil") + } + }) + + t.Run("success", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "test-trunk"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{}, + }, + } + expectedTrunks := []trunks.Trunk{ + {ID: "id1", Name: "test-trunk"}, + {ID: "id2", Name: "test-trunk"}, + } + mockClient.EXPECT().ListTrunk(ctx, gomock.Any()).Return(expectedTrunks, nil) + + iter, ok := actuator.ListOSResourcesForAdoption(ctx, obj) + if !ok { + t.Error("Expected ok to be true") + } + + var results []*trunks.Trunk + for trunk, err := range iter { + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + results = append(results, trunk) + } + + if len(results) != 2 { + t.Errorf("Expected 2 trunks, got %d", len(results)) + } + }) + + t.Run("error", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "test-trunk"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{}, + }, + } + expectedErr := errors.New("list error") + mockClient.EXPECT().ListTrunk(ctx, gomock.Any()).Return(nil, expectedErr) + + iter, ok := actuator.ListOSResourcesForAdoption(ctx, obj) + if !ok { + t.Error("Expected ok to be true even on error") + } + + var gotErr error + for _, err := range iter { + gotErr = err + break + } + + if gotErr != expectedErr { + t.Errorf("Expected error '%v', got '%v'", expectedErr, gotErr) + } + }) +} + +func TestDeleteResource(t *testing.T) { + ctx := context.Background() + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + mockClient := osclientsmock.NewMockNetworkClient(mockCtrl) + actuator := trunkActuator{osClient: mockClient} + + t.Run("success", func(t *testing.T) { + osResource := &trunks.Trunk{ID: "test-id"} + mockClient.EXPECT().DeleteTrunk(ctx, "test-id").Return(nil) + + status := actuator.DeleteResource(ctx, nil, osResource) + if status != nil { + needsReschedule, err := status.NeedsReschedule() + if needsReschedule || err != nil { + t.Errorf("Expected nil status, got needsReschedule=%v, err=%v", needsReschedule, err) + } + } + }) + + t.Run("error", func(t *testing.T) { + osResource := &trunks.Trunk{ID: "test-id"} + expectedErr := errors.New("delete error") + mockClient.EXPECT().DeleteTrunk(ctx, "test-id").Return(expectedErr) + + status := actuator.DeleteResource(ctx, nil, osResource) + if status == nil { + t.Fatal("Expected non-nil status on error") + } + needsReschedule, err := status.NeedsReschedule() + if !needsReschedule { + t.Error("Expected needsReschedule to be true") + } + if err == nil { + t.Error("Expected error in status") + } + }) +} + +func TestUpdateResource(t *testing.T) { + ctx := ctrl.LoggerInto(context.Background(), ctrl.Log) + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + mockClient := osclientsmock.NewMockNetworkClient(mockCtrl) + actuator := trunkActuator{osClient: mockClient} + + t.Run("no changes", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "test-trunk"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Name: ptr.To(orcv1alpha1.OpenStackName("test-trunk")), + }, + }, + } + osResource := &trunks.Trunk{ + ID: "test-id", + Name: "test-trunk", + Description: "", + AdminStateUp: true, + RevisionNumber: 1, + } + + status := actuator.updateResource(ctx, obj, osResource) + if status != nil { + needsReschedule, _ := status.NeedsReschedule() + if needsReschedule { + t.Error("Expected no status when no changes") + } + } + }) + + t.Run("name change", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "test-trunk"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Name: ptr.To(orcv1alpha1.OpenStackName("new-name")), + }, + }, + } + osResource := &trunks.Trunk{ + ID: "test-id", + Name: "old-name", + RevisionNumber: 1, + } + + expectedTrunk := &trunks.Trunk{ID: "test-id", Name: "new-name"} + mockClient.EXPECT().UpdateTrunk(ctx, "test-id", gomock.Any()).Return(expectedTrunk, nil) + + status := actuator.updateResource(ctx, obj, osResource) + if status == nil { + t.Fatal("Expected non-nil status after update") + } + // Status should indicate refresh is needed (status will have a refresh message) + }) + + t.Run("description change", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "test-trunk"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Description: ptr.To(orcv1alpha1.NeutronDescription("new desc")), + }, + }, + } + osResource := &trunks.Trunk{ + ID: "test-id", + Name: "test-trunk", + Description: "old desc", + RevisionNumber: 1, + } + + expectedTrunk := &trunks.Trunk{ID: "test-id", Description: "new desc"} + mockClient.EXPECT().UpdateTrunk(ctx, "test-id", gomock.Any()).Return(expectedTrunk, nil) + + status := actuator.updateResource(ctx, obj, osResource) + if status == nil { + t.Fatal("Expected non-nil status after update") + } + }) + + t.Run("conflict error", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "test-trunk"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Name: ptr.To(orcv1alpha1.OpenStackName("new-name")), + }, + }, + } + osResource := &trunks.Trunk{ + ID: "test-id", + Name: "old-name", + RevisionNumber: 1, + } + + conflictErr := gophercloud.ErrUnexpectedResponseCode{Actual: 409} + mockClient.EXPECT().UpdateTrunk(ctx, "test-id", gomock.Any()).Return(nil, conflictErr) + + status := actuator.updateResource(ctx, obj, osResource) + if status == nil { + t.Fatal("Expected non-nil status on error") + } + needsReschedule, err := status.NeedsReschedule() + if !needsReschedule { + t.Error("Expected needsReschedule to be true on conflict") + } + if err == nil { + t.Error("Expected error in status") + } + // Check that it's a terminal error + var terminalError *orcerrors.TerminalError + if !errors.As(err, &terminalError) { + t.Error("Expected terminal error on conflict") + } + }) +} + +func TestReconcileSubports(t *testing.T) { + ctx := ctrl.LoggerInto(context.Background(), ctrl.Log) + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + scheme := runtime.NewScheme() + orcv1alpha1.AddToScheme(scheme) + corev1.AddToScheme(scheme) + + mockClient := osclientsmock.NewMockNetworkClient(mockCtrl) + k8sClient := fake.NewClientBuilder().WithScheme(scheme).Build() + actuator := trunkActuator{osClient: mockClient, k8sClient: k8sClient} + + t.Run("no resource spec", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + Spec: orcv1alpha1.TrunkSpec{Resource: nil}, + } + osResource := &trunks.Trunk{ID: "test-id"} + + status := actuator.reconcileSubports(ctx, obj, osResource) + if status != nil { + t.Errorf("Expected nil status, got %v", status) + } + }) + + t.Run("no changes needed", func(t *testing.T) { + // Create a fresh k8sClient for this test to avoid state from previous tests + testK8sClient := fake.NewClientBuilder().WithScheme(scheme).Build() + testActuator := trunkActuator{osClient: mockClient, k8sClient: testK8sClient} + + port1 := &orcv1alpha1.Port{ + ObjectMeta: metav1.ObjectMeta{ + Name: "port1", + Namespace: "default", + Finalizers: []string{finalizer}, + }, + Status: orcv1alpha1.PortStatus{ + ID: ptr.To("port-id-1"), + Conditions: []metav1.Condition{ + {Type: "Available", Status: metav1.ConditionTrue}, + }, + }, + } + testK8sClient.Create(ctx, port1) + + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "trunk", Namespace: "default"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Subports: []orcv1alpha1.Subport{ + { + PortRef: "port1", + SegmentationType: "vlan", + SegmentationID: 100, + }, + }, + }, + }, + } + osResource := &trunks.Trunk{ + ID: "trunk-id", + } + + currentSubports := []trunks.Subport{ + { + PortID: "port-id-1", + SegmentationType: "vlan", + SegmentationID: 100, + }, + } + + mockClient.EXPECT().ListTrunkSubports(ctx, "trunk-id").Return(currentSubports, nil) + + status := testActuator.reconcileSubports(ctx, obj, osResource) + if status != nil { + t.Errorf("Expected nil status when no changes, got %v", status) + } + }) + + t.Run("add subport", func(t *testing.T) { + // Create a fresh k8sClient for this test to avoid state from previous tests + testK8sClient := fake.NewClientBuilder().WithScheme(scheme).Build() + testActuator := trunkActuator{osClient: mockClient, k8sClient: testK8sClient} + + port1 := &orcv1alpha1.Port{ + ObjectMeta: metav1.ObjectMeta{ + Name: "port1", + Namespace: "default", + Finalizers: []string{finalizer}, + }, + Status: orcv1alpha1.PortStatus{ + ID: ptr.To("port-id-1"), + Conditions: []metav1.Condition{ + {Type: "Available", Status: metav1.ConditionTrue}, + }, + }, + } + testK8sClient.Create(ctx, port1) + + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "trunk", Namespace: "default"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Subports: []orcv1alpha1.Subport{ + { + PortRef: "port1", + SegmentationType: "vlan", + SegmentationID: 100, + }, + }, + }, + }, + } + osResource := &trunks.Trunk{ID: "trunk-id"} + + mockClient.EXPECT().ListTrunkSubports(ctx, "trunk-id").Return([]trunks.Subport{}, nil) + expectedTrunk := &trunks.Trunk{ID: "trunk-id"} + mockClient.EXPECT().AddSubports(ctx, "trunk-id", gomock.Any()).Return(expectedTrunk, nil) + + status := testActuator.reconcileSubports(ctx, obj, osResource) + if status == nil { + t.Fatal("Expected non-nil status after adding subport") + } + // Status should indicate refresh is needed (status will have a refresh message) + }) + + t.Run("remove subport", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "trunk", Namespace: "default"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Subports: []orcv1alpha1.Subport{}, + }, + }, + } + osResource := &trunks.Trunk{ID: "trunk-id"} + + currentSubports := []trunks.Subport{ + { + PortID: "port-id-1", + SegmentationType: "vlan", + SegmentationID: 100, + }, + } + + mockClient.EXPECT().ListTrunkSubports(ctx, "trunk-id").Return(currentSubports, nil) + mockClient.EXPECT().RemoveSubports(ctx, "trunk-id", gomock.Any()).Return(nil) + + status := actuator.reconcileSubports(ctx, obj, osResource) + if status == nil { + t.Fatal("Expected non-nil status after removing subport") + } + // Status should indicate refresh is needed (status will have a refresh message) + }) + + t.Run("list subports error", func(t *testing.T) { + obj := &orcv1alpha1.Trunk{ + ObjectMeta: metav1.ObjectMeta{Name: "trunk", Namespace: "default"}, + Spec: orcv1alpha1.TrunkSpec{ + Resource: &orcv1alpha1.TrunkResourceSpec{ + Subports: []orcv1alpha1.Subport{}, + }, + }, + } + osResource := &trunks.Trunk{ID: "trunk-id"} + + expectedErr := errors.New("list error") + mockClient.EXPECT().ListTrunkSubports(ctx, "trunk-id").Return(nil, expectedErr) + + status := actuator.reconcileSubports(ctx, obj, osResource) + if status == nil { + t.Fatal("Expected non-nil status on error") + } + needsReschedule, err := status.NeedsReschedule() + if !needsReschedule { + t.Error("Expected needsReschedule to be true on error") + } + if err == nil { + t.Error("Expected error in status") + } + }) +} + + diff --git a/internal/controllers/trunk/controller.go b/internal/controllers/trunk/controller.go new file mode 100644 index 000000000..5fead1d3e --- /dev/null +++ b/internal/controllers/trunk/controller.go @@ -0,0 +1,186 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 trunk + +import ( + "context" + "errors" + + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/controller" + + orcv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + "github.com/k-orc/openstack-resource-controller/v2/pkg/predicates" + + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/interfaces" + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/reconciler" + "github.com/k-orc/openstack-resource-controller/v2/internal/scope" + "github.com/k-orc/openstack-resource-controller/v2/internal/util/credentials" + "github.com/k-orc/openstack-resource-controller/v2/internal/util/dependency" +) + +// +kubebuilder:rbac:groups=openstack.k-orc.cloud,resources=trunks,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=openstack.k-orc.cloud,resources=trunks/status,verbs=get;update;patch + +const controllerName = "trunk" + +var ( + portDependency = dependency.NewDeletionGuardDependency[*orcv1alpha1.TrunkList, *orcv1alpha1.Port]( + "spec.resource.portRef", + func(trunk *orcv1alpha1.Trunk) []string { + resource := trunk.Spec.Resource + if resource == nil { + return nil + } + return []string{string(resource.PortRef)} + }, + finalizer, externalObjectFieldOwner, + ) + + portImportDependency = dependency.NewDependency[*orcv1alpha1.TrunkList, *orcv1alpha1.Port]( + "spec.import.filter.portRef", + func(trunk *orcv1alpha1.Trunk) []string { + resource := trunk.Spec.Import + if resource == nil || resource.Filter == nil || resource.Filter.PortRef == nil { + return nil + } + return []string{string(*resource.Filter.PortRef)} + }, + ) + + subportDependency = dependency.NewDeletionGuardDependency[*orcv1alpha1.TrunkList, *orcv1alpha1.Port]( + "spec.resource.subports[].portRef", + func(trunk *orcv1alpha1.Trunk) []string { + if trunk.Spec.Resource == nil { + return nil + } + ports := make([]string, len(trunk.Spec.Resource.Subports)) + for i := range trunk.Spec.Resource.Subports { + ports[i] = string(trunk.Spec.Resource.Subports[i].PortRef) + } + return ports + }, + finalizer, externalObjectFieldOwner, + dependency.OverrideDependencyName("subport"), + ) + + projectDependency = dependency.NewDeletionGuardDependency[*orcv1alpha1.TrunkList, *orcv1alpha1.Project]( + "spec.resource.projectRef", + func(trunk *orcv1alpha1.Trunk) []string { + resource := trunk.Spec.Resource + if resource == nil || resource.ProjectRef == nil { + return nil + } + return []string{string(*resource.ProjectRef)} + }, + finalizer, externalObjectFieldOwner, + ) + + projectImportDependency = dependency.NewDependency[*orcv1alpha1.TrunkList, *orcv1alpha1.Project]( + "spec.import.filter.projectRef", + func(trunk *orcv1alpha1.Trunk) []string { + resource := trunk.Spec.Import + if resource == nil || resource.Filter == nil || resource.Filter.ProjectRef == nil { + return nil + } + return []string{string(*resource.Filter.ProjectRef)} + }, + ) +) + +type trunkReconcilerConstructor struct { + scopeFactory scope.Factory +} + +func New(scopeFactory scope.Factory) interfaces.Controller { + return trunkReconcilerConstructor{ + scopeFactory: scopeFactory, + } +} + +func (trunkReconcilerConstructor) GetName() string { + return controllerName +} + +// SetupWithManager sets up the controller with the Manager. +func (c trunkReconcilerConstructor) SetupWithManager(ctx context.Context, mgr ctrl.Manager, options controller.Options) error { + log := ctrl.LoggerFrom(ctx) + k8sClient := mgr.GetClient() + + portWatchEventHandler, err := portDependency.WatchEventHandler(log, k8sClient) + if err != nil { + return err + } + + portImportWatchEventHandler, err := portImportDependency.WatchEventHandler(log, k8sClient) + if err != nil { + return err + } + + subportWatchEventHandler, err := subportDependency.WatchEventHandler(log, k8sClient) + if err != nil { + return err + } + + projectWatchEventHandler, err := projectDependency.WatchEventHandler(log, k8sClient) + if err != nil { + return err + } + + projectImportWatchEventHandler, err := projectImportDependency.WatchEventHandler(log, k8sClient) + if err != nil { + return err + } + + builder := ctrl.NewControllerManagedBy(mgr). + WithOptions(options). + For(&orcv1alpha1.Trunk{}). + Watches(&orcv1alpha1.Port{}, portWatchEventHandler, + builder.WithPredicates(predicates.NewBecameAvailable(log, &orcv1alpha1.Port{})), + ). + // A second watch is necessary because we need a different handler that omits deletion guards + Watches(&orcv1alpha1.Port{}, portImportWatchEventHandler, + builder.WithPredicates(predicates.NewBecameAvailable(log, &orcv1alpha1.Port{})), + ). + Watches(&orcv1alpha1.Port{}, subportWatchEventHandler, + builder.WithPredicates(predicates.NewBecameAvailable(log, &orcv1alpha1.Port{})), + ). + Watches(&orcv1alpha1.Project{}, projectWatchEventHandler, + builder.WithPredicates(predicates.NewBecameAvailable(log, &orcv1alpha1.Project{})), + ). + // A second watch is necessary because we need a different handler that omits deletion guards + Watches(&orcv1alpha1.Project{}, projectImportWatchEventHandler, + builder.WithPredicates(predicates.NewBecameAvailable(log, &orcv1alpha1.Project{})), + ) + + if err := errors.Join( + portDependency.AddToManager(ctx, mgr), + portImportDependency.AddToManager(ctx, mgr), + subportDependency.AddToManager(ctx, mgr), + projectDependency.AddToManager(ctx, mgr), + projectImportDependency.AddToManager(ctx, mgr), + credentialsDependency.AddToManager(ctx, mgr), + credentials.AddCredentialsWatch(log, mgr.GetClient(), builder, credentialsDependency), + ); err != nil { + return err + } + + r := reconciler.NewController(controllerName, mgr.GetClient(), c.scopeFactory, trunkHelperFactory{}, trunkStatusWriter{}) + return builder.Complete(&r) +} + diff --git a/internal/controllers/trunk/status.go b/internal/controllers/trunk/status.go new file mode 100644 index 000000000..38e12f6ec --- /dev/null +++ b/internal/controllers/trunk/status.go @@ -0,0 +1,90 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 trunk + +import ( + "github.com/go-logr/logr" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/interfaces" + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/progress" + orcapplyconfigv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/applyconfiguration/api/v1alpha1" +) + +const ( + TrunkStatusActive = "ACTIVE" + TrunkStatusDown = "DOWN" +) + +type objectApplyPT = *orcapplyconfigv1alpha1.TrunkApplyConfiguration +type statusApplyPT = *orcapplyconfigv1alpha1.TrunkStatusApplyConfiguration + +type trunkStatusWriter struct{} + +var _ interfaces.ResourceStatusWriter[orcObjectPT, *osResourceT, objectApplyPT, statusApplyPT] = trunkStatusWriter{} + +func (trunkStatusWriter) GetApplyConfig(name, namespace string) objectApplyPT { + return orcapplyconfigv1alpha1.Trunk(name, namespace) +} + +func (trunkStatusWriter) ResourceAvailableStatus(orcObject orcObjectPT, osResource *osResourceT) (metav1.ConditionStatus, progress.ReconcileStatus) { + if osResource == nil { + if orcObject.Status.ID == nil { + return metav1.ConditionFalse, nil + } else { + return metav1.ConditionUnknown, nil + } + } + + // Both active and down trunks are Available + if osResource.Status == TrunkStatusActive || osResource.Status == TrunkStatusDown { + return metav1.ConditionTrue, nil + } + return metav1.ConditionFalse, nil +} + +func (trunkStatusWriter) ApplyResourceStatus(log logr.Logger, osResource *osResourceT, statusApply statusApplyPT) { + resourceStatus := orcapplyconfigv1alpha1.TrunkResourceStatus(). + WithName(osResource.Name). + WithAdminStateUp(osResource.AdminStateUp). + WithStatus(osResource.Status). + WithProjectID(osResource.ProjectID). + WithPortID(osResource.PortID). + WithTags(osResource.Tags...). + WithRevisionNumber(int64(osResource.RevisionNumber)). + WithCreatedAt(metav1.NewTime(osResource.CreatedAt)). + WithUpdatedAt(metav1.NewTime(osResource.UpdatedAt)) + + if osResource.Description != "" { + resourceStatus = resourceStatus.WithDescription(osResource.Description) + } + + if len(osResource.Subports) > 0 { + subports := make([]*orcapplyconfigv1alpha1.SubportStatusApplyConfiguration, len(osResource.Subports)) + for i := range osResource.Subports { + subportStatus := orcapplyconfigv1alpha1.SubportStatus(). + WithPortID(osResource.Subports[i].PortID). + WithSegmentationType(osResource.Subports[i].SegmentationType). + WithSegmentationID(int32(osResource.Subports[i].SegmentationID)) + subports[i] = subportStatus + } + resourceStatus.WithSubports(subports...) + } + + statusApply.WithResource(resourceStatus) +} + diff --git a/internal/controllers/trunk/tests/trunk-create-full/00-assert.yaml b/internal/controllers/trunk/tests/trunk-create-full/00-assert.yaml new file mode 100644 index 000000000..6091e47f9 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-full/00-assert.yaml @@ -0,0 +1,64 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-create-full +status: + resource: + name: trunk-create-full-override + description: Trunk from "create full" test + adminStateUp: true + status: ACTIVE + tags: + - tag1 + - tag2 + subports: + - portID: "" + segmentationType: vlan + segmentationID: 100 + - portID: "" + segmentationType: vlan + segmentationID: 200 +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +resourceRefs: + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: trunk + name: trunk-create-full + ref: trunk + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: port + name: trunk-create-full + ref: port + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: port + name: trunk-create-full-subport1 + ref: subport1 + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: port + name: trunk-create-full-subport2 + ref: subport2 + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: project + name: trunk-create-full + ref: project +assertAll: + - celExpr: "trunk.status.id != ''" + - celExpr: "trunk.status.resource.createdAt != ''" + - celExpr: "trunk.status.resource.updatedAt != ''" + - celExpr: "trunk.status.resource.portID == port.status.id" + - celExpr: "trunk.status.resource.name == 'trunk-create-full-override'" + - celExpr: "trunk.status.resource.description == 'Trunk from \"create full\" test'" + - celExpr: "trunk.status.resource.adminStateUp == true" + - celExpr: "trunk.status.resource.projectID == project.status.id" + - celExpr: "size(trunk.status.resource.subports) == 2" + - celExpr: "trunk.status.resource.subports[0].portID == subport1.status.id" + - celExpr: "trunk.status.resource.subports[0].segmentationType == 'vlan'" + - celExpr: "trunk.status.resource.subports[0].segmentationID == 100" + - celExpr: "trunk.status.resource.subports[1].portID == subport2.status.id" + - celExpr: "trunk.status.resource.subports[1].segmentationType == 'vlan'" + - celExpr: "trunk.status.resource.subports[1].segmentationID == 200" + - celExpr: "'tag1' in trunk.status.resource.tags" + - celExpr: "'tag2' in trunk.status.resource.tags" + diff --git a/internal/controllers/trunk/tests/trunk-create-full/00-create-resource.yaml b/internal/controllers/trunk/tests/trunk-create-full/00-create-resource.yaml new file mode 100644 index 000000000..118756c2f --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-full/00-create-resource.yaml @@ -0,0 +1,108 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Project +metadata: + name: trunk-create-full +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: {} +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Network +metadata: + name: trunk-create-full +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + projectRef: trunk-create-full +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Subnet +metadata: + name: trunk-create-full +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + networkRef: trunk-create-full + ipVersion: 4 + cidr: 192.168.157.0/24 + projectRef: trunk-create-full +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Port +metadata: + name: trunk-create-full +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-create-full-port + description: Parent port for trunk-create-full + networkRef: trunk-create-full + projectRef: trunk-create-full +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Port +metadata: + name: trunk-create-full-subport1 +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-create-full-subport1 + networkRef: trunk-create-full + projectRef: trunk-create-full +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Port +metadata: + name: trunk-create-full-subport2 +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-create-full-subport2 + networkRef: trunk-create-full + projectRef: trunk-create-full +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-create-full +spec: + cloudCredentialsRef: + cloudName: openstack-admin + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-create-full-override + description: Trunk from "create full" test + portRef: trunk-create-full + adminStateUp: true + tags: + - tag1 + - tag2 + subports: + - portRef: trunk-create-full-subport1 + segmentationType: vlan + segmentationID: 100 + - portRef: trunk-create-full-subport2 + segmentationType: vlan + segmentationID: 200 + projectRef: trunk-create-full + diff --git a/internal/controllers/trunk/tests/trunk-create-full/README.md b/internal/controllers/trunk/tests/trunk-create-full/README.md new file mode 100644 index 000000000..ad105a3a0 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-full/README.md @@ -0,0 +1,18 @@ +# Create a trunk with all options + +## Step 00 + +Create a trunk with all fields set: +- Custom name +- Description +- Admin state +- Tags +- Subports with VLAN segmentation +- Project reference + +Verify that all fields are correctly reflected in the observed state. + +## Reference + +https://k-orc.cloud/development/writing-tests/#create-full + diff --git a/internal/controllers/trunk/tests/trunk-create-minimal/00-assert.yaml b/internal/controllers/trunk/tests/trunk-create-minimal/00-assert.yaml new file mode 100644 index 000000000..98f62359e --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-minimal/00-assert.yaml @@ -0,0 +1,30 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-create-minimal +status: + resource: + name: trunk-create-minimal + adminStateUp: true + status: ACTIVE +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +resourceRefs: + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: trunk + name: trunk-create-minimal + ref: trunk + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: port + name: trunk-create-minimal + ref: port +assertAll: + - celExpr: "trunk.status.id != ''" + - celExpr: "trunk.status.resource.createdAt != ''" + - celExpr: "trunk.status.resource.updatedAt != ''" + - celExpr: "trunk.status.resource.portID == port.status.id" + - celExpr: "trunk.status.resource.name == 'trunk-create-minimal'" + - celExpr: "trunk.status.resource.adminStateUp == true" + diff --git a/internal/controllers/trunk/tests/trunk-create-minimal/00-create-resource.yaml b/internal/controllers/trunk/tests/trunk-create-minimal/00-create-resource.yaml new file mode 100644 index 000000000..33ef84722 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-minimal/00-create-resource.yaml @@ -0,0 +1,13 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-create-minimal +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + portRef: trunk-create-minimal + diff --git a/internal/controllers/trunk/tests/trunk-create-minimal/00-prerequisites.yaml b/internal/controllers/trunk/tests/trunk-create-minimal/00-prerequisites.yaml new file mode 100644 index 000000000..4b9042767 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-minimal/00-prerequisites.yaml @@ -0,0 +1,44 @@ +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - command: kubectl create secret generic openstack-clouds --from-file=clouds.yaml=${E2E_KUTTL_OSCLOUDS} ${E2E_KUTTL_CACERT_OPT} + namespaced: true +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Network +metadata: + name: trunk-create-minimal +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-create-minimal +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Subnet +metadata: + name: trunk-create-minimal +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + networkRef: trunk-create-minimal + ipVersion: 4 + cidr: 192.168.156.0/24 +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Port +metadata: + name: trunk-create-minimal +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + networkRef: trunk-create-minimal + diff --git a/internal/controllers/trunk/tests/trunk-create-minimal/01-assert.yaml b/internal/controllers/trunk/tests/trunk-create-minimal/01-assert.yaml new file mode 100644 index 000000000..251abc20d --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-minimal/01-assert.yaml @@ -0,0 +1,12 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +resourceRefs: + - apiVersion: v1 + kind: Secret + name: openstack-clouds + ref: secret +assertAll: + - celExpr: "secret.metadata.deletionTimestamp != 0" + - celExpr: "'openstack.k-orc.cloud/trunk' in secret.metadata.finalizers" + diff --git a/internal/controllers/trunk/tests/trunk-create-minimal/01-delete-secret.yaml b/internal/controllers/trunk/tests/trunk-create-minimal/01-delete-secret.yaml new file mode 100644 index 000000000..a4cb499df --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-minimal/01-delete-secret.yaml @@ -0,0 +1,6 @@ +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - command: kubectl delete secret openstack-clouds --wait=false + namespaced: true + diff --git a/internal/controllers/trunk/tests/trunk-create-minimal/README.md b/internal/controllers/trunk/tests/trunk-create-minimal/README.md new file mode 100644 index 000000000..f3fa33767 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-create-minimal/README.md @@ -0,0 +1,16 @@ +# Create a trunk with the minimum options + +## Step 00 + +Create a minimal trunk, that sets only the required fields (portRef), and verify that the observed state corresponds to the spec. + +Also validate that the OpenStack resource uses the name of the ORC object when it is not specified. + +## Step 01 + +Try deleting the secret and ensure that it is not deleted thanks to the finalizer. + +## Reference + +https://k-orc.cloud/development/writing-tests/#create-minimal + diff --git a/internal/controllers/trunk/tests/trunk-update/00-assert.yaml b/internal/controllers/trunk/tests/trunk-update/00-assert.yaml new file mode 100644 index 000000000..c3b738632 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/00-assert.yaml @@ -0,0 +1,13 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +resourceRefs: + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: trunk + name: trunk-update + ref: trunk +assertAll: + - celExpr: "trunk.status.id != ''" + - celExpr: "trunk.status.resource.name == 'trunk-update'" + - celExpr: "trunk.status.resource.adminStateUp == true" + diff --git a/internal/controllers/trunk/tests/trunk-update/00-minimal-resource.yaml b/internal/controllers/trunk/tests/trunk-update/00-minimal-resource.yaml new file mode 100644 index 000000000..990eab8f3 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/00-minimal-resource.yaml @@ -0,0 +1,14 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-update +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + portRef: trunk-update + adminStateUp: true + diff --git a/internal/controllers/trunk/tests/trunk-update/00-prerequisites.yaml b/internal/controllers/trunk/tests/trunk-update/00-prerequisites.yaml new file mode 100644 index 000000000..de6f33262 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/00-prerequisites.yaml @@ -0,0 +1,44 @@ +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - command: kubectl create secret generic openstack-clouds --from-file=clouds.yaml=${E2E_KUTTL_OSCLOUDS} ${E2E_KUTTL_CACERT_OPT} + namespaced: true +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Network +metadata: + name: trunk-update +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-update +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Subnet +metadata: + name: trunk-update +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + networkRef: trunk-update + ipVersion: 4 + cidr: 192.168.158.0/24 +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Port +metadata: + name: trunk-update +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + networkRef: trunk-update + diff --git a/internal/controllers/trunk/tests/trunk-update/01-assert.yaml b/internal/controllers/trunk/tests/trunk-update/01-assert.yaml new file mode 100644 index 000000000..b0c7694a9 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/01-assert.yaml @@ -0,0 +1,15 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +resourceRefs: + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: trunk + name: trunk-update + ref: trunk +assertAll: + - celExpr: "trunk.status.resource.name == 'trunk-update-updated'" + - celExpr: "trunk.status.resource.description == 'trunk-update-updated'" + - celExpr: "trunk.status.resource.adminStateUp == false" + - celExpr: "'tag1' in trunk.status.resource.tags" + - celExpr: "'tag2' in trunk.status.resource.tags" + diff --git a/internal/controllers/trunk/tests/trunk-update/01-updated-resource.yaml b/internal/controllers/trunk/tests/trunk-update/01-updated-resource.yaml new file mode 100644 index 000000000..0dbc6956a --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/01-updated-resource.yaml @@ -0,0 +1,19 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-update +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + name: trunk-update-updated + description: trunk-update-updated + portRef: trunk-update + adminStateUp: false + tags: + - tag1 + - tag2 + diff --git a/internal/controllers/trunk/tests/trunk-update/02-assert.yaml b/internal/controllers/trunk/tests/trunk-update/02-assert.yaml new file mode 100644 index 000000000..bd433e88a --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/02-assert.yaml @@ -0,0 +1,14 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +resourceRefs: + - apiVersion: openstack.k-orc.cloud/v1alpha1 + kind: trunk + name: trunk-update + ref: trunk +assertAll: + - celExpr: "trunk.status.resource.name == 'trunk-update'" + - celExpr: "trunk.status.resource.description == ''" + - celExpr: "trunk.status.resource.adminStateUp == true" + - celExpr: "size(trunk.status.resource.tags) == 0" + diff --git a/internal/controllers/trunk/tests/trunk-update/02-reverted-resource.yaml b/internal/controllers/trunk/tests/trunk-update/02-reverted-resource.yaml new file mode 100644 index 000000000..990eab8f3 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/02-reverted-resource.yaml @@ -0,0 +1,14 @@ +--- +apiVersion: openstack.k-orc.cloud/v1alpha1 +kind: Trunk +metadata: + name: trunk-update +spec: + cloudCredentialsRef: + cloudName: openstack + secretName: openstack-clouds + managementPolicy: managed + resource: + portRef: trunk-update + adminStateUp: true + diff --git a/internal/controllers/trunk/tests/trunk-update/README.md b/internal/controllers/trunk/tests/trunk-update/README.md new file mode 100644 index 000000000..f8056b138 --- /dev/null +++ b/internal/controllers/trunk/tests/trunk-update/README.md @@ -0,0 +1,26 @@ +# Update a trunk + +This test verifies that mutable fields of a trunk can be updated. + +## Step 00 + +Create a minimal trunk and verify its initial state. + +## Step 01 + +Update the trunk with: +- New name +- Description +- Admin state (false) +- Tags + +Verify that the changes are reflected in the observed status. + +## Step 02 + +Revert the changes back to the minimal configuration and verify that the resource status is similar to the one we had in step 00. + +## Reference + +https://k-orc.cloud/development/writing-tests/#update + diff --git a/internal/controllers/trunk/zz_generated.adapter.go b/internal/controllers/trunk/zz_generated.adapter.go new file mode 100644 index 000000000..9e6bef3b1 --- /dev/null +++ b/internal/controllers/trunk/zz_generated.adapter.go @@ -0,0 +1,88 @@ +// Code generated by resource-generator. DO NOT EDIT. +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 trunk + +import ( + orcv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + "github.com/k-orc/openstack-resource-controller/v2/internal/controllers/generic/interfaces" +) + +// Fundamental types +type ( + orcObjectT = orcv1alpha1.Trunk + orcObjectListT = orcv1alpha1.TrunkList + resourceSpecT = orcv1alpha1.TrunkResourceSpec + filterT = orcv1alpha1.TrunkFilter +) + +// Derived types +type ( + orcObjectPT = *orcObjectT + adapterI = interfaces.APIObjectAdapter[orcObjectPT, resourceSpecT, filterT] + adapterT = trunkAdapter +) + +type trunkAdapter struct { + *orcv1alpha1.Trunk +} + +var _ adapterI = &adapterT{} + +func (f adapterT) GetObject() orcObjectPT { + return f.Trunk +} + +func (f adapterT) GetManagementPolicy() orcv1alpha1.ManagementPolicy { + return f.Spec.ManagementPolicy +} + +func (f adapterT) GetManagedOptions() *orcv1alpha1.ManagedOptions { + return f.Spec.ManagedOptions +} + +func (f adapterT) GetStatusID() *string { + return f.Status.ID +} + +func (f adapterT) GetResourceSpec() *resourceSpecT { + return f.Spec.Resource +} + +func (f adapterT) GetImportID() *string { + if f.Spec.Import == nil { + return nil + } + return f.Spec.Import.ID +} + +func (f adapterT) GetImportFilter() *filterT { + if f.Spec.Import == nil { + return nil + } + return f.Spec.Import.Filter +} + +// getResourceName returns the name of the OpenStack resource we should use. +// This method is not implemented as part of APIObjectAdapter as it is intended +// to be used by resource actuators, which don't use the adapter. +func getResourceName(orcObject orcObjectPT) string { + if orcObject.Spec.Resource.Name != nil { + return string(*orcObject.Spec.Resource.Name) + } + return orcObject.Name +} diff --git a/internal/controllers/trunk/zz_generated.controller.go b/internal/controllers/trunk/zz_generated.controller.go new file mode 100644 index 000000000..e99ea3d01 --- /dev/null +++ b/internal/controllers/trunk/zz_generated.controller.go @@ -0,0 +1,45 @@ +// Code generated by resource-generator. DO NOT EDIT. +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 trunk + +import ( + corev1 "k8s.io/api/core/v1" + + "github.com/k-orc/openstack-resource-controller/v2/internal/util/dependency" + orcstrings "github.com/k-orc/openstack-resource-controller/v2/internal/util/strings" +) + +var ( + // NOTE: controllerName must be defined in any controller using this template + + // finalizer is the string this controller adds to an object's Finalizers + finalizer = orcstrings.GetFinalizerName(controllerName) + + // externalObjectFieldOwner is the field owner we use when using + // server-side-apply on objects we don't control + externalObjectFieldOwner = orcstrings.GetSSAFieldOwner(controllerName) + + credentialsDependency = dependency.NewDeletionGuardDependency[*orcObjectListT, *corev1.Secret]( + "spec.cloudCredentialsRef.secretName", + func(obj orcObjectPT) []string { + return []string{obj.Spec.CloudCredentialsRef.SecretName} + }, + finalizer, externalObjectFieldOwner, + dependency.OverrideDependencyName("credentials"), + ) +) diff --git a/internal/osclients/mock/networking.go b/internal/osclients/mock/networking.go index 9b5e25046..41baf525f 100644 --- a/internal/osclients/mock/networking.go +++ b/internal/osclients/mock/networking.go @@ -34,6 +34,7 @@ import ( routers "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/layer3/routers" groups "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/security/groups" rules "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/security/rules" + trunks "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/trunks" networks "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/networks" ports "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/ports" subnets "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/subnets" @@ -80,6 +81,21 @@ func (mr *MockNetworkClientMockRecorder) AddRouterInterface(ctx, id, opts any) * return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRouterInterface", reflect.TypeOf((*MockNetworkClient)(nil).AddRouterInterface), ctx, id, opts) } +// AddSubports mocks base method. +func (m *MockNetworkClient) AddSubports(ctx context.Context, id string, opts trunks.AddSubportsOptsBuilder) (*trunks.Trunk, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AddSubports", ctx, id, opts) + ret0, _ := ret[0].(*trunks.Trunk) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AddSubports indicates an expected call of AddSubports. +func (mr *MockNetworkClientMockRecorder) AddSubports(ctx, id, opts any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubports", reflect.TypeOf((*MockNetworkClient)(nil).AddSubports), ctx, id, opts) +} + // CreateFloatingIP mocks base method. func (m *MockNetworkClient) CreateFloatingIP(ctx context.Context, opts floatingips.CreateOptsBuilder) (*floatingips.FloatingIP, error) { m.ctrl.T.Helper() @@ -185,6 +201,21 @@ func (mr *MockNetworkClientMockRecorder) CreateSubnet(ctx, opts any) *gomock.Cal return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSubnet", reflect.TypeOf((*MockNetworkClient)(nil).CreateSubnet), ctx, opts) } +// CreateTrunk mocks base method. +func (m *MockNetworkClient) CreateTrunk(ctx context.Context, opts trunks.CreateOptsBuilder) (*trunks.Trunk, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateTrunk", ctx, opts) + ret0, _ := ret[0].(*trunks.Trunk) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateTrunk indicates an expected call of CreateTrunk. +func (mr *MockNetworkClientMockRecorder) CreateTrunk(ctx, opts any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateTrunk", reflect.TypeOf((*MockNetworkClient)(nil).CreateTrunk), ctx, opts) +} + // DeleteFloatingIP mocks base method. func (m *MockNetworkClient) DeleteFloatingIP(ctx context.Context, id string) error { m.ctrl.T.Helper() @@ -283,6 +314,20 @@ func (mr *MockNetworkClientMockRecorder) DeleteSubnet(ctx, id any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSubnet", reflect.TypeOf((*MockNetworkClient)(nil).DeleteSubnet), ctx, id) } +// DeleteTrunk mocks base method. +func (m *MockNetworkClient) DeleteTrunk(ctx context.Context, id string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteTrunk", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteTrunk indicates an expected call of DeleteTrunk. +func (mr *MockNetworkClientMockRecorder) DeleteTrunk(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteTrunk", reflect.TypeOf((*MockNetworkClient)(nil).DeleteTrunk), ctx, id) +} + // GetFloatingIP mocks base method. func (m *MockNetworkClient) GetFloatingIP(ctx context.Context, id string) (*floatingips.FloatingIP, error) { m.ctrl.T.Helper() @@ -388,6 +433,21 @@ func (mr *MockNetworkClientMockRecorder) GetSubnet(ctx, id any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnet", reflect.TypeOf((*MockNetworkClient)(nil).GetSubnet), ctx, id) } +// GetTrunk mocks base method. +func (m *MockNetworkClient) GetTrunk(ctx context.Context, id string) (*trunks.Trunk, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTrunk", ctx, id) + ret0, _ := ret[0].(*trunks.Trunk) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTrunk indicates an expected call of GetTrunk. +func (mr *MockNetworkClientMockRecorder) GetTrunk(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTrunk", reflect.TypeOf((*MockNetworkClient)(nil).GetTrunk), ctx, id) +} + // ListFloatingIP mocks base method. func (m *MockNetworkClient) ListFloatingIP(ctx context.Context, opts floatingips.ListOptsBuilder) iter.Seq2[*floatingips.FloatingIP, error] { m.ctrl.T.Helper() @@ -487,6 +547,36 @@ func (mr *MockNetworkClientMockRecorder) ListSubnet(ctx, opts any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSubnet", reflect.TypeOf((*MockNetworkClient)(nil).ListSubnet), ctx, opts) } +// ListTrunk mocks base method. +func (m *MockNetworkClient) ListTrunk(ctx context.Context, opts trunks.ListOptsBuilder) ([]trunks.Trunk, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListTrunk", ctx, opts) + ret0, _ := ret[0].([]trunks.Trunk) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListTrunk indicates an expected call of ListTrunk. +func (mr *MockNetworkClientMockRecorder) ListTrunk(ctx, opts any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTrunk", reflect.TypeOf((*MockNetworkClient)(nil).ListTrunk), ctx, opts) +} + +// ListTrunkSubports mocks base method. +func (m *MockNetworkClient) ListTrunkSubports(ctx context.Context, trunkID string) ([]trunks.Subport, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListTrunkSubports", ctx, trunkID) + ret0, _ := ret[0].([]trunks.Subport) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListTrunkSubports indicates an expected call of ListTrunkSubports. +func (mr *MockNetworkClientMockRecorder) ListTrunkSubports(ctx, trunkID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListTrunkSubports", reflect.TypeOf((*MockNetworkClient)(nil).ListTrunkSubports), ctx, trunkID) +} + // RemoveRouterInterface mocks base method. func (m *MockNetworkClient) RemoveRouterInterface(ctx context.Context, id string, opts routers.RemoveInterfaceOptsBuilder) (*routers.InterfaceInfo, error) { m.ctrl.T.Helper() @@ -502,6 +592,20 @@ func (mr *MockNetworkClientMockRecorder) RemoveRouterInterface(ctx, id, opts any return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveRouterInterface", reflect.TypeOf((*MockNetworkClient)(nil).RemoveRouterInterface), ctx, id, opts) } +// RemoveSubports mocks base method. +func (m *MockNetworkClient) RemoveSubports(ctx context.Context, id string, opts trunks.RemoveSubportsOptsBuilder) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RemoveSubports", ctx, id, opts) + ret0, _ := ret[0].(error) + return ret0 +} + +// RemoveSubports indicates an expected call of RemoveSubports. +func (mr *MockNetworkClientMockRecorder) RemoveSubports(ctx, id, opts any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveSubports", reflect.TypeOf((*MockNetworkClient)(nil).RemoveSubports), ctx, id, opts) +} + // ReplaceAllAttributesTags mocks base method. func (m *MockNetworkClient) ReplaceAllAttributesTags(ctx context.Context, resourceType, resourceID string, opts attributestags.ReplaceAllOptsBuilder) ([]string, error) { m.ctrl.T.Helper() @@ -606,3 +710,18 @@ func (mr *MockNetworkClientMockRecorder) UpdateSubnet(ctx, id, opts any) *gomock mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSubnet", reflect.TypeOf((*MockNetworkClient)(nil).UpdateSubnet), ctx, id, opts) } + +// UpdateTrunk mocks base method. +func (m *MockNetworkClient) UpdateTrunk(ctx context.Context, id string, opts trunks.UpdateOptsBuilder) (*trunks.Trunk, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateTrunk", ctx, id, opts) + ret0, _ := ret[0].(*trunks.Trunk) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateTrunk indicates an expected call of UpdateTrunk. +func (mr *MockNetworkClientMockRecorder) UpdateTrunk(ctx, id, opts any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateTrunk", reflect.TypeOf((*MockNetworkClient)(nil).UpdateTrunk), ctx, id, opts) +} diff --git a/internal/osclients/networking.go b/internal/osclients/networking.go index 99156d64e..74e99798d 100644 --- a/internal/osclients/networking.go +++ b/internal/osclients/networking.go @@ -102,6 +102,15 @@ type NetworkClient interface { GetSubnet(ctx context.Context, id string) (*subnets.Subnet, error) UpdateSubnet(ctx context.Context, id string, opts subnets.UpdateOptsBuilder) (*subnets.Subnet, error) + ListTrunk(ctx context.Context, opts trunks.ListOptsBuilder) ([]trunks.Trunk, error) + GetTrunk(ctx context.Context, id string) (*trunks.Trunk, error) + CreateTrunk(ctx context.Context, opts trunks.CreateOptsBuilder) (*trunks.Trunk, error) + UpdateTrunk(ctx context.Context, id string, opts trunks.UpdateOptsBuilder) (*trunks.Trunk, error) + DeleteTrunk(ctx context.Context, id string) error + ListTrunkSubports(ctx context.Context, trunkID string) ([]trunks.Subport, error) + AddSubports(ctx context.Context, id string, opts trunks.AddSubportsOptsBuilder) (*trunks.Trunk, error) + RemoveSubports(ctx context.Context, id string, opts trunks.RemoveSubportsOptsBuilder) error + ReplaceAllAttributesTags(ctx context.Context, resourceType string, resourceID string, opts attributestags.ReplaceAllOptsBuilder) ([]string, error) } @@ -214,10 +223,18 @@ func (c networkClient) UpdatePort(ctx context.Context, id string, opts ports.Upd return &portExt, nil } +func (c networkClient) GetTrunk(ctx context.Context, id string) (*trunks.Trunk, error) { + return trunks.Get(ctx, c.serviceClient, id).Extract() +} + func (c networkClient) CreateTrunk(ctx context.Context, opts trunks.CreateOptsBuilder) (*trunks.Trunk, error) { return trunks.Create(ctx, c.serviceClient, opts).Extract() } +func (c networkClient) UpdateTrunk(ctx context.Context, id string, opts trunks.UpdateOptsBuilder) (*trunks.Trunk, error) { + return trunks.Update(ctx, c.serviceClient, id, opts).Extract() +} + func (c networkClient) DeleteTrunk(ctx context.Context, id string) error { return trunks.Delete(ctx, c.serviceClient, id).ExtractErr() } @@ -226,10 +243,6 @@ func (c networkClient) ListTrunkSubports(ctx context.Context, trunkID string) ([ return trunks.GetSubports(ctx, c.serviceClient, trunkID).Extract() } -func (c networkClient) RemoveSubports(ctx context.Context, id string, opts trunks.RemoveSubportsOpts) error { - _, err := trunks.RemoveSubports(ctx, c.serviceClient, id, opts).Extract() - return err -} func (c networkClient) ListTrunk(ctx context.Context, opts trunks.ListOptsBuilder) ([]trunks.Trunk, error) { allPages, err := trunks.List(c.serviceClient, opts).AllPages(ctx) @@ -239,6 +252,15 @@ func (c networkClient) ListTrunk(ctx context.Context, opts trunks.ListOptsBuilde return trunks.ExtractTrunks(allPages) } +func (c networkClient) AddSubports(ctx context.Context, id string, opts trunks.AddSubportsOptsBuilder) (*trunks.Trunk, error) { + return trunks.AddSubports(ctx, c.serviceClient, id, opts).Extract() +} + +func (c networkClient) RemoveSubports(ctx context.Context, id string, opts trunks.RemoveSubportsOptsBuilder) error { + _, err := trunks.RemoveSubports(ctx, c.serviceClient, id, opts).Extract() + return err +} + func (c networkClient) CreateRouter(ctx context.Context, opts routers.CreateOptsBuilder) (*routers.Router, error) { return routers.Create(ctx, c.serviceClient, opts).Extract() } diff --git a/kuttl-test.yaml b/kuttl-test.yaml index 1ab9f1b89..7ba92b4fa 100644 --- a/kuttl-test.yaml +++ b/kuttl-test.yaml @@ -15,6 +15,7 @@ testDirs: - ./internal/controllers/server/tests/ - ./internal/controllers/servergroup/tests/ - ./internal/controllers/subnet/tests/ +- ./internal/controllers/trunk/tests/ - ./internal/controllers/volume/tests/ - ./internal/controllers/volumetype/tests/ timeout: 240 diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/subport.go b/pkg/clients/applyconfiguration/api/v1alpha1/subport.go new file mode 100644 index 000000000..41d035e28 --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/subport.go @@ -0,0 +1,61 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" +) + +// SubportApplyConfiguration represents a declarative configuration of the Subport type for use +// with apply. +type SubportApplyConfiguration struct { + PortRef *apiv1alpha1.KubernetesNameRef `json:"portRef,omitempty"` + SegmentationType *string `json:"segmentationType,omitempty"` + SegmentationID *int32 `json:"segmentationID,omitempty"` +} + +// SubportApplyConfiguration constructs a declarative configuration of the Subport type for use with +// apply. +func Subport() *SubportApplyConfiguration { + return &SubportApplyConfiguration{} +} + +// WithPortRef sets the PortRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PortRef field is set to the value of the last call. +func (b *SubportApplyConfiguration) WithPortRef(value apiv1alpha1.KubernetesNameRef) *SubportApplyConfiguration { + b.PortRef = &value + return b +} + +// WithSegmentationType sets the SegmentationType field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the SegmentationType field is set to the value of the last call. +func (b *SubportApplyConfiguration) WithSegmentationType(value string) *SubportApplyConfiguration { + b.SegmentationType = &value + return b +} + +// WithSegmentationID sets the SegmentationID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the SegmentationID field is set to the value of the last call. +func (b *SubportApplyConfiguration) WithSegmentationID(value int32) *SubportApplyConfiguration { + b.SegmentationID = &value + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/subportstatus.go b/pkg/clients/applyconfiguration/api/v1alpha1/subportstatus.go new file mode 100644 index 000000000..7f5982148 --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/subportstatus.go @@ -0,0 +1,57 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +// SubportStatusApplyConfiguration represents a declarative configuration of the SubportStatus type for use +// with apply. +type SubportStatusApplyConfiguration struct { + PortID *string `json:"portID,omitempty"` + SegmentationType *string `json:"segmentationType,omitempty"` + SegmentationID *int32 `json:"segmentationID,omitempty"` +} + +// SubportStatusApplyConfiguration constructs a declarative configuration of the SubportStatus type for use with +// apply. +func SubportStatus() *SubportStatusApplyConfiguration { + return &SubportStatusApplyConfiguration{} +} + +// WithPortID sets the PortID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PortID field is set to the value of the last call. +func (b *SubportStatusApplyConfiguration) WithPortID(value string) *SubportStatusApplyConfiguration { + b.PortID = &value + return b +} + +// WithSegmentationType sets the SegmentationType field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the SegmentationType field is set to the value of the last call. +func (b *SubportStatusApplyConfiguration) WithSegmentationType(value string) *SubportStatusApplyConfiguration { + b.SegmentationType = &value + return b +} + +// WithSegmentationID sets the SegmentationID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the SegmentationID field is set to the value of the last call. +func (b *SubportStatusApplyConfiguration) WithSegmentationID(value int32) *SubportStatusApplyConfiguration { + b.SegmentationID = &value + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunk.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunk.go new file mode 100644 index 000000000..948d40e2d --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunk.go @@ -0,0 +1,281 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + internal "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/applyconfiguration/internal" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + managedfields "k8s.io/apimachinery/pkg/util/managedfields" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// TrunkApplyConfiguration represents a declarative configuration of the Trunk type for use +// with apply. +type TrunkApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *TrunkSpecApplyConfiguration `json:"spec,omitempty"` + Status *TrunkStatusApplyConfiguration `json:"status,omitempty"` +} + +// Trunk constructs a declarative configuration of the Trunk type for use with +// apply. +func Trunk(name, namespace string) *TrunkApplyConfiguration { + b := &TrunkApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("Trunk") + b.WithAPIVersion("openstack.k-orc.cloud/v1alpha1") + return b +} + +// ExtractTrunk extracts the applied configuration owned by fieldManager from +// trunk. If no managedFields are found in trunk for fieldManager, a +// TrunkApplyConfiguration is returned with only the Name, Namespace (if applicable), +// APIVersion and Kind populated. It is possible that no managed fields were found for because other +// field managers have taken ownership of all the fields previously owned by fieldManager, or because +// the fieldManager never owned fields any fields. +// trunk must be a unmodified Trunk API object that was retrieved from the Kubernetes API. +// ExtractTrunk provides a way to perform a extract/modify-in-place/apply workflow. +// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously +// applied if another fieldManager has updated or force applied any of the previously applied fields. +// Experimental! +func ExtractTrunk(trunk *apiv1alpha1.Trunk, fieldManager string) (*TrunkApplyConfiguration, error) { + return extractTrunk(trunk, fieldManager, "") +} + +// ExtractTrunkStatus is the same as ExtractTrunk except +// that it extracts the status subresource applied configuration. +// Experimental! +func ExtractTrunkStatus(trunk *apiv1alpha1.Trunk, fieldManager string) (*TrunkApplyConfiguration, error) { + return extractTrunk(trunk, fieldManager, "status") +} + +func extractTrunk(trunk *apiv1alpha1.Trunk, fieldManager string, subresource string) (*TrunkApplyConfiguration, error) { + b := &TrunkApplyConfiguration{} + err := managedfields.ExtractInto(trunk, internal.Parser().Type("com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.Trunk"), fieldManager, b, subresource) + if err != nil { + return nil, err + } + b.WithName(trunk.Name) + b.WithNamespace(trunk.Namespace) + + b.WithKind("Trunk") + b.WithAPIVersion("openstack.k-orc.cloud/v1alpha1") + return b, nil +} +func (b TrunkApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Kind field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithKind(value string) *TrunkApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the APIVersion field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithAPIVersion(value string) *TrunkApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithName(value string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the GenerateName field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithGenerateName(value string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Namespace field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithNamespace(value string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UID field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithUID(value types.UID) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ResourceVersion field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithResourceVersion(value string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Generation field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithGeneration(value int64) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreationTimestamp field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithCreationTimestamp(value metav1.Time) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionTimestamp field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *TrunkApplyConfiguration) WithLabels(entries map[string]string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *TrunkApplyConfiguration) WithAnnotations(entries map[string]string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *TrunkApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *TrunkApplyConfiguration) WithFinalizers(values ...string) *TrunkApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *TrunkApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Spec field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithSpec(value *TrunkSpecApplyConfiguration) *TrunkApplyConfiguration { + b.Spec = value + return b +} + +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *TrunkApplyConfiguration) WithStatus(value *TrunkStatusApplyConfiguration) *TrunkApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *TrunkApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *TrunkApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *TrunkApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *TrunkApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunkfilter.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunkfilter.go new file mode 100644 index 000000000..3ab2b232a --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunkfilter.go @@ -0,0 +1,111 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" +) + +// TrunkFilterApplyConfiguration represents a declarative configuration of the TrunkFilter type for use +// with apply. +type TrunkFilterApplyConfiguration struct { + Name *apiv1alpha1.OpenStackName `json:"name,omitempty"` + Description *apiv1alpha1.NeutronDescription `json:"description,omitempty"` + PortRef *apiv1alpha1.KubernetesNameRef `json:"portRef,omitempty"` + ProjectRef *apiv1alpha1.KubernetesNameRef `json:"projectRef,omitempty"` + FilterByNeutronTagsApplyConfiguration `json:",inline"` +} + +// TrunkFilterApplyConfiguration constructs a declarative configuration of the TrunkFilter type for use with +// apply. +func TrunkFilter() *TrunkFilterApplyConfiguration { + return &TrunkFilterApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *TrunkFilterApplyConfiguration) WithName(value apiv1alpha1.OpenStackName) *TrunkFilterApplyConfiguration { + b.Name = &value + return b +} + +// WithDescription sets the Description field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Description field is set to the value of the last call. +func (b *TrunkFilterApplyConfiguration) WithDescription(value apiv1alpha1.NeutronDescription) *TrunkFilterApplyConfiguration { + b.Description = &value + return b +} + +// WithPortRef sets the PortRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PortRef field is set to the value of the last call. +func (b *TrunkFilterApplyConfiguration) WithPortRef(value apiv1alpha1.KubernetesNameRef) *TrunkFilterApplyConfiguration { + b.PortRef = &value + return b +} + +// WithProjectRef sets the ProjectRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProjectRef field is set to the value of the last call. +func (b *TrunkFilterApplyConfiguration) WithProjectRef(value apiv1alpha1.KubernetesNameRef) *TrunkFilterApplyConfiguration { + b.ProjectRef = &value + return b +} + +// WithTags adds the given value to the Tags field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tags field. +func (b *TrunkFilterApplyConfiguration) WithTags(values ...apiv1alpha1.NeutronTag) *TrunkFilterApplyConfiguration { + for i := range values { + b.FilterByNeutronTagsApplyConfiguration.Tags = append(b.FilterByNeutronTagsApplyConfiguration.Tags, values[i]) + } + return b +} + +// WithTagsAny adds the given value to the TagsAny field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the TagsAny field. +func (b *TrunkFilterApplyConfiguration) WithTagsAny(values ...apiv1alpha1.NeutronTag) *TrunkFilterApplyConfiguration { + for i := range values { + b.FilterByNeutronTagsApplyConfiguration.TagsAny = append(b.FilterByNeutronTagsApplyConfiguration.TagsAny, values[i]) + } + return b +} + +// WithNotTags adds the given value to the NotTags field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the NotTags field. +func (b *TrunkFilterApplyConfiguration) WithNotTags(values ...apiv1alpha1.NeutronTag) *TrunkFilterApplyConfiguration { + for i := range values { + b.FilterByNeutronTagsApplyConfiguration.NotTags = append(b.FilterByNeutronTagsApplyConfiguration.NotTags, values[i]) + } + return b +} + +// WithNotTagsAny adds the given value to the NotTagsAny field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the NotTagsAny field. +func (b *TrunkFilterApplyConfiguration) WithNotTagsAny(values ...apiv1alpha1.NeutronTag) *TrunkFilterApplyConfiguration { + for i := range values { + b.FilterByNeutronTagsApplyConfiguration.NotTagsAny = append(b.FilterByNeutronTagsApplyConfiguration.NotTagsAny, values[i]) + } + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunkimport.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunkimport.go new file mode 100644 index 000000000..5b482302f --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunkimport.go @@ -0,0 +1,48 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +// TrunkImportApplyConfiguration represents a declarative configuration of the TrunkImport type for use +// with apply. +type TrunkImportApplyConfiguration struct { + ID *string `json:"id,omitempty"` + Filter *TrunkFilterApplyConfiguration `json:"filter,omitempty"` +} + +// TrunkImportApplyConfiguration constructs a declarative configuration of the TrunkImport type for use with +// apply. +func TrunkImport() *TrunkImportApplyConfiguration { + return &TrunkImportApplyConfiguration{} +} + +// WithID sets the ID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ID field is set to the value of the last call. +func (b *TrunkImportApplyConfiguration) WithID(value string) *TrunkImportApplyConfiguration { + b.ID = &value + return b +} + +// WithFilter sets the Filter field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Filter field is set to the value of the last call. +func (b *TrunkImportApplyConfiguration) WithFilter(value *TrunkFilterApplyConfiguration) *TrunkImportApplyConfiguration { + b.Filter = value + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunkresourcespec.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunkresourcespec.go new file mode 100644 index 000000000..1e0fc7711 --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunkresourcespec.go @@ -0,0 +1,104 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" +) + +// TrunkResourceSpecApplyConfiguration represents a declarative configuration of the TrunkResourceSpec type for use +// with apply. +type TrunkResourceSpecApplyConfiguration struct { + Name *apiv1alpha1.OpenStackName `json:"name,omitempty"` + Description *apiv1alpha1.NeutronDescription `json:"description,omitempty"` + PortRef *apiv1alpha1.KubernetesNameRef `json:"portRef,omitempty"` + Tags []apiv1alpha1.NeutronTag `json:"tags,omitempty"` + AdminStateUp *bool `json:"adminStateUp,omitempty"` + Subports []SubportApplyConfiguration `json:"subports,omitempty"` + ProjectRef *apiv1alpha1.KubernetesNameRef `json:"projectRef,omitempty"` +} + +// TrunkResourceSpecApplyConfiguration constructs a declarative configuration of the TrunkResourceSpec type for use with +// apply. +func TrunkResourceSpec() *TrunkResourceSpecApplyConfiguration { + return &TrunkResourceSpecApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *TrunkResourceSpecApplyConfiguration) WithName(value apiv1alpha1.OpenStackName) *TrunkResourceSpecApplyConfiguration { + b.Name = &value + return b +} + +// WithDescription sets the Description field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Description field is set to the value of the last call. +func (b *TrunkResourceSpecApplyConfiguration) WithDescription(value apiv1alpha1.NeutronDescription) *TrunkResourceSpecApplyConfiguration { + b.Description = &value + return b +} + +// WithPortRef sets the PortRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PortRef field is set to the value of the last call. +func (b *TrunkResourceSpecApplyConfiguration) WithPortRef(value apiv1alpha1.KubernetesNameRef) *TrunkResourceSpecApplyConfiguration { + b.PortRef = &value + return b +} + +// WithTags adds the given value to the Tags field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tags field. +func (b *TrunkResourceSpecApplyConfiguration) WithTags(values ...apiv1alpha1.NeutronTag) *TrunkResourceSpecApplyConfiguration { + for i := range values { + b.Tags = append(b.Tags, values[i]) + } + return b +} + +// WithAdminStateUp sets the AdminStateUp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AdminStateUp field is set to the value of the last call. +func (b *TrunkResourceSpecApplyConfiguration) WithAdminStateUp(value bool) *TrunkResourceSpecApplyConfiguration { + b.AdminStateUp = &value + return b +} + +// WithSubports adds the given value to the Subports field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Subports field. +func (b *TrunkResourceSpecApplyConfiguration) WithSubports(values ...*SubportApplyConfiguration) *TrunkResourceSpecApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSubports") + } + b.Subports = append(b.Subports, *values[i]) + } + return b +} + +// WithProjectRef sets the ProjectRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProjectRef field is set to the value of the last call. +func (b *TrunkResourceSpecApplyConfiguration) WithProjectRef(value apiv1alpha1.KubernetesNameRef) *TrunkResourceSpecApplyConfiguration { + b.ProjectRef = &value + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunkresourcestatus.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunkresourcestatus.go new file mode 100644 index 000000000..9f997f571 --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunkresourcestatus.go @@ -0,0 +1,138 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// TrunkResourceStatusApplyConfiguration represents a declarative configuration of the TrunkResourceStatus type for use +// with apply. +type TrunkResourceStatusApplyConfiguration struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + PortID *string `json:"portID,omitempty"` + ProjectID *string `json:"projectID,omitempty"` + Status *string `json:"status,omitempty"` + Tags []string `json:"tags,omitempty"` + AdminStateUp *bool `json:"adminStateUp,omitempty"` + Subports []SubportStatusApplyConfiguration `json:"subports,omitempty"` + NeutronStatusMetadataApplyConfiguration `json:",inline"` +} + +// TrunkResourceStatusApplyConfiguration constructs a declarative configuration of the TrunkResourceStatus type for use with +// apply. +func TrunkResourceStatus() *TrunkResourceStatusApplyConfiguration { + return &TrunkResourceStatusApplyConfiguration{} +} + +// WithName sets the Name field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Name field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithName(value string) *TrunkResourceStatusApplyConfiguration { + b.Name = &value + return b +} + +// WithDescription sets the Description field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Description field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithDescription(value string) *TrunkResourceStatusApplyConfiguration { + b.Description = &value + return b +} + +// WithPortID sets the PortID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PortID field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithPortID(value string) *TrunkResourceStatusApplyConfiguration { + b.PortID = &value + return b +} + +// WithProjectID sets the ProjectID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProjectID field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithProjectID(value string) *TrunkResourceStatusApplyConfiguration { + b.ProjectID = &value + return b +} + +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithStatus(value string) *TrunkResourceStatusApplyConfiguration { + b.Status = &value + return b +} + +// WithTags adds the given value to the Tags field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Tags field. +func (b *TrunkResourceStatusApplyConfiguration) WithTags(values ...string) *TrunkResourceStatusApplyConfiguration { + for i := range values { + b.Tags = append(b.Tags, values[i]) + } + return b +} + +// WithAdminStateUp sets the AdminStateUp field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the AdminStateUp field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithAdminStateUp(value bool) *TrunkResourceStatusApplyConfiguration { + b.AdminStateUp = &value + return b +} + +// WithSubports adds the given value to the Subports field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Subports field. +func (b *TrunkResourceStatusApplyConfiguration) WithSubports(values ...*SubportStatusApplyConfiguration) *TrunkResourceStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithSubports") + } + b.Subports = append(b.Subports, *values[i]) + } + return b +} + +// WithCreatedAt sets the CreatedAt field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CreatedAt field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithCreatedAt(value v1.Time) *TrunkResourceStatusApplyConfiguration { + b.NeutronStatusMetadataApplyConfiguration.CreatedAt = &value + return b +} + +// WithUpdatedAt sets the UpdatedAt field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdatedAt field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithUpdatedAt(value v1.Time) *TrunkResourceStatusApplyConfiguration { + b.NeutronStatusMetadataApplyConfiguration.UpdatedAt = &value + return b +} + +// WithRevisionNumber sets the RevisionNumber field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the RevisionNumber field is set to the value of the last call. +func (b *TrunkResourceStatusApplyConfiguration) WithRevisionNumber(value int64) *TrunkResourceStatusApplyConfiguration { + b.NeutronStatusMetadataApplyConfiguration.RevisionNumber = &value + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunkspec.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunkspec.go new file mode 100644 index 000000000..2eaef7903 --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunkspec.go @@ -0,0 +1,79 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" +) + +// TrunkSpecApplyConfiguration represents a declarative configuration of the TrunkSpec type for use +// with apply. +type TrunkSpecApplyConfiguration struct { + Import *TrunkImportApplyConfiguration `json:"import,omitempty"` + Resource *TrunkResourceSpecApplyConfiguration `json:"resource,omitempty"` + ManagementPolicy *apiv1alpha1.ManagementPolicy `json:"managementPolicy,omitempty"` + ManagedOptions *ManagedOptionsApplyConfiguration `json:"managedOptions,omitempty"` + CloudCredentialsRef *CloudCredentialsReferenceApplyConfiguration `json:"cloudCredentialsRef,omitempty"` +} + +// TrunkSpecApplyConfiguration constructs a declarative configuration of the TrunkSpec type for use with +// apply. +func TrunkSpec() *TrunkSpecApplyConfiguration { + return &TrunkSpecApplyConfiguration{} +} + +// WithImport sets the Import field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Import field is set to the value of the last call. +func (b *TrunkSpecApplyConfiguration) WithImport(value *TrunkImportApplyConfiguration) *TrunkSpecApplyConfiguration { + b.Import = value + return b +} + +// WithResource sets the Resource field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Resource field is set to the value of the last call. +func (b *TrunkSpecApplyConfiguration) WithResource(value *TrunkResourceSpecApplyConfiguration) *TrunkSpecApplyConfiguration { + b.Resource = value + return b +} + +// WithManagementPolicy sets the ManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ManagementPolicy field is set to the value of the last call. +func (b *TrunkSpecApplyConfiguration) WithManagementPolicy(value apiv1alpha1.ManagementPolicy) *TrunkSpecApplyConfiguration { + b.ManagementPolicy = &value + return b +} + +// WithManagedOptions sets the ManagedOptions field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ManagedOptions field is set to the value of the last call. +func (b *TrunkSpecApplyConfiguration) WithManagedOptions(value *ManagedOptionsApplyConfiguration) *TrunkSpecApplyConfiguration { + b.ManagedOptions = value + return b +} + +// WithCloudCredentialsRef sets the CloudCredentialsRef field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CloudCredentialsRef field is set to the value of the last call. +func (b *TrunkSpecApplyConfiguration) WithCloudCredentialsRef(value *CloudCredentialsReferenceApplyConfiguration) *TrunkSpecApplyConfiguration { + b.CloudCredentialsRef = value + return b +} diff --git a/pkg/clients/applyconfiguration/api/v1alpha1/trunkstatus.go b/pkg/clients/applyconfiguration/api/v1alpha1/trunkstatus.go new file mode 100644 index 000000000..ccf85550d --- /dev/null +++ b/pkg/clients/applyconfiguration/api/v1alpha1/trunkstatus.go @@ -0,0 +1,66 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 applyconfiguration-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// TrunkStatusApplyConfiguration represents a declarative configuration of the TrunkStatus type for use +// with apply. +type TrunkStatusApplyConfiguration struct { + Conditions []v1.ConditionApplyConfiguration `json:"conditions,omitempty"` + ID *string `json:"id,omitempty"` + Resource *TrunkResourceStatusApplyConfiguration `json:"resource,omitempty"` +} + +// TrunkStatusApplyConfiguration constructs a declarative configuration of the TrunkStatus type for use with +// apply. +func TrunkStatus() *TrunkStatusApplyConfiguration { + return &TrunkStatusApplyConfiguration{} +} + +// WithConditions adds the given value to the Conditions field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Conditions field. +func (b *TrunkStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *TrunkStatusApplyConfiguration { + for i := range values { + if values[i] == nil { + panic("nil value passed to WithConditions") + } + b.Conditions = append(b.Conditions, *values[i]) + } + return b +} + +// WithID sets the ID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ID field is set to the value of the last call. +func (b *TrunkStatusApplyConfiguration) WithID(value string) *TrunkStatusApplyConfiguration { + b.ID = &value + return b +} + +// WithResource sets the Resource field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Resource field is set to the value of the last call. +func (b *TrunkStatusApplyConfiguration) WithResource(value *TrunkResourceStatusApplyConfiguration) *TrunkStatusApplyConfiguration { + b.Resource = value + return b +} diff --git a/pkg/clients/applyconfiguration/internal/internal.go b/pkg/clients/applyconfiguration/internal/internal.go index 6e7bbcce3..a883e0299 100644 --- a/pkg/clients/applyconfiguration/internal/internal.go +++ b/pkg/clients/applyconfiguration/internal/internal.go @@ -2444,6 +2444,211 @@ var schemaYAML = typed.YAMLObject(`types: - name: resource type: namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.SubnetResourceStatus +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.Subport + map: + fields: + - name: portRef + type: + scalar: string + default: "" + - name: segmentationID + type: + scalar: numeric + default: 0 + - name: segmentationType + type: + scalar: string + default: "" +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.SubportStatus + map: + fields: + - name: portID + type: + scalar: string + - name: segmentationID + type: + scalar: numeric + - name: segmentationType + type: + scalar: string +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.Trunk + map: + fields: + - name: apiVersion + type: + scalar: string + - name: kind + type: + scalar: string + - name: metadata + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta + default: {} + - name: spec + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkSpec + default: {} + - name: status + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkStatus + default: {} +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkFilter + map: + fields: + - name: description + type: + scalar: string + - name: name + type: + scalar: string + - name: notTags + type: + list: + elementType: + scalar: string + elementRelationship: associative + - name: notTagsAny + type: + list: + elementType: + scalar: string + elementRelationship: associative + - name: portRef + type: + scalar: string + - name: projectRef + type: + scalar: string + - name: tags + type: + list: + elementType: + scalar: string + elementRelationship: associative + - name: tagsAny + type: + list: + elementType: + scalar: string + elementRelationship: associative +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkImport + map: + fields: + - name: filter + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkFilter + - name: id + type: + scalar: string +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkResourceSpec + map: + fields: + - name: adminStateUp + type: + scalar: boolean + - name: description + type: + scalar: string + - name: name + type: + scalar: string + - name: portRef + type: + scalar: string + default: "" + - name: projectRef + type: + scalar: string + - name: subports + type: + list: + elementType: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.Subport + elementRelationship: atomic + - name: tags + type: + list: + elementType: + scalar: string + elementRelationship: associative +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkResourceStatus + map: + fields: + - name: adminStateUp + type: + scalar: boolean + - name: createdAt + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time + - name: description + type: + scalar: string + - name: name + type: + scalar: string + - name: portID + type: + scalar: string + - name: projectID + type: + scalar: string + - name: revisionNumber + type: + scalar: numeric + - name: status + type: + scalar: string + - name: subports + type: + list: + elementType: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.SubportStatus + elementRelationship: atomic + - name: tags + type: + list: + elementType: + scalar: string + elementRelationship: atomic + - name: updatedAt + type: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Time +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkSpec + map: + fields: + - name: cloudCredentialsRef + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.CloudCredentialsReference + default: {} + - name: import + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkImport + - name: managedOptions + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.ManagedOptions + - name: managementPolicy + type: + scalar: string + - name: resource + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkResourceSpec +- name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkStatus + map: + fields: + - name: conditions + type: + list: + elementType: + namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition + elementRelationship: associative + keys: + - type + - name: id + type: + scalar: string + - name: resource + type: + namedType: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.TrunkResourceStatus - name: com.github.k-orc.openstack-resource-controller.v2.api.v1alpha1.UserDataSpec map: fields: diff --git a/pkg/clients/applyconfiguration/utils.go b/pkg/clients/applyconfiguration/utils.go index 2950e1663..fce8d71ca 100644 --- a/pkg/clients/applyconfiguration/utils.go +++ b/pkg/clients/applyconfiguration/utils.go @@ -280,6 +280,24 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &apiv1alpha1.SubnetSpecApplyConfiguration{} case v1alpha1.SchemeGroupVersion.WithKind("SubnetStatus"): return &apiv1alpha1.SubnetStatusApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("Subport"): + return &apiv1alpha1.SubportApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("SubportStatus"): + return &apiv1alpha1.SubportStatusApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("Trunk"): + return &apiv1alpha1.TrunkApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("TrunkFilter"): + return &apiv1alpha1.TrunkFilterApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("TrunkImport"): + return &apiv1alpha1.TrunkImportApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("TrunkResourceSpec"): + return &apiv1alpha1.TrunkResourceSpecApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("TrunkResourceStatus"): + return &apiv1alpha1.TrunkResourceStatusApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("TrunkSpec"): + return &apiv1alpha1.TrunkSpecApplyConfiguration{} + case v1alpha1.SchemeGroupVersion.WithKind("TrunkStatus"): + return &apiv1alpha1.TrunkStatusApplyConfiguration{} case v1alpha1.SchemeGroupVersion.WithKind("UserDataSpec"): return &apiv1alpha1.UserDataSpecApplyConfiguration{} case v1alpha1.SchemeGroupVersion.WithKind("Volume"): diff --git a/pkg/clients/clientset/clientset/typed/api/v1alpha1/api_client.go b/pkg/clients/clientset/clientset/typed/api/v1alpha1/api_client.go index d074fbd67..46621a37c 100644 --- a/pkg/clients/clientset/clientset/typed/api/v1alpha1/api_client.go +++ b/pkg/clients/clientset/clientset/typed/api/v1alpha1/api_client.go @@ -41,6 +41,7 @@ type OpenstackV1alpha1Interface interface { ServersGetter ServerGroupsGetter SubnetsGetter + TrunksGetter VolumesGetter VolumeTypesGetter } @@ -102,6 +103,10 @@ func (c *OpenstackV1alpha1Client) Subnets(namespace string) SubnetInterface { return newSubnets(c, namespace) } +func (c *OpenstackV1alpha1Client) Trunks(namespace string) TrunkInterface { + return newTrunks(c, namespace) +} + func (c *OpenstackV1alpha1Client) Volumes(namespace string) VolumeInterface { return newVolumes(c, namespace) } diff --git a/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_api_client.go b/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_api_client.go index 83249ddf2..5c151f7e1 100644 --- a/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_api_client.go +++ b/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_api_client.go @@ -80,6 +80,10 @@ func (c *FakeOpenstackV1alpha1) Subnets(namespace string) v1alpha1.SubnetInterfa return newFakeSubnets(c, namespace) } +func (c *FakeOpenstackV1alpha1) Trunks(namespace string) v1alpha1.TrunkInterface { + return newFakeTrunks(c, namespace) +} + func (c *FakeOpenstackV1alpha1) Volumes(namespace string) v1alpha1.VolumeInterface { return newFakeVolumes(c, namespace) } diff --git a/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_trunk.go b/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_trunk.go new file mode 100644 index 000000000..c66994f9e --- /dev/null +++ b/pkg/clients/clientset/clientset/typed/api/v1alpha1/fake/fake_trunk.go @@ -0,0 +1,49 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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 ( + v1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/applyconfiguration/api/v1alpha1" + typedapiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/clientset/clientset/typed/api/v1alpha1" + gentype "k8s.io/client-go/gentype" +) + +// fakeTrunks implements TrunkInterface +type fakeTrunks struct { + *gentype.FakeClientWithListAndApply[*v1alpha1.Trunk, *v1alpha1.TrunkList, *apiv1alpha1.TrunkApplyConfiguration] + Fake *FakeOpenstackV1alpha1 +} + +func newFakeTrunks(fake *FakeOpenstackV1alpha1, namespace string) typedapiv1alpha1.TrunkInterface { + return &fakeTrunks{ + gentype.NewFakeClientWithListAndApply[*v1alpha1.Trunk, *v1alpha1.TrunkList, *apiv1alpha1.TrunkApplyConfiguration]( + fake.Fake, + namespace, + v1alpha1.SchemeGroupVersion.WithResource("trunks"), + v1alpha1.SchemeGroupVersion.WithKind("Trunk"), + func() *v1alpha1.Trunk { return &v1alpha1.Trunk{} }, + func() *v1alpha1.TrunkList { return &v1alpha1.TrunkList{} }, + func(dst, src *v1alpha1.TrunkList) { dst.ListMeta = src.ListMeta }, + func(list *v1alpha1.TrunkList) []*v1alpha1.Trunk { return gentype.ToPointerSlice(list.Items) }, + func(list *v1alpha1.TrunkList, items []*v1alpha1.Trunk) { list.Items = gentype.FromPointerSlice(items) }, + ), + fake, + } +} diff --git a/pkg/clients/clientset/clientset/typed/api/v1alpha1/generated_expansion.go b/pkg/clients/clientset/clientset/typed/api/v1alpha1/generated_expansion.go index 5fdc4ca2a..fd2f14737 100644 --- a/pkg/clients/clientset/clientset/typed/api/v1alpha1/generated_expansion.go +++ b/pkg/clients/clientset/clientset/typed/api/v1alpha1/generated_expansion.go @@ -44,6 +44,8 @@ type ServerGroupExpansion interface{} type SubnetExpansion interface{} +type TrunkExpansion interface{} + type VolumeExpansion interface{} type VolumeTypeExpansion interface{} diff --git a/pkg/clients/clientset/clientset/typed/api/v1alpha1/trunk.go b/pkg/clients/clientset/clientset/typed/api/v1alpha1/trunk.go new file mode 100644 index 000000000..48c8406bc --- /dev/null +++ b/pkg/clients/clientset/clientset/typed/api/v1alpha1/trunk.go @@ -0,0 +1,74 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + context "context" + + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + applyconfigurationapiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/applyconfiguration/api/v1alpha1" + scheme "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/clientset/clientset/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + gentype "k8s.io/client-go/gentype" +) + +// TrunksGetter has a method to return a TrunkInterface. +// A group's client should implement this interface. +type TrunksGetter interface { + Trunks(namespace string) TrunkInterface +} + +// TrunkInterface has methods to work with Trunk resources. +type TrunkInterface interface { + Create(ctx context.Context, trunk *apiv1alpha1.Trunk, opts v1.CreateOptions) (*apiv1alpha1.Trunk, error) + Update(ctx context.Context, trunk *apiv1alpha1.Trunk, opts v1.UpdateOptions) (*apiv1alpha1.Trunk, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, trunk *apiv1alpha1.Trunk, opts v1.UpdateOptions) (*apiv1alpha1.Trunk, 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) (*apiv1alpha1.Trunk, error) + List(ctx context.Context, opts v1.ListOptions) (*apiv1alpha1.TrunkList, 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 *apiv1alpha1.Trunk, err error) + Apply(ctx context.Context, trunk *applyconfigurationapiv1alpha1.TrunkApplyConfiguration, opts v1.ApplyOptions) (result *apiv1alpha1.Trunk, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, trunk *applyconfigurationapiv1alpha1.TrunkApplyConfiguration, opts v1.ApplyOptions) (result *apiv1alpha1.Trunk, err error) + TrunkExpansion +} + +// trunks implements TrunkInterface +type trunks struct { + *gentype.ClientWithListAndApply[*apiv1alpha1.Trunk, *apiv1alpha1.TrunkList, *applyconfigurationapiv1alpha1.TrunkApplyConfiguration] +} + +// newTrunks returns a Trunks +func newTrunks(c *OpenstackV1alpha1Client, namespace string) *trunks { + return &trunks{ + gentype.NewClientWithListAndApply[*apiv1alpha1.Trunk, *apiv1alpha1.TrunkList, *applyconfigurationapiv1alpha1.TrunkApplyConfiguration]( + "trunks", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *apiv1alpha1.Trunk { return &apiv1alpha1.Trunk{} }, + func() *apiv1alpha1.TrunkList { return &apiv1alpha1.TrunkList{} }, + ), + } +} diff --git a/pkg/clients/informers/externalversions/api/v1alpha1/interface.go b/pkg/clients/informers/externalversions/api/v1alpha1/interface.go index e8130e3b3..34764cce2 100644 --- a/pkg/clients/informers/externalversions/api/v1alpha1/interface.go +++ b/pkg/clients/informers/externalversions/api/v1alpha1/interface.go @@ -50,6 +50,8 @@ type Interface interface { ServerGroups() ServerGroupInformer // Subnets returns a SubnetInformer. Subnets() SubnetInformer + // Trunks returns a TrunkInformer. + Trunks() TrunkInformer // Volumes returns a VolumeInformer. Volumes() VolumeInformer // VolumeTypes returns a VolumeTypeInformer. @@ -132,6 +134,11 @@ func (v *version) Subnets() SubnetInformer { return &subnetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } +// Trunks returns a TrunkInformer. +func (v *version) Trunks() TrunkInformer { + return &trunkInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + // Volumes returns a VolumeInformer. func (v *version) Volumes() VolumeInformer { return &volumeInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/pkg/clients/informers/externalversions/api/v1alpha1/trunk.go b/pkg/clients/informers/externalversions/api/v1alpha1/trunk.go new file mode 100644 index 000000000..a0c0a293c --- /dev/null +++ b/pkg/clients/informers/externalversions/api/v1alpha1/trunk.go @@ -0,0 +1,102 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + context "context" + time "time" + + v2apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + clientset "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/clientset/clientset" + internalinterfaces "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/informers/externalversions/internalinterfaces" + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/pkg/clients/listers/api/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// TrunkInformer provides access to a shared informer and lister for +// Trunks. +type TrunkInformer interface { + Informer() cache.SharedIndexInformer + Lister() apiv1alpha1.TrunkLister +} + +type trunkInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewTrunkInformer constructs a new informer for Trunk 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 NewTrunkInformer(client clientset.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredTrunkInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredTrunkInformer constructs a new informer for Trunk 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 NewFilteredTrunkInformer(client clientset.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.OpenstackV1alpha1().Trunks(namespace).List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.OpenstackV1alpha1().Trunks(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.OpenstackV1alpha1().Trunks(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.OpenstackV1alpha1().Trunks(namespace).Watch(ctx, options) + }, + }, + &v2apiv1alpha1.Trunk{}, + resyncPeriod, + indexers, + ) +} + +func (f *trunkInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredTrunkInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *trunkInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&v2apiv1alpha1.Trunk{}, f.defaultInformer) +} + +func (f *trunkInformer) Lister() apiv1alpha1.TrunkLister { + return apiv1alpha1.NewTrunkLister(f.Informer().GetIndexer()) +} diff --git a/pkg/clients/informers/externalversions/generic.go b/pkg/clients/informers/externalversions/generic.go index 7636a772f..f0e4379dc 100644 --- a/pkg/clients/informers/externalversions/generic.go +++ b/pkg/clients/informers/externalversions/generic.go @@ -79,6 +79,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Openstack().V1alpha1().ServerGroups().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("subnets"): return &genericInformer{resource: resource.GroupResource(), informer: f.Openstack().V1alpha1().Subnets().Informer()}, nil + case v1alpha1.SchemeGroupVersion.WithResource("trunks"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Openstack().V1alpha1().Trunks().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("volumes"): return &genericInformer{resource: resource.GroupResource(), informer: f.Openstack().V1alpha1().Volumes().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("volumetypes"): diff --git a/pkg/clients/listers/api/v1alpha1/expansion_generated.go b/pkg/clients/listers/api/v1alpha1/expansion_generated.go index fb8033554..05192a80c 100644 --- a/pkg/clients/listers/api/v1alpha1/expansion_generated.go +++ b/pkg/clients/listers/api/v1alpha1/expansion_generated.go @@ -122,6 +122,14 @@ type SubnetListerExpansion interface{} // SubnetNamespaceLister. type SubnetNamespaceListerExpansion interface{} +// TrunkListerExpansion allows custom methods to be added to +// TrunkLister. +type TrunkListerExpansion interface{} + +// TrunkNamespaceListerExpansion allows custom methods to be added to +// TrunkNamespaceLister. +type TrunkNamespaceListerExpansion interface{} + // VolumeListerExpansion allows custom methods to be added to // VolumeLister. type VolumeListerExpansion interface{} diff --git a/pkg/clients/listers/api/v1alpha1/trunk.go b/pkg/clients/listers/api/v1alpha1/trunk.go new file mode 100644 index 000000000..6dd678340 --- /dev/null +++ b/pkg/clients/listers/api/v1alpha1/trunk.go @@ -0,0 +1,70 @@ +/* +Copyright 2025 The ORC Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + apiv1alpha1 "github.com/k-orc/openstack-resource-controller/v2/api/v1alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// TrunkLister helps list Trunks. +// All objects returned here must be treated as read-only. +type TrunkLister interface { + // List lists all Trunks in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*apiv1alpha1.Trunk, err error) + // Trunks returns an object that can list and get Trunks. + Trunks(namespace string) TrunkNamespaceLister + TrunkListerExpansion +} + +// trunkLister implements the TrunkLister interface. +type trunkLister struct { + listers.ResourceIndexer[*apiv1alpha1.Trunk] +} + +// NewTrunkLister returns a new TrunkLister. +func NewTrunkLister(indexer cache.Indexer) TrunkLister { + return &trunkLister{listers.New[*apiv1alpha1.Trunk](indexer, apiv1alpha1.Resource("trunk"))} +} + +// Trunks returns an object that can list and get Trunks. +func (s *trunkLister) Trunks(namespace string) TrunkNamespaceLister { + return trunkNamespaceLister{listers.NewNamespaced[*apiv1alpha1.Trunk](s.ResourceIndexer, namespace)} +} + +// TrunkNamespaceLister helps list and get Trunks. +// All objects returned here must be treated as read-only. +type TrunkNamespaceLister interface { + // List lists all Trunks in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*apiv1alpha1.Trunk, err error) + // Get retrieves the Trunk from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*apiv1alpha1.Trunk, error) + TrunkNamespaceListerExpansion +} + +// trunkNamespaceLister implements the TrunkNamespaceLister +// interface. +type trunkNamespaceLister struct { + listers.ResourceIndexer[*apiv1alpha1.Trunk] +} diff --git a/website/docs/crd-reference.md b/website/docs/crd-reference.md index 13eeca962..319bdb2e7 100644 --- a/website/docs/crd-reference.md +++ b/website/docs/crd-reference.md @@ -23,6 +23,7 @@ Package v1alpha1 contains API Schema definitions for the openstack v1alpha1 API - [Server](#server) - [ServerGroup](#servergroup) - [Subnet](#subnet) +- [Trunk](#trunk) - [Volume](#volume) - [VolumeType](#volumetype) @@ -171,6 +172,7 @@ _Appears in:_ - [ServerGroupSpec](#servergroupspec) - [ServerSpec](#serverspec) - [SubnetSpec](#subnetspec) +- [TrunkSpec](#trunkspec) - [VolumeSpec](#volumespec) - [VolumeTypeSpec](#volumetypespec) @@ -411,6 +413,7 @@ _Appears in:_ - [RouterFilter](#routerfilter) - [SecurityGroupFilter](#securitygroupfilter) - [SubnetFilter](#subnetfilter) +- [TrunkFilter](#trunkfilter) | Field | Description | Default | Validation | | --- | --- | --- | --- | @@ -1354,6 +1357,9 @@ _Appears in:_ - [ServerVolumeSpec](#servervolumespec) - [SubnetFilter](#subnetfilter) - [SubnetResourceSpec](#subnetresourcespec) +- [Subport](#subport) +- [TrunkFilter](#trunkfilter) +- [TrunkResourceSpec](#trunkresourcespec) - [UserDataSpec](#userdataspec) - [VolumeResourceSpec](#volumeresourcespec) @@ -1410,6 +1416,7 @@ _Appears in:_ - [ServerGroupSpec](#servergroupspec) - [ServerSpec](#serverspec) - [SubnetSpec](#subnetspec) +- [TrunkSpec](#trunkspec) - [VolumeSpec](#volumespec) - [VolumeTypeSpec](#volumetypespec) @@ -1440,6 +1447,7 @@ _Appears in:_ - [ServerGroupSpec](#servergroupspec) - [ServerSpec](#serverspec) - [SubnetSpec](#subnetspec) +- [TrunkSpec](#trunkspec) - [VolumeSpec](#volumespec) - [VolumeTypeSpec](#volumetypespec) @@ -1632,6 +1640,8 @@ _Appears in:_ - [SecurityGroupRule](#securitygrouprule) - [SubnetFilter](#subnetfilter) - [SubnetResourceSpec](#subnetresourcespec) +- [TrunkFilter](#trunkfilter) +- [TrunkResourceSpec](#trunkresourcespec) @@ -1649,6 +1659,7 @@ _Appears in:_ - [PortResourceStatus](#portresourcestatus) - [SecurityGroupResourceStatus](#securitygroupresourcestatus) - [SubnetResourceStatus](#subnetresourcestatus) +- [TrunkResourceStatus](#trunkresourcestatus) | Field | Description | Default | Validation | | --- | --- | --- | --- | @@ -1682,6 +1693,8 @@ _Appears in:_ - [SecurityGroupResourceSpec](#securitygroupresourcespec) - [SubnetFilter](#subnetfilter) - [SubnetResourceSpec](#subnetresourcespec) +- [TrunkFilter](#trunkfilter) +- [TrunkResourceSpec](#trunkresourcespec) @@ -1735,6 +1748,8 @@ _Appears in:_ - [ServerResourceSpec](#serverresourcespec) - [SubnetFilter](#subnetfilter) - [SubnetResourceSpec](#subnetresourcespec) +- [TrunkFilter](#trunkfilter) +- [TrunkResourceSpec](#trunkresourcespec) - [VolumeFilter](#volumefilter) - [VolumeResourceSpec](#volumeresourcespec) - [VolumeTypeFilter](#volumetypefilter) @@ -3222,6 +3237,192 @@ _Appears in:_ | `resource` _[SubnetResourceStatus](#subnetresourcestatus)_ | resource contains the observed state of the OpenStack resource. | | | +#### Subport + + + +Subport represents a subport that will be attached to a trunk. + + + +_Appears in:_ +- [TrunkResourceSpec](#trunkresourcespec) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `portRef` _[KubernetesNameRef](#kubernetesnameref)_ | portRef is a reference to the ORC Port which will be used as a subport. | | MaxLength: 253
MinLength: 1
| +| `segmentationType` _string_ | segmentationType is the type of segmentation to use (e.g., "vlan"). | | MaxLength: 64
| +| `segmentationID` _integer_ | segmentationID is the segmentation identifier (e.g., VLAN ID). | | | + + +#### SubportStatus + + + +SubportStatus represents the observed state of a subport. + + + +_Appears in:_ +- [TrunkResourceStatus](#trunkresourcestatus) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `portID` _string_ | portID is the ID of the port used as a subport. | | MaxLength: 1024
| +| `segmentationType` _string_ | segmentationType is the type of segmentation used. | | MaxLength: 1024
| +| `segmentationID` _integer_ | segmentationID is the segmentation identifier. | | | + + +#### Trunk + + + +Trunk is the Schema for an ORC resource. + + + + + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `apiVersion` _string_ | `openstack.k-orc.cloud/v1alpha1` | | | +| `kind` _string_ | `Trunk` | | | +| `metadata` _[ObjectMeta](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.29/#objectmeta-v1-meta)_ | Refer to Kubernetes API documentation for fields of `metadata`. | | | +| `spec` _[TrunkSpec](#trunkspec)_ | spec specifies the desired state of the resource. | | | +| `status` _[TrunkStatus](#trunkstatus)_ | status defines the observed state of the resource. | | | + + +#### TrunkFilter + + + +TrunkFilter specifies a filter to select a trunk. At least one parameter must be specified. + +_Validation:_ +- MinProperties: 1 + +_Appears in:_ +- [TrunkImport](#trunkimport) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `name` _[OpenStackName](#openstackname)_ | name of the existing resource | | MaxLength: 255
MinLength: 1
Pattern: `^[^,]+$`
| +| `description` _[NeutronDescription](#neutrondescription)_ | description of the existing resource | | MaxLength: 255
MinLength: 1
| +| `portRef` _[KubernetesNameRef](#kubernetesnameref)_ | portRef is a reference to the ORC Port which this trunk is associated with. | | MaxLength: 253
MinLength: 1
| +| `projectRef` _[KubernetesNameRef](#kubernetesnameref)_ | projectRef is a reference to the ORC Project this resource is associated with.
Typically, only used by admin. | | MaxLength: 253
MinLength: 1
| +| `tags` _[NeutronTag](#neutrontag) array_ | tags is a list of tags to filter by. If specified, the resource must
have all of the tags specified to be included in the result. | | MaxItems: 64
MaxLength: 255
MinLength: 1
| +| `tagsAny` _[NeutronTag](#neutrontag) array_ | tagsAny is a list of tags to filter by. If specified, the resource
must have at least one of the tags specified to be included in the
result. | | MaxItems: 64
MaxLength: 255
MinLength: 1
| +| `notTags` _[NeutronTag](#neutrontag) array_ | notTags is a list of tags to filter by. If specified, resources which
contain all of the given tags will be excluded from the result. | | MaxItems: 64
MaxLength: 255
MinLength: 1
| +| `notTagsAny` _[NeutronTag](#neutrontag) array_ | notTagsAny is a list of tags to filter by. If specified, resources
which contain any of the given tags will be excluded from the result. | | MaxItems: 64
MaxLength: 255
MinLength: 1
| + + +#### TrunkImport + + + +TrunkImport specifies an existing resource which will be imported instead of +creating a new one + +_Validation:_ +- MaxProperties: 1 +- MinProperties: 1 + +_Appears in:_ +- [TrunkSpec](#trunkspec) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `id` _string_ | id contains the unique identifier of an existing OpenStack resource. Note
that when specifying an import by ID, the resource MUST already exist.
The ORC object will enter an error state if the resource does not exist. | | Format: uuid
| +| `filter` _[TrunkFilter](#trunkfilter)_ | filter contains a resource query which is expected to return a single
result. The controller will continue to retry if filter returns no
results. If filter returns multiple results the controller will set an
error state and will not continue to retry. | | MinProperties: 1
| + + +#### TrunkResourceSpec + + + + + + + +_Appears in:_ +- [TrunkSpec](#trunkspec) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `name` _[OpenStackName](#openstackname)_ | name is a human-readable name of the trunk. If not set, the object's name will be used. | | MaxLength: 255
MinLength: 1
Pattern: `^[^,]+$`
| +| `description` _[NeutronDescription](#neutrondescription)_ | description is a human-readable description for the resource. | | MaxLength: 255
MinLength: 1
| +| `portRef` _[KubernetesNameRef](#kubernetesnameref)_ | portRef is a reference to the ORC Port which will be used as the parent port for this trunk. | | MaxLength: 253
MinLength: 1
| +| `tags` _[NeutronTag](#neutrontag) array_ | tags is a list of tags which will be applied to the trunk. | | MaxItems: 64
MaxLength: 255
MinLength: 1
| +| `adminStateUp` _boolean_ | adminStateUp is the administrative state of the trunk, which is up (true) or down (false). | | | +| `subports` _[Subport](#subport) array_ | subports are the subports that will be attached to this trunk. | | MaxItems: 128
| +| `projectRef` _[KubernetesNameRef](#kubernetesnameref)_ | projectRef is a reference to the ORC Project this resource is associated with.
Typically, only used by admin. | | MaxLength: 253
MinLength: 1
| + + +#### TrunkResourceStatus + + + + + + + +_Appears in:_ +- [TrunkStatus](#trunkstatus) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `name` _string_ | name is the human-readable name of the resource. Might not be unique. | | MaxLength: 1024
| +| `description` _string_ | description is a human-readable description for the resource. | | MaxLength: 1024
| +| `portID` _string_ | portID is the ID of the parent port. | | MaxLength: 1024
| +| `projectID` _string_ | projectID is the project owner of the resource. | | MaxLength: 1024
| +| `status` _string_ | status indicates the current status of the resource. | | MaxLength: 1024
| +| `tags` _string array_ | tags is the list of tags on the resource. | | MaxItems: 64
items:MaxLength: 1024
| +| `adminStateUp` _boolean_ | adminStateUp is the administrative state of the trunk,
which is up (true) or down (false). | | | +| `subports` _[SubportStatus](#subportstatus) array_ | subports is a list of subports attached to this trunk. | | MaxItems: 128
| +| `createdAt` _[Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.29/#time-v1-meta)_ | createdAt shows the date and time when the resource was created. The date and time stamp format is ISO 8601 | | | +| `updatedAt` _[Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.29/#time-v1-meta)_ | updatedAt shows the date and time when the resource was updated. The date and time stamp format is ISO 8601 | | | +| `revisionNumber` _integer_ | revisionNumber optionally set via extensions/standard-attr-revisions | | | + + +#### TrunkSpec + + + +TrunkSpec defines the desired state of an ORC object. + + + +_Appears in:_ +- [Trunk](#trunk) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `import` _[TrunkImport]provider.go +(#trunkimport)_ | import refers to an existing OpenStack resource which will be imported instead of
creating a new one. | | MaxProperties: 1
MinProperties: 1
| +| `resource` _[TrunkResourceSpec](#trunkresourcespec)_ | resource specifies the desired state of the resource.
resource may not be specified if the management policy is `unmanaged`.
resource must be specified if the management policy is `managed`. | | | +| `managementPolicy` _[ManagementPolicy](#managementpolicy)_ | managementPolicy defines how ORC will treat the object. Valid values are
`managed`: ORC will create, update, and delete the resource; `unmanaged`:
ORC will import an existing resource, and will not apply updates to it or
delete it. | managed | Enum: [managed unmanaged]
| +| `managedOptions` _[ManagedOptions](#managedoptions)_ | managedOptions specifies options which may be applied to managed objects. | | | +| `cloudCredentialsRef` _[CloudCredentialsReference](#cloudcredentialsreference)_ | cloudCredentialsRef points to a secret containing OpenStack credentials | | | + + +#### TrunkStatus + + + +TrunkStatus defines the observed state of an ORC resource. + + + +_Appears in:_ +- [Trunk](#trunk) + +| Field | Description | Default | Validation | +| --- | --- | --- | --- | +| `conditions` _[Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.29/#condition-v1-meta) array_ | conditions represents the observed status of the object.
Known .status.conditions.type are: "Available", "Progressing"
Available represents the availability of the OpenStack resource. If it is
true then the resource is ready for use.
Progressing indicates whether the controller is still attempting to
reconcile the current state of the OpenStack resource to the desired
state. Progressing will be False either because the desired state has
been achieved, or because some terminal error prevents it from ever being
achieved and the controller is no longer attempting to reconcile. If
Progressing is True, an observer waiting on the resource should continue
to wait. | | MaxItems: 32
| +| `id` _string_ | id is the unique identifier of the OpenStack resource. | | | +| `resource` _[TrunkResourceStatus](#trunkresourcestatus)_ | resource contains the observed state of the OpenStack resource. | | | + + #### UserDataSpec