Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions apis/analytics/v1alpha1/account_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2025 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"

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

// AccountIdentity defines the resource reference to AnalyticsAccount, which "External" field
// holds the GCP identifier for the KRM object.
type AccountIdentity struct {
id string
}

func (i *AccountIdentity) String() string {
return "accounts/" + i.id
}

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

func (i *AccountIdentity) SetID(id string) {
i.id = id
return
}

// New builds a AccountIdentity from the Config Connector Account object.
func NewAccountIdentity(ctx context.Context, reader client.Reader, obj *AnalyticsAccount) (*AccountIdentity, error) {
// Attempt to get the service-generated resource ID.
resourceID := common.ValueOf(obj.Spec.ResourceID)
if resourceID == "" && obj.Status.ExternalRef != nil { // Reconciliation after creation is completed.
savedResourceID, err := ParseAccountExternal(common.ValueOf(obj.Status.ExternalRef))
if err != nil {
return nil, err
}
resourceID = savedResourceID
}

id := &AccountIdentity{
id: resourceID,
}

// Attempt to ensure ID is immutable, by verifying against previously-set `status.externalRef`.
externalRef := common.ValueOf(obj.Status.ExternalRef)
if externalRef != "" {
if id.String() != externalRef {
return nil, fmt.Errorf("cannot update AnalyticsAccount identity (old=%q, new=%q): identity is immutable", externalRef, id.String())
}
}

return id, nil
}

func ParseAccountExternal(external string) (resourceID string, err error) {
tokens := strings.Split(external, "/")
if len(tokens) != 2 || tokens[0] != "accounts" {
return "", fmt.Errorf("format of AnalyticsAccount external=%q was not known (use accounts/{{accountID}})", external)
}
resourceID = tokens[1]
return resourceID, nil
}
83 changes: 83 additions & 0 deletions apis/analytics/v1alpha1/account_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright 2025 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"

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

// AccountRef defines the resource reference to AnalyticsAccount, which "External" field
// holds the GCP identifier for the KRM object.
type AccountRef struct {
// A reference to an externally managed AnalyticsAccount resource.
// Should be in the format "projects/{{projectID}}/locations/{{location}}/accounts/{{accountID}}".
External string `json:"external,omitempty"`

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

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

// NormalizedExternal provision the "External" value for other resource that depends on AnalyticsAccount.
// If the "External" is given in the other resource's spec.AnalyticsAccountRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual AnalyticsAccount object from the cluster.
func (r *AccountRef) 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", AnalyticsAccountGVK.Kind)
}
// From given External
if r.External != "" {
if _, err := ParseAccountExternal(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(AnalyticsAccountGVK)
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", AnalyticsAccountGVK, 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
}
127 changes: 127 additions & 0 deletions apis/analytics/v1alpha1/account_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Copyright 2025 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 (
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var AnalyticsAccountGVK = GroupVersion.WithKind("AnalyticsAccount")

// AnalyticsAccountSpec defines the desired state of AnalyticsAccount
// +kcc:spec:proto=google.analytics.admin.v1beta.Account
type AnalyticsAccountSpec struct {
// The AnalyticsAccount name. It's generated by the service.
// Providing resource ID via this field indicates resource acquisition instead of creation.
ResourceID *string `json:"resourceID,omitempty"`

// Required. Human-readable display name for this account.
// +kcc:proto:field=google.analytics.admin.v1beta.Account.display_name
// +required
DisplayName *string `json:"displayName,omitempty"`

// Country of business. Must be a Unicode CLDR region code.
// +kcc:proto:field=google.analytics.admin.v1beta.Account.region_code
// +required
RegionCode *string `json:"regionCode,omitempty"`

// Got the following error if 'redirect_uri' field is empty when provisioning the ticket for account creation:
// rpc error: code = InvalidArgument desc = The value for the 'redirect_uri' field was empty, but must be provided.

// Redirect URI where the user will be sent after accepting Terms of Service.
// +kcc:proto:field=google.analytics.admin.v1beta.ProvisionAccountTicketRequest.redirect_uri
// +required
RedirectURI *string `json:"redirectURI,omitempty"`
}

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

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

// AnalyticsAccountObservedState is the state of the AnalyticsAccount resource as most recently observed in GCP.
// +kcc:observedstate:proto=google.analytics.admin.v1beta.Account
type AnalyticsAccountObservedState struct {
// Output only. Time when this account was originally created.
// +kcc:proto:field=google.analytics.admin.v1beta.Account.create_time
CreateTime *string `json:"createTime,omitempty"`

// Output only. Time when account payload fields were last updated.
// +kcc:proto:field=google.analytics.admin.v1beta.Account.update_time
UpdateTime *string `json:"updateTime,omitempty"`

// Output only. Indicates whether this Account is soft-deleted or not. Deleted
// accounts are excluded from List results unless specifically requested.
// +kcc:proto:field=google.analytics.admin.v1beta.Account.deleted
Deleted *bool `json:"deleted,omitempty"`

// Output only. The URI for a Google Marketing Platform organization resource.
// Only set when this account is connected to a GMP organization.
// Format: marketingplatformadmin.googleapis.com/organizations/{org_id}
// +kcc:proto:field=google.analytics.admin.v1beta.Account.gmp_organization
GMPOrganization *string `json:"gmpOrganization,omitempty"`

// Output only. The ticket ID received after provisioning the account.
// Accept the Terms of Service in
// https://analytics.google.com/analytics/web/?provisioningSignup=false#/termsofservice/ACCOUNT_TICKET_ID
// to complete the creation of a Google Analytics account.
// +kcc:proto:field=google.analytics.admin.v1beta.ProvisionAccountTicketResponse.account_ticket_id
AccountTicketID *string `json:"accountTicketID,omitempty"`
}

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

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

// +required
Spec AnalyticsAccountSpec `json:"spec,omitempty"`
Status AnalyticsAccountStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&AnalyticsAccount{}, &AnalyticsAccountList{})
}
16 changes: 16 additions & 0 deletions apis/analytics/v1alpha1/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2025 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.

// +kcc:proto=google.analytics.admin.v1beta
package v1alpha1
33 changes: 33 additions & 0 deletions apis/analytics/v1alpha1/groupversion_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2025 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.

// +kubebuilder:object:generate=true
// +groupName=analytics.cnrm.cloud.google.com
package v1alpha1

import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)

var (
// GroupVersion is group version used to register these objects
GroupVersion = schema.GroupVersion{Group: "analytics.cnrm.cloud.google.com", Version: "v1alpha1"}

// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}

// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
)
21 changes: 21 additions & 0 deletions apis/analytics/v1alpha1/types.generated.go

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

Loading
Loading