Skip to content
This repository was archived by the owner on Jul 18, 2025. It is now read-only.

Commit c64eeae

Browse files
committed
refactoring..
1 parent 185a65c commit c64eeae

File tree

7 files changed

+152
-129
lines changed

7 files changed

+152
-129
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ CAPI_KIND_CLUSTER_NAME ?= capi-test
231231
# It is set by Prow GIT_TAG, a git-based tag of the form vYYYYMMDD-hash, e.g., v20210120-v0.3.10-308-gc61521971
232232

233233
# Next release is: v0.3.2
234-
TAG ?= v0.3.2-preview.39
234+
TAG ?= v0.3.2-preview.47
235235
ARCH ?= $(shell go env GOARCH)
236236
ALL_ARCH = amd64 arm arm64
237237

config/default/manager_image_patch.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,5 @@ spec:
77
template:
88
spec:
99
containers:
10-
- image: ghcr.io/patricklaabs/cluster-api-addon-provider-cdk8s/cluster-api-cdk8s-controller:v0.3.2-preview.39
10+
- image: ghcr.io/patricklaabs/cluster-api-addon-provider-cdk8s/cluster-api-cdk8s-controller:v0.3.2-preview.47
1111
name: manager

config/default/manager_image_patch.yaml-e

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,5 @@ spec:
77
template:
88
spec:
99
containers:
10-
- image: ghcr.io/patricklaabs/cluster-api-addon-provider-cdk8s/cluster-api-cdk8s-controller:v0.3.2-preview.39
10+
- image: ghcr.io/patricklaabs/cluster-api-addon-provider-cdk8s/cluster-api-cdk8s-controller:v0.3.2-preview.47
1111
name: manager

controllers/cdk8sappproxy/cdk8sappproxy_git_operator.go

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ import (
1212
"path/filepath"
1313
)
1414

15-
func (r *Reconciler) prepareSource(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, proxyNamespacedName types.NamespacedName, logger logr.Logger, operation string) (string, string, error) {
16-
var appSourcePath string
17-
var currentCommitHash string
15+
func (r *Reconciler) prepareSource(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, proxyNamespacedName types.NamespacedName, logger logr.Logger, operation string) (appSourcePath string, currentCommitHash string, err error) {
1816
gitImpl := &gitoperator.GitImplementer{}
1917
var buf bytes.Buffer
2018
gitSpec := cdk8sAppProxy.Spec.GitRepository
@@ -52,17 +50,15 @@ func (r *Reconciler) prepareSource(ctx context.Context, cdk8sAppProxy *addonsv1a
5250
}
5351
default:
5452
err := errors.New("no source specified")
55-
if operation == OperationNormal { // Poller management and status updates for normal flow
56-
//r.stopGitPoller(proxyNamespacedName, logger)
53+
if operation == OperationNormal {
5754
if cdk8sAppProxy != nil {
5855
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.EmptyGitRepositoryReason, "No source specified during "+operation, err, false)
5956
}
6057
} else if operation == OperationDeletion && cdk8sAppProxy != nil {
61-
// For deletion, if source can't be determined, we might still want to remove finalizer.
6258
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.EmptyGitRepositoryReason, "No source specified, cannot determine resources to delete during "+operation, err, true)
6359
}
6460

65-
return "", "", err
61+
return appSourcePath, currentCommitHash, err
6662
}
6763

6864
return appSourcePath, currentCommitHash, nil

controllers/cdk8sappproxy/cdk8sappproxy_reconciler.go

Lines changed: 83 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -59,36 +59,15 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
5959

