Skip to content

Commit

Permalink
feat: Promote Workstation to v1beta1
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonvigil committed Dec 13, 2024
1 parent c48449f commit acd40d5
Show file tree
Hide file tree
Showing 26 changed files with 1,464 additions and 91 deletions.
141 changes: 141 additions & 0 deletions apis/workstations/v1beta1/workstation_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// 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"

"github.com/GoogleCloudPlatform/k8s-config-connector/apis/common"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// WorkstationIdentity defines the resource reference to Workstation.
type WorkstationIdentity struct {
parent *WorkstationParent
id string
}

func (i *WorkstationIdentity) String() string {
return i.parent.String() + "/workstations/" + i.id
}

func (i *WorkstationIdentity) ID() string {
return i.id
}

func (i *WorkstationIdentity) Parent() *WorkstationParent {
return i.parent
}

type WorkstationParent struct {
ProjectID string
Location string
Cluster string
Config string
}

func (p *WorkstationParent) String() string {
return "projects/" + p.ProjectID + "/locations/" + p.Location + "/workstationClusters/" + p.Cluster + "/workstationConfigs/" + p.Config
}

// New builds a WorkstationIdentity from the Config Connector Workstation object.
func NewWorkstationIdentity(ctx context.Context, reader client.Reader, obj *Workstation) (*WorkstationIdentity, error) {
// Get Parent
configRef := obj.Spec.Parent
if configRef == nil {
return nil, fmt.Errorf("no parent config")
}
configExternal, err := configRef.NormalizedExternal(ctx, reader, obj.Namespace)
if err != nil {
return nil, fmt.Errorf("cannot resolve config: %w", err)
}
configParent, config, err := ParseWorkstationConfigExternal(configExternal)
if err != nil {
return nil, fmt.Errorf("cannot parse external config: %w", err)
}
projectID := configParent.ProjectID
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
location := configParent.Location
if location == "" {
return nil, fmt.Errorf("cannot resolve location")
}
cluster := configParent.Cluster
if cluster == "" {
return nil, fmt.Errorf("cannot resolve cluster")
}

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

// Use approved External
externalRef := common.ValueOf(obj.Status.ExternalRef)
if externalRef != "" {
// Validate desired with actual
actualParent, actualResourceID, err := ParseWorkstationExternal(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 actualParent.Cluster != cluster {
return nil, fmt.Errorf("spec.cluster changed, expect %s, got %s", actualParent.Cluster, cluster)
}
if actualParent.Config != config {
return nil, fmt.Errorf("spec.config changed, expect %s, got %s", actualParent.Config, config)
}
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)
}
}
return &WorkstationIdentity{
parent: &WorkstationParent{
ProjectID: projectID,
Location: location,
Cluster: cluster,
Config: config,
},
id: resourceID,
}, nil
}

func ParseWorkstationExternal(external string) (parent *WorkstationParent, resourceID string, err error) {
tokens := strings.Split(external, "/")
if len(tokens) != 10 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "workstationClusters" || tokens[6] != "workstationConfigs" || tokens[8] != "workstations" {
return nil, "", fmt.Errorf("format of Workstation external=%q was not known (use projects/<projectID>/locations/<location>/workstationClusters/<workstationclusterID>/workstationConfigs/<workstationconfigID>/workstations/<workstationID>)", external)
}
parent = &WorkstationParent{
ProjectID: tokens[1],
Location: tokens[3],
Cluster: tokens[5],
Config: tokens[7],
}
resourceID = tokens[9]
return parent, resourceID, nil
}
83 changes: 83 additions & 0 deletions apis/workstations/v1beta1/workstation_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// 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"

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

// WorkstationRef defines the resource reference to Workstation, which "External" field
// holds the GCP identifier for the KRM object.
type WorkstationRef struct {
// A reference to an externally managed Workstation resource.
// Should be in the format "projects/<projectID>/locations/<location>/workstationClusters/<workstationclusterID>/workstationConfigs/<workstationconfigID>/workstations/<workstationID>".
External string `json:"external,omitempty"`

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

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

// NormalizedExternal provision the "External" value for other resource that depends on Workstation.
// If the "External" is given in the other resource's spec.WorkstationRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual Workstation object from the cluster.
func (r *WorkstationRef) 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", WorkstationGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := ParseWorkstationExternal(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(WorkstationGVK)
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", WorkstationGVK, 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
}
132 changes: 132 additions & 0 deletions apis/workstations/v1beta1/workstation_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// 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 WorkstationGVK = GroupVersion.WithKind("Workstation")

// WorkstationSpec defines the desired state of Workstation
// +kcc:proto=google.cloud.workstations.v1.Workstation
type WorkstationSpec struct {
// Parent is a reference to the parent WorkstationConfig for this Workstation.
Parent *WorkstationConfigRef `json:"parentRef"`

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

// Optional. Human-readable name for this workstation.
DisplayName *string `json:"displayName,omitempty"`

// Optional. Client-specified annotations.
Annotations []WorkstationAnnotation `json:"annotations,omitempty"`

// Optional.
// [Labels](https://cloud.google.com/workstations/docs/label-resources) that
// are applied to the workstation and that are also propagated to the
// underlying Compute Engine resources.
Labels []WorkstationLabel `json:"labels,omitempty"`
}

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

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

// WorkstationSpec defines the desired state of Workstation
// +kcc:proto=google.cloud.workstations.v1.Workstation
// WorkstationObservedState is the state of the Workstation resource as most recently observed in GCP.
type WorkstationObservedState struct {
// Output only. A system-assigned unique identifier for this workstation.
UID *string `json:"uid,omitempty"`

// Output only. Time when this workstation was created.
CreateTime *string `json:"createTime,omitempty"`

// Output only. Time when this workstation was most recently updated.
UpdateTime *string `json:"updateTime,omitempty"`

// Output only. Time when this workstation was most recently successfully
// started, regardless of the workstation's initial state.
StartTime *string `json:"startTime,omitempty"`

// Output only. Time when this workstation was soft-deleted.
DeleteTime *string `json:"deleteTime,omitempty"`

// Output only. Checksum computed by the server. May be sent on update and
// delete requests to make sure that the client has an up-to-date value
// before proceeding.
Etag *string `json:"etag,omitempty"`

// Output only. Current state of the workstation.
State *string `json:"state,omitempty"`

// Output only. Host to which clients can send HTTPS traffic that will be
// received by the workstation. Authorized traffic will be received to the
// workstation as HTTP on port 80. To send traffic to a different port,
// clients may prefix the host with the destination port in the format
// `{port}-{host}`.
Host *string `json:"host,omitempty"`
}

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

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

// +required
Spec WorkstationSpec `json:"spec,omitempty"`
Status WorkstationStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&Workstation{}, &WorkstationList{})
}
Loading

0 comments on commit acd40d5

Please sign in to comment.