scheduler util: handle cache.DeletedFinalStateUnknown in As

Informer callbacks must be prepared to get cache.DeletedFinalStateUnknown as
the deleted object. They can use that as hint that some information may have
been missed, but typically they just retrieve the stored object inside it.
This commit is contained in:
Patrick Ohly 2023-07-08 12:50:25 +02:00
parent ef48efc736
commit e01db32573

View File

@ -31,6 +31,7 @@ import (
"k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/retry"
corev1helpers "k8s.io/component-helpers/scheduling/corev1"
"k8s.io/klog/v2"
@ -164,6 +165,8 @@ func IsScalarResourceName(name v1.ResourceName) bool {
// As converts two objects to the given type.
// Both objects must be of the same type. If not, an error is returned.
// nil objects are allowed and will be converted to nil.
// For oldObj, cache.DeletedFinalStateUnknown is handled and the
// object stored in it will be converted instead.
func As[T runtime.Object](oldObj, newobj interface{}) (T, T, error) {
var oldTyped T
var newTyped T
@ -176,6 +179,9 @@ func As[T runtime.Object](oldObj, newobj interface{}) (T, T, error) {
}
if oldObj != nil {
if realOldObj, ok := oldObj.(cache.DeletedFinalStateUnknown); ok {
oldObj = realOldObj.Obj
}
oldTyped, ok = oldObj.(T)
if !ok {
return oldTyped, newTyped, fmt.Errorf("expected %T, but got %T", oldTyped, oldObj)