Skip to content

Commit

Permalink
optimize KObjs
Browse files Browse the repository at this point in the history
KObjs used to do significant work regardless whether the log entry would get
written at all. We can delay doing that work and (typically) skip it entirely
by just capturing the parameter and lazily converting to the actual slice if
needed in MarshalLog.

This depends on MarshalLog support in klog and other logger backends. If
changing the output to a string is acceptable, then adding a String function is
a safer alternative.
  • Loading branch information
pohly committed Apr 27, 2022
1 parent a0ed0fd commit fa1e391
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
25 changes: 20 additions & 5 deletions k8s_references.go
Expand Up @@ -76,19 +76,34 @@ func KRef(namespace, name string) ObjectRef {
}
}

// KObjs returns slice of ObjectRef from an slice of ObjectMeta
func KObjs(arg interface{}) []ObjectRef {
s := reflect.ValueOf(arg)
type kobjs struct {
arg interface{}
}

func (k kobjs) MarshalLog() interface{} {
s := reflect.ValueOf(k.arg)
var empty []ObjectRef
if s.Kind() != reflect.Slice {
return nil
// This mirrors the traditional behavior, but perhaps isn't
// what we want?
return empty
}
objectRefs := make([]ObjectRef, 0, s.Len())
for i := 0; i < s.Len(); i++ {
if v, ok := s.Index(i).Interface().(KMetadata); ok {
objectRefs = append(objectRefs, KObj(v))
} else {
return nil
// This mirrors the traditional behavior, but perhaps isn't
// what we want?
return empty
}
}
return objectRefs
}

// KObjs returns an object that will be logged like
// a slice of ObjectRefs for each entry in the parameter
// slice. If the parameter is not a slice, nil will be logged.
func KObjs(arg interface{}) logr.Marshaler {
return kobjs{arg}
}
5 changes: 3 additions & 2 deletions klog_test.go
Expand Up @@ -1845,8 +1845,9 @@ func TestKObjs(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if !reflect.DeepEqual(KObjs(tt.obj), tt.want) {
t.Errorf("\nwant:\t %v\n got:\t %v", tt.want, KObjs(tt.obj))
got := KObjs(tt.obj).MarshalLog()
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("\nwant:\t %v\n got:\t %v", tt.want, got)
}
})
}
Expand Down

0 comments on commit fa1e391

Please sign in to comment.