From 299da1aa3b2a0458d9569fb19cdc2c8aeb14ee77 Mon Sep 17 00:00:00 2001 From: Emilien Macchi Date: Fri, 8 Apr 2022 10:23:21 -0400 Subject: [PATCH] Bug 2073398: Fix InstanceCreate port & trunk cleanup With this change, the port and trunk cleanups are triggered by any early failure of InstanceCreate. When InstanceCreate creates ports and if it creates trunks, these resources will be deleted if any of the next steps fail and cause the server never to be created. Note: the trunk will be deleted first, then the ports. --- pkg/cloud/openstack/clients/machineservice.go | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/pkg/cloud/openstack/clients/machineservice.go b/pkg/cloud/openstack/clients/machineservice.go index 3d11b82a91..9c919ac0ac 100644 --- a/pkg/cloud/openstack/clients/machineservice.go +++ b/pkg/cloud/openstack/clients/machineservice.go @@ -663,6 +663,18 @@ func (is *InstanceService) InstanceCreate(clusterName string, name string, clust if err != nil { return nil, fmt.Errorf("Failed to create port err: %v", err) } + defer func() { + // If the server is created in Nova, the lifetime of the associated ports will be + // bound to it. This deferred cleanup function tackles the case where a port was created + // but never attached to a server. In that case, the port must be removed manually. + if server == nil { + if err := ports.Delete(is.networkClient, port.ID).ExtractErr(); err != nil { + klog.Infof("Failed to delete stale port %q", port.ID) + } else { + klog.Infof("Deleted stale port %q", port.ID) + } + } + }() portTags := deduplicateList(append(machineTags, portOpt.Tags...)) _, err = attributestags.ReplaceAll(is.networkClient, "ports", port.ID, attributestags.ReplaceAllOpts{ @@ -675,10 +687,20 @@ func (is *InstanceService) InstanceCreate(clusterName string, name string, clust }) if config.Trunk == true { - _, err := getOrCreateTrunk(is, port, machineTags) + trunk, err := getOrCreateTrunk(is, port, machineTags) if err != nil { return nil, err } + defer func() { + // We need to cleanup the trunks before we remove the staled ports. + if server == nil { + if err := trunks.Delete(is.networkClient, trunk.ID).ExtractErr(); err != nil { + klog.Infof("Failed to delete stale trunk %q", trunk.ID) + } else { + klog.Infof("Deleted stale trunk %q", trunk.ID) + } + } + }() } }