From f04d77d687dcd5f2dbc546a92ab46a14b5c00d84 Mon Sep 17 00:00:00 2001 From: Doug MacEachern Date: Tue, 23 Nov 2021 10:37:52 -0800 Subject: [PATCH] fix: avoid possible panic in HostSystem.ManagementIPs If the HostSystem.Config or HostSystem.Config.VirtualNicManagerInfo fields are nil, the ManagementIPs method would panic. I was not able to reproduce this situation in a real VC, even with disconnecting a host from VC. Assuming this state is possible while an ESX host is being upgraded. Updated the test to nil both fields to ensure we don't panic. --- object/host_system.go | 12 +++++++++++- object/host_system_test.go | 34 +++++++++++++++++++++------------- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/object/host_system.go b/object/host_system.go index 7d1fa841c..ddf6cb8f1 100644 --- a/object/host_system.go +++ b/object/host_system.go @@ -82,7 +82,17 @@ func (h HostSystem) ManagementIPs(ctx context.Context) ([]net.IP, error) { return nil, err } - return internal.HostSystemManagementIPs(mh.Config.VirtualNicManagerInfo.NetConfig), nil + config := mh.Config + if config == nil { + return nil, nil + } + + info := config.VirtualNicManagerInfo + if info == nil { + return nil, nil + } + + return internal.HostSystemManagementIPs(info.NetConfig), nil } func (h HostSystem) Disconnect(ctx context.Context) (*Task, error) { diff --git a/object/host_system_test.go b/object/host_system_test.go index 6ba26f297..31caf4c31 100644 --- a/object/host_system_test.go +++ b/object/host_system_test.go @@ -15,7 +15,6 @@ package object_test import ( "context" - "log" "testing" "github.com/vmware/govmomi/find" @@ -24,16 +23,8 @@ import ( ) func TestHostSystemManagementIPs(t *testing.T) { - m := simulator.ESX() - m.Run(func(ctx context.Context, c *vim25.Client) error { - finder := find.NewFinder(c, false) - dc, err := finder.DefaultDatacenter(ctx) - if err != nil { - log.Fatalf("Failed to get default DC") - } - finder.SetDatacenter(dc) - - host, err := finder.DefaultHostSystem(ctx) + simulator.Test(func(ctx context.Context, c *vim25.Client) { + host, err := find.NewFinder(c).HostSystem(ctx, "DC0_C0_H0") if err != nil { t.Fatal(err) } @@ -43,11 +34,28 @@ func TestHostSystemManagementIPs(t *testing.T) { t.Fatal(err) } if len(ips) != 1 { - t.Fatalf("no mgmt ip found") + t.Fatal("no mgmt ip found") } if ips[0].String() != "127.0.0.1" { t.Fatalf("Expected management ip %s, got %s", "127.0.0.1", ips[0].String()) } - return nil + + // These fields can be nil while ESX is being upgraded + hs := simulator.Map.Get(host.Reference()).(*simulator.HostSystem) + tests := []func(){ + func() { hs.Config.VirtualNicManagerInfo = nil }, + func() { hs.Config = nil }, + } + + for _, f := range tests { + f() + ips, err = host.ManagementIPs(ctx) + if err != nil { + t.Fatal(err) + } + if len(ips) != 0 { + t.Fatal("expected zero ips") + } + } }) }