From 479bb3562f1eb1e1075aea0431c58654b4504212 Mon Sep 17 00:00:00 2001 From: Pengfei Ni Date: Mon, 31 Aug 2020 08:08:41 +0000 Subject: [PATCH] Ensure getPrimaryInterfaceID not panic when network interfaces for Azure VMSS are null --- .../src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go | 8 ++++++-- .../legacy-cloud-providers/azure/azure_vmss_test.go | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go index 34848babce3..fabd58c6804 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go +++ b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go @@ -534,17 +534,21 @@ func (ss *scaleSet) GetPrivateIPsByNodeName(nodeName string) ([]string, error) { // This returns the full identifier of the primary NIC for the given VM. func (ss *scaleSet) getPrimaryInterfaceID(machine compute.VirtualMachineScaleSetVM) (string, error) { + if machine.NetworkProfile == nil || machine.NetworkProfile.NetworkInterfaces == nil { + return "", fmt.Errorf("failed to find the network interfaces for vm %s", to.String(machine.Name)) + } + if len(*machine.NetworkProfile.NetworkInterfaces) == 1 { return *(*machine.NetworkProfile.NetworkInterfaces)[0].ID, nil } for _, ref := range *machine.NetworkProfile.NetworkInterfaces { - if *ref.Primary { + if to.Bool(ref.Primary) { return *ref.ID, nil } } - return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", *machine.Name) + return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", to.String(machine.Name)) } // getVmssMachineID returns the full identifier of a vmss virtual machine. diff --git a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_test.go b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_test.go index 8ef023e0342..55ad4f032a7 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_test.go +++ b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_test.go @@ -949,6 +949,11 @@ func TestGetPrimaryInterfaceID(t *testing.T) { }, expectedErr: fmt.Errorf("failed to find a primary nic for the vm. vmname=\"vm\""), }, + { + description: "GetPrimaryInterfaceID should report an error if there's no network interface on the VMSS VM", + existedInterfaces: []compute.NetworkInterfaceReference{}, + expectedErr: fmt.Errorf("failed to find the network interfaces for vm vm"), + }, } for _, test := range testCases { @@ -963,6 +968,9 @@ func TestGetPrimaryInterfaceID(t *testing.T) { }, }, } + if len(test.existedInterfaces) == 0 { + vm.VirtualMachineScaleSetVMProperties.NetworkProfile = nil + } id, err := ss.getPrimaryInterfaceID(vm) assert.Equal(t, test.expectedErr, err, test.description+", but an error occurs")