Skip to content

Commit

Permalink
pkg/resource: add WithLogger to applicators
Browse files Browse the repository at this point in the history
Signed-off-by: Dr. Stefan Schimanski <[email protected]>
  • Loading branch information
sttts committed Aug 29, 2023
1 parent a645d31 commit f3d2175
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 6 deletions.
18 changes: 18 additions & 0 deletions pkg/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ package logging

import (
"github.com/go-logr/logr"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// A Logger logs messages. Messages may be supplemented by structured data.
Expand Down Expand Up @@ -92,3 +93,20 @@ func (l logrLogger) Debug(msg string, keysAndValues ...any) {
func (l logrLogger) WithValues(keysAndValues ...any) Logger {
return logrLogger{log: l.log.WithValues(keysAndValues...)} //nolint:logrlint // False positive - logrlint thinks there's an odd number of args.
}

// ForResource returns logging values for a resource.
func ForResource(object client.Object) []string {
ret := make([]string, 0, 10)
gvk := object.GetObjectKind().GroupVersionKind()
ret = append(ret,
"name", object.GetName(),
"kind", gvk.Kind,
"version", gvk.Version,
"group", gvk.Group,
)
if ns := object.GetNamespace(); ns != "" {
ret = append(ret, "namespace", ns)
}

return ret
}
27 changes: 25 additions & 2 deletions pkg/resource/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/meta"
)

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

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

// WithLogger sets the logger on the APIPatchingApplicator.
func (a *APIPatchingApplicator) WithLogger(l logging.Logger) *APIPatchingApplicator {
a.optionalLog = l
return a
}

// Apply changes to the supplied object. The object will be created if it does
// not exist, or patched if it does. If the object does exist, it will only be
// patched if the passed object has the same or an empty resource version.
Expand Down Expand Up @@ -83,6 +91,10 @@ func (a *APIPatchingApplicator) Apply(ctx context.Context, obj client.Object, ao
}
}

if err := LogDiff(a.optionalLog, current, obj); err != nil {
return err
}

// TODO(negz): Allow callers to override the kind of patch used.
return errors.Wrap(a.client.Patch(ctx, obj, client.MergeFromWithOptions(current, client.MergeFromWithOptimisticLock{})), "cannot patch object")
}
Expand All @@ -102,7 +114,8 @@ func groupResource(c client.Client, o client.Object) (schema.GroupResource, erro
// An APIUpdatingApplicator applies changes to an object by either creating or
// updating it in a Kubernetes API server.
type APIUpdatingApplicator struct {
client client.Client
client client.Client
optionalLog logging.Logger // can be nil
}

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

// WithLogger sets the logger on the APIUpdatingApplicator.
func (a *APIUpdatingApplicator) WithLogger(l logging.Logger) *APIUpdatingApplicator {
a.optionalLog = l
return a
}

// Apply changes to the supplied object. The object will be created if it does
// not exist, or updated if it does.
func (a *APIUpdatingApplicator) Apply(ctx context.Context, obj client.Object, ao ...ApplyOption) error {
Expand All @@ -137,6 +156,10 @@ func (a *APIUpdatingApplicator) Apply(ctx context.Context, obj client.Object, ao
}
}

if err := LogDiff(a.optionalLog, current, obj); err != nil {
return err
}

return errors.Wrap(a.client.Update(ctx, obj), "cannot update object")
}

Expand Down
16 changes: 13 additions & 3 deletions pkg/resource/providerconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (

xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/meta"
)

Expand Down Expand Up @@ -123,13 +124,22 @@ func (fn TrackerFn) Track(ctx context.Context, mg Managed) error {
// A ProviderConfigUsageTracker tracks usages of a ProviderConfig by creating or
// updating the appropriate ProviderConfigUsage.
type ProviderConfigUsageTracker struct {
c Applicator
of ProviderConfigUsage
c Applicator
of ProviderConfigUsage
log logging.Logger
client client.Client
}

// NewProviderConfigUsageTracker creates a ProviderConfigUsageTracker.
func NewProviderConfigUsageTracker(c client.Client, of ProviderConfigUsage) *ProviderConfigUsageTracker {
return &ProviderConfigUsageTracker{c: NewAPIUpdatingApplicator(c), of: of}
return &ProviderConfigUsageTracker{c: NewAPIUpdatingApplicator(c), of: of, log: logging.NewNopLogger(), client: c}
}

// WithLogger adds a logger to the ProviderConfigUsageTracker.
func (u *ProviderConfigUsageTracker) WithLogger(l logging.Logger) *ProviderConfigUsageTracker {
u.log = l
u.c = NewAPIUpdatingApplicator(u.client).WithLogger(l)
return u
}

// Track that the supplied Managed resource is using the ProviderConfig it
Expand Down
3 changes: 2 additions & 1 deletion pkg/resource/providerconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/resource/fake"
"github.com/crossplane/crossplane-runtime/pkg/test"
)
Expand Down Expand Up @@ -317,7 +318,7 @@ func TestTrack(t *testing.T) {

for name, tc := range cases {
t.Run(name, func(t *testing.T) {
ut := &ProviderConfigUsageTracker{c: tc.fields.c, of: tc.fields.of}
ut := &ProviderConfigUsageTracker{c: tc.fields.c, of: tc.fields.of, log: logging.NewNopLogger()}
got := ut.Track(tc.args.ctx, tc.args.mg)
if diff := cmp.Diff(tc.want, got, test.EquateErrors()); diff != "" {
t.Errorf("\n%s\nut.Track(...): -want error, +got error:\n%s\n", tc.reason, diff)
Expand Down
27 changes: 27 additions & 0 deletions pkg/resource/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ package resource

import (
"context"
"encoding/json"
"strings"

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

xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/meta"
)

Expand Down Expand Up @@ -270,6 +273,30 @@ func UpdateFn(fn func(current, desired runtime.Object)) ApplyOption {
}
}

// LogDiff logs the diff between current and desired object.
func LogDiff(log logging.Logger, current, desired runtime.Object) error {
if log == nil {
return nil
}

oldData, err := json.Marshal(current)
if err != nil {
return errors.Wrapf(err, "failed to Marshal old data for %T", current)
}
newData, err := json.Marshal(desired)
if err != nil {
return errors.Wrapf(err, "failed to Marshal new data for %T", desired)
}
patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData)
if err != nil {
return errors.Wrapf(err, "failed to create patch for %T", current)
}

log.WithValues("diff", string(patchBytes)).Info("patching object")

return nil
}

type errNotControllable struct{ error }

func (e errNotControllable) NotControllable() bool {
Expand Down

0 comments on commit f3d2175

Please sign in to comment.