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

Commit df7c633

Browse files
committed
cleanup
1 parent 1624e97 commit df7c633

File tree

8 files changed

+103
-157
lines changed

8 files changed

+103
-157
lines changed

Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ RUN apt-get update && \
8080
apt-get install -y --no-install-recommends ca-certificates=20240203~22.04.1 curl=7.81.0-1ubuntu1.20 && \
8181
curl -fsSL https://deb.nodesource.com/setup_18.x | bash - && \
8282
apt-get install -y nodejs=18.19.1-1nodesource1 && \
83-
npm install -g [email protected].108 && \
83+
npm install -g [email protected].109 && \
8484
curl -fsSL -o go1.24.4.linux-amd64.tar.gz https://go.dev/dl/go1.24.4.linux-amd64.tar.gz && \
8585
tar -C /usr/local -xzf go1.24.4.linux-amd64.tar.gz && \
8686
rm go1.24.4.linux-amd64.tar.gz && \

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.22
234+
TAG ?= v0.3.2-preview.24
235235
ARCH ?= $(shell go env GOARCH)
236236
ALL_ARCH = amd64 arm arm64
237237

README.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,24 +36,25 @@ The `Cdk8sAppProxy` CustomResourceDefinition (CRD) is used to manage the deploym
3636

3737
### Example Manifest
3838

39-
An example of a `Cdk8sAppProxy` manifest can be found in [`examples/cdk8sappproxy_sample.yaml`](./examples/cdk8sappproxy_sample.yaml). Below is a snippet:
39+
An example of a `Cdk8sAppProxy` manifest can be found in [`examples/cdk8sappproxy_sample-go.yaml`](./examples/cdk8sappproxy_sample.yaml). Below is a snippet:
4040

