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

Commit 0c2d2a2

Browse files
committed
refactoring
1 parent 6fdd3e9 commit 0c2d2a2

File tree

5 files changed

+18
-187
lines changed

5 files changed

+18
-187
lines changed

controllers/cdk8sappproxy/cdk8sappproxy_controller.go

Lines changed: 0 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -186,71 +186,6 @@ func (r *Reconciler) parseManifestFiles(manifestFiles []string, logger logr.Logg
186186
return parsedResources, nil
187187
}
188188

189-
func (r *Reconciler) deleteResourcesFromClusters(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, logger logr.Logger) error {
190-
// Get target clusters
191-
clusterList, err := r.getTargetClustersForDeletion(ctx, cdk8sAppProxy, logger)
192-
if err != nil {
193-
return err
194-
}
195-
196-
// Delete resources from each cluster
197-
for _, cluster := range clusterList.Items {
198-
clusterLogger := logger.WithValues("targetCluster", cluster.Name)
199-
200-
dynamicClient, err := r.getDynamicClientForCluster(ctx, cdk8sAppProxy.Namespace, cluster.Name)
201-
if err != nil {
202-
clusterLogger.Error(err, "Failed to get dynamic client for cluster during deletion, skipping this cluster")
203-
204-
continue
205-
}
206-
207-
clusterLogger.Info("Successfully created dynamic client for cluster deletion")
208-
209-
for _, resource := range parsedResources {
210-
gvr := resource.GroupVersionKind().GroupVersion().WithResource(getPluralFromKind(resource.GetKind()))
211-
clusterLogger.Info("Deleting resource from cluster", "GVK", resource.GroupVersionKind().String(), "Name", resource.GetName(), "Namespace", resource.GetNamespace())
212-
213-
err := dynamicClient.Resource(gvr).Namespace(resource.GetNamespace()).Delete(ctx, resource.GetName(), metav1.DeleteOptions{})
214-
215-
switch {
216-
case err != nil && !apierrors.IsNotFound(err):
217-
clusterLogger.Error(err, "Failed to delete resource from cluster", "resourceName", resource.GetName())
218-
case apierrors.IsNotFound(err):
219-
clusterLogger.Info("Resource already deleted from cluster", "resourceName", resource.GetName())
220-
case err == nil:
221-
clusterLogger.Info("Successfully deleted resource from cluster", "resourceName", resource.GetName())
222-
}
223-
}
224-
}
225-
226-
return nil
227-
}
228-
229-
func (r *Reconciler) getTargetClustersForDeletion(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (*clusterv1.ClusterList, error) {
230-
clusterList := &clusterv1.ClusterList{}
231-
selector, err := metav1.LabelSelectorAsSelector(&cdk8sAppProxy.Spec.ClusterSelector)
232-
if err != nil {
233-
logger.Error(err, "failed to parse ClusterSelector during deletion")
234-
235-
return nil, err
236-
}
237-
238-
logger.Info("Listing clusters for deletion", "selector", selector.String(), "namespace", cdk8sAppProxy.Namespace)
239-
if err := r.List(ctx, clusterList, client.MatchingLabelsSelector{Selector: selector}, client.InNamespace(cdk8sAppProxy.Namespace)); err != nil {
240-
logger.Error(err, "Failed to list clusters during deletion, requeuing")
241-
242-
return nil, err
243-
}
244-
245-
clusterNames := make([]string, 0, len(clusterList.Items))
246-
for _, c := range clusterList.Items {
247-
clusterNames = append(clusterNames, c.Name)
248-
}
249-
logger.Info("Found clusters for deletion", "count", len(clusterList.Items), "names", clusterNames)
250-
251-
return clusterList, nil
252-
}
253-
254189
func (r *Reconciler) finalizeDeletion(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, proxyNamespacedName types.NamespacedName, logger logr.Logger) error {
255190
logger.Info("Starting finalization process")
256191

controllers/cdk8sappproxy/cdk8sappproxy_git_operator.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ import (
88
"path/filepath"
99
)
1010

11-
func (r *Reconciler) prepareSource(cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (appSourcePath string, currentCommitHash string, err error) {
11+
func (r *Reconciler) prepareSource(cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (appSourcePath string, err error) {
1212
gitImpl := &gitoperator.GitImplementer{}
1313
var buf bytes.Buffer
1414
gitSpec := cdk8sAppProxy.Spec.GitRepository
1515

1616
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
17-
1817
directory, err := gitImpl.Clone(gitSpec.URL, &buf)
1918
if err != nil {
2019
logger.Error(err, addonsv1alpha1.GitCloneFailedCondition, "Failed to clone git repository")
@@ -25,7 +24,7 @@ func (r *Reconciler) prepareSource(cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy,
2524
logger.Error(err, addonsv1alpha1.GitHashFailureReason, "Failed to get local git hash")
2625
}
2726

28-
currentCommitHash = retrieveCommitHash
27+
currentCommitHash := retrieveCommitHash
2928
if currentCommitHash != "" && cdk8sAppProxy != nil {
3029
cdk8sAppProxy.Status.LastRemoteGitHash = currentCommitHash
3130
logger.Info("Updated cdk8sAppProxy.Status.LastRemoteGitHash with the latest commit hash from remote", "lastRemoteGitHash", currentCommitHash)
@@ -36,8 +35,8 @@ func (r *Reconciler) prepareSource(cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy,
3635
logger.Info("Adjusted appSourcePath for repository subpath", "subPath", gitSpec.Path, "finalPath", appSourcePath)
3736
}
3837

39-
return appSourcePath, currentCommitHash, err
38+
return appSourcePath, err
4039
}
4140

42-
return appSourcePath, currentCommitHash, nil
41+
return appSourcePath, err
4342
}

controllers/cdk8sappproxy/cdk8sappproxy_reconciler.go

Lines changed: 9 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
8989
}
9090

9191
// Prepare a source path and get current commit hash
92-
appSourcePath, _, err := r.prepareSource(cdk8sAppProxy, logger)
92+
appSourcePath, err := r.prepareSource(cdk8sAppProxy, logger)
9393
if err != nil {
9494
return ctrl.Result{}, err
9595
}
@@ -108,10 +108,9 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
108108
}
109109

110110
// Determine if apply is needed
111-
_, clusterList, err := r.applyNeeded(ctx, cdk8sAppProxy, parsedResources, logger)
111+
clusterList, err := r.applyNeeded(ctx, cdk8sAppProxy, parsedResources, logger)
112112
if err != nil {
113113
logger.Error(err, "Failed to determine if apply is needed")
114-
//return ctrl.Result{}, err
115114
}
116115

117116
_, err = r.applyResourcesToClusters(ctx, cdk8sAppProxy, parsedResources, clusterList, proxyNamespacedName, logger)
@@ -146,7 +145,7 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
146145
}
147146
if polling {
148147
logger.Info("Detected changes in git repository, proceeding with reconciliation.")
149-
appSourcePath, _, err = r.prepareSource(cdk8sAppProxy, logger)
148+
appSourcePath, err = r.prepareSource(cdk8sAppProxy, logger)
150149
if err != nil {
151150
logger.Error(err, "Prepare source for reconciliation")
152151
}
@@ -169,17 +168,17 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
169168
if len(parsedResources) == 0 {
170169
if err := r.handleNoResources(ctx, cdk8sAppProxy, logger); err != nil {
171170
logger.Error(err, "Failed to handle no resources case")
171+
172172
return
173173
}
174174

175175
logger.Info("No valid Kubernetes resources parsed from manifest files, skipping apply.")
176176
}
177177

178178
// Determine if apply is needed
179-
_, clusterList, err := r.applyNeeded(ctx, cdk8sAppProxy, parsedResources, logger)
179+
clusterList, err := r.applyNeeded(ctx, cdk8sAppProxy, parsedResources, logger)
180180
if err != nil {
181181
logger.Error(err, "Failed to determine if apply is needed")
182-
//return ctrl.Result{}, err
183182
}
184183

185184
_, err = r.applyResourcesToClusters(ctx, cdk8sAppProxy, parsedResources, clusterList, proxyNamespacedName, logger)
@@ -191,6 +190,7 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
191190
}
192191
case <-ctx.Done():
193192
logger.Info("Stopping git repository polling loop due to context cancellation.")
193+
194194
return
195195
}
196196
}
@@ -228,16 +228,16 @@ func (r *Reconciler) handleNoResources(ctx context.Context, cdk8sAppProxy *addon
228228
return nil
229229
}
230230

231-
func (r *Reconciler) applyNeeded(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, logger logr.Logger) (bool, clusterv1.ClusterList, error) {
231+
func (r *Reconciler) applyNeeded(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, logger logr.Logger) (clusterv1.ClusterList, error) {
232232
var clusterList clusterv1.ClusterList
233233

234234
_, list, err := r.verifyResourcesOnClusters(ctx, cdk8sAppProxy, parsedResources, logger)
235235
if err != nil {
236-
return false, clusterList, err
236+
return clusterList, err
237237
}
238238
clusterList = list
239239

240-
return true, clusterList, nil
240+
return clusterList, nil
241241
}
242242

243243
func (r *Reconciler) verifyResourcesOnClusters(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, parsedResources []*unstructured.Unstructured, logger logr.Logger) (bool, clusterv1.ClusterList, error) {
@@ -305,107 +305,6 @@ func (r *Reconciler) verifyResourcesOnClusters(ctx context.Context, cdk8sAppProx
305305
return foundMissingResourcesOnAnyCluster, clusterList, nil
306306
}
307307

308-
func (r *Reconciler) checkGitOrAnnotationTriggers(cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, currentCommitHash string, forceSynthAndApplyDueToDeletion bool, logger logr.Logger) bool {
309-
// Check for periodic git poller trigger
310-
if cdk8sAppProxy.Status.LastRemoteGitHash != "" &&
311-
cdk8sAppProxy.Status.LastRemoteGitHash != cdk8sAppProxy.Status.LastProcessedGitHash &&
312-
cdk8sAppProxy.Status.LastRemoteGitHash != currentCommitHash {
313-
logger.Info("Reconciliation proceeding due to change detected by git poller.",
314-
"lastRemoteGitHash", cdk8sAppProxy.Status.LastRemoteGitHash,
315-
"lastProcessedGitHash", cdk8sAppProxy.Status.LastProcessedGitHash,
316-
"currentCommitHash", currentCommitHash)
317-
318-
return true
319-
}
320-
321-
// Check for git repository changes
322-
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
323-
if currentCommitHash == "" {
324-
logger.Info("currentCommitHash is unexpectedly empty for Git source; proceeding with update as a precaution.")
325-
326-
return true
327-
}
328-
329-
lastProcessedGitHash := cdk8sAppProxy.Status.LastProcessedGitHash
330-
gitSpecRef := cdk8sAppProxy.Spec.GitRepository.Reference
331-
repositoryHasChanged := currentCommitHash != lastProcessedGitHash
332-
isInitialDeployment := lastProcessedGitHash == ""
333-
334-
if isInitialDeployment {
335-
logger.Info("Initial deployment or no last processed hash found. Proceeding with cdk8s synth and apply.", "currentCommitHash", currentCommitHash, "reference", gitSpecRef)
336-
337-
return true
338-
}
339-
if repositoryHasChanged {
340-
logger.Info("Git repository has changed (current clone vs last processed), proceeding with update.", "currentCommitHash", currentCommitHash, "lastProcessedGitHash", lastProcessedGitHash, "reference", gitSpecRef)
341-
342-
return true
343-
}
344-
logger.Info("No new Git changes detected (current clone matches last processed, and no pending poller detection).", "commitHash", currentCommitHash, "reference", gitSpecRef)
345-
} else if cdk8sAppProxy.Status.ObservedGeneration == 0 {
346-
logger.Info("Initial processing for source type without explicit change detection. Proceeding with cdk8s synth and apply.")
347-
348-
return true
349-
}
350-
351-
// Check for deletion trigger
352-
if forceSynthAndApplyDueToDeletion {
353-
logger.Info("Forcing synth and apply because reconciliation was triggered by a resource deletion")
354-
355-
return true
356-
}
357-
358-
return false
359-
}
360-
361-
func (r *Reconciler) reestablishWatchesForExistingResources(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) error {
362-
// Get the source and parse resources to know what should be watched
363-
appSourcePath, _, err := r.prepareSource(cdk8sAppProxy, logger)
364-
if err != nil {
365-
return err
366-
}
367-
368-
parsedResources, err := r.synthesizeAndParseResources(appSourcePath, logger)
369-
if err != nil {
370-
return err
371-
}
372-
373-
// Get target clusters
374-
selector, err := metav1.LabelSelectorAsSelector(&cdk8sAppProxy.Spec.ClusterSelector)
375-
if err != nil {
376-
return err
377-
}
378-
379-
var clusterList clusterv1.ClusterList
380-
if err := r.List(ctx, &clusterList, client.MatchingLabelsSelector{Selector: selector}); err != nil {
381-
return err
382-
}
383-
384-
proxyNamespacedName := types.NamespacedName{Name: cdk8sAppProxy.Name, Namespace: cdk8sAppProxy.Namespace}
385-
386-
// Re-establish watches for each resource on each cluster
387-
for _, cluster := range clusterList.Items {
388-
dynamicClient, err := r.getDynamicClientForCluster(ctx, cluster.Namespace, cluster.Name)
389-
if err != nil {
390-
logger.Error(err, "Failed to get dynamic client for watch re-establishment", "cluster", cluster.Name)
391-
392-
continue
393-
}
394-
395-
for _, resource := range parsedResources {
396-
gvk := resource.GroupVersionKind()
397-
398-
if err := r.WatchManager.StartWatch(ctx, dynamicClient, gvk, resource.GetNamespace(), resource.GetName(), proxyNamespacedName); err != nil {
399-
logger.Error(err, "Failed to re-establish watch", "cluster", cluster.Name, "resource", resource.GetName())
400-
} else {
401-
logger.Info("Re-established watch for existing resource", "cluster", cluster.Name, "resource", resource.GetName())
402-
}
403-
}
404-
}
405-
406-
return nil
407-
}
408-
409308
//nolint:unparam // ctrl.Result is required for controller-runtime reconciler pattern
410309
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) {
411310
logger.Info("Proceeding with application of resources to target clusters.")
@@ -440,7 +339,6 @@ func (r *Reconciler) applyResourcesToClusters(ctx context.Context, cdk8sAppProxy
440339
cdk8sAppProxy.Status.ObservedGeneration = cdk8sAppProxy.Generation
441340
conditions.MarkTrue(cdk8sAppProxy, addonsv1alpha1.DeploymentProgressingCondition)
442341
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
443-
//cdk8sAppProxy.Status.LastProcessedGitHash = currentCommitHash
444342
}
445343
if err := r.Status().Update(ctx, cdk8sAppProxy); err != nil {
446344
logger.Error(err, "Failed to update status when no resources to apply")
@@ -504,8 +402,6 @@ func (r *Reconciler) applyResourcesToClusters(ctx context.Context, cdk8sAppProxy
504402

505403
// If we reach here, the overallSuccess is true.
506404
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
507-
//cdk8sAppProxy.Status.LastProcessedGitHash = currentCommitHash
508-
//logger.Info("Successfully updated LastProcessedGitHash in status after application", "hash", currentCommitHash)
509405
}
510406

511407
cdk8sAppProxy.Status.ObservedGeneration = cdk8sAppProxy.Generation

controllers/cdk8sappproxy/git/git.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func (g *GitImplementer) Clone(repoUrl string, writer *bytes.Buffer) (directory
3131

3232
directory, err = os.MkdirTemp("", tempDirPattern)
3333
if err != nil {
34-
return directory, fmt.Errorf("failed to create temporary directory: %v", err)
34+
return directory, fmt.Errorf("failed to create temporary directory: %w", err)
3535
}
3636

3737
// Check if repo and directory are empty.
@@ -102,7 +102,7 @@ func (g *GitImplementer) Hash(repo string, branch string) (hash string, err erro
102102
refs, err := remoterepo.List(&git.ListOptions{})
103103
if err != nil {
104104
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
105-
return hash, fmt.Errorf("failed to list remote refs: %v", err)
105+
return hash, fmt.Errorf("failed to list remote refs: %w", err)
106106
}
107107

108108
refName := plumbing.NewBranchReferenceName(branch)
@@ -118,7 +118,7 @@ func (g *GitImplementer) Hash(repo string, branch string) (hash string, err erro
118118
localRepo, err := git.PlainOpen(repo)
119119
if err != nil {
120120
//return hash, fmt.Errorf("%s", addonsv1alpha1.GitHashFailureReason)
121-
return hash, fmt.Errorf("failed to open local git repository: %v", err)
121+
return hash, fmt.Errorf("failed to open local git repository: %w", err)
122122
}
123123

124124
headRef, err := localRepo.Head()
@@ -135,6 +135,7 @@ func (g *GitImplementer) Hash(repo string, branch string) (hash string, err erro
135135

136136
return hash, err
137137
}
138+
138139
return hash, err
139140
}
140141

controllers/cdk8sappproxy/git/git_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -897,7 +897,7 @@ func TestEmptyChecker(t *testing.T) {
897897
}
898898
}
899899

900-
// Helper functions
900+
// Helper functions.
901901
func setupTestRepo(t *testing.T) string {
902902
t.Helper()
903903
tempDir := t.TempDir()

0 commit comments

Comments
 (0)