Skip to content

Commit f3d2175

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

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
@@ -27,6 +27,7 @@ import (
2727
"sigs.k8s.io/controller-runtime/pkg/client"
2828

2929
"github.com/crossplane/crossplane-runtime/pkg/errors"
30+
"github.com/crossplane/crossplane-runtime/pkg/logging"
3031
"github.com/crossplane/crossplane-runtime/pkg/meta"
3132
)
3233

@@ -38,7 +39,8 @@ const (
3839
// An APIPatchingApplicator applies changes to an object by either creating or
3940
// patching it in a Kubernetes API server.
4041
type APIPatchingApplicator struct {
41-
client client.Client
42+
client client.Client
43+
optionalLog logging.Logger // can be nil
4244
}
4345

4446
// NewAPIPatchingApplicator returns an Applicator that applies changes to an
@@ -47,6 +49,12 @@ func NewAPIPatchingApplicator(c client.Client) *APIPatchingApplicator {
4749
return &APIPatchingApplicator{client: c}
4850
}
4951

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

94+
if err := LogDiff(a.optionalLog, current, obj); err != nil {
95+
return err
96+
}
97+
8698
// TODO(negz): Allow callers to override the kind of patch used.
8799
return errors.Wrap(a.client.Patch(ctx, obj, client.MergeFromWithOptions(current, client.MergeFromWithOptimisticLock{})), "cannot patch object")
88100
}
@@ -102,7 +114,8 @@ func groupResource(c client.Client, o client.Object) (schema.GroupResource, erro
102114
// An APIUpdatingApplicator applies changes to an object by either creating or
103115
// updating it in a Kubernetes API server.
104116
type APIUpdatingApplicator struct {
105-
client client.Client
117+
client client.Client
118+
optionalLog logging.Logger // can be nil
106119
}
107120

108121
// NewAPIUpdatingApplicator returns an Applicator that applies changes to an
@@ -114,6 +127,12 @@ func NewAPIUpdatingApplicator(c client.Client) *APIUpdatingApplicator {
114127
return &APIUpdatingApplicator{client: c}
115128
}
116129

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

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

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)