Skip to content

Commit

Permalink
Merge pull request GoogleCloudPlatform#3027 from ericpang777/ssm12
Browse files Browse the repository at this point in the history
Define SecureSourceManagerRepository API
  • Loading branch information
google-oss-prow[bot] authored Nov 11, 2024
2 parents b39c172 + ab2a211 commit f6633b1
Show file tree
Hide file tree
Showing 15 changed files with 1,881 additions and 0 deletions.
1 change: 1 addition & 0 deletions apis/securesourcemanager/v1alpha1/instance_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type SecureSourceManagerInstanceSpec struct {
ProjectRef *refs.ProjectRef `json:"projectRef"`

/* Immutable. Location of the instance. */
// +required
Location string `json:"location"`

/* Immutable. Optional. The name of the resource. Used for creation and acquisition. When unset, the value of `metadata.name` is used as the default. */
Expand Down
191 changes: 191 additions & 0 deletions apis/securesourcemanager/v1alpha1/repository_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// 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 v1alpha1

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 = &SecureSourceManagerRepositoryRef{}

// SecureSourceManagerRepositoryRef defines the resource reference to SecureSourceManagerRepository, which "External" field
// holds the GCP identifier for the KRM object.
type SecureSourceManagerRepositoryRef struct {
// A reference to an externally managed SecureSourceManagerRepository resource.
// Should be in the format "projects/<projectID>/locations/<location>/repositories/<repositoryID>".
External string `json:"external,omitempty"`

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

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

parent *SecureSourceManagerRepositoryParent
}

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

// Get Parent
projectRef, err := refsv1beta1.ResolveProject(ctx, reader, obj, obj.Spec.ProjectRef)
if err != nil {
return nil, err
}
projectID := projectRef.ProjectID
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
location := obj.Spec.Location
id.parent = &SecureSourceManagerRepositoryParent{ProjectID: projectID, Location: location}

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

// Validate desired with actual
actualParent, actualResourceID, err := parseSecureSourceManagerRepositoryExternal(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.Location != location {
return nil, fmt.Errorf("spec.location changed, expect %s, got %s", actualParent.Location, location)
}
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 = &SecureSourceManagerRepositoryParent{ProjectID: projectID, Location: location}
return id, nil
}

func (r *SecureSourceManagerRepositoryRef) Parent() (*SecureSourceManagerRepositoryParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, _, err := parseSecureSourceManagerRepositoryExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("SecureSourceManagerRepositoryRef not initialized from `NewSecureSourceManagerRepositoryRef` or `NormalizedExternal`")
}

func (r *SecureSourceManagerRepositoryRef) ResourceID() (string, error) {
if r.External == "" {
return "", fmt.Errorf("reference has not been normalized (external is empty)")
}

_, resourceID, err := parseSecureSourceManagerRepositoryExternal(r.External)
if err != nil {
return "", err
}
return resourceID, nil
}

type SecureSourceManagerRepositoryParent struct {
ProjectID string
Location string
}

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

func asSecureSourceManagerRepositoryExternal(parent *SecureSourceManagerRepositoryParent, resourceID string) (external string) {
return parent.String() + "/repositories/" + resourceID
}

func parseSecureSourceManagerRepositoryExternal(external string) (parent *SecureSourceManagerRepositoryParent, resourceID string, err error) {
external = strings.TrimPrefix(external, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "repositories" {
return nil, "", fmt.Errorf("format of SecureSourceManagerRepository external=%q was not known (use projects/<projectId>/locations/<location>/repositories/<repositoryID>)", external)
}
parent = &SecureSourceManagerRepositoryParent{
ProjectID: tokens[1],
Location: tokens[3],
}
resourceID = tokens[5]
return parent, resourceID, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// 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 v1alpha1

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"
)

var SecureSourceManagerRepositoryGVK = GroupVersion.WithKind("SecureSourceManagerRepository")

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

// SecureSourceManagerRepositorySpec defines the desired state of SecureSourceManagerRepository
// +kcc:proto=google.cloud.securesourcemanager.v1.Repository
type SecureSourceManagerRepositorySpec struct {
/* Immutable. The Project that this resource belongs to. */
// +required
ProjectRef *refs.ProjectRef `json:"projectRef"`

/* Immutable. Location of the instance. */
// +required
Location string `json:"location"`

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

// The name of the instance in which the repository is hosted, formatted as
// `projects/{project_number}/locations/{location_id}/instances/{instance_id}`
// +required
InstanceRef *SecureSourceManagerInstanceRef `json:"instanceRef,omitempty"`

// Input only. Initial configurations for the repository.
InitialConfig *Repository_InitialConfig `json:"initialConfig,omitempty"`
}

// SecureSourceManagerRepositoryStatus defines the config connector machine state of SecureSourceManagerRepository
type SecureSourceManagerRepositoryStatus 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 SecureSourceManagerRepository resource in GCP.
ExternalRef *string `json:"externalRef,omitempty"`

// ObservedState is the state of the resource as most recently observed in GCP.
ObservedState *SecureSourceManagerRepositoryObservedState `json:"observedState,omitempty"`
}

// SecureSourceManagerRepositoryObservedState is the state of the SecureSourceManagerRepository resource as most recently observed in GCP.
type SecureSourceManagerRepositoryObservedState struct {
// // Output only. Create timestamp.
// CreateTime *string `json:"createTime,omitempty"`

// // Output only. Update timestamp.
// UpdateTime *string `json:"updateTime,omitempty"`

// Output only. URIs for the repository.
URIs *Repository_URIs `json:"uris,omitempty"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:resource:categories=gcp,shortName=gcpsecuresourcemanagerrepository;gcpsecuresourcemanagerrepositories
// +kubebuilder:subresource:status
// +kubebuilder:metadata:labels="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'"

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

// +required
Spec SecureSourceManagerRepositorySpec `json:"spec,omitempty"`
Status SecureSourceManagerRepositoryStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&SecureSourceManagerRepository{}, &SecureSourceManagerRepositoryList{})
}
Loading

0 comments on commit f6633b1

Please sign in to comment.