Fix(cli): guard vela top against nil rest.Config panic (#7279)

K8SVersion, velaCorePodUsage, and velaCLusterGatewayPodUsage in
references/cli/top/model/info.go called kubernetes.NewForConfig /
metrics.NewForConfig without checking for a nil *rest.Config first.
client-go panics with a nil-pointer dereference in that case instead
of returning an error, so vela top crashes instead of showing
Unknown/N/A for those fields.

Confirmed via two independent call paths that both panicked before
this fix: InfoBoard.Init (references/cli/top/component) and
App.Init (references/cli/top/view).

Added regression tests for all three functions with a nil config.

Signed-off-by: sakirr05 <sakirahmed75531@gmail.com>
Co-authored-by: sakirr05 <sakirahmed75531@gmail.com>
(cherry picked from commit 66e9107688)
This commit is contained in:
sakirr
2026-08-12 10:25:33 +00:00
committed by github-actions[bot]
parent 2f3e83d0a2
commit 88a970d5d1
2 changed files with 31 additions and 0 deletions
+9
View File
@@ -86,6 +86,9 @@ func (i *Info) ClusterNum() string {
// K8SVersion return k8s version info
func K8SVersion(cfg *rest.Config) string {
if cfg == nil {
return Unknown
}
c, err := kubernetes.NewForConfig(cfg)
if err != nil {
return Unknown
@@ -141,6 +144,9 @@ func ApplicationRunningNum(cfg *rest.Config) string {
}
func velaCorePodUsage(cfg *rest.Config) (*v1beta1.PodMetrics, error) {
if cfg == nil {
return nil, errors.New("no rest.Config available")
}
ctx := context.Background()
c, err := metrics.NewForConfig(cfg)
if err != nil {
@@ -194,6 +200,9 @@ func VelaCoreRatio(c client.Client, cfg *rest.Config) (string, string, string, s
}
func velaCLusterGatewayPodUsage(cfg *rest.Config) (*v1beta1.PodMetrics, error) {
if cfg == nil {
return nil, errors.New("no rest.Config available")
}
ctx := context.Background()
c, err := metrics.NewForConfig(cfg)
if err != nil {
+22
View File
@@ -22,6 +22,8 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/stretchr/testify/assert"
clicommon "github.com/oam-dev/kubevela/references/common"
)
func TestInfo_CurrentContext(t *testing.T) {
@@ -46,6 +48,26 @@ func TestInfo_GOLangVersion(t *testing.T) {
assert.Contains(t, GOLangVersion(), "go")
}
func TestInfo_K8SVersion_NilConfig(t *testing.T) {
assert.Equal(t, Unknown, K8SVersion(nil))
}
func TestInfo_VelaCoreRatio_NilConfig(t *testing.T) {
cpuL, memL, cpuR, memR := VelaCoreRatio(nil, nil)
assert.Equal(t, clicommon.MetricsNA, cpuL)
assert.Equal(t, clicommon.MetricsNA, memL)
assert.Equal(t, clicommon.MetricsNA, cpuR)
assert.Equal(t, clicommon.MetricsNA, memR)
}
func TestInfo_CLusterGatewayRatio_NilConfig(t *testing.T) {
cpuL, memL, cpuR, memR := CLusterGatewayRatio(nil, nil)
assert.Equal(t, clicommon.MetricsNA, cpuL)
assert.Equal(t, clicommon.MetricsNA, memL)
assert.Equal(t, clicommon.MetricsNA, cpuR)
assert.Equal(t, clicommon.MetricsNA, memR)
}
var _ = Describe("test info", func() {
It("running app num", func() {
Expect(ApplicationRunningNum(cfg)).To(Equal("1/1"))