Skip to content

Commit

Permalink
Merge pull request GoogleCloudPlatform#2146 from yuwenma/cbwp-unified…
Browse files Browse the repository at this point in the history
…-mapper-2

chore: use auto-generated mapper in cbwp
  • Loading branch information
google-oss-prow[bot] authored Jun 26, 2024
2 parents 50411bd + d70d4b2 commit a9d635f
Show file tree
Hide file tree
Showing 4 changed files with 228 additions and 215 deletions.
176 changes: 0 additions & 176 deletions apis/cloudbuild/v1alpha1/conversion.go

This file was deleted.

100 changes: 100 additions & 0 deletions pkg/controller/direct/cloudbuild/maputils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// 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 cloudbuild

import (
"errors"
"fmt"
"strings"
"time"

"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/known/timestamppb"
)

type MapContext struct {
errs []error
}

func (c *MapContext) Errorf(msg string, args ...interface{}) {
c.errs = append(c.errs, fmt.Errorf(msg, args...))
}

func (c *MapContext) Err() error {
return errors.Join(c.errs...)
}

type ProtoEnum interface {
~int32
Descriptor() protoreflect.EnumDescriptor
}

func Enum_ToProto[U ProtoEnum](mapCtx *MapContext, in *string) U {
var defaultU U
descriptor := defaultU.Descriptor()

inValue := ValueOf(in)
if inValue == "" {
unspecifiedValue := U(0)
return unspecifiedValue
}

n := descriptor.Values().Len()
for i := 0; i < n; i++ {
value := descriptor.Values().Get(i)
if string(value.Name()) == inValue {
v := U(value.Number())
return v
}
}

var validValues []string
for i := 0; i < n; i++ {
value := descriptor.Values().Get(i)
validValues = append(validValues, string(value.Name()))
}

mapCtx.Errorf("unknown enum value %q for %v (valid values are %v)", inValue, descriptor.FullName(), strings.Join(validValues, ", "))
return 0
}

func Enum_FromProto[U ProtoEnum](mapCtx *MapContext, v U) *string {
descriptor := v.Descriptor()

if v == 0 {
return nil
}

val := descriptor.Values().ByNumber(protoreflect.EnumNumber(v))
if val == nil {
mapCtx.Errorf("unknown enum value %d", v)
return nil
}
s := string(val.Name())
return &s
}

func LazyPtr[V comparable](v V) *V {
var defaultV V
if v == defaultV {
return nil
}
return &v
}

func ToOpenAPIDateTime(ts *timestamppb.Timestamp) *string {
formatted := ts.AsTime().Format(time.RFC3339)
return &formatted
}
58 changes: 19 additions & 39 deletions pkg/controller/direct/cloudbuild/workerpool_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"fmt"
"reflect"
"strings"
"time"

gcp "cloud.google.com/go/cloudbuild/apiv1/v2"
cloudbuildpb "cloud.google.com/go/cloudbuild/apiv1/v2/cloudbuildpb"
Expand All @@ -35,7 +34,6 @@ import (
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/controller/direct/registry"
"github.com/googleapis/gax-go/v2/apierror"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
Expand Down Expand Up @@ -171,13 +169,13 @@ func (a *Adapter) Create(ctx context.Context, u *unstructured.Unstructured) erro
}

desired := a.desired.DeepCopy()
wp := &cloudbuildpb.WorkerPool{
Name: a.fullyQualifiedName(),
}
err := krm.Convert_WorkerPool_KRM_To_API_v1(desired, wp)
if err != nil {
return fmt.Errorf("converting workerpool spec to api: %w", err)

mapCtx := &MapContext{}
wp := CloudBuildWorkerPoolSpec_ToProto(mapCtx, &desired.Spec)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
wp.Name = a.fullyQualifiedName()
req := &cloudbuildpb.CreateWorkerPoolRequest{
Parent: a.getParent(),
WorkerPoolId: a.resourceID,
Expand All @@ -191,12 +189,12 @@ func (a *Adapter) Create(ctx context.Context, u *unstructured.Unstructured) erro
if err != nil {
return fmt.Errorf("cloudbuildworkerpool %s waiting creation failed: %w", wp.Name, err)
}

status := &krm.CloudBuildWorkerPoolStatus{}
if err := krm.Convert_WorkerPool_API_v1_To_KRM_status(created, status); err != nil {
return fmt.Errorf("update workerpool status %w", err)
status.ObservedState = CloudBuildWorkerPoolObservedState_FromProto(mapCtx, created)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
status.ObservedState.CreateTime = ToOpenAPIDateTime(created.GetCreateTime())
status.ObservedState.UpdateTime = ToOpenAPIDateTime(created.GetUpdateTime())
resRef, err := NewResourceRef(created)
if err != nil {
return err
Expand Down Expand Up @@ -265,15 +263,14 @@ func (a *Adapter) Update(ctx context.Context, u *unstructured.Unstructured) erro
return nil
}

wp := &cloudbuildpb.WorkerPool{
Name: a.fullyQualifiedName(),
Etag: a.actual.Etag,
}
desired := a.desired.DeepCopy()
err := krm.Convert_WorkerPool_KRM_To_API_v1(desired, wp)
if err != nil {
return fmt.Errorf("converting workerpool spec to api: %w", err)
mapCtx := &MapContext{}
wp := CloudBuildWorkerPoolSpec_ToProto(mapCtx, &desired.Spec)
if mapCtx.Err() != nil {
return mapCtx.Err()
}
wp.Name = a.fullyQualifiedName()
wp.Etag = a.actual.Etag
req := &cloudbuildpb.UpdateWorkerPoolRequest{
WorkerPool: wp,
UpdateMask: updateMask,
Expand All @@ -287,11 +284,10 @@ func (a *Adapter) Update(ctx context.Context, u *unstructured.Unstructured) erro
return fmt.Errorf("cloudbuildworkerpool %s waiting update failed: %w", wp.Name, err)
}
status := &krm.CloudBuildWorkerPoolStatus{}
if err := krm.Convert_WorkerPool_API_v1_To_KRM_status(updated, status); err != nil {
return fmt.Errorf("update workerpool status %w", err)
status.ObservedState = CloudBuildWorkerPoolObservedState_FromProto(mapCtx, updated)
if mapCtx.Err() != nil {
return fmt.Errorf("update workerpool status %w", mapCtx.Err())
}
status.ObservedState.CreateTime = ToOpenAPIDateTime(updated.GetCreateTime())
status.ObservedState.UpdateTime = ToOpenAPIDateTime(updated.GetUpdateTime())
// This value should not be updated. Just in case.
resRef, err := NewResourceRef(updated)
if err != nil {
Expand Down Expand Up @@ -416,19 +412,3 @@ func HasHTTPCode(err error, code int) bool {
}
return false
}

// LazyPtr returns a pointer to v, unless it is the empty value, in which case it returns nil.
// It is essentially the inverse of ValueOf, though it is lossy
// because we can't tell nil and empty apart without a pointer.
func LazyPtr[T comparable](v T) *T {
var defaultValue T
if v == defaultValue {
return nil
}
return &v
}

func ToOpenAPIDateTime(ts *timestamppb.Timestamp) *string {
formatted := ts.AsTime().Format(time.RFC3339)
return &formatted
}
Loading

0 comments on commit a9d635f

Please sign in to comment.