Skip to content

Commit

Permalink
Merge branch 'GoogleCloudPlatform:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
nb-goog authored Nov 1, 2024
2 parents 2aa66a3 + aa336a6 commit bdb8597
Show file tree
Hide file tree
Showing 148 changed files with 14,042 additions and 6,018 deletions.
118 changes: 118 additions & 0 deletions apis/compute/v1beta1/computetargettcpproxy_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1beta1

import (
refs "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)

var (
ComputeTargetTCPProxyGVK = schema.GroupVersionKind{
Group: GroupVersion.Group,
Version: GroupVersion.Version,
Kind: "ComputeTargetTCPProxy",
}
)

// ComputeTargetTCPProxySpec defines the desired state of ComputeTargetTCPProxy
// +kcc:proto=google.cloud.compute.v1.TargetTcpProxy
type ComputeTargetTCPProxySpec struct {
// A reference to the ComputeBackendService resource.
// +required
BackendServiceRef *refs.ComputeBackendServiceRef `json:"backendServiceRef"`

// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="Description is immutable"
// Immutable. An optional description of this resource.
Description *string `json:"description,omitempty"`

// The geographical location of the ComputeTargetTCPProxy.
// Reference: GCP definition of regions/zones (https://cloud.google.com/compute/docs/regions-zones/)
// +optional
Location *string `json:"location"`

// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="ProxyBind is immutable"
// Immutable. This field only applies when the forwarding rule that references
// this target proxy has a loadBalancingScheme set to INTERNAL_SELF_MANAGED.
ProxyBind *bool `json:"proxyBind,omitempty"`

// Specifies the type of proxy header to append before sending data to
// the backend. Default value: "NONE" Possible values: ["NONE", "PROXY_V1"].
ProxyHeader *string `json:"proxyHeader,omitempty"`

// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="ResourceID is immutable"
// Immutable. The ComputeTargetTCPProxy name. If not given, the metadata.name will be used.
ResourceID *string `json:"resourceID,omitempty"`
}

// ComputeTargetTCPProxyStatus defines the config connector machine state of ComputeTargetTCPProxy
type ComputeTargetTCPProxyStatus struct {
// Conditions represent the latest available observations of the object's current state.
Conditions []v1alpha1.Condition `json:"conditions,omitempty"`

// ObservedGeneration is the generation of the resource that was most recently observed by the Config Connector controller. If this is equal to metadata.generation, then that means that the current reported status reflects the most recent desired state of the resource.
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`

// A unique specifier for the ComputeTargetTCPProxy resource in GCP.
ExternalRef *string `json:"externalRef,omitempty"`

// Creation timestamp in RFC3339 text format.
CreationTimestamp *string `json:"creationTimestamp,omitempty"`

// The unique identifier for the resource.
ProxyId *int64 `json:"proxyId,omitempty"`

// The SelfLink for the resource.
SelfLink *string `json:"selfLink,omitempty"`
}

// ComputeTargetTCPProxyObservedState is the state of the ComputeTargetTCPProxy resource as most recently observed in GCP.
type ComputeTargetTCPProxyObservedState struct {
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:resource:categories=gcp,shortName=gcpcomputetargettcpproxy;gcpcomputetargettcpproxies
// +kubebuilder:subresource:status
// +kubebuilder:metadata:labels="cnrm.cloud.google.com/tf2crd=true";"cnrm.cloud.google.com/stability-level=stable";"cnrm.cloud.google.com/managed-by-kcc=true";"cnrm.cloud.google.com/system=true"
// +kubebuilder:printcolumn:name="Age",JSONPath=".metadata.creationTimestamp",type="date"
// +kubebuilder:printcolumn:name="Ready",JSONPath=".status.conditions[?(@.type=='Ready')].status",type="string",description="When 'True', the most recent reconcile of the resource succeeded"
// +kubebuilder:printcolumn:name="Status",JSONPath=".status.conditions[?(@.type=='Ready')].reason",type="string",description="The reason for the value in 'Ready'"
// +kubebuilder:printcolumn:name="Status Age",JSONPath=".status.conditions[?(@.type=='Ready')].lastTransitionTime",type="date",description="The last transition time for the value in 'Status'"

// ComputeTargetTCPProxy is the Schema for the ComputeTargetTCPProxy API
// +k8s:openapi-gen=true
type ComputeTargetTCPProxy struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

// +required
Spec ComputeTargetTCPProxySpec `json:"spec,omitempty"`
Status ComputeTargetTCPProxyStatus `json:"status,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// ComputeTargetTCPProxyList contains a list of ComputeTargetTCPProxy
type ComputeTargetTCPProxyList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []ComputeTargetTCPProxy `json:"items"`
}

func init() {
SchemeBuilder.Register(&ComputeTargetTCPProxy{}, &ComputeTargetTCPProxyList{})
}
11 changes: 2 additions & 9 deletions apis/compute/v1beta1/forwardingrule_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,12 @@ import (
commonv1alpha1 "github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/common/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)

var (
// SchemeBuilder is used to add go types to the GroupVersionKind scheme.
SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion}

// AddToScheme is a global function that registers this API group & version to a scheme
AddToScheme = SchemeBuilder.AddToScheme

ComputeForwardingRuleGVK = schema.GroupVersionKind{
Group: SchemeGroupVersion.Group,
Version: SchemeGroupVersion.Version,
Group: GroupVersion.Group,
Version: GroupVersion.Version,
Kind: "ComputeForwardingRule",
}
)
Expand Down
33 changes: 33 additions & 0 deletions apis/compute/v1beta1/groupversion_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2024 Google LLC
//
// 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.

// +kubebuilder:object:generate=true
// +groupName=compute.cnrm.cloud.google.com
package v1beta1

import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)

