client.Object occasionally returns empty string when calling for GroupVersionKind
davlucal opened this issue · comments
I am building a wrapper client around sigs.k8s.io/controller-runtime/pkg/client
using the following code:
// Delete implements client.Client.Delete
func (c *K8sMetricsClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error {
crType := obj.GetObjectKind().GroupVersionKind().Kind
namespace := obj.GetNamespace()
operation := "delete"
if crType == "" {
fmt.Printf("DELETE: crType is empty for object: %q %q ", obj.GetName(), obj.GetNamespace())
pc, file, line, ok := rt.Caller(1)
if !ok {
fmt.Println("Could not retrieve caller information")
} else {
// Retrieve the function name using runtime.FuncForPC
callerFunction := rt.FuncForPC(pc).Name()
// Print the caller information
fmt.Printf("Caller: %s, File: %s, Line: %d\n", callerFunction, file, line)
}
}
err := c.client.Delete(ctx, obj, opts...)
if err != nil {
ProcessK8sCallMetric(c.controllerName, crType, namespace, operation, "fail")
return err
}
ProcessK8sCallMetric(c.controllerName, crType, namespace, operation, "success")
return nil
}
The issue is that crType
is an empty string for some types.
GET: crType is empty for object: "" "" Caller: ***/pkg/util.fetchValueFromDefaultsConfigMap, File: /workspace/pkg/util/config.go, Line: 33
Here is the function that calls Get
:
corev1 "k8s.io/api/core/v1"
// blah blah code
var configmap corev1.ConfigMap
if err := c.Get(ctx, common.DefaultsConfigMap(), &configmap); err != nil {
return 0, err
}
I am pretty sure the types are registered in my controller's main.go
via:
import clientgoscheme "k8s.io/client-go/kubernetes/scheme"
func init() {
......
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
}
This issue happens sometimes, but in most of the cases i am able to see the type correctly showing up.
/kind support
The type meta fields are not populated most of the time, never assume that they are. Use apiutil.GVKForObject
to find the GVK for a given object.
@alvaroaleman Thank you for the response! Using apiutil.GVKForObject
fixed my issue. Why are the type meta fields not populated 'most of the time'?
Because it is something you can not rely on, as those are string fields. if you do pod := &corev1.Pod{}
, it won't have them set. Inside your code, the scheme is what provides this information, never the object itself except for generic objects like unstructured.Unstructured
Understand your point now. Thanks so much.