From 1b07ee7987105b9d7c03c68c7ac84d9dffc272fd Mon Sep 17 00:00:00 2001 From: Yousong Zhou Date: Mon, 22 Mar 2021 19:17:51 +0800 Subject: [PATCH] region: fix setting nic index When a guest has two nics, changing ip address of the 1st will cause the new nic after detach then attach to be "1", colliding with the original nic of index 1 --- pkg/compute/models/guests.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/pkg/compute/models/guests.go b/pkg/compute/models/guests.go index 7a63ee5c96..d485fed311 100644 --- a/pkg/compute/models/guests.go +++ b/pkg/compute/models/guests.go @@ -2702,12 +2702,26 @@ func (self *SGuest) getAttach2NetworkCount(net *SNetwork) (int, error) { return q.CountWithError() } -func (self *SGuest) getMaxNicIndex() int8 { +func (self *SGuest) getUsableNicIndex() int8 { nics, err := self.GetNetworks("") if err != nil { return -1 } - return int8(len(nics)) + maxIndex := int8(len(nics)) + for i := int8(0); i <= maxIndex; i++ { + found := true + for j := range nics { + if nics[j].Index == i { + found = false + break + } + } + if found { + return i + } + } + panic(fmt.Sprintf("cannot find usable nic index for guest %s(%s)", + self.Name, self.Id)) } func (self *SGuest) setOSProfile(ctx context.Context, userCred mcclient.TokenCredential, profile jsonutils.JSONObject) error { @@ -2848,7 +2862,7 @@ func (self *SGuest) attach2NetworkOnce( nicDriver = args.nicDriver ) if index < 0 { - index = self.getMaxNicIndex() + index = self.getUsableNicIndex() } if nicDriver == "" { osProf := self.GetOSProfile()