var (
// GroupVersion is group version used to register these objects
GroupVersion = schema.GroupVersion{Group: "compute.cnrm.cloud.google.com", Version: "v1beta1"}

// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}

// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
)
183 changes: 183 additions & 0 deletions apis/compute/v1beta1/targettcpproxy_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1beta1

import (
"context"
"fmt"
"strings"

refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)

var _ refsv1beta1.ExternalNormalizer = &ComputeTargetTCPProxyRef{}

// ComputeTargetTCPProxyRef defines the resource reference to ComputeTargetTCPProxy, which "External" field
// holds the GCP identifier for the KRM object.
type ComputeTargetTCPProxyRef struct {
// A reference to an externally managed ComputeTargetTCPProxy resource.
// Should be in the format "projects/<projectID>/regions/<region>/targetTcpProxies/<targettcpproxyID>".
External string `json:"external,omitempty"`

// The name of a ComputeTargetTCPProxy resource.
Name string `json:"name,omitempty"`

// The namespace of a ComputeTargetTCPProxy resource.
Namespace string `json:"namespace,omitempty"`

parent *ComputeTargetTCPProxyParent
}

// NormalizedExternal provision the "External" value for other resource that depends on ComputeTargetTCPProxy.
// If the "External" is given in the other resource's spec.ComputeTargetTCPProxyRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual ComputeTargetTCPProxy object from the cluster.
func (r *ComputeTargetTCPProxyRef) NormalizedExternal(ctx context.Context, reader client.Reader, otherNamespace string) (string, error) {
if r.External != "" && r.Name != "" {
return "", fmt.Errorf("cannot specify both name and external on %s reference", ComputeTargetTCPProxyGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := parseComputeTargetTCPProxyExternal(r.External); err != nil {
return "", err
}
return r.External, nil
}

// From the Config Connector object
if r.Namespace == "" {
r.Namespace = otherNamespace
}
key := types.NamespacedName{Name: r.Name, Namespace: r.Namespace}
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(ComputeTargetTCPProxyGVK)
if err := reader.Get(ctx, key, u); err != nil {
if apierrors.IsNotFound(err) {
return "", k8s.NewReferenceNotFoundError(u.GroupVersionKind(), key)
}
return "", fmt.Errorf("reading referenced %s %s: %w", ComputeTargetTCPProxyGVK, key, err)
}
// Get external from status.externalRef. This is the most trustworthy place.
actualExternalRef, _, err := unstructured.NestedString(u.Object, "status", "externalRef")
if err != nil {
return "", fmt.Errorf("reading status.externalRef: %w", err)
}
if actualExternalRef == "" {
return "", k8s.NewReferenceNotReadyError(u.GroupVersionKind(), key)
}
r.External = actualExternalRef
return r.External, nil
}

// New builds a ComputeTargetTCPProxyRef from the Config Connector ComputeTargetTCPProxy object.
func NewComputeTargetTCPProxyRef(ctx context.Context, reader client.Reader, obj *ComputeTargetTCPProxy, u *unstructured.Unstructured) (*ComputeTargetTCPProxyRef, error) {
id := &ComputeTargetTCPProxyRef{}

// Get Parent
projectID, err := refsv1beta1.ResolveProjectID(ctx, reader, u)
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
region := valueOf(obj.Spec.Location)
id.parent = &ComputeTargetTCPProxyParent{ProjectID: projectID, Region: region}

// Get desired ID
resourceID := valueOf(obj.Spec.ResourceID)
if resourceID == "" {
resourceID = obj.GetName()
}
if resourceID == "" {
return nil, fmt.Errorf("cannot resolve resource ID")
}

// Use approved External
externalRef := valueOf(obj.Status.ExternalRef)
if externalRef == "" {
id.External = asComputeTargetTCPProxyExternal(id.parent, resourceID)
return id, nil
}

// Validate desired with actual
actualParent, actualResourceID, err := parseComputeTargetTCPProxyExternal(externalRef)
if err != nil {
return nil, err
}
if actualParent.ProjectID != projectID {
return nil, fmt.Errorf("spec.projectRef changed, expect %s, got %s", actualParent.ProjectID, projectID)
}
if actualParent.Region != region {
return nil, fmt.Errorf("spec.location changed, expect %s, got %s", actualParent.Region, region)
}
if actualResourceID != resourceID {
return nil, fmt.Errorf("cannot reset `metadata.name` or `spec.resourceID` to %s, since it has already assigned to %s",
resourceID, actualResourceID)
}
id.External = externalRef
id.parent = &ComputeTargetTCPProxyParent{ProjectID: projectID, Region: region}
return id, nil
}

func (r *ComputeTargetTCPProxyRef) Parent() (*ComputeTargetTCPProxyParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, _, err := parseComputeTargetTCPProxyExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("ComputeTargetTCPProxyRef not initialized from `NewComputeTargetTCPProxyRef` or `NormalizedExternal`")
}

type ComputeTargetTCPProxyParent struct {
ProjectID string
Region string
}

func (p *ComputeTargetTCPProxyParent) String() string {
return "projects/" + p.ProjectID + "/regions/" + p.Region
}

func asComputeTargetTCPProxyExternal(parent *ComputeTargetTCPProxyParent, resourceID string) (external string) {
return parent.String() + "/targetTcpProxies/" + resourceID
}

func parseComputeTargetTCPProxyExternal(external string) (parent *ComputeTargetTCPProxyParent, resourceID string, err error) {
external = strings.TrimPrefix(external, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "regions" || tokens[4] != "targetTcpProxies" {
return nil, "", fmt.Errorf("format of ComputeTargetTCPProxy external=%q was not known (use projects/<projectId>/regions/<region>/targetTcpProxies/<targettcpproxyID>)", external)
}
parent = &ComputeTargetTCPProxyParent{
ProjectID: tokens[1],
Region: tokens[3],
}
resourceID = tokens[5]
return parent, resourceID, nil
}

func valueOf[T any](t *T) T {
var zeroVal T
if t == nil {
return zeroVal
}
return *t
}
Loading

0 comments on commit bdb8597

Please sign in to comment.