Skip to content

Commit

Permalink
Merge branch 'master' into configToBeta
Browse files Browse the repository at this point in the history
  • Loading branch information
nb-goog authored Nov 2, 2024
2 parents c15db8f + 1e723b5 commit 8276a97
Show file tree
Hide file tree
Showing 38 changed files with 1,566 additions and 1,389 deletions.
16 changes: 16 additions & 0 deletions apis/spanner/v1beta1/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// 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.

// +kcc:proto=google.spanner.admin.instance.v1
package v1beta1
33 changes: 33 additions & 0 deletions apis/spanner/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=spanner.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: "spanner.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
)
177 changes: 177 additions & 0 deletions apis/spanner/v1beta1/instance_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// 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 = &SpannerInstanceRef{}

// SpannerInstanceRef defines the resource reference to SpannerInstance, which "External" field
// holds the GCP identifier for the KRM object.
type SpannerInstanceRef struct {
// A reference to an externally managed SpannerInstance resource.
// Should be in the format "projects/<projectID>/instances/<instanceID>".
External string `json:"external,omitempty"`

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

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

parent *SpannerInstanceParent
}

// NormalizedExternal provision the "External" value for other resource that depends on SpannerInstance.
// If the "External" is given in the other resource's spec.SpannerInstanceRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual SpannerInstance object from the cluster.
func (r *SpannerInstanceRef) 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", SpannerInstanceGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := parseSpannerInstanceExternal(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(SpannerInstanceGVK)
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", SpannerInstanceGVK, 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 SpannerInstanceRef from the Config Connector SpannerInstance object.
func NewSpannerInstanceRef(ctx context.Context, reader client.Reader, obj *SpannerInstance, u *unstructured.Unstructured) (*SpannerInstanceRef, error) {
id := &SpannerInstanceRef{}

projectID, err := refsv1beta1.ResolveProjectID(ctx, reader, u)
if err != nil {
return nil, err
}

id.parent = &SpannerInstanceParent{ProjectID: projectID}

// 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 = asSpannerInstanceExternal(id.parent, resourceID)
return id, nil
}

// Validate desired with actual
actualParent, actualResourceID, err := parseSpannerInstanceExternal(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 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 = &SpannerInstanceParent{ProjectID: projectID}
return id, nil
}

func (r *SpannerInstanceRef) Parent() (*SpannerInstanceParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, _, err := parseSpannerInstanceExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("SpannerInstanceRef not initialized from `NewSpannerInstanceRef` or `NormalizedExternal`")
}

type SpannerInstanceParent struct {
ProjectID string
}

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

func asSpannerInstanceExternal(parent *SpannerInstanceParent, resourceID string) (external string) {
return parent.String() + "/instances/" + resourceID
}

func parseSpannerInstanceExternal(external string) (parent *SpannerInstanceParent, resourceID string, err error) {
external = strings.TrimPrefix(external, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 4 || tokens[0] != "projects" || tokens[2] != "instances" {
return nil, "", fmt.Errorf("format of SpannerInstance external=%q was not known (use projects/<projectId>/instances/<instanceID>)", external)
}
parent = &SpannerInstanceParent{
ProjectID: tokens[1],
}
resourceID = tokens[3]
return parent, resourceID, nil
}

func valueOf[T any](t *T) T {
var zeroVal T
if t == nil {
return zeroVal
}
return *t
}
107 changes: 107 additions & 0 deletions apis/spanner/v1beta1/instance_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// 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 (
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var SpannerInstanceGVK = GroupVersion.WithKind("SpannerInstance")

// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.

// SpannerInstanceSpec defines the desired state of SpannerInstance
// +kcc:proto=google.spanner.admin.instance.v1.Instance
type SpannerInstanceSpec struct {
// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="Config field is immutable"
/* Immutable. The name of the instance's configuration (similar but not
quite the same as a region) which defines the geographic placement and
replication of your databases in this instance. It determines where your data
is stored. Values are typically of the form 'regional-europe-west1' , 'us-central' etc.
In order to obtain a valid list please consult the
[Configuration section of the docs](https://cloud.google.com/spanner/docs/instances). */
Config string `json:"config"`

/* The descriptive name for this instance as it appears in UIs. Must be
unique per project and between 4 and 30 characters in length. */
DisplayName string `json:"displayName"`

// +optional
NumNodes *int64 `json:"numNodes,omitempty"`

// +optional
ProcessingUnits *int64 `json:"processingUnits,omitempty"`

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

// SpannerInstanceStatus defines the config connector machine state of SpannerInstance
type SpannerInstanceStatus struct {
/* Conditions represent the latest available observations of the
SpannerInstance'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. */
// +optional
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`

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

/* Instance status: 'CREATING' or 'READY'. */
// +optional
State *string `json:"state,omitempty"`
}

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

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// TODO(user): make sure the pluralizaiton below is correct
// +kubebuilder:resource:categories=gcp,shortName=gcpspannerinstance;gcpspannerinstances
// +kubebuilder:subresource:status
// +kubebuilder:metadata:labels="cnrm.cloud.google.com/tf2crd=true";"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'"

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

// +required
Spec SpannerInstanceSpec `json:"spec,omitempty"`
Status SpannerInstanceStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&SpannerInstance{}, &SpannerInstanceList{})
}
Loading

0 comments on commit 8276a97

Please sign in to comment.