Skip to content

Commit 8ee328f

Browse files
committed
pkg/resource: add WithLogger to applicators
Signed-off-by: Dr. Stefan Schimanski <[email protected]>
1 parent 94a1a05 commit 8ee328f

File tree

5 files changed

+85
-6
lines changed

5 files changed

+85
-6
lines changed

pkg/logging/logging.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ package logging
3838

3939
import (
4040
"github.com/go-logr/logr"
41+
"sigs.k8s.io/controller-runtime/pkg/client"
4142
)
4243

4344
// A Logger logs messages. Messages may be supplemented by structured data.
@@ -92,3 +93,20 @@ func (l logrLogger) Debug(msg string, keysAndValues ...any) {
9293
func (l logrLogger) WithValues(keysAndValues ...any) Logger {
9394
return logrLogger{log: l.log.WithValues(keysAndValues...)} //nolint:logrlint // False positive - logrlint thinks there's an odd number of args.
9495
}
96+
97+
// ForResource returns logging values for a resource.
98+
func ForResource(object client.Object) []string {
99+
ret := make([]string, 0, 10)
100+
gvk := object.GetObjectKind().GroupVersionKind()
101+
ret = append(ret,
102+
"name", object.GetName(),
103+
"kind", gvk.Kind,
104+
"version", gvk.Version,
105+
"group", gvk.Group,
106+
)
107+
if ns := object.GetNamespace(); ns != "" {
108+
ret = append(ret, "namespace", ns)
109+
}
110+
111+
return ret
112+
}

pkg/resource/api.go

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"sigs.k8s.io/controller-runtime/pkg/client"
2626

2727
"github.com/crossplane/crossplane-runtime/pkg/errors"
28+
"github.com/crossplane/crossplane-runtime/pkg/logging"
2829
"github.com/crossplane/crossplane-runtime/pkg/meta"
2930
)
3031

@@ -36,7 +37,8 @@ const (
3637
// An APIPatchingApplicator applies changes to an object by either creating or
3738
// patching it in a Kubernetes API server.
3839
type APIPatchingApplicator struct {
39-
client client.Client
40+
client client.Client
41+
optionalLog logging.Logger // can be nil
4042
}
4143

4244
// NewAPIPatchingApplicator returns an Applicator that applies changes to an
@@ -45,6 +47,12 @@ func NewAPIPatchingApplicator(c client.Client) *APIPatchingApplicator {
4547
return &APIPatchingApplicator{client: c}
4648
}
4749

50+
// WithLogger sets the logger on the APIPatchingApplicator.
51+
func (a *APIPatchingApplicator) WithLogger(l logging.Logger) *APIPatchingApplicator {
52+
a.optionalLog = l
53+
return a
54+
}
55+
4856
// Apply changes to the supplied object. The object will be created if it does
4957
// not exist, or patched if it does. If the object does exist, it will only be
5058
// patched if the passed object has the same or an empty resource version.
@@ -81,6 +89,10 @@ func (a *APIPatchingApplicator) Apply(ctx context.Context, obj client.Object, ao
8189
}
8290
}
8391

92+
if err := LogDiff(a.optionalLog, current, obj); err != nil {
93+
return err
94+
}
95+
8496
// TODO(negz): Allow callers to override the kind of patch used.
8597
return errors.Wrap(a.client.Patch(ctx, obj, client.MergeFromWithOptions(current, client.MergeFromWithOptimisticLock{})), "cannot patch object")
8698
}
@@ -100,7 +112,8 @@ func groupResource(c client.Client, o client.Object) (schema.GroupResource, erro
100112
// An APIUpdatingApplicator applies changes to an object by either creating or
101113
// updating it in a Kubernetes API server.
102114
type APIUpdatingApplicator struct {
103-
client client.Client
115+
client client.Client
116+
optionalLog logging.Logger // can be nil
104117
}
105118

106119
// NewAPIUpdatingApplicator returns an Applicator that applies changes to an
@@ -112,6 +125,12 @@ func NewAPIUpdatingApplicator(c client.Client) *APIUpdatingApplicator {
112125
return &APIUpdatingApplicator{client: c}
113126
}
114127

128+
// WithLogger sets the logger on the APIUpdatingApplicator.
129+
func (a *APIUpdatingApplicator) WithLogger(l logging.Logger) *APIUpdatingApplicator {
130+
a.optionalLog = l
131+
return a
132+
}
133+
115134
// Apply changes to the supplied object. The object will be created if it does
116135
// not exist, or updated if it does.
117136
func (a *APIUpdatingApplicator) Apply(ctx context.Context, obj client.Object, ao ...ApplyOption) error {
@@ -135,6 +154,10 @@ func (a *APIUpdatingApplicator) Apply(ctx context.Context, obj client.Object, ao
135154
}
136155
}
137156

157+
if err := LogDiff(a.optionalLog, current, obj); err != nil {
158+
return err
159+
}
160+
138161
return errors.Wrap(a.client.Update(ctx, obj), "cannot update object")
139162
}
140163

