From d76107c2c9d01723eab4e3d13c64620ae1b0a5b7 Mon Sep 17 00:00:00 2001 From: Davanum Srinivas Date: Tue, 12 Nov 2024 04:34:32 -0500 Subject: [PATCH] Set the UserAgent in client-go based calls to kube-apiserver (#11569) Signed-off-by: Davanum Srinivas --- pkg/config/client.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/pkg/config/client.go b/pkg/config/client.go index c1006481cb..af31a2a064 100644 --- a/pkg/config/client.go +++ b/pkg/config/client.go @@ -3,12 +3,23 @@ package config import ( "fmt" "math" + "runtime" "k8s.io/cli-runtime/pkg/genericclioptions" rest "k8s.io/client-go/rest" clientcmd "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/release-utils/version" ) +// withUserAgent explicitly sets the UserAgent field in rest.Config which is +// then used by client-go for calls to the API server, helps with debugging issues +func withUserAgent(restConfig *rest.Config, err error) (*rest.Config, error) { + if err != nil && restConfig != nil { + restConfig.UserAgent = fmt.Sprintf("Kyverno/%s (%s; %s)", version.GetVersionInfo().GitVersion, runtime.GOOS, runtime.GOARCH) + } + return restConfig, err +} + // CreateClientConfig creates client config and applies rate limit QPS and burst func CreateClientConfig(kubeconfig string, qps float64, burst int) (*rest.Config, error) { clientConfig, err := createClientConfig(kubeconfig) @@ -20,15 +31,15 @@ func CreateClientConfig(kubeconfig string, qps float64, burst int) (*rest.Config } clientConfig.Burst = burst clientConfig.QPS = float32(qps) - return clientConfig, nil + return withUserAgent(clientConfig, nil) } // createClientConfig creates client config func createClientConfig(kubeconfig string) (*rest.Config, error) { if kubeconfig == "" { - return rest.InClusterConfig() + return withUserAgent(rest.InClusterConfig()) } - return clientcmd.BuildConfigFromFlags("", kubeconfig) + return withUserAgent(clientcmd.BuildConfigFromFlags("", kubeconfig)) } // CreateClientConfigWithContext creates client config from custom kubeconfig file and context @@ -37,5 +48,5 @@ func CreateClientConfigWithContext(kubeconfig string, context string) (*rest.Con kubernetesConfig := genericclioptions.NewConfigFlags(true) kubernetesConfig.KubeConfig = &kubeconfig kubernetesConfig.Context = &context - return kubernetesConfig.ToRESTConfig() + return withUserAgent(kubernetesConfig.ToRESTConfig()) }