@@ -17,26 +17,17 @@ limitations under the License.
1717package cdk8sappproxy
1818
1919import (
20- "bytes"
2120 "context"
22- "io/fs"
23- "os"
24- "os/exec"
25- "path/filepath"
2621 "strings"
2722
2823 addonsv1alpha1 "github.com/PatrickLaabs/cluster-api-addon-provider-cdk8s/api/v1alpha1"
29- "github.com/go-logr/logr"
3024 "github.com/pkg/errors"
3125 corev1 "k8s.io/api/core/v1"
3226 apierrors "k8s.io/apimachinery/pkg/api/errors"
3327 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
34- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
3528 "k8s.io/apimachinery/pkg/labels"
36- "k8s.io/apimachinery/pkg/runtime"
3729 "k8s.io/apimachinery/pkg/runtime/schema"
3830 "k8s.io/apimachinery/pkg/types"
39- k8syaml "k8s.io/apimachinery/pkg/util/yaml"
4031 "k8s.io/client-go/dynamic"
4132 "k8s.io/client-go/tools/clientcmd"
4233 clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
@@ -56,7 +47,7 @@ func (r *Reconciler) checkIfResourceExists(ctx context.Context, dynClient dynami
5647 if apierrors .IsNotFound (err ) {
5748 return false , nil
5849 }
59- // Some other error occurred
50+
6051 return false , errors .Wrapf (err , "failed to get namespaced resource %s/%s with GVR %s" , namespace , name , gvr .String ())
6152 }
6253 } else {
@@ -65,154 +56,20 @@ func (r *Reconciler) checkIfResourceExists(ctx context.Context, dynClient dynami
6556 if apierrors .IsNotFound (err ) {
6657 return false , nil
6758 }
68- // Some other error occurred
59+
6960 return false , errors .Wrapf (err , "failed to get cluster-scoped resource %s with GVR %s" , name , gvr .String ())
7061 }
7162 }
7263
7364 return true , nil
7465}
7566
76- func (r * Reconciler ) synthesizeAndParseResources (appSourcePath string , logger logr.Logger ) ([]* unstructured.Unstructured , error ) {
77- reason := addonsv1alpha1 .Cdk8sSynthFailedReason
78- // Synthesize cdk8s application
79- if err := r .synthesizeCdk8sApp (appSourcePath , logger , reason ); err != nil {
80- return nil , err
81- }
82-
83- // Find manifest files
84- manifestFiles , err := r .findManifestFiles (appSourcePath , logger , reason )
85- if err != nil {
86- return nil , err
87- }
88-
89- // Parse resources from manifest files using the consolidated function
90- return r .parseManifestFiles (manifestFiles , logger , reason )
91- }
92-
93- func (r * Reconciler ) synthesizeCdk8sApp (appSourcePath string , logger logr.Logger , operation string ) error {
94- logger .Info ("Synthesizing cdk8s application" , "effectiveSourcePath" , appSourcePath , "operation" , operation )
95-
96- // npmInstall := cmdRunnerFactory("npm", "install")
97- // npmInstall.SetDir(appSourcePath)
98- // output, err := npmInstall.CombinedOutput()
99- // if err != nil {
100- // logger.Error(err, "npm installation failed", "output", string(output), "operation:", OperationNpmInstall)
101- // }
102-
103- synth := exec .Command ("cdk8s" , "synth" )
104- synth .Dir = appSourcePath
105- if err := synth .Run (); err != nil {
106- logger .Error (err , "Failed to synth cdk8s application" , "effectiveSourcePath" , appSourcePath )
107-
108- return err
109- }
110-
111- logger .Info ("Synthesized cdk8s application" , "effectiveSourcePath" , appSourcePath , "operation" , operation )
112-
113- return nil
114- }
115-
116- func (r * Reconciler ) findManifestFiles (appSourcePath string , logger logr.Logger , operation string ) ([]string , error ) {
117- distPath := filepath .Join (appSourcePath , "dist" )
118-
119- var manifestFiles []string
120- walkErr := filepath .WalkDir (distPath , func (path string , d fs.DirEntry , err error ) error {
121- if err != nil {
122- return err
123- }
124- if ! d .IsDir () && (strings .HasSuffix (d .Name (), ".yaml" ) || strings .HasSuffix (d .Name (), ".yml" )) {
125- manifestFiles = append (manifestFiles , path )
126- }
127-
128- return nil
129- })
130-
131- if walkErr != nil {
132- logger .Error (walkErr , "Failed to walk dist directory" , "operation" , operation )
133-
134- return nil , walkErr
135- }
136-
137- logger .Info ("Found manifest files" , "count" , len (manifestFiles ), "operation" , operation )
138-
139- return manifestFiles , nil
140- }
141-
142- func (r * Reconciler ) parseManifestFiles (manifestFiles []string , logger logr.Logger , operation string ) ([]* unstructured.Unstructured , error ) {
143- var parsedResources []* unstructured.Unstructured
144-
145- for _ , manifestFile := range manifestFiles {
146- logger .Info ("Processing manifest file" , "file" , manifestFile , "operation" , operation )
147-
148- fileContent , readErr := os .ReadFile (manifestFile )
149- if readErr != nil {
150- logger .Error (readErr , "Failed to read manifest file" , "file" , manifestFile , "operation" , operation )
151-
152- return nil , readErr
153- }
154-
155- yamlDecoder := k8syaml .NewYAMLOrJSONDecoder (bytes .NewReader (fileContent ), 100 )
156-
157- for {
158- var rawObj runtime.RawExtension
159- if err := yamlDecoder .Decode (& rawObj ); err != nil {
160- if err .Error () == "EOF" {
161- break
162- }
163- logger .Error (err , "Failed to decode YAML from manifest file" , "file" , manifestFile , "operation" , operation )
164-
165- return nil , err
166- }
167-
168- if rawObj .Raw == nil {
169- continue
170- }
171-
172- u := & unstructured.Unstructured {}
173- if _ , _ , err := unstructured .UnstructuredJSONScheme .Decode (rawObj .Raw , nil , u ); err != nil {
174- logger .Error (err , "Failed to decode RawExtension to Unstructured" , "file" , manifestFile , "operation" , operation )
175-
176- return nil , err
177- }
178-
179- parsedResources = append (parsedResources , u )
180- logger .Info ("Parsed resource" , "GVK" , u .GroupVersionKind ().String (), "Name" , u .GetName (), "Namespace" , u .GetNamespace (), "operation" , operation )
181- }
182- }
183-
184- logger .Info ("Total resources parsed" , "count" , len (parsedResources ), "operation" , operation )
185-
186- return parsedResources , nil
187- }
188-
189- func (r * Reconciler ) finalizeDeletion (ctx context.Context , cdk8sAppProxy * addonsv1alpha1.Cdk8sAppProxy , proxyNamespacedName types.NamespacedName , logger logr.Logger ) error {
190- logger .Info ("Starting finalization process" )
191-
192- // Cancel any active watches for this Cdk8sAppProxy using the new WatchManager
193- logger .Info ("Cleaning up active watches for Cdk8sAppProxy before deletion" )
194- r .WatchManager .CleanupWatches (proxyNamespacedName )
195- logger .Info ("Completed cleanup of active watches" )
196-
197- // Remove finalizer
198- logger .Info ("Finished deletion logic, removing finalizer" )
199- controllerutil .RemoveFinalizer (cdk8sAppProxy , Finalizer )
200- if err := r .Update (ctx , cdk8sAppProxy ); err != nil {
201- logger .Error (err , "Failed to remove finalizer" )
202-
203- return err
204- }
205- logger .Info ("Finalizer removed successfully" )
206-
207- return nil
208- }
209-
210- func (r * Reconciler ) getDynamicClientForCluster (ctx context.Context , secretNamespace , clusterName string ) (dynamic.Interface , error ) {
67+ func (r * Reconciler ) getDynamicClientForCluster (ctx context.Context , secretNamespace , clusterName string ) (dynamicClient dynamic.Interface , err error ) {
21168 logger := log .FromContext (ctx ).WithValues ("secretNamespace" , secretNamespace , "clusterName" , clusterName )
21269 kubeconfigSecretName := clusterName + "-kubeconfig"
21370
21471 kubeconfigSecret := & corev1.Secret {}
215- if err : = r .Get (ctx , client.ObjectKey {Namespace : secretNamespace , Name : kubeconfigSecretName }, kubeconfigSecret ); err != nil {
72+ if err = r .Get (ctx , client.ObjectKey {Namespace : secretNamespace , Name : kubeconfigSecretName }, kubeconfigSecret ); err != nil {
21673 logger .Error (err , "Failed to get Kubeconfig secret" )
21774
21875 return nil , errors .Wrapf (err , "failed to get kubeconfig secret %s/%s" , secretNamespace , kubeconfigSecretName )
@@ -229,17 +86,17 @@ func (r *Reconciler) getDynamicClientForCluster(ctx context.Context, secretNames
22986 if err != nil {
23087 logger .Error (err , "Failed to create REST config from Kubeconfig" )
23188
232- return nil , errors .Wrapf (err , "failed to create REST config from kubeconfig for cluster %s" , clusterName )
89+ return dynamicClient , errors .Wrapf (err , "failed to create REST config from kubeconfig for cluster %s" , clusterName )
23390 }
234- dynamicClient , err : = dynamic .NewForConfig (restConfig )
91+ dynamicClient , err = dynamic .NewForConfig (restConfig )
23592 if err != nil {
23693 logger .Error (err , "Failed to create dynamic client" )
23794
238- return nil , errors .Wrapf (err , "failed to create dynamic client for cluster %s" , clusterName )
95+ return dynamicClient , errors .Wrapf (err , "failed to create dynamic client for cluster %s" , clusterName )
23996 }
24097 logger .Info ("Successfully created dynamic client" )
24198
242- return dynamicClient , nil
99+ return dynamicClient , err
243100}
244101
245102// Consolidated error handling.
@@ -298,13 +155,13 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
298155
299156// ClusterToCdk8sAppProxyMapper is a handler.ToRequestsFunc to be used to enqeue requests for Cdk8sAppProxyReconciler.
300157// It maps CAPI Cluster events to Cdk8sAppProxy events.
301- func (r * Reconciler ) ClusterToCdk8sAppProxyMapper (ctx context.Context , o client.Object ) []ctrl.Request {
158+ func (r * Reconciler ) ClusterToCdk8sAppProxyMapper (ctx context.Context , o client.Object ) ( requests []ctrl.Request ) {
302159 logger := log .FromContext (ctx )
303160 cluster , ok := o .(* clusterv1.Cluster )
304161 if ! ok {
305162 logger .Error (errors .Errorf ("unexpected type %T, expected Cluster" , o ), "failed to cast object to Cluster" , "object" , o )
306163
307- return nil
164+ return requests
308165 }
309166
310167 logger = logger .WithValues ("clusterName" , cluster .Name , "clusterNamespace" , cluster .Namespace )
@@ -325,7 +182,6 @@ func (r *Reconciler) ClusterToCdk8sAppProxyMapper(ctx context.Context, o client.
325182 }
326183 logger .Info ("Checking Cdk8sAppProxies for matches" , "count" , len (proxies .Items ))
327184
328- var requests []ctrl.Request
329185 for _ , proxy := range proxies .Items {
330186 proxyLogger := logger .WithValues ("cdk8sAppProxyName" , proxy .Name , "cdk8sAppProxyNamespace" , proxy .Namespace )
331187 proxyLogger .Info ("Evaluating Cdk8sAppProxy" )
0 commit comments