pkg/resource/providerconfig.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929

3030
xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
3131
"github.com/crossplane/crossplane-runtime/pkg/errors"
32+
"github.com/crossplane/crossplane-runtime/pkg/logging"
3233
"github.com/crossplane/crossplane-runtime/pkg/meta"
3334
)
3435

@@ -123,13 +124,22 @@ func (fn TrackerFn) Track(ctx context.Context, mg Managed) error {
123124
// A ProviderConfigUsageTracker tracks usages of a ProviderConfig by creating or
124125
// updating the appropriate ProviderConfigUsage.
125126
type ProviderConfigUsageTracker struct {
126-
c Applicator
127-
of ProviderConfigUsage
127+
c Applicator
128+
of ProviderConfigUsage
129+
log logging.Logger
130+
client client.Client
128131
}
129132

130133
// NewProviderConfigUsageTracker creates a ProviderConfigUsageTracker.
131134
func NewProviderConfigUsageTracker(c client.Client, of ProviderConfigUsage) *ProviderConfigUsageTracker {
132-
return &ProviderConfigUsageTracker{c: NewAPIUpdatingApplicator(c), of: of}
135+
return &ProviderConfigUsageTracker{c: NewAPIUpdatingApplicator(c), of: of, log: logging.NewNopLogger(), client: c}
136+
}
137+
138+
// WithLogger adds a logger to the ProviderConfigUsageTracker.
139+
func (u *ProviderConfigUsageTracker) WithLogger(l logging.Logger) *ProviderConfigUsageTracker {
140+
u.log = l
141+
u.c = NewAPIUpdatingApplicator(u.client).WithLogger(l)
142+
return u
133143
}
134144

135145
// Track that the supplied Managed resource is using the ProviderConfig it

pkg/resource/providerconfig_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727

2828
xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
2929
"github.com/crossplane/crossplane-runtime/pkg/errors"
30+
"github.com/crossplane/crossplane-runtime/pkg/logging"
3031
"github.com/crossplane/crossplane-runtime/pkg/resource/fake"
3132
"github.com/crossplane/crossplane-runtime/pkg/test"
3233
)
@@ -317,7 +318,7 @@ func TestTrack(t *testing.T) {
317318

318319
for name, tc := range cases {
319320
t.Run(name, func(t *testing.T) {
320-
ut := &ProviderConfigUsageTracker{c: tc.fields.c, of: tc.fields.of}
321+
ut := &ProviderConfigUsageTracker{c: tc.fields.c, of: tc.fields.of, log: logging.NewNopLogger()}
321322
got := ut.Track(tc.args.ctx, tc.args.mg)
322323
if diff := cmp.Diff(tc.want, got, test.EquateErrors()); diff != "" {
323324
t.Errorf("\n%s\nut.Track(...): -want error, +got error:\n%s\n", tc.reason, diff)

pkg/resource/resource.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ package resource
1818

1919
import (
2020
"context"
21+
"encoding/json"
2122
"strings"
2223

24+
jsonpatch "github.com/evanphx/json-patch/v5"
2325
corev1 "k8s.io/api/core/v1"
2426
kerrors "k8s.io/apimachinery/pkg/api/errors"
2527
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -32,6 +34,7 @@ import (
3234

3335
xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
3436
"github.com/crossplane/crossplane-runtime/pkg/errors"
37+
"github.com/crossplane/crossplane-runtime/pkg/logging"
3538
"github.com/crossplane/crossplane-runtime/pkg/meta"
3639
)
3740

@@ -270,6 +273,30 @@ func UpdateFn(fn func(current, desired runtime.Object)) ApplyOption {
270273
}
271274
}
272275

276+
// LogDiff logs the diff between current and desired object.
277+
func LogDiff(log logging.Logger, current, desired runtime.Object) error {
278+
if log == nil {
279+
return nil
280+
}
281+
282+
oldData, err := json.Marshal(current)
283+
if err != nil {
284+
return errors.Wrapf(err, "failed to Marshal old data for %T", current)
285+
}
286+
newData, err := json.Marshal(desired)
287+
if err != nil {
288+
return errors.Wrapf(err, "failed to Marshal new data for %T", desired)
289+
}
290+
patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData)
291+
if err != nil {
292+
return errors.Wrapf(err, "failed to create patch for %T", current)
293+
}
294+
295+
log.WithValues("diff", string(patchBytes)).Info("patching object")
296+
297+
return nil
298+
}
299+
273300
type errNotControllable struct{ error }
274301

275302
func (e errNotControllable) NotControllable() bool {

0 commit comments

Comments
 (0)