6060
func (r *Reconciler) reconcileDelete(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy) (ctrl.Result, error) {
6161
logger := log.FromContext(ctx).WithValues("cdk8sappproxy", types.NamespacedName{Name: cdk8sAppProxy.Name, Namespace: cdk8sAppProxy.Namespace}, "reconcile_type", "delete")
62-
logger.Info("Starting reconcileDelete")
6362

6463
proxyNamespacedName := types.NamespacedName{Name: cdk8sAppProxy.Name, Namespace: cdk8sAppProxy.Namespace}
6564

66-
// Stop any active git poller
67-
//r.stopGitPoller(proxyNamespacedName, logger)
68-
6965
if !controllerutil.ContainsFinalizer(cdk8sAppProxy, Finalizer) {
7066
logger.Info("Finalizer already removed, nothing to do.")
7167

7268
return ctrl.Result{}, nil
7369
}
7470

75-
// Get a source path for deletion
76-
appSourcePath, _, err := r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationDeletion)
77-
if err != nil {
78-
return ctrl.Result{}, err
79-
}
80-
81-
// Get resources to delete
82-
parsedResources, err := r.synthesizeAndParseResources(appSourcePath, logger)
83-
if err != nil {
84-
return ctrl.Result{}, err
85-
}
86-
87-
// Delete resources from target clusters
88-
if err := r.deleteResourcesFromClusters(ctx, cdk8sAppProxy, parsedResources, logger); err != nil {
89-
return ctrl.Result{}, err
90-
}
91-
9271
// Clean up watches and remove finalizer
9372
if err := r.finalizeDeletion(ctx, cdk8sAppProxy, proxyNamespacedName, logger); err != nil {
9473
return ctrl.Result{}, err
@@ -104,31 +83,51 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
10483

10584
proxyNamespacedName := types.NamespacedName{Name: cdk8sAppProxy.Name, Namespace: cdk8sAppProxy.Namespace}
10685

107-
// Handle deletion trigger annotation
108-
forceSynthAndApplyDueToDeletion, err := r.handleDeletionTriggerAnnotation(ctx, cdk8sAppProxy, logger)
109-
if err != nil {
110-
return ctrl.Result{}, err
111-
}
112-
11386
// Add finalizer if needed
11487
if shouldRequeue, err := r.ensureFinalizer(ctx, cdk8sAppProxy, logger); err != nil || shouldRequeue {
11588
return ctrl.Result{Requeue: shouldRequeue}, err
11689
}
11790

11891
// Prepare a source path and get current commit hash
119-
appSourcePath, currentCommitHash, err := r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationNormal)
92+
appSourcePath, _, err := r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationNormal)
93+
if err != nil {
94+
return ctrl.Result{}, err
95+
}
96+
97+
parsedResources, err := r.synthesizeAndParseResources(appSourcePath, logger)
12098
if err != nil {
99+
logger.Error(err, "failed to synthesize and parse resources", "appSourcePath", appSourcePath)
100+
}
101+
102+
if len(parsedResources) == 0 {
103+
if err := r.handleNoResources(ctx, cdk8sAppProxy, logger); err != nil {
104+
return ctrl.Result{}, err
105+
}
106+
107+
return ctrl.Result{}, nil
108+
}
109+
110+
// Determine if apply is needed
111+
_, clusterList, err := r.applyNeeded(ctx, cdk8sAppProxy, parsedResources, logger)
112+
if err != nil {
113+
logger.Error(err, "Failed to determine if apply is needed")
114+
//return ctrl.Result{}, err
115+
}
116+
117+
_, err = r.applyResourcesToClusters(ctx, cdk8sAppProxy, parsedResources, clusterList, proxyNamespacedName, logger)
118+
if err != nil {
119+
logger.Error(err, "Failed to apply resources to clusters", "appSourcePath", appSourcePath)
120+
121121
return ctrl.Result{}, err
122122
}
123123

124-
pollInterval := 1 * time.Minute
124+
pollInterval := 5 * time.Minute
125125
if cdk8sAppProxy.Spec.GitRepository.ReferencePollInterval != nil {
126126
pollInterval = cdk8sAppProxy.Spec.GitRepository.ReferencePollInterval.Duration
127127
}
128128

129129
repoUrl := cdk8sAppProxy.Spec.GitRepository.URL
130130
branch := cdk8sAppProxy.Spec.GitRepository.Reference
131-
tempDirPattern := "/tmp/cdk8s-git-clone-"
132131
buf := &bytes.Buffer{}
133132
polling := false
134133