4141
```yaml
4242
apiVersion: addons.cluster.x-k8s.io/v1alpha1
4343
kind: Cdk8sAppProxy
4444
metadata:
45-
name: cdk8s-sample-app
45+
name: cdk8s-sample-app-go
4646
namespace: default
4747
spec:
4848
gitRepository:
49-
url: "https://github.com/PatrickLaabs/cluster-api-addon-provider-cdk8s/examples/cdk8s-sample-deployment"
49+
url: "https://github.com/PatrickLaabs/cluster-api-addon-provider-cdk8s"
5050
reference: "main"
51-
path: "."
51+
referencePollInterval: '5'
52+
path: "examples/cdk8s-sample-deployment"
5253
# authSecretRef:
5354
# name: git-credentials
5455
clusterSelector: {}
55-
# matchLabels:
56-
# environment: development
56+
# matchLabels:
57+
# environment: development
5758
# ---
5859
# apiVersion: v1
5960
# kind: Secret

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.21
10+
- image: ghcr.io/patricklaabs/cluster-api-addon-provider-cdk8s/cluster-api-cdk8s-controller:v0.3.2-preview.24
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.21
10+
- image: ghcr.io/patricklaabs/cluster-api-addon-provider-cdk8s/cluster-api-cdk8s-controller:v0.3.2-preview.24
1111
name: manager

controllers/cdk8sappproxy/cdk8sappproxy_controller.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -139,12 +139,12 @@ func (r *Reconciler) synthesizeAndParseResources(appSourcePath string, logger lo
139139
func (r *Reconciler) synthesizeCdk8sApp(appSourcePath string, logger logr.Logger, operation string) error {
140140
logger.Info("Synthesizing cdk8s application", "effectiveSourcePath", appSourcePath, "operation", OperationSynthesize)
141141

142-
npmInstall := cmdRunnerFactory("npm", "install")
143-
npmInstall.SetDir(appSourcePath)
144-
output, err := npmInstall.CombinedOutput()
145-
if err != nil {
146-
logger.Error(err, "npm installation failed", "output", string(output), "operation:", OperationNpmInstall)
147-
}
142+
// npmInstall := cmdRunnerFactory("npm", "install")
143+
// npmInstall.SetDir(appSourcePath)
144+
// output, err := npmInstall.CombinedOutput()
145+
// if err != nil {
146+
// logger.Error(err, "npm installation failed", "output", string(output), "operation:", OperationNpmInstall)
147+
// }
148148

149149
synthCmd := cmdRunnerFactory("cdk8s", "synth")
150150
synthCmd.SetDir(appSourcePath)
@@ -156,6 +156,7 @@ func (r *Reconciler) synthesizeCdk8sApp(appSourcePath string, logger logr.Logger
156156
}
157157

158158
logger.Info("cdk8s synth successful", "outputSummary", truncateString(string(output), 200), "operation", operation)
159+
159160
return nil
160161
}
161162

controllers/cdk8sappproxy/cdk8sappproxy_git_operator.go

Lines changed: 82 additions & 138 deletions
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,6 @@ func (r *Reconciler) cloneGitRepository(ctx context.Context, cdk8sAppProxy *addo
9696
return nil
9797
}
9898

99-
func getPollInterval(c *addonsv1alpha1.Cdk8sAppProxy) time.Duration {
100-
if c.Spec.GitRepository != nil && c.Spec.GitRepository.ReferencePollInterval != nil {
101-
return c.Spec.GitRepository.ReferencePollInterval.Duration
102-
}
103-
return 5 * time.Minute // default
104-
}
105-
10699
// pollGitRepository periodically checks the remote git repository for changes.
107100
func (r *Reconciler) pollGitRepository(ctx context.Context, proxyName types.NamespacedName) {
108101
logger := log.FromContext(ctx).WithValues("cdk8sappproxy", proxyName.String(), "goroutine", "pollGitRepository")
@@ -114,7 +107,13 @@ func (r *Reconciler) pollGitRepository(ctx context.Context, proxyName types.Name
114107

115108
return
116109
}
117-
pollInterval := getPollInterval(cdk8sAppProxy)
110+
111+
var pollInterval time.Duration
112+
if cdk8sAppProxy.Spec.GitRepository.ReferencePollInterval == nil {
113+
pollInterval = 5 * time.Minute
114+
} else {
115+
pollInterval = cdk8sAppProxy.Spec.GitRepository.ReferencePollInterval.Duration
116+
}
118117

119118
ticker := time.NewTicker(pollInterval)
120119
defer ticker.Stop()
@@ -156,58 +155,6 @@ func (r *Reconciler) pollGitRepositoryOnce(ctx context.Context, proxyName types.
156155
return r.handleGitRepositoryChange(ctx, proxyName, cdk8sAppProxy, remoteCommitHash, logger)
157156
}
158157

159-
func (r *Reconciler) prepareSourceForDeletion(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (string, func(), error) {
160-
if cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "" {
161-
return r.prepareGitSourceForDeletion(ctx, cdk8sAppProxy, logger)
162-
}
163-
164-
err := errors.New("GitRepository not specified, cannot determine resources to delete")
165-
logger.Info(err.Error())
166-
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.SourceNotSpecifiedReason, "Cannot determine resources to delete during deletion", err, true)
167-
168-
return "", func() {}, err
169-
}
170-
171-
func (r *Reconciler) prepareGitSourceForDeletion(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (string, func(), error) {
172-
gitSpec := cdk8sAppProxy.Spec.GitRepository
173-
logger.Info("Using GitRepository source for deletion logic", "url", gitSpec.URL, "reference", gitSpec.Reference, "path", gitSpec.Path)
174-
175-
tempDir, err := os.MkdirTemp("", "cdk8s-git-delete-")
176-
if err != nil {
177-
logger.Error(err, "failed to create temp dir for git clone during deletion")
178-
179-
return "", func() {}, err
180-
}
181-
182-
cleanupFunc := func() {
183-
if err := os.RemoveAll(tempDir); err != nil {
184-
logger.Error(err, "Failed to remove temporary clone directory for deletion", "tempDir", tempDir)
185-
}
186-
}
187-
188-
logger.Info("Created temporary directory for clone during deletion", "tempDir", tempDir)
189-
190-
if err := r.cloneGitRepository(ctx, nil, gitSpec, tempDir, logger, OperationDeletion); err != nil {
191-
cleanupFunc()
192-
193-
return "", func() {}, err
194-
}
195-
196-
if err := r.checkoutGitReference(ctx, nil, gitSpec, tempDir, logger, OperationDeletion); err != nil {
197-
cleanupFunc()
198-
199-
return "", func() {}, err
200-
}
201-
202-
appSourcePath := tempDir
203-
if gitSpec.Path != "" {
204-
appSourcePath = filepath.Join(tempDir, gitSpec.Path)
205-
logger.Info("Adjusted appSourcePath for deletion", "subPath", gitSpec.Path, "finalPath", appSourcePath)
206-
}
207-
208-
return appSourcePath, cleanupFunc, nil
209-
}
210-
211158
func (r *Reconciler) findRemoteCommitHash(refs []*plumbing.Reference, refName plumbing.ReferenceName, logger logr.Logger) (string, error) {
212159
// First, try to find the exact reference
213160
for _, ref := range refs {
@@ -330,111 +277,108 @@ func (r *Reconciler) updateRemoteGitHashStatus(ctx context.Context, proxyName ty
330277
return nil
331278
}
332279

333-
func (r *Reconciler) prepareSource(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, proxyNamespacedName types.NamespacedName, logger logr.Logger) (string, string, func(), error) {
280+
// prepareSource determines the source path for cdk8s application files, handling Git or local paths.
281+
// It returns the application source path, current commit hash (if applicable), a cleanup function, and an error.
282+
// The 'operation' parameter informs logging and error handling, especially for deletion scenarios.
283+
func (r *Reconciler) prepareSource(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, proxyNamespacedName types.NamespacedName, logger logr.Logger, operation string) (string, string, func(), error) {
334284
var appSourcePath string
335285
var currentCommitHash string
336286
var cleanupFunc func()
337287

338288
switch {
339289
case cdk8sAppProxy.Spec.GitRepository != nil && cdk8sAppProxy.Spec.GitRepository.URL != "":
340-
path, hash, cleanup, err := r.prepareGitSource(ctx, cdk8sAppProxy, logger)
290+
gitSpec := cdk8sAppProxy.Spec.GitRepository
291+
logger.Info("Determined source type: GitRepository", "url", gitSpec.URL, "reference", gitSpec.Reference, "path", gitSpec.Path, "operation", operation)
292+
293+
tempDirPattern := "cdk8s-git-clone-"
294+
if operation == OperationDeletion {
295+
tempDirPattern = "cdk8s-git-delete-"
296+
}
297+
tempDir, err := os.MkdirTemp("", tempDirPattern)
341298
if err != nil {
299+
logger.Error(err, "Failed to create temp directory for git clone", "operation", operation)
300+
// For normal operation, update status. For deletion, the Cdk8sAppProxy might be nil or finalizer needs removal.
301+
if operation == OperationNormal && cdk8sAppProxy != nil {
302+
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.GitCloneFailedReason, "Failed to create temp dir for git clone", err, false)
303+
}
304+
342305
return "", "", nil, err
343306
}
344-
appSourcePath = path
345-
currentCommitHash = hash
346-
cleanupFunc = cleanup
347-
348-
// Store current commit hash in status
349-
if currentCommitHash != "" {
350-
cdk8sAppProxy.Status.LastRemoteGitHash = currentCommitHash
351-
logger.Info("Updated cdk8sAppProxy.Status.LastRemoteGitHash with the latest commit hash from remote", "lastRemoteGitHash", currentCommitHash)
352-
}
353307

354-
// Stop any existing git poller for a local path
355-
if cancel, ok := r.ActiveGitPollers[proxyNamespacedName]; ok {
356-
logger.Info("GitRepository spec removed or empty, stopping existing git poller.")
357-
cancel()
358-
delete(r.ActiveGitPollers, proxyNamespacedName)
308+
cleanupFunc = func() {
309+
if err := os.RemoveAll(tempDir); err != nil {
310+
logger.Error(err, "Failed to remove temporary clone directory", "tempDir", tempDir, "operation", operation)
311+
}
359312
}
313+
logger.Info("Created temporary directory for clone", "tempDir", tempDir, "operation", operation)
360314

361-
default:
362-
err := errors.New("no source specified")
363-
logger.Error(err, "No source specified")
364-
if cancel, ok := r.ActiveGitPollers[proxyNamespacedName]; ok {
365-
logger.Info("Source spec is invalid or removed, stopping existing git poller.")
366-
cancel()
367-
delete(r.ActiveGitPollers, proxyNamespacedName)
315+
// Pass cdk8sAppProxy as nil if it's a deletion operation where status updates are handled differently or not needed.
316+
var proxyForGitOps *addonsv1alpha1.Cdk8sAppProxy
317+
if operation == OperationNormal {
318+
proxyForGitOps = cdk8sAppProxy
368319
}
369-
// Use the new consolidated error handler - removeFinalizer = false for normal operations
370-
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.SourceNotSpecifiedReason, "No GitRepository specified", err, false)
371-
372-
return "", "", nil, err
373-
}
374-
375-
return appSourcePath, currentCommitHash, cleanupFunc, nil
376-
}
377320

378-
func (r *Reconciler) prepareGitSource(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) (string, string, func(), error) {
379-
gitSpec := cdk8sAppProxy.Spec.GitRepository
380-
logger.Info("Determined source type: GitRepository", "url", gitSpec.URL, "reference", gitSpec.Reference, "path", gitSpec.Path)
381-
382-
tempDir, err := os.MkdirTemp("", "cdk8s-git-clone-")
383-
if err != nil {
384-
logger.Error(err, "Failed to create temp directory for git clone")
385-
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.GitCloneFailedReason, "Failed to create temp dir for git clone", err, false)
321+
if err := r.cloneGitRepository(ctx, proxyForGitOps, gitSpec, tempDir, logger, operation); err != nil {
322+
cleanupFunc()
386323

387-
return "", "", nil, err
388-
}
389-
390-
cleanupFunc := func() {
391-
if err := os.RemoveAll(tempDir); err != nil {
392-
logger.Error(err, "Failed to remove temporary clone directory", "tempDir", tempDir)
324+
return "", "", nil, err
393325
}
394-
}
395326

396-
logger.Info("Created temporary directory for clone", "tempDir", tempDir)
327+
if err := r.checkoutGitReference(ctx, proxyForGitOps, gitSpec, tempDir, logger, operation); err != nil {
328+
cleanupFunc()
397329

398-
// Clone repository
399-
if err := r.cloneGitRepository(ctx, cdk8sAppProxy, gitSpec, tempDir, logger, OperationNormal); err != nil {
400-
cleanupFunc()
401-
402-
return "", "", nil, err
403-
}
330+
return "", "", nil, err
331+
}
404332

405-
// Checkout-specific reference if specified
406-
if err := r.checkoutGitReference(ctx, cdk8sAppProxy, gitSpec, tempDir, logger, OperationNormal); err != nil {
407-
cleanupFunc()
333+
appSourcePath = tempDir
334+
if gitSpec.Path != "" {
335+
appSourcePath = filepath.Join(tempDir, gitSpec.Path)
336+
logger.Info("Adjusted appSourcePath for repository subpath", "subPath", gitSpec.Path, "finalPath", appSourcePath, "operation", operation)
337+
}
408338

409-
return "", "", nil, err
410-
}
339+
// Only get commit hash for normal operations, not for deletion prep.
340+
if operation == OperationNormal {
341+
logger.Info("Attempting to retrieve current commit hash from Git repository", "repoDir", tempDir)
342+
repo, err := git.PlainOpen(tempDir)
343+
if err != nil {
344+
cleanupFunc()
345+
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.GitCloneFailedReason, "Failed to open git repository post-clone: "+err.Error(), err, false)
411346

412-
// Determine a final app source path
413-
appSourcePath := tempDir
414-
if gitSpec.Path != "" {
415-
appSourcePath = filepath.Join(tempDir, gitSpec.Path)
416-
logger.Info("Adjusted appSourcePath for repository subpath", "subPath", gitSpec.Path, "finalPath", appSourcePath)
417-
}
347+
return "", "", nil, err
348+
}
349+
headRef, err := repo.Head()
350+
if err != nil {
351+
cleanupFunc()
352+
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.GitCloneFailedReason, "Failed to get HEAD reference from git repository post-clone: "+err.Error(), err, false)
418353

419-
// Get current commit hash inline
420-
logger.Info("Attempting to retrieve current commit hash from Git repository", "repoDir", tempDir)
421-
repo, err := git.PlainOpen(tempDir)
422-
if err != nil {
423-
cleanupFunc()
354+
return "", "", nil, err
355+
}
356+
currentCommitHash = headRef.Hash().String()
357+
logger.Info("Successfully retrieved current commit hash from Git repository", "commitHash", currentCommitHash)
424358

425-
return "", "", nil, r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.GitCloneFailedReason, "Failed to open git repository: "+err.Error(), err, false)
426-
}
359+
// Store current commit hash in status
360+
if currentCommitHash != "" && cdk8sAppProxy != nil {
361+
cdk8sAppProxy.Status.LastRemoteGitHash = currentCommitHash
362+
logger.Info("Updated cdk8sAppProxy.Status.LastRemoteGitHash with the latest commit hash from remote", "lastRemoteGitHash", currentCommitHash)
363+
}
364+
}
427365

428-
headRef, err := repo.Head()
429-
if err != nil {
430-
cleanupFunc()
366+
default:
367+
err := errors.New("no source specified (neither GitRepository nor LocalPath)")
368+
logger.Error(err, "No source specified", "operation", operation)
369+
if operation == OperationNormal { // Poller management and status updates for normal flow
370+
r.stopGitPoller(proxyNamespacedName, logger)
371+
if cdk8sAppProxy != nil {
372+
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.SourceNotSpecifiedReason, err.Error(), err, false)
373+
}
374+
} else if operation == OperationDeletion && cdk8sAppProxy != nil {
375+
// For deletion, if source can't be determined, we might still want to remove finalizer.
376+
_ = r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.SourceNotSpecifiedReason, "Cannot determine resources to delete: "+err.Error(), err, true)
377+
}
431378

432-
return "", "", nil, r.updateStatusWithError(ctx, cdk8sAppProxy, addonsv1alpha1.GitCloneFailedReason, "Failed to get HEAD reference from git repository: "+err.Error(), err, false)
379+
return "", "", nil, err
433380
}
434381

435-
currentCommitHash := headRef.Hash().String()
436-
logger.Info("Successfully retrieved current commit hash from Git repository", "commitHash", currentCommitHash)
437-
438382
return appSourcePath, currentCommitHash, cleanupFunc, nil
439383
}
440384

controllers/cdk8sappproxy/cdk8sappproxy_reconciler.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func (r *Reconciler) reconcileDelete(ctx context.Context, cdk8sAppProxy *addonsv
7171
}
7272

7373
// Get a source path for deletion
74-
appSourcePath, cleanup, err := r.prepareSourceForDeletion(ctx, cdk8sAppProxy, logger)
74+
appSourcePath, _, cleanup, err := r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationDeletion)
7575
if err != nil {
7676
return ctrl.Result{}, err
7777
}
@@ -114,7 +114,7 @@ func (r *Reconciler) reconcileNormal(ctx context.Context, cdk8sAppProxy *addonsv
114114
}
115115

116116
// Prepare a source path and get current commit hash
117-
appSourcePath, currentCommitHash, cleanup, err := r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger)
117+
appSourcePath, currentCommitHash, cleanup, err := r.prepareSource(ctx, cdk8sAppProxy, proxyNamespacedName, logger, OperationNormal)
118118
if err != nil {
119119
return ctrl.Result{}, err
120120
}
@@ -377,7 +377,7 @@ func (r *Reconciler) handleSkipApply(ctx context.Context, cdk8sAppProxy *addonsv
377377

378378
func (r *Reconciler) reestablishWatchesForExistingResources(ctx context.Context, cdk8sAppProxy *addonsv1alpha1.Cdk8sAppProxy, logger logr.Logger) error {
379379
// Get the source and parse resources to know what should be watched
380-
appSourcePath, _, cleanup, err := r.prepareSource(ctx, cdk8sAppProxy, types.NamespacedName{Name: cdk8sAppProxy.Name, Namespace: cdk8sAppProxy.Namespace}, logger)
380+
appSourcePath, _, cleanup, err := r.prepareSource(ctx, cdk8sAppProxy, types.NamespacedName{Name: cdk8sAppProxy.Name, Namespace: cdk8sAppProxy.Namespace}, logger, OperationNormal)
381381
if err != nil {
382382
return err
383383
}

0 commit comments

Comments
 (0)