Skip to content

Commit 058a89b

Browse files
Merge pull request #4180 from acpana/resource-deploy-deploypolicy-crd-2-done
feat: types, CRDs, mappers, fuzzers for CloudDeployDeployPolicy
2 parents 4a146e6 + eb465b1 commit 058a89b

10 files changed

+2277
-263
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package v1alpha1
16+
17+
import (
18+
"context"
19+
"fmt"
20+
"strings"
21+
22+
"github.com/GoogleCloudPlatform/k8s-config-connector/apis/common"
23+
refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
24+
"sigs.k8s.io/controller-runtime/pkg/client"
25+
)
26+
27+
// DeployPolicyIdentity defines the resource reference to DeployDeployPolicy, which "External" field
28+
// holds the GCP identifier for the KRM object.
29+
type DeployPolicyIdentity struct {
30+
parent *DeployPolicyParent
31+
id string
32+
}
33+
34+
func (i *DeployPolicyIdentity) String() string {
35+
return i.parent.String() + "/deploypolicys/" + i.id
36+
}
37+
38+
func (i *DeployPolicyIdentity) ID() string {
39+
return i.id
40+
}
41+
42+
func (i *DeployPolicyIdentity) Parent() *DeployPolicyParent {
43+
return i.parent
44+
}
45+
46+
type DeployPolicyParent struct {
47+
ProjectID string
48+
Location string
49+
}
50+
51+
func (p *DeployPolicyParent) String() string {
52+
return "projects/" + p.ProjectID + "/locations/" + p.Location
53+
}
54+
55+
// New builds a DeployPolicyIdentity from the Config Connector DeployPolicy object.
56+
func NewDeployPolicyIdentity(ctx context.Context, reader client.Reader, obj *CloudDeployDeployPolicy) (*DeployPolicyIdentity, error) {
57+
58+
// Get Parent
59+
projectRef, err := refsv1beta1.ResolveProject(ctx, reader, obj.GetNamespace(), obj.Spec.ProjectRef)
60+
if err != nil {
61+
return nil, err
62+
}
63+
projectID := projectRef.ProjectID
64+
if projectID == "" {
65+
return nil, fmt.Errorf("cannot resolve project")
66+
}
67+
location := obj.Spec.Location
68+
69+
// Get desired ID
70+
resourceID := common.ValueOf(obj.Spec.ResourceID)
71+
if resourceID == "" {
72+
resourceID = obj.GetName()
73+
}
74+
if resourceID == "" {
75+
return nil, fmt.Errorf("cannot resolve resource ID")
76+
}
77+
78+
// Use approved External
79+
externalRef := common.ValueOf(obj.Status.ExternalRef)
80+
if externalRef != "" {
81+
// Validate desired with actual
82+
actualParent, actualResourceID, err := ParseDeployPolicyExternal(externalRef)
83+
if err != nil {
84+
return nil, err
85+
}
86+
if actualParent.ProjectID != projectID {
87+
return nil, fmt.Errorf("spec.projectRef changed, expect %s, got %s", actualParent.ProjectID, projectID)
88+
}
89+
if actualParent.Location != location {
90+
return nil, fmt.Errorf("spec.location changed, expect %s, got %s", actualParent.Location, location)
91+
}
92+
if actualResourceID != resourceID {
93+
return nil, fmt.Errorf("cannot reset `metadata.name` or `spec.resourceID` to %s, since it has already assigned to %s",
94+
resourceID, actualResourceID)
95+
}
96+
}
97+
return &DeployPolicyIdentity{
98+
parent: &DeployPolicyParent{
99+
ProjectID: projectID,
100+
Location: location,
101+
},
102+
id: resourceID,
103+
}, nil
104+
}
105+
106+
func ParseDeployPolicyExternal(external string) (parent *DeployPolicyParent, resourceID string, err error) {
107+
tokens := strings.Split(external, "/")
108+
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "deploypolicys" {
109+
return nil, "", fmt.Errorf("format of DeployDeployPolicy external=%q was not known (use projects/{{projectID}}/locations/{{location}}/deploypolicys/{{deploypolicyID}})", external)
110+
}
111+
parent = &DeployPolicyParent{
112+
ProjectID: tokens[1],
113+
Location: tokens[3],
114+
}
115+
resourceID = tokens[5]
116+
return parent, resourceID, nil
117+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package v1alpha1
16+
17+
import (
18+
"context"
19+
"fmt"
20+
21+
refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
22+
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
23+
apierrors "k8s.io/apimachinery/pkg/api/errors"
24+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
25+
"k8s.io/apimachinery/pkg/types"
26+
"sigs.k8s.io/controller-runtime/pkg/client"
27+
)
28+
29+
var _ refsv1beta1.ExternalNormalizer = &DeployPolicyRef{}
30+
31+
// DeployPolicyRef defines the resource reference to DeployDeployPolicy, which "External" field
32+
// holds the GCP identifier for the KRM object.
33+
type DeployPolicyRef struct {
34+
// A reference to an externally managed DeployDeployPolicy resource.
35+
// Should be in the format "projects/{{projectID}}/locations/{{location}}/deploypolicys/{{deploypolicyID}}".
36+
External string `json:"external,omitempty"`
37+
38+
// The name of a DeployDeployPolicy resource.
39+
Name string `json:"name,omitempty"`
40+
41+
// The namespace of a DeployDeployPolicy resource.
42+
Namespace string `json:"namespace,omitempty"`
43+
}
44+
45+
// NormalizedExternal provision the "External" value for other resource that depends on DeployDeployPolicy.
46+
// If the "External" is given in the other resource's spec.DeployDeployPolicyRef, the given value will be used.
47+
// Otherwise, the "Name" and "Namespace" will be used to query the actual DeployDeployPolicy object from the cluster.
48+
func (r *DeployPolicyRef) NormalizedExternal(ctx context.Context, reader client.Reader, otherNamespace string) (string, error) {
49+
if r.External != "" && r.Name != "" {
50+
return "", fmt.Errorf("cannot specify both name and external on %s reference", DeployDeployPolicyGVK.Kind)
51+
}
52+
// From given External
53+
if r.External != "" {
54+
if _, _, err := ParseDeployPolicyExternal(r.External); err != nil {
55+
return "", err
56+
}
57+
return r.External, nil
58+
}
59+
60+
// From the Config Connector object
61+
if r.Namespace == "" {
62+
r.Namespace = otherNamespace
63+
}
64+
key := types.NamespacedName{Name: r.Name, Namespace: r.Namespace}
65+
u := &unstructured.Unstructured{}
66+
u.SetGroupVersionKind(DeployDeployPolicyGVK)
67+
if err := reader.Get(ctx, key, u); err != nil {
68+
if apierrors.IsNotFound(err) {
69+
return "", k8s.NewReferenceNotFoundError(u.GroupVersionKind(), key)
70+
}
71+
return "", fmt.Errorf("reading referenced %s %s: %w", DeployDeployPolicyGVK, key, err)
72+
}
73+
// Get external from status.externalRef. This is the most trustworthy place.
74+
actualExternalRef, _, err := unstructured.NestedString(u.Object, "status", "externalRef")
75+
if err != nil {
76+
return "", fmt.Errorf("reading status.externalRef: %w", err)
77+
}
78+
if actualExternalRef == "" {
79+
return "", k8s.NewReferenceNotReadyError(u.GroupVersionKind(), key)
80+
}
81+
r.External = actualExternalRef
82+
return r.External, nil
83+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package v1alpha1
16+
17+
import (
18+
refs "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
19+
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
20+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
21+
)
22+
23+
var DeployDeployPolicyGVK = GroupVersion.WithKind("CloudDeployDeployPolicy")
24+
25+
type Parent struct {
26+
// +required
27+
ProjectRef *refs.ProjectRef `json:"projectRef"`
28+
29+
// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="Location field is immutable"
30+
// Immutable.
31+
// +required
32+
Location string `json:"location"`
33+
}
34+
35+
// DeployPolicySpec defines the desired state of DeployDeployPolicy
36+
// +kcc:proto=google.cloud.deploy.v1.DeployPolicy
37+
type DeployPolicySpec struct {
38+
Parent `json:",inline"`
39+
40+
// The DeployDeployPolicy name. If not given, the metadata.name will be used.
41+
ResourceID *string `json:"resourceID,omitempty"`
42+
43+
// Description of the `DeployPolicy`. Max length is 255 characters.
44+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.description
45+
Description *string `json:"description,omitempty"`
46+
47+
// NOT YET
48+
// // User annotations. These attributes can only be set and used by the
49+
// // user, and not by Cloud Deploy. Annotations must meet the following
50+
// // constraints:
51+
// //
52+
// // * Annotations are key/value pairs.
53+
// // * Valid annotation keys have two segments: an optional prefix and name,
54+
// // separated by a slash (`/`).
55+
// // * The name segment is required and must be 63 characters or less,
56+
// // beginning and ending with an alphanumeric character (`[a-z0-9A-Z]`) with
57+
// // dashes (`-`), underscores (`_`), dots (`.`), and alphanumerics between.
58+
// // * The prefix is optional. If specified, the prefix must be a DNS subdomain:
59+
// // a series of DNS labels separated by dots(`.`), not longer than 253
60+
// // characters in total, followed by a slash (`/`).
61+
// //
62+
// // See
63+
// // https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/#syntax-and-character-set
64+
// // for more details.
65+
// // +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.annotations
66+
// Annotations map[string]string `json:"annotations,omitempty"`
67+
68+
// // Labels are attributes that can be set and used by both the
69+
// // user and by Cloud Deploy. Labels must meet the following constraints:
70+
// //
71+
// // * Keys and values can contain only lowercase letters, numeric characters,
72+
// // underscores, and dashes.
73+
// // * All characters must use UTF-8 encoding, and international characters are
74+
// // allowed.
75+
// // * Keys must start with a lowercase letter or international character.
76+
// // * Each resource is limited to a maximum of 64 labels.
77+
// //
78+
// // Both keys and values are additionally constrained to be <= 128 bytes.
79+
// // +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.labels
80+
// Labels map[string]string `json:"labels,omitempty"`
81+
82+
// When suspended, the policy will not prevent actions from occurring, even
83+
// if the action violates the policy.
84+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.suspended
85+
Suspended *bool `json:"suspended,omitempty"`
86+
87+
// Required. Selected resources to which the policy will be applied. At least
88+
// one selector is required. If one selector matches the resource the policy
89+
// applies. For example, if there are two selectors and the action being
90+
// attempted matches one of them, the policy will apply to that action.
91+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.selectors
92+
Selectors []DeployPolicyResourceSelector `json:"selectors,omitempty"`
93+
94+
// Required. Rules to apply. At least one rule must be present.
95+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.rules
96+
Rules []PolicyRule `json:"rules,omitempty"`
97+
98+
// NOT YET
99+
// // The weak etag of the `Automation` resource.
100+
// // This checksum is computed by the server based on the value of other
101+
// // fields, and may be sent on update and delete requests to ensure the
102+
// // client has an up-to-date value before proceeding.
103+
// // +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.etag
104+
// Etag *string `json:"etag,omitempty"`
105+
}
106+
107+
// DeployPolicyStatus defines the config connector machine state of DeployDeployPolicy
108+
type DeployPolicyStatus struct {
109+
/* Conditions represent the latest available observations of the
110+
object's current state. */
111+
Conditions []v1alpha1.Condition `json:"conditions,omitempty"`
112+
113+
// 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.
114+
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`
115+
116+
// A unique specifier for the DeployDeployPolicy resource in GCP.
117+
ExternalRef *string `json:"externalRef,omitempty"`
118+
119+
// ObservedState is the state of the resource as most recently observed in GCP.
120+
ObservedState *DeployPolicyObservedState `json:"observedState,omitempty"`
121+
}
122+
123+
// DeployPolicyObservedState is the state of the DeployDeployPolicy resource as most recently observed in GCP.
124+
// +kcc:proto=google.cloud.deploy.v1.DeployPolicy
125+
type DeployPolicyObservedState struct {
126+
// Output only. Name of the `DeployPolicy`. Format is
127+
// `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`.
128+
// The `deployPolicy` component must match `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`
129+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.name
130+
Name *string `json:"name,omitempty"`
131+
132+
// Output only. Unique identifier of the `DeployPolicy`.
133+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.uid
134+
Uid *string `json:"uid,omitempty"`
135+
136+
// Output only. Time at which the deploy policy was created.
137+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.create_time
138+
CreateTime *string `json:"createTime,omitempty"`
139+
140+
// Output only. Most recent time at which the deploy policy was updated.
141+
// +kcc:proto:field=google.cloud.deploy.v1.DeployPolicy.update_time
142+
UpdateTime *string `json:"updateTime,omitempty"`
143+
}
144+
145+
// +genclient
146+
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
147+
// +kubebuilder:resource:categories=gcp,shortName=gcpcodedeploydeploypolicy;gcpcodedeploydeploypolicies
148+
// +kubebuilder:subresource:status
149+
// +kubebuilder:metadata:labels="cnrm.cloud.google.com/managed-by-kcc=true";"cnrm.cloud.google.com/system=true"
150+
// +kubebuilder:printcolumn:name="Age",JSONPath=".metadata.creationTimestamp",type="date"
151+
// +kubebuilder:printcolumn:name="Ready",JSONPath=".status.conditions[?(@.type=='Ready')].status",type="string",description="When 'True', the most recent reconcile of the resource succeeded"
152+
// +kubebuilder:printcolumn:name="Status",JSONPath=".status.conditions[?(@.type=='Ready')].reason",type="string",description="The reason for the value in 'Ready'"
153+
// +kubebuilder:printcolumn:name="Status Age",JSONPath=".status.conditions[?(@.type=='Ready')].lastTransitionTime",type="date",description="The last transition time for the value in 'Status'"
154+
155+
// CloudDeployDeployPolicy is the Schema for the CloudDeployDeployPolicy API
156+
// +k8s:openapi-gen=true
157+
type CloudDeployDeployPolicy struct {
158+
metav1.TypeMeta `json:",inline"`
159+
metav1.ObjectMeta `json:"metadata,omitempty"`
160+
161+
// +required
162+
Spec DeployPolicySpec `json:"spec,omitempty"`
163+
Status DeployPolicyStatus `json:"status,omitempty"`
164+
}
165+
166+
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
167+
// CloudDeployDeployPolicyList contains a list of DeployDeployPolicy
168+
type CloudDeployDeployPolicyList struct {
169+
metav1.TypeMeta `json:",inline"`
170+
metav1.ListMeta `json:"metadata,omitempty"`
171+
Items []CloudDeployDeployPolicy `json:"items"`
172+
}
173+
174+
func init() {
175+
SchemeBuilder.Register(&CloudDeployDeployPolicy{}, &CloudDeployDeployPolicyList{})
176+
}

0 commit comments

Comments
 (0)