@@ -141,16 +140,50 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
141140
select {
142141
case <-ticker.C:
143142
logger.Info("Polling git repository for changes", "repoUrl", repoUrl, "branch", branch)
144-
polling, err = gitImpl.Poll(repoUrl, branch, tempDirPattern, buf)
143+
polling, err = gitImpl.Poll(repoUrl, branch, appSourcePath, buf)
145144
if err != nil {
146145
logger.Error(err, "Polling git repository", "repoUrl", repoUrl, "branch", branch)
147146
}
148147
if polling {
149148
logger.Info("Detected changes in git repository, proceeding with reconciliation.")
150-
appSourcePath, currentCommitHash, err = r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationNormal)
149+
appSourcePath, _, err = r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationNormal)
151150
if err != nil {
152151
logger.Error(err, "Prepare source for reconciliation")
153152
}
153+
154+
// Synthesize and parse resources
155+
_, err := r.synthesizeAndParseResources(appSourcePath, logger)
156+
if err != nil {
157+
logger.Error(err, "failed to synthesize and parse resources", "appSourcePath", appSourcePath)
158+
}
159+
160+
parsedResources, err := r.synthesizeAndParseResources(appSourcePath, logger)
161+
if err != nil {
162+
logger.Error(err, "failed to synthesize and parse resources", "appSourcePath", appSourcePath)
163+
}
164+
165+
if len(parsedResources) == 0 {
166+
if err := r.handleNoResources(ctx, cdk8sAppProxy, logger); err != nil {
167+
logger.Error(err, "Failed to handle no resources case")
168+
return
169+
}
170+
171+
logger.Info("No valid Kubernetes resources parsed from manifest files, skipping apply.")
172+
}
173+
174+
// Determine if apply is needed
175+
_, clusterList, err := r.applyNeeded(ctx, cdk8sAppProxy, parsedResources, logger)
176+
if err != nil {
177+
logger.Error(err, "Failed to determine if apply is needed")
178+
//return ctrl.Result{}, err
179+
}
180+
181+
_, err = r.applyResourcesToClusters(ctx, cdk8sAppProxy, parsedResources, clusterList, proxyNamespacedName, logger)
182+
if err != nil {
183+
logger.Error(err, "Failed to apply resources to clusters", "appSourcePath", appSourcePath)
184+
185+
return
186+
}
154187
}
155188
case <-ctx.Done():
156189
logger.Info("Stopping git repository polling loop due to context cancellation.")
@@ -159,36 +192,7 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
159192
}
160193
}()
161194

162-
// Synthesize and parse resources
163-
parsedResources, err := r.synthesizeAndParseResources(appSourcePath, logger)
164-
if err != nil {
165-
return ctrl.Result{}, err
166-
}
167-
168-
if len(parsedResources) == 0 {
169-
if err := r.handleNoResources(ctx, cdk8sAppProxy, logger); err != nil {
170-
return ctrl.Result{}, err
171-
}
172-
173-
return ctrl.Result{}, nil
174-
}
175-
176-
// Determine if apply is needed
177-
applyNeeded, clusterList, err := r.determineIfApplyNeeded(ctx, cdk8sAppProxy, parsedResources, currentCommitHash, forceSynthAndApplyDueToDeletion, logger)
178-
if err != nil {
179-
return ctrl.Result{}, err
180-
}
181-
182-
if !applyNeeded {
183-
if err := r.handleSkipApply(ctx, cdk8sAppProxy, currentCommitHash, logger); err != nil {
184-
return ctrl.Result{}, err
185-
}
186-
187-
return ctrl.Result{}, nil
188-
}
189-
190-
// Apply resources to clusters
191-
return r.applyResourcesToClusters(ctx, cdk8sAppProxy, parsedResources, clusterList, currentCommitHash, proxyNamespacedName, logger)
195+
return ctrl.Result{}, nil
192196
}
193197

