Skip to content

Commit e0abf35

Browse files
committed
Add contextual logging for work agent
Signed-off-by: Jian Qiu <[email protected]>
1 parent 35b6d79 commit e0abf35

18 files changed

+101
-62
lines changed

pkg/work/helper/helper_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"testing"
99

1010
"github.com/google/go-cmp/cmp"
11-
"github.com/openshift/library-go/pkg/operator/events/eventstesting"
1211
corev1 "k8s.io/api/core/v1"
1312
"k8s.io/apimachinery/pkg/api/equality"
1413
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -342,7 +341,7 @@ func TestDeleteAppliedResourcess(t *testing.T) {
342341
for _, c := range cases {
343342
t.Run(c.name, func(t *testing.T) {
344343
fakeDynamicClient := fakedynamic.NewSimpleDynamicClient(scheme, c.existingResources...)
345-
actual, err := DeleteAppliedResources(context.TODO(), c.resourcesToRemove, "testing", fakeDynamicClient, eventstesting.NewTestingEventRecorder(t), c.owner)
344+
actual, err := DeleteAppliedResources(context.TODO(), c.resourcesToRemove, "testing", fakeDynamicClient, c.owner)
346345
if err != nil {
347346
t.Errorf("unexpected err: %v", err)
348347
}

pkg/work/helper/helpers.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111
"time"
1212

1313
"github.com/openshift/library-go/pkg/controller/factory"
14-
"github.com/openshift/library-go/pkg/operator/events"
1514
"github.com/openshift/library-go/pkg/operator/resource/resourcehelper"
1615
"github.com/openshift/library-go/pkg/operator/resource/resourcemerge"
1716
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
@@ -169,11 +168,12 @@ func DeleteAppliedResources(
169168
resources []workapiv1.AppliedManifestResourceMeta,
170169
reason string,
171170
dynamicClient dynamic.Interface,
172-
recorder events.Recorder,
173171
owner metav1.OwnerReference) ([]workapiv1.AppliedManifestResourceMeta, []error) {
174172
var resourcesPendingFinalization []workapiv1.AppliedManifestResourceMeta
175173
var errs []error
176174

175+
logger := klog.FromContext(ctx)
176+
177177
// set owner to be removed
178178
ownerCopy := owner.DeepCopy()
179179
ownerCopy.UID = types.UID(fmt.Sprintf("%s-", owner.UID))
@@ -190,7 +190,8 @@ func DeleteAppliedResources(
190190
Namespace(resource.Namespace).
191191
Get(ctx, resource.Name, metav1.GetOptions{})
192192
if errors.IsNotFound(err) {
193-
klog.Infof("Resource %v with key %s/%s is removed Successfully", gvr, resource.Namespace, resource.Name)
193+
logger.Info("Resource is removed Successfully",
194+
"gvr", gvr, "resourceNamespace", resource.Namespace, "resourceName", resource.Name)
194195
continue
195196
}
196197

@@ -256,7 +257,8 @@ func DeleteAppliedResources(
256257
}
257258

258259
resourcesPendingFinalization = append(resourcesPendingFinalization, resource)
259-
recorder.Eventf("ResourceDeleted", "Deleted resource %v with key %s/%s because %s.", gvr, resource.Namespace, resource.Name, reason)
260+
logger.Info("Deleted resource",
261+
"gvr", gvr, "resourceNamespace", resource.Namespace, "resourceName", resource.Name, "reason", reason)
260262
}
261263

262264
return resourcesPendingFinalization, errs
@@ -409,6 +411,8 @@ func FindManifestCondition(resourceMeta workapiv1.ManifestResourceMeta, manifest
409411

410412
func ApplyOwnerReferences(ctx context.Context, dynamicClient dynamic.Interface, gvr schema.GroupVersionResource,
411413
existing runtime.Object, requiredOwner metav1.OwnerReference) error {
414+
logger := klog.FromContext(ctx)
415+
412416
accessor, err := meta.Accessor(existing)
413417
if err != nil {
414418
return fmt.Errorf("type %t cannot be accessed: %v", existing, err)
@@ -432,7 +436,8 @@ func ApplyOwnerReferences(ctx context.Context, dynamicClient dynamic.Interface,
432436
return err
433437
}
434438

435-
klog.V(2).Infof("Patching resource %v %s/%s with patch %s", gvr, accessor.GetNamespace(), accessor.GetName(), string(patchData))
439+
logger.V(2).Info("Patching resource",
440+
"gvr", gvr, "resourceNamespace", accessor.GetNamespace(), "resourceName", accessor.GetName(), "patch", string(patchData))
436441
_, err = dynamicClient.Resource(gvr).Namespace(accessor.GetNamespace()).Patch(ctx, accessor.GetName(), types.MergePatchType, patchData, metav1.PatchOptions{})
437442
return err
438443
}

pkg/work/spoke/apply/create_only_apply.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package apply
22

33
import (
44
"context"
5-
"fmt"
65

76
"github.com/openshift/library-go/pkg/operator/events"
87
"github.com/openshift/library-go/pkg/operator/resource/resourcemerge"
@@ -12,6 +11,7 @@ import (
1211
"k8s.io/apimachinery/pkg/runtime"
1312
"k8s.io/apimachinery/pkg/runtime/schema"
1413
"k8s.io/client-go/dynamic"
14+
"k8s.io/klog/v2"
1515

1616
workapiv1 "open-cluster-management.io/api/work/v1"
1717

@@ -31,8 +31,9 @@ func (c *CreateOnlyApply) Apply(ctx context.Context,
3131
required *unstructured.Unstructured,
3232
owner metav1.OwnerReference,
3333
_ *workapiv1.ManifestConfigOption,
34-
recorder events.Recorder) (runtime.Object, error) {
34+
_ events.Recorder) (runtime.Object, error) {
3535

36+
logger := klog.FromContext(ctx)
3637
obj, err := c.client.
3738
Resource(gvr).
3839
Namespace(required.GetNamespace()).
@@ -42,8 +43,8 @@ func (c *CreateOnlyApply) Apply(ctx context.Context,
4243
obj, err = c.client.Resource(gvr).Namespace(required.GetNamespace()).Create(
4344
ctx, resourcemerge.WithCleanLabelsAndAnnotations(required).(*unstructured.Unstructured), metav1.CreateOptions{})
4445
if err != nil {
45-
recorder.Eventf(fmt.Sprintf(
46-
"%s Created", required.GetKind()), "Created %s/%s because it was missing", required.GetNamespace(), required.GetName())
46+
logger.Info("Resource created because of missing",
47+
"kind", required.GetKind(), "resourceNamespace", required.GetNamespace(), "resourceName", required.GetName())
4748
}
4849
}
4950

pkg/work/spoke/apply/read_only_apply.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ package apply
22

33
import (
44
"context"
5-
"fmt"
65

76
"github.com/openshift/library-go/pkg/operator/events"
87
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
98
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
109
"k8s.io/apimachinery/pkg/runtime"
1110
"k8s.io/apimachinery/pkg/runtime/schema"
11+
"k8s.io/klog/v2"
1212

1313
workapiv1 "open-cluster-management.io/api/work/v1"
1414
)
@@ -24,9 +24,9 @@ func (c *ReadOnlyApply) Apply(ctx context.Context,
2424
required *unstructured.Unstructured,
2525
_ metav1.OwnerReference,
2626
_ *workapiv1.ManifestConfigOption,
27-
recorder events.Recorder) (runtime.Object, error) {
28-
29-
recorder.Eventf(fmt.Sprintf(
30-
"%s noop", required.GetKind()), "Noop for %s/%s because its read-only", required.GetNamespace(), required.GetName())
27+
_ events.Recorder) (runtime.Object, error) {
28+
logger := klog.FromContext(ctx)
29+
logger.Info("Noop because its read-only",
30+
"kind", required.GetKind(), "resourceNamespace", required.GetNamespace(), "resourceName", required.GetName())
3131
return required, nil
3232
}

pkg/work/spoke/apply/server_side_apply.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414
"k8s.io/apimachinery/pkg/runtime"
1515
"k8s.io/apimachinery/pkg/runtime/schema"
1616
"k8s.io/client-go/dynamic"
17-
"k8s.io/client-go/tools/cache"
1817
"k8s.io/client-go/util/jsonpath"
1918
"k8s.io/klog/v2"
2019

@@ -45,7 +44,7 @@ func (c *ServerSideApply) Apply(
4544
requiredOriginal *unstructured.Unstructured,
4645
owner metav1.OwnerReference,
4746
applyOption *workapiv1.ManifestConfigOption,
48-
recorder events.Recorder) (runtime.Object, error) {
47+
_ events.Recorder) (runtime.Object, error) {
4948
logger := klog.FromContext(ctx)
5049
// Currently, if the required object has zero creationTime in metadata, it will cause
5150
// kube-apiserver to increment generation even if nothing else changes. more details see:
@@ -114,10 +113,9 @@ func (c *ServerSideApply) Apply(
114113
Resource(gvr).
115114
Namespace(required.GetNamespace()).
116115
Apply(ctx, required.GetName(), required, metav1.ApplyOptions{FieldManager: fieldManager, Force: force})
117-
resourceKey, _ := cache.MetaNamespaceKeyFunc(required)
118-
recorder.Eventf(fmt.Sprintf(
119-
"Server Side Applied %s %s", required.GetKind(), resourceKey),
120-
"Patched with field manager %s, err %v", fieldManager, err)
116+
logger.Info("Server side applied",
117+
"kind", required.GetKind(), "resourceNamespace", required.GetNamespace(),
118+
"resourceName", required.GetName(), "fieldManager", fieldManager)
121119

122120
if errors.IsConflict(err) {
123121
return obj, &ServerSideApplyConflictError{ssaErr: err}

pkg/work/spoke/apply/update_apply.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package apply
22

33
import (
44
"context"
5-
"fmt"
65
"reflect"
76
"strings"
87

@@ -18,6 +17,7 @@ import (
1817
"k8s.io/apimachinery/pkg/runtime/schema"
1918
"k8s.io/client-go/dynamic"
2019
"k8s.io/client-go/kubernetes"
20+
"k8s.io/klog/v2"
2121
"k8s.io/utils/pointer"
2222

2323
workapiv1 "open-cluster-management.io/api/work/v1"
@@ -48,7 +48,6 @@ func (c *UpdateApply) Apply(
4848
owner metav1.OwnerReference,
4949
_ *workapiv1.ManifestConfigOption,
5050
recorder events.Recorder) (runtime.Object, error) {
51-
5251
clientHolder := resourceapply.NewClientHolder().
5352
WithAPIExtensionsClient(c.apiExtensionClient).
5453
WithKubernetes(c.kubeclient).
@@ -84,15 +83,16 @@ func (c *UpdateApply) applyUnstructured(
8483
gvr schema.GroupVersionResource,
8584
recorder events.Recorder,
8685
cache resourceapply.ResourceCache) (*unstructured.Unstructured, bool, error) {
86+
logger := klog.FromContext(ctx)
8787
existing, err := c.dynamicClient.
8888
Resource(gvr).
8989
Namespace(required.GetNamespace()).
9090
Get(ctx, required.GetName(), metav1.GetOptions{})
9191
if apierrors.IsNotFound(err) {
9292
actual, err := c.dynamicClient.Resource(gvr).Namespace(required.GetNamespace()).Create(
9393
ctx, resourcemerge.WithCleanLabelsAndAnnotations(required).(*unstructured.Unstructured), metav1.CreateOptions{})
94-
recorder.Eventf(fmt.Sprintf(
95-
"%s Created", required.GetKind()), "Created %s/%s because it was missing", required.GetNamespace(), required.GetName())
94+
logger.Info("Created resource because it was missing",
95+
"kind", required.GetKind(), "resourceNamespace", required.GetNamespace(), "resourceName", required.GetName())
9696
cache.UpdateCachedResourceMetadata(required, actual)
9797
return actual, true, err
9898
}
@@ -130,8 +130,8 @@ func (c *UpdateApply) applyUnstructured(
130130
required.SetResourceVersion(existing.GetResourceVersion())
131131
actual, err := c.dynamicClient.Resource(gvr).Namespace(required.GetNamespace()).Update(
132132
ctx, required, metav1.UpdateOptions{})
133-
recorder.Eventf(fmt.Sprintf(
134-
"%s Updated", required.GetKind()), "Updated %s/%s", required.GetNamespace(), required.GetName())
133+
logger.Info("Updated resource",
134+
"kind", required.GetKind(), "resourceNamespace", required.GetNamespace(), "resourceName", required.GetName())
135135
cache.UpdateCachedResourceMetadata(required, actual)
136136
return actual, true, err
137137
}

pkg/work/spoke/auth/basic/auth.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ func (v *SarValidator) CheckSubjectAccessReviews(ctx context.Context, sa *workap
134134
// CheckEscalation checks whether the sa is escalated to operate the gvr(RBAC) resources.
135135
func (v *SarValidator) CheckEscalation(ctx context.Context, sa *workapiv1.ManifestWorkSubjectServiceAccount,
136136
gvr schema.GroupVersionResource, namespace, name string, obj *unstructured.Unstructured) error {
137-
137+
logger := klog.FromContext(ctx)
138138
if gvr.Group != "rbac.authorization.k8s.io" {
139139
return nil
140140
}
@@ -152,8 +152,8 @@ func (v *SarValidator) CheckEscalation(ctx context.Context, sa *workapiv1.Manife
152152
DryRun: []string{"All"},
153153
})
154154
if apierrors.IsForbidden(err) {
155-
klog.Infof("not allowed to apply the resource %s %s, %s %s, error: %s",
156-
gvr.Group, gvr.Resource, namespace, name, err.Error())
155+
logger.Info("not allowed to apply the resource",
156+
"gvr", gvr, "resourceNamespace", namespace, "resourceName", name, "error", err)
157157
return &NotAllowedError{
158158
Err: fmt.Errorf("not allowed to apply the resource %s %s, %s %s, error: permission escalation",
159159
gvr.Group, gvr.Resource, namespace, name),

pkg/work/spoke/auth/cache/auth.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ func (v *sarCacheValidator) Start(ctx context.Context) {
101101
func (v *sarCacheValidator) Validate(ctx context.Context, executor *workapiv1.ManifestWorkExecutor,
102102
gvr schema.GroupVersionResource, namespace, name string,
103103
ownedByTheWork bool, obj *unstructured.Unstructured) error {
104+
logger := klog.FromContext(ctx)
104105
if executor == nil {
105106
return nil
106107
}
@@ -128,7 +129,8 @@ func (v *sarCacheValidator) Validate(ctx context.Context, executor *workapiv1.Ma
128129
return err
129130
}
130131
} else {
131-
klog.V(4).Infof("Get auth from cache executor %s, dimension: %+v allow: %v", executorKey, dimension, *allowed)
132+
logger.V(4).Info("Get auth from cache executor",
133+
"executorKey", executorKey, "dimension", dimension, "allowed", *allowed)
132134
if !*allowed {
133135
return &basic.NotAllowedError{
134136
Err: fmt.Errorf("not allowed to apply the resource %s %s, %s %s",

pkg/work/spoke/controllers/finalizercontroller/add_finalizer_controller.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import (
1717
"open-cluster-management.io/ocm/pkg/common/queue"
1818
)
1919

20+
const manifestWorkAddFinalizerController = "ManifestWorkAddFinalizerController"
21+
2022
// AddFinalizerController is to add the cluster.open-cluster-management.io/manifest-work-cleanup finalizer to manifestworks.
2123
type AddFinalizerController struct {
2224
patcher patcher.Patcher[*workapiv1.ManifestWork, workapiv1.ManifestWorkSpec, workapiv1.ManifestWorkStatus]
@@ -40,12 +42,14 @@ func NewAddFinalizerController(
4042

4143
return factory.New().
4244
WithInformersQueueKeysFunc(queue.QueueKeyByMetaName, manifestWorkInformer.Informer()).
43-
WithSync(controller.sync).ToController("ManifestWorkAddFinalizerController", recorder)
45+
WithSync(controller.sync).ToController(manifestWorkAddFinalizerController, recorder)
4446
}
4547

4648
func (m *AddFinalizerController) sync(ctx context.Context, controllerContext factory.SyncContext) error {
4749
manifestWorkName := controllerContext.QueueKey()
48-
klog.V(5).Infof("Reconciling ManifestWork %q", manifestWorkName)
50+
logger := klog.FromContext(ctx).WithName(manifestWorkAddFinalizerController).
51+
WithValues("manifestWorkName", manifestWorkName)
52+
logger.V(5).Info("Reconciling ManifestWork")
4953

5054
manifestWork, err := m.manifestWorkLister.Get(manifestWorkName)
5155
if errors.IsNotFound(err) {

pkg/work/spoke/controllers/finalizercontroller/appliedmanifestwork_finalize_controller.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import (
2424
"open-cluster-management.io/ocm/pkg/work/helper"
2525
)
2626

27+
const appliedManifestWorkFinalizer = "AppliedManifestWorkFinalizer"
28+
2729
// AppliedManifestWorkFinalizeController handles cleanup of appliedmanifestwork resources before deletion is allowed.
2830
// It should handle all appliedmanifestworks belonging to this agent identified by the agentID.
2931
type AppliedManifestWorkFinalizeController struct {
@@ -54,12 +56,15 @@ func NewAppliedManifestWorkFinalizeController(
5456
return factory.New().
5557
WithFilteredEventsInformersQueueKeysFunc(queue.QueueKeyByMetaName,
5658
helper.AppliedManifestworkAgentIDFilter(agentID), appliedManifestWorkInformer.Informer()).
57-
WithSync(controller.sync).ToController("AppliedManifestWorkFinalizer", recorder)
59+
WithSync(controller.sync).ToController(appliedManifestWorkFinalizer, recorder)
5860
}
5961

6062
func (m *AppliedManifestWorkFinalizeController) sync(ctx context.Context, controllerContext factory.SyncContext) error {
6163
appliedManifestWorkName := controllerContext.QueueKey()
62-
klog.V(5).Infof("Reconciling AppliedManifestWork %q", appliedManifestWorkName)
64+
logger := klog.FromContext(ctx).WithName(appliedManifestWorkFinalizer).
65+
WithValues("appliedManifestWorkName", appliedManifestWorkName)
66+
logger.V(5).Info("Reconciling AppliedManifestWork")
67+
ctx = klog.NewContext(ctx, logger)
6368

6469
appliedManifestWork, err := m.appliedManifestWorkLister.Get(appliedManifestWorkName)
6570
if errors.IsNotFound(err) {
@@ -77,6 +82,7 @@ func (m *AppliedManifestWorkFinalizeController) sync(ctx context.Context, contro
7782
// before removing finalizer from appliedmanifestwork
7883
func (m *AppliedManifestWorkFinalizeController) syncAppliedManifestWork(ctx context.Context,
7984
controllerContext factory.SyncContext, originalManifestWork *workapiv1.AppliedManifestWork) error {
85+
logger := klog.FromContext(ctx)
8086
appliedManifestWork := originalManifestWork.DeepCopy()
8187

8288
// no work to do until we're deleted
@@ -96,7 +102,7 @@ func (m *AppliedManifestWorkFinalizeController) syncAppliedManifestWork(ctx cont
96102
// scoped resource correctly.
97103
reason := fmt.Sprintf("manifestwork %s is terminating", appliedManifestWork.Spec.ManifestWorkName)
98104
resourcesPendingFinalization, errs := helper.DeleteAppliedResources(
99-
ctx, appliedManifestWork.Status.AppliedResources, reason, m.spokeDynamicClient, controllerContext.Recorder(), *owner)
105+
ctx, appliedManifestWork.Status.AppliedResources, reason, m.spokeDynamicClient, *owner)
100106
appliedManifestWork.Status.AppliedResources = resourcesPendingFinalization
101107
updatedAppliedManifestWork, err := m.patcher.PatchStatus(ctx, appliedManifestWork, appliedManifestWork.Status, originalManifestWork.Status)
102108
if err != nil {
@@ -111,7 +117,7 @@ func (m *AppliedManifestWorkFinalizeController) syncAppliedManifestWork(ctx cont
111117

112118
// requeue the work until all applied resources are deleted and finalized if the appliedmanifestwork itself is not updated
113119
if len(resourcesPendingFinalization) != 0 {
114-
klog.V(4).Infof("%d resources pending deletions in %s", len(resourcesPendingFinalization), appliedManifestWork.Name)
120+
logger.V(4).Info("resources pending deletions", "numOfResources", len(resourcesPendingFinalization))
115121
controllerContext.Queue().AddAfter(appliedManifestWork.Name, m.rateLimiter.When(appliedManifestWork.Name))
116122
return nil
117123
}

0 commit comments

Comments
 (0)