Skip to content

Commit 41d7e7a

Browse files
author
alexander-demicev
committed
Add new logs and improve structure
Signed-off-by: alexander-demicev <alexandr.demicev@suse.com>
1 parent 0979fdf commit 41d7e7a

File tree

12 files changed

+95
-71
lines changed

12 files changed

+95
-71
lines changed

cmd/plugin/cmd/delete.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -299,16 +299,16 @@ func deleteProviders(ctx context.Context, client ctrlclient.Client, providerList
299299
if err := client.List(ctx, providerList, selector); meta.IsNoMatchError(err) || apierrors.IsNotFound(err) {
300300
return true, nil
301301
} else if err != nil {
302-
log.Error(err, fmt.Sprintf("Unable to list providers to delete, %#v", err))
302+
log.Error(err, "Unable to list providers to delete")
303303
return false, err
304304
}
305305

306306
for _, provider := range providerList.GetItems() {
307-
log.Info(fmt.Sprintf("Deleting %s %s/%s", provider.GetType(), provider.GetName(), provider.GetNamespace()))
307+
log.Info("Deleting provider", "type", provider.GetType(), "name", provider.GetName(), "namespace", provider.GetNamespace())
308308

309309
provider, ok := provider.(genericProvider)
310310
if !ok {
311-
log.Info(fmt.Sprintf("Expected to get GenericProvider for %s", gvk))
311+
log.Info("Expected to get GenericProvider", "gvk", gvk)
312312
continue
313313
}
314314

@@ -318,7 +318,7 @@ func deleteProviders(ctx context.Context, client ctrlclient.Client, providerList
318318

319319
if deleteOpts.includeNamespace {
320320
if strings.HasPrefix(provider.GetNamespace(), "kube-") || provider.GetNamespace() == "default" {
321-
log.Info(fmt.Sprintf("Skipping system namespace %s", provider.GetNamespace()))
321+
log.Info("Skipping system namespace", "namespace", provider.GetNamespace())
322322
continue
323323
}
324324

@@ -330,7 +330,7 @@ func deleteProviders(ctx context.Context, client ctrlclient.Client, providerList
330330
}
331331

332332
if len(providerList.GetItems()) > 0 {
333-
log.Info(fmt.Sprintf("%d items remaning...", len(providerList.GetItems())))
333+
log.Info("Items remaining", "count", len(providerList.GetItems()))
334334
return false, nil
335335
}
336336

internal/controller/client_proxy.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ import (
2727

2828
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2929
"k8s.io/client-go/rest"
30-
"k8s.io/klog/v2"
3130

3231
clusterctlv1 "sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3"
3332
"sigs.k8s.io/cluster-api/cmd/clusterctl/client/cluster"
3433
"sigs.k8s.io/cluster-api/cmd/clusterctl/client/repository"
34+
ctrl "sigs.k8s.io/controller-runtime"
3535
"sigs.k8s.io/controller-runtime/pkg/client"
3636
)
3737

@@ -107,6 +107,7 @@ func (k *controllerProxy) GetResourceNames(ctx context.Context, groupVersion, ki
107107

108108
// ListResources lists namespaced and cluster-wide resources for a component matching the labels.
109109
func (k *controllerProxy) ListResources(ctx context.Context, labels map[string]string, namespaces ...string) ([]unstructured.Unstructured, error) {
110+
log := ctrl.LoggerFrom(ctx)
110111
resourceList := []*metav1.APIResourceList{
111112
{
112113
GroupVersion: "v1",
@@ -160,7 +161,7 @@ func (k *controllerProxy) ListResources(ctx context.Context, labels map[string]s
160161
return nil, err
161162
}
162163

163-
klog.V(3).InfoS("listed", "kind", resourceKind.Kind, "count", len(objList.Items))
164+
log.V(2).Info("Listed resources", "kind", resourceKind.Kind, "count", len(objList.Items))
164165

165166
ret = append(ret, objList.Items...)
166167
}
@@ -170,7 +171,7 @@ func (k *controllerProxy) ListResources(ctx context.Context, labels map[string]s
170171
return nil, err
171172
}
172173

173-
klog.V(3).InfoS("listed", "kind", resourceKind.Kind, "count", len(objList.Items))
174+
log.V(2).Info("Listed resources", "kind", resourceKind.Kind, "count", len(objList.Items))
174175

175176
ret = append(ret, objList.Items...)
176177
}

internal/controller/configmaps_to_providers.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func newConfigMapToProviderFuncMapForProviderList(k8sClient client.Client, provi
6464
}
6565

6666
if selector.Matches(configMapLabels) {
67-
log.V(1).Info("ConfigMap matches provider selector, enqueueing reconcile request")
67+
log.Info("ConfigMap matches provider selector, enqueueing reconcile request")
6868

6969
requests = append(requests, reconcile.Request{NamespacedName: client.ObjectKeyFromObject(provider)})
7070
}

internal/controller/genericprovider_controller.go

Lines changed: 19 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,8 @@ func (r *GenericProviderReconciler) Reconcile(ctx context.Context, req reconcile
140140
if apierrors.IsNotFound(err) {
141141
// Object not found, return. Created objects are automatically garbage collected.
142142
// For additional cleanup logic use finalizers.
143+
log.Info("Provider not found, skipping reconciliation")
144+
143145
return ctrl.Result{}, nil
144146
}
145147
// Error reading the object - requeue the request.
@@ -167,12 +169,16 @@ func (r *GenericProviderReconciler) Reconcile(ctx context.Context, req reconcile
167169

168170
// Add finalizer first if not exist to avoid the race condition between init and delete
169171
if !controllerutil.ContainsFinalizer(r.Provider, operatorv1.ProviderFinalizer) {
172+
log.Info("Adding finalizer, requeueing")
170173
controllerutil.AddFinalizer(r.Provider, operatorv1.ProviderFinalizer)
174+
171175
return ctrl.Result{}, nil
172176
}
173177

174178
// Handle deletion reconciliation loop.
175179
if !r.Provider.GetDeletionTimestamp().IsZero() {
180+
log.Info("Provider marked for deletion, entering delete reconciliation")
181+
176182
res, err := r.reconcileDelete(ctx, r.Provider)
177183
if err != nil {
178184
return reconcile.Result{}, err
@@ -381,25 +387,17 @@ func addObjectToHash(hash hash.Hash, object interface{}) error {
381387

382388
// providerHash calculates hash for provider and referenced objects.
383389
func providerHash(ctx context.Context, client client.Client, hash hash.Hash, provider genericprovider.GenericProvider) error {
384-
log := log.FromContext(ctx)
385-
386390
err := addObjectToHash(hash, provider.GetSpec())
387391
if err != nil {
388-
log.Error(err, "failed to calculate provider hash")
389-
390-
return err
392+
return fmt.Errorf("failed to calculate provider hash: %w", err)
391393
}
392394

393395
if err := addConfigSecretToHash(ctx, client, hash, provider); err != nil {
394-
log.Error(err, "failed to calculate secret hash")
395-
396-
return err
396+
return fmt.Errorf("failed to calculate secret hash: %w", err)
397397
}
398398

399399
if err := addConfigMapToHash(ctx, client, hash, provider); err != nil {
400-
log.Error(err, "failed to calculate configmap hash")
401-
402-
return err
400+
return fmt.Errorf("failed to calculate configmap hash: %w", err)
403401
}
404402

405403
return nil
@@ -444,23 +442,17 @@ func (p *PhaseReconciler) ApplyFromCache(ctx context.Context) (*Result, error) {
444442
// secret does not exist, nothing to apply
445443
return &Result{}, nil
446444
} else if err != nil {
447-
log.Error(err, "failed to get provider cache")
448-
449445
return &Result{}, fmt.Errorf("failed to get provider cache: %w", err)
450446
}
451447

452448
// calculate combined hash for provider and config map cache
453449
hash := sha256.New()
454450
if err := providerHash(ctx, p.ctrlClient, hash, p.provider); err != nil {
455-
log.Error(err, "failed to calculate provider hash")
456-
457451
return &Result{}, err
458452
}
459453

460454
if err := addObjectToHash(hash, secret.Data); err != nil {
461-
log.Error(err, "failed to calculate config map hash")
462-
463-
return &Result{}, err
455+
return &Result{}, fmt.Errorf("failed to calculate config map hash: %w", err)
464456
}
465457

466458
data, err := os.ReadFile(configPath)
@@ -471,9 +463,7 @@ func (p *PhaseReconciler) ApplyFromCache(ctx context.Context) (*Result, error) {
471463
}
472464

473465
if err := addObjectToHash(hash, data); err != nil {
474-
log.Error(err, "failed to calculate clusterctl.yaml file hash")
475-
476-
return &Result{}, nil
466+
return &Result{}, err
477467
}
478468

479469
cacheHash := fmt.Sprintf("%x", hash.Sum(nil))
@@ -499,8 +489,6 @@ func (p *PhaseReconciler) ApplyFromCache(ctx context.Context) (*Result, error) {
499489
compressed := secret.GetAnnotations()[operatorv1.CompressedAnnotation] == operatorv1.TrueValue
500490

501491
if err := p.applyManifestsFromData(ctx, secret.Data, compressed); err != nil {
502-
log.Error(err, "failed to apply objects from cache")
503-
504492
return &Result{}, err
505493
}
506494

@@ -514,6 +502,8 @@ func (p *PhaseReconciler) ApplyFromCache(ctx context.Context) (*Result, error) {
514502
func (p *PhaseReconciler) applyManifestsFromData(ctx context.Context, data map[string][]byte, compressed bool) error {
515503
log := log.FromContext(ctx)
516504

505+
log.V(2).Info("Applying manifests from cache", "entries", len(data), "compressed", compressed)
506+
517507
var errs []error
518508

519509
for _, raw := range data {
@@ -524,18 +514,14 @@ func (p *PhaseReconciler) applyManifestsFromData(ctx context.Context, data map[s
524514

525515
manifest, err = decompressData(raw)
526516
if err != nil {
527-
log.Error(err, "failed to decompress yaml")
528-
529-
return err
517+
return fmt.Errorf("failed to decompress yaml: %w", err)
530518
}
531519
}
532520

533521
var manifests []unstructured.Unstructured
534522

535523
if err := json.Unmarshal(manifest, &manifests); err != nil {
536-
log.Error(err, "failed to convert yaml to unstructured")
537-
538-
return err
524+
return fmt.Errorf("failed to convert yaml to unstructured: %w", err)
539525
}
540526

541527
for i := range manifests {
@@ -550,6 +536,8 @@ func (p *PhaseReconciler) applyManifestsFromData(ctx context.Context, data map[s
550536

551537
// setCacheHash calculates current provider and secret hash, and updates it on the secret.
552538
func setCacheHash(ctx context.Context, cl client.Client, provider genericprovider.GenericProvider) error {
539+
log := log.FromContext(ctx)
540+
553541
secret := &corev1.Secret{}
554542
if err := cl.Get(ctx, client.ObjectKey{Name: ProviderCacheName(provider), Namespace: provider.GetNamespace()}, secret); err != nil {
555543
return fmt.Errorf("failed to get cache secret: %w", err)
@@ -583,6 +571,8 @@ func setCacheHash(ctx context.Context, cl client.Client, provider genericprovide
583571

584572
cacheHash := fmt.Sprintf("%x", hash.Sum(nil))
585573

574+
log.V(2).Info("Setting cache hash", "hash", cacheHash, "provider", provider.GetName())
575+
586576
annotations := secret.GetAnnotations()
587577
if annotations == nil {
588578
annotations = map[string]string{}

internal/controller/healthcheck/healthcheck_controller.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,12 +148,16 @@ func (r *GenericProviderHealthCheckReconciler) Reconcile(ctx context.Context, re
148148

149149
// Stop earlier if this provider is not fully installed yet.
150150
if !conditions.IsTrue(typedProvider, operatorv1.ProviderInstalledCondition) {
151+
log.V(2).Info("Provider not fully installed yet, requeueing")
152+
151153
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
152154
}
153155

154156
// Compare provider's Ready condition with the deployment's Available condition and stop if they already match.
155157
currentReadyCondition := conditions.Get(typedProvider, clusterv1.ReadyCondition)
156158
if currentReadyCondition != nil && deploymentAvailableCondition != nil && currentReadyCondition.Status == metav1.ConditionStatus(deploymentAvailableCondition.Status) {
159+
log.V(5).Info("Health check conditions already in sync, skipping")
160+
157161
return result, nil
158162
}
159163

@@ -169,6 +173,8 @@ func (r *GenericProviderHealthCheckReconciler) Reconcile(ctx context.Context, re
169173
reason = operatorv1.DeploymentAvailableReason
170174
}
171175

176+
log.Info("Updating provider health status", "available", deploymentAvailableCondition.Status)
177+
172178
conditions.Set(typedProvider, metav1.Condition{
173179
Type: clusterv1.ReadyCondition,
174180
Status: metav1.ConditionStatus(deploymentAvailableCondition.Status),

internal/controller/manifests_downloader.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ func (p *PhaseReconciler) DownloadManifests(ctx context.Context) (*Result, error
7373
return &Result{}, nil
7474
}
7575

76-
log.Info("Downloading provider manifests")
76+
log.Info("Downloading provider manifests", "version", p.provider.GetSpec().Version)
7777

7878
if p.providerConfig.URL() != fakeURL {
7979
p.repo, err = util.RepositoryFactory(ctx, p.providerConfig, p.configClient.Variables())
@@ -90,6 +90,8 @@ func (p *PhaseReconciler) DownloadManifests(ctx context.Context) (*Result, error
9090
// User didn't set the version, try to get repository default.
9191
spec.Version = p.repo.DefaultVersion()
9292

93+
log.Info("Using repository default version", "version", spec.Version)
94+
9395
// Add version to the provider spec.
9496
p.provider.SetSpec(spec)
9597
}
@@ -98,11 +100,15 @@ func (p *PhaseReconciler) DownloadManifests(ctx context.Context) (*Result, error
98100

99101
// Fetch the provider metadata and components yaml files from the provided repository GitHub/GitLab or OCI source
100102
if p.provider.GetSpec().FetchConfig != nil && p.provider.GetSpec().FetchConfig.OCI != "" {
103+
log.Info("Downloading manifests from OCI source", "oci", p.provider.GetSpec().FetchConfig.OCI)
104+
101105
configMap, err = OCIConfigMap(ctx, p.provider, OCIAuthentication(p.configClient.Variables()))
102106
if err != nil {
103107
return &Result{}, wrapPhaseError(err, operatorv1.ComponentsFetchErrorReason, operatorv1.ProviderInstalledCondition)
104108
}
105109
} else {
110+
log.Info("Downloading manifests from repository", "url", p.providerConfig.URL())
111+
106112
configMap, err = RepositoryConfigMap(ctx, p.provider, p.repo)
107113
if err != nil {
108114
err = fmt.Errorf("failed to create config map for provider %q: %w", p.provider.GetName(), err)
@@ -141,9 +147,13 @@ func (p *PhaseReconciler) checkConfigMapExists(ctx context.Context, labelSelecto
141147

142148
// Finalize applies combined hash to a configMap, in order to mark provider provisioning completed.
143149
func (p *PhaseReconciler) Finalize(ctx context.Context) (*Result, error) {
150+
log := ctrl.LoggerFrom(ctx)
151+
144152
err := setCacheHash(ctx, p.ctrlClient, p.provider)
145153
if err != nil {
146-
ctrl.LoggerFrom(ctx).V(5).Error(err, "Failed to update providers hash")
154+
log.V(5).Error(err, "Failed to update providers hash")
155+
} else {
156+
log.Info("Provider reconciliation finalized successfully")
147157
}
148158

149159
return &Result{}, wrapPhaseError(err, "FailedToUpdateProvidersHash", operatorv1.ProviderInstalledCondition)

internal/controller/oci_source.go

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -215,15 +215,11 @@ func parseOCISource(url string, version string) (string, string, bool) {
215215

216216
// CopyOCIStore collects artifacts from the provider OCI url and creates a map of file contents.
217217
func CopyOCIStore(ctx context.Context, url string, version string, store *mapStore, credential *auth.Credential) error {
218-
log := log.FromContext(ctx)
219-
220218
url, version, plainHTTP := parseOCISource(url, version)
221219

222220
repo, err := remote.NewRepository(url)
223221
if err != nil {
224-
log.Error(err, "Invalid registry URL specified")
225-
226-
return err
222+
return fmt.Errorf("invalid registry URL specified: %w", err)
227223
}
228224

229225
if credential != nil {
@@ -245,9 +241,7 @@ func CopyOCIStore(ctx context.Context, url string, version string, store *mapSto
245241
},
246242
})
247243
if err != nil {
248-
log.Error(err, "Unable to copy OCI content to store")
249-
250-
return err
244+
return fmt.Errorf("unable to copy OCI content to store: %w", err)
251245
}
252246

253247
return nil
@@ -276,16 +270,14 @@ func OCIAuthentication(c configclient.VariablesClient) *auth.Credential {
276270
func FetchOCI(ctx context.Context, provider operatorv1.GenericProvider, cred *auth.Credential) (*mapStore, error) {
277271
log := log.FromContext(ctx)
278272

279-
log.Info("Custom fetch configuration OCI url was provided")
273+
log.V(2).Info("Custom fetch configuration OCI url was provided")
280274

281275
// Prepare components store for the provider type.
282276
store := NewMapStore(provider)
283277

284278
err := CopyOCIStore(ctx, provider.GetSpec().FetchConfig.OCI, provider.GetSpec().Version, &store, cred)
285279
if err != nil {
286-
log.Error(err, "Unable to copy OCI content")
287-
288-
return nil, err
280+
return nil, fmt.Errorf("unable to copy OCI content: %w", err)
289281
}
290282

291283
return &store, nil

internal/controller/phase_fetch.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ func (p *PhaseReconciler) Fetch(ctx context.Context) (*Result, error) {
4949
// Check if components exceed the resource size.
5050
p.needsCompression = needToCompress(componentsFile)
5151

52+
log.V(2).Info("Fetched components file", "size", len(componentsFile), "needsCompression", p.needsCompression)
53+
5254
// Generate a set of new objects using the clusterctl library. NewComponents() will do the yaml processing,
5355
// like ensure all the provider components are in proper namespace, replace variables, etc. See the clusterctl
5456
// documentation for more details.
@@ -95,7 +97,6 @@ func (p *PhaseReconciler) Store(ctx context.Context) (*Result, error) {
9597

9698
kinds, _, err := scheme.Scheme.ObjectKinds(&corev1.Secret{})
9799
if err != nil || len(kinds) == 0 {
98-
log.Error(err, "cannot fetch kind of the Secret resource")
99100
err = fmt.Errorf("cannot fetch kind of the Secret resource: %w", err)
100101

101102
return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition)
@@ -147,8 +148,6 @@ func (p *PhaseReconciler) Store(ctx context.Context) (*Result, error) {
147148
}
148149

149150
if err := p.ctrlClient.Patch(ctx, secret, client.Apply, client.ForceOwnership, client.FieldOwner(cacheOwner)); err != nil {
150-
log.Error(err, "failed to apply cache config map")
151-
152151
return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition)
153152
}
154153

@@ -182,12 +181,16 @@ func addNamespaceIfMissing(objs []unstructured.Unstructured, targetNamespace str
182181
return objs
183182
}
184183

185-
func (p *PhaseReconciler) ReportStatus(_ context.Context) (*Result, error) {
184+
func (p *PhaseReconciler) ReportStatus(ctx context.Context) (*Result, error) {
185+
log := ctrl.LoggerFrom(ctx)
186+
186187
status := p.provider.GetStatus()
187188
status.Contract = &p.contract
188189
installedVersion := p.components.Version()
189190
status.InstalledVersion = &installedVersion
190191
p.provider.SetStatus(status)
191192

193+
log.V(2).Info("Reported provider status", "contract", p.contract, "installedVersion", installedVersion)
194+
192195
return &Result{}, nil
193196
}

0 commit comments

Comments
 (0)