194198
func (r *Reconciler) handleDeletionTriggerAnnotation(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (bool, error) {
@@ -268,6 +272,18 @@ func (r *Reconciler) determineIfApplyNeeded(ctx context.Context, cdk8sAppProxy *
268272
return true, clusterList, nil
269273
}
270274

275+
func (r *Reconciler) applyNeeded(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, logger logr.Logger) (bool, clusterv1.ClusterList, error) {
276+
var clusterList clusterv1.ClusterList
277+
278+
_, list, err := r.verifyResourcesOnClusters(ctx, cdk8sAppProxy, parsedResources, logger)
279+
if err != nil {
280+
return false, clusterList, err
281+
}
282+
clusterList = list
283+
284+
return true, clusterList, nil
285+
}
286+
271287
func (r *Reconciler) verifyResourcesOnClusters(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, logger logr.Logger) (bool, clusterv1.ClusterList, error) {
272288
var clusterList clusterv1.ClusterList
273289
foundMissingResourcesOnAnyCluster := false
@@ -460,7 +476,7 @@ func (r *Reconciler) reestablishWatchesForExistingResources(ctx context.Context,
460476
}
461477

462478
//nolint:unparam // ctrl.Result is required for controller-runtime reconciler pattern
463-
func (r *Reconciler) applyResourcesToClusters(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, clusterList clusterv1.ClusterList, currentCommitHash string, proxyNamespacedName types.NamespacedName, logger logr.Logger) (ctrl.Result, error) {
479+
func (r *Reconciler) applyResourcesToClusters(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, clusterList clusterv1.ClusterList, proxyNamespacedName types.NamespacedName, logger logr.Logger) (ctrl.Result, error) {
464480
logger.Info("Proceeding with application of resources to target clusters.")
465481

466482
// Ensure clusterList is populated if needed
@@ -492,8 +508,8 @@ func (r *Reconciler) applyResourcesToClusters(ctx context.Context, cdk8sAppProxy
492508
logger.Info("No parsed resources to apply, skipping application to clusters.")
493509
cdk8sAppProxy.Status.ObservedGeneration = cdk8sAppProxy.Generation
494510
conditions.MarkTrue(cdk8sAppProxy, addonsv1alpha1.DeploymentProgressingCondition)
495-
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" && currentCommitHash != "" {
496-
cdk8sAppProxy.Status.LastProcessedGitHash = currentCommitHash
511+
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
512+
//cdk8sAppProxy.Status.LastProcessedGitHash = currentCommitHash
497513
}
498514
if err := r.Status().Update(ctx, cdk8sAppProxy); err != nil {
499515
logger.Error(err, "Failed to update status when no resources to apply")
@@ -557,8 +573,8 @@ func (r *Reconciler) applyResourcesToClusters(ctx context.Context, cdk8sAppProxy
557573

558574
// If we reach here, the overallSuccess is true.
559575
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
560-
cdk8sAppProxy.Status.LastProcessedGitHash = currentCommitHash
561-
logger.Info("Successfully updated LastProcessedGitHash in status after application", "hash", currentCommitHash)
576+
//cdk8sAppProxy.Status.LastProcessedGitHash = currentCommitHash
577+
//logger.Info("Successfully updated LastProcessedGitHash in status after application", "hash", currentCommitHash)
562578
}
563579

564580
cdk8sAppProxy.Status.ObservedGeneration = cdk8sAppProxy.Generation

controllers/cdk8sappproxy/git/git.go

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,28 +59,30 @@ func (g *GitImplementer) Poll(repoUrl string, branch string, directory string, w
5959

6060
err = validateRepoUrl(repoUrl, writer)
6161
if err != nil {
62-
fmt.Fprintf(writer, "%s", addonsv1alpha1.GitHashFailureReason)
62+
fmt.Fprintf(writer, "%s", addonsv1alpha1.InvalidGitRepositoryReason)
6363

6464
return detectedChanges, err
6565
}
6666
if directory == "" {
67-
fmt.Fprintf(writer, "%s", addonsv1alpha1.GitHashFailureReason)
67+
fmt.Fprintf(writer, "%s", addonsv1alpha1.EmptyGitRepositoryReason)
6868

6969
return detectedChanges, err
7070
}
7171

7272
// get hash from local repo
7373
localHash, err := localGitHash(directory, writer)
7474
if err != nil {
75-
fmt.Fprintf(writer, "%s", addonsv1alpha1.GitHashFailureReason)
75+
//fmt.Fprintf(writer, "%s", addonsv1alpha1.GitHashFailureReason)
76+
fmt.Fprintf(writer, "localGitHash error")
7677

7778
return detectedChanges, err
7879
}
7980

8081
// Get Hash from remote repo
8182
remoteHash, err := remoteGitHash(repoUrl, branch, writer)
8283
if err != nil {
83-
fmt.Fprintf(writer, "%s", addonsv1alpha1.GitHashFailureReason)
84+
//fmt.Fprintf(writer, "%s", addonsv1alpha1.GitHashFailureReason)
85+
fmt.Fprintf(writer, "remoteGitHash error")
8486

8587
return detectedChanges, err
8688
}
@@ -118,17 +120,20 @@ func localGitHash(directory string, writer *bytes.Buffer) (hash string, err erro
118120
hash = "0"
119121
repo, err := git.PlainOpen(directory)
120122
if err != nil {
121-
return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
123+
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
124+
return hash, fmt.Errorf("failed to open local git repository: %v", err)
122125
}
123126

124127
headRef, err := repo.Head()
125128
if err != nil {
126-
return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
129+
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
130+
return hash, fmt.Errorf("failed to get head for local git repo: %v", err)
127131
}
128132

129133
hash = headRef.Hash().String()
130134
if hash == "" {
131-
return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
135+
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
136+
return hash, fmt.Errorf("failed to retrieve hash for local git repo")
132137
}
133138

134139
return hash, err
@@ -149,7 +154,8 @@ func remoteGitHash(repoUrl string, branch string, writer *bytes.Buffer) (hash st
149154

150155
refs, err := repo.List(&git.ListOptions{})
151156
if err != nil {
152-
return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
157+
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
158+
return hash, fmt.Errorf("failed to list remote refs: %v", err)
153159
}
154160

155161
refName := plumbing.NewBranchReferenceName(branch)
@@ -159,5 +165,6 @@ func remoteGitHash(repoUrl string, branch string, writer *bytes.Buffer) (hash st
159165
}
160166
}
161167

162-
return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
168+
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
169+
return hash, fmt.Errorf("failed to find remote ref for branch %s: %v", branch, refs)
163170
}

0 commit comments

Comments
 (0)