Skip to content

Commit

Permalink
Add externalRef for ComputeFirewallPolicyRule
Browse files Browse the repository at this point in the history
  • Loading branch information
gemmahou committed Oct 30, 2024
1 parent 7fa9f2d commit 8736e1e
Show file tree
Hide file tree
Showing 9 changed files with 345 additions and 81 deletions.
166 changes: 166 additions & 0 deletions apis/compute/v1beta1/computefirewallpolicyrule_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
// 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 = &ComputeFirewallPolicyRuleRef{}

// ComputeFirewallPolicyRuleRef defines the resource reference to ComputeFirewallPolicyRule, which "External" field
// holds the GCP identifier for the KRM object.
type ComputeFirewallPolicyRuleRef struct {
// A reference to an externally managed ComputeFirewallPolicyRule resource.
// Should be in the format "locations/global/firewallPolicies/<firewallPolicy>/rules/<priority>".
External string `json:"external,omitempty"`

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

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

parent *ComputeFirewallPolicyRuleParent
}

// NormalizedExternal provision the "External" value for other resource that depends on ComputeFirewallPolicyRule.
// If the "External" is given in the other resource's spec.ComputeFirewallPolicyRuleRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual ComputeFirewallPolicyRule object from the cluster.
func (r *ComputeFirewallPolicyRuleRef) 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", ComputeFirewallPolicyRuleGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := parseComputeFirewallPolicyRuleExternal(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(ComputeFirewallPolicyRuleGVK)
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", ComputeFirewallPolicyRuleGVK, 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 "", fmt.Errorf("ComputeFirewallPolicyRule is not ready yet")
}
r.External = actualExternalRef
return r.External, nil
}

// New builds a NewComputeFirewallPolicyRuleRef from the Config Connector ComputeFirewallPolicyRule object.
func NewComputeFirewallPolicyRuleRef(ctx context.Context, reader client.Reader, obj *ComputeFirewallPolicyRule) (*ComputeFirewallPolicyRuleRef, error) {
id := &ComputeFirewallPolicyRuleRef{}

firewallPolicyRef, err := refsv1beta1.ResolveComputeFirewallPolicy(ctx, reader, obj, obj.Spec.FirewallPolicyRef)
if err != nil {
return nil, err
}
firewallPolicy := firewallPolicyRef.External
if firewallPolicy == "" {
return nil, fmt.Errorf("cannot resolve firewallPolicy")
}

id.parent = &ComputeFirewallPolicyRuleParent{FirewallPolicy: firewallPolicy}

// Get priority. Priority is a required field
priority := fmt.Sprintf("%v", obj.Spec.Priority)

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

// Validate desired with actual
actualParent, actualPriority, err := parseComputeFirewallPolicyRuleExternal(externalRef)
if err != nil {
return nil, err
}
if actualParent.FirewallPolicy != firewallPolicy {
return nil, fmt.Errorf("spec.firewallPolicyRef changed, expect %s, got %s", actualParent.FirewallPolicy, firewallPolicy)
}
if actualPriority != priority {
return nil, fmt.Errorf("cannot reset `spec.priority` to %s, since it has already assigned to %s",
priority, actualPriority)
}
id.External = externalRef
id.parent = &ComputeFirewallPolicyRuleParent{FirewallPolicy: firewallPolicy}
return id, nil
}

func (r *ComputeFirewallPolicyRuleRef) Parent() (*ComputeFirewallPolicyRuleParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, _, err := parseComputeFirewallPolicyRuleExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("ComputeFirewallPolicyRule not initialized from `NewComputeFirewallPolicyRuleRef` or `NormalizedExternal`")
}

type ComputeFirewallPolicyRuleParent struct {
FirewallPolicy string
}

func (p *ComputeFirewallPolicyRuleParent) String() string {
return "locations/global/firewallPolicies/" + p.FirewallPolicy
}

func asComputeFirewallPolicyRuleExternal(parent *ComputeFirewallPolicyRuleParent, priority string) (external string) {
return parent.String() + "/rules/" + priority
}

func parseComputeFirewallPolicyRuleExternal(external string) (parent *ComputeFirewallPolicyRuleParent, priority string, err error) {
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "locations" || tokens[2] != "firewallPolicies" || tokens[4] != "rules" {
return nil, "", fmt.Errorf("format of ComputeFirewallPolicyRule external=%q was not known (use firewallPolicies/<firewallPolicy>/rules/<priority>)", external)
}
parent = &ComputeFirewallPolicyRuleParent{
FirewallPolicy: tokens[3],
}
priority = tokens[5]
return parent, priority, nil
}
35 changes: 35 additions & 0 deletions apis/compute/v1beta1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 46 additions & 0 deletions apis/refs/v1beta1/computerefs.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,49 @@ type ComputeFirewallPolicyRef struct {
/* The `namespace` field of a `ComputeFirewallPolicy ` resource. */
Namespace string `json:"namespace,omitempty"`
}

func ResolveComputeFirewallPolicy(ctx context.Context, reader client.Reader, src client.Object, ref *ComputeFirewallPolicyRef) (*ComputeFirewallPolicyRef, error) {
if ref == nil {
return nil, nil
}

if ref.External != "" {
if ref.Name != "" {
return nil, fmt.Errorf("cannot specify both name and external on reference")
}
return ref, nil
}

if ref.Name == "" {
return nil, fmt.Errorf("must specify either name or external on reference")
}

key := types.NamespacedName{
Namespace: ref.Namespace,
Name: ref.Name,
}
if key.Namespace == "" {
key.Namespace = src.GetNamespace()
}

computeFirewallPolicy := &unstructured.Unstructured{}
computeFirewallPolicy.SetGroupVersionKind(schema.GroupVersionKind{
Group: "compute.cnrm.cloud.google.com",
Version: "v1beta1",
Kind: "ComputeFirewallPolicy",
})
if err := reader.Get(ctx, key, computeFirewallPolicy); err != nil {
if apierrors.IsNotFound(err) {
return nil, k8s.NewReferenceNotFoundError(computeFirewallPolicy.GroupVersionKind(), key)
}
return nil, fmt.Errorf("error reading referenced ComputeFirewallPolicy %v: %w", key, err)
}

resourceID, err := GetResourceID(computeFirewallPolicy)
if err != nil {
return nil, err
}

return &ComputeFirewallPolicyRef{
External: fmt.Sprintf("%s", resourceID)}, nil
}
Loading

0 comments on commit 8736e1e

Please sign in to comment.