From ebd3cb3945fec7f843001413f455dc232e96a654 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?p=C3=BDrus?= Date: Mon, 4 Nov 2024 08:03:28 +0100 Subject: [PATCH] [occm] passthrough context to gophercloud calls (#2697) --- pkg/openstack/loadbalancer.go | 82 +++++++++---------- pkg/openstack/loadbalancer_sg.go | 40 ++++----- pkg/openstack/loadbalancer_subnet_match.go | 22 +++-- .../loadbalancer_subnet_match_test.go | 2 +- pkg/openstack/openstack.go | 3 +- pkg/openstack/routes.go | 58 ++++++------- pkg/util/openstack/network.go | 22 ++--- 7 files changed, 114 insertions(+), 115 deletions(-) diff --git a/pkg/openstack/loadbalancer.go b/pkg/openstack/loadbalancer.go index ea39a3cc74..a753920018 100644 --- a/pkg/openstack/loadbalancer.go +++ b/pkg/openstack/loadbalancer.go @@ -225,7 +225,7 @@ func getListenerProtocol(protocol corev1.Protocol, svcConf *serviceConfig) liste } } -func (lbaas *LbaasV2) createOctaviaLoadBalancer(name, clusterName string, service *corev1.Service, nodes []*corev1.Node, svcConf *serviceConfig) (*loadbalancers.LoadBalancer, error) { +func (lbaas *LbaasV2) createOctaviaLoadBalancer(ctx context.Context, name, clusterName string, service *corev1.Service, nodes []*corev1.Node, svcConf *serviceConfig) (*loadbalancers.LoadBalancer, error) { createOpts := loadbalancers.CreateOpts{ Name: name, Description: fmt.Sprintf("Kubernetes external service %s/%s from cluster %s", service.Namespace, service.Name, clusterName), @@ -297,7 +297,7 @@ func (lbaas *LbaasV2) createOctaviaLoadBalancer(name, clusterName string, servic } mc := metrics.NewMetricContext("loadbalancer", "create") - loadbalancer, err := loadbalancers.Create(context.TODO(), lbaas.lb, createOpts).Extract() + loadbalancer, err := loadbalancers.Create(ctx, lbaas.lb, createOpts).Extract() if mc.ObserveRequest(err) != nil { var printObj interface{} = createOpts if opts, err := json.Marshal(createOpts); err == nil { @@ -329,7 +329,7 @@ func (lbaas *LbaasV2) createOctaviaLoadBalancer(name, clusterName string, servic // GetLoadBalancer returns whether the specified load balancer exists and its status func (lbaas *LbaasV2) GetLoadBalancer(ctx context.Context, clusterName string, service *corev1.Service) (*corev1.LoadBalancerStatus, bool, error) { name := lbaas.GetLoadBalancerName(ctx, clusterName, service) - legacyName := lbaas.getLoadBalancerLegacyName(ctx, clusterName, service) + legacyName := lbaas.getLoadBalancerLegacyName(service) lbID := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerID, "") var loadbalancer *loadbalancers.LoadBalancer var err error @@ -349,7 +349,7 @@ func (lbaas *LbaasV2) GetLoadBalancer(ctx context.Context, clusterName string, s status := &corev1.LoadBalancerStatus{} portID := loadbalancer.VipPortID if portID != "" { - floatIP, err := openstackutil.GetFloatingIPByPortID(lbaas.network, portID) + floatIP, err := openstackutil.GetFloatingIPByPortID(ctx, lbaas.network, portID) if err != nil { return nil, false, fmt.Errorf("failed when trying to get floating IP for port %s: %v", portID, err) } @@ -369,7 +369,7 @@ func (lbaas *LbaasV2) GetLoadBalancerName(_ context.Context, clusterName string, } // getLoadBalancerLegacyName returns the legacy load balancer name for backward compatibility. -func (lbaas *LbaasV2) getLoadBalancerLegacyName(_ context.Context, _ string, service *corev1.Service) string { +func (lbaas *LbaasV2) getLoadBalancerLegacyName(service *corev1.Service) string { return cloudprovider.DefaultLoadBalancerName(service) } @@ -590,10 +590,10 @@ func (lbaas *LbaasV2) deleteOctaviaListeners(lbID string, listenerList []listene return nil } -func (lbaas *LbaasV2) createFloatingIP(msg string, floatIPOpts floatingips.CreateOpts) (*floatingips.FloatingIP, error) { +func (lbaas *LbaasV2) createFloatingIP(ctx context.Context, msg string, floatIPOpts floatingips.CreateOpts) (*floatingips.FloatingIP, error) { klog.V(4).Infof("%s floating ip with opts %+v", msg, floatIPOpts) mc := metrics.NewMetricContext("floating_ip", "create") - floatIP, err := floatingips.Create(context.TODO(), lbaas.network, floatIPOpts).Extract() + floatIP, err := floatingips.Create(ctx, lbaas.network, floatIPOpts).Extract() err = PreserveGopherError(err) if mc.ObserveRequest(err) != nil { return floatIP, fmt.Errorf("error creating LB floatingip: %v", err) @@ -601,7 +601,7 @@ func (lbaas *LbaasV2) createFloatingIP(msg string, floatIPOpts floatingips.Creat return floatIP, err } -func (lbaas *LbaasV2) updateFloatingIP(floatingip *floatingips.FloatingIP, portID *string) (*floatingips.FloatingIP, error) { +func (lbaas *LbaasV2) updateFloatingIP(ctx context.Context, floatingip *floatingips.FloatingIP, portID *string) (*floatingips.FloatingIP, error) { floatUpdateOpts := floatingips.UpdateOpts{ PortID: portID, } @@ -611,7 +611,7 @@ func (lbaas *LbaasV2) updateFloatingIP(floatingip *floatingips.FloatingIP, portI klog.V(4).Infof("Detaching floating ip %q from port %q", floatingip.FloatingIP, floatingip.PortID) } mc := metrics.NewMetricContext("floating_ip", "update") - floatingip, err := floatingips.Update(context.TODO(), lbaas.network, floatingip.ID, floatUpdateOpts).Extract() + floatingip, err := floatingips.Update(ctx, lbaas.network, floatingip.ID, floatUpdateOpts).Extract() if mc.ObserveRequest(err) != nil { return nil, fmt.Errorf("error updating LB floatingip %+v: %v", floatUpdateOpts, err) } @@ -631,12 +631,12 @@ func (lbaas *LbaasV2) updateFloatingIP(floatingip *floatingips.FloatingIP, portI // a) If Spec.LoadBalancerIP is not set, just create a random FIP in the external network and use that. // b) If Spec.LoadBalancerIP is specified, try to create a FIP with that address. By default this is not allowed by // the Neutron policy for regular users! -func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Service, lb *loadbalancers.LoadBalancer, svcConf *serviceConfig, isLBOwner bool) (string, error) { +func (lbaas *LbaasV2) ensureFloatingIP(ctx context.Context, clusterName string, service *corev1.Service, lb *loadbalancers.LoadBalancer, svcConf *serviceConfig, isLBOwner bool) (string, error) { serviceName := fmt.Sprintf("%s/%s", service.Namespace, service.Name) // We need to fetch the FIP attached to load balancer's VIP port for both codepaths portID := lb.VipPortID - floatIP, err := openstackutil.GetFloatingIPByPortID(lbaas.network, portID) + floatIP, err := openstackutil.GetFloatingIPByPortID(ctx, lbaas.network, portID) if err != nil { return "", fmt.Errorf("failed when getting floating IP for port %s: %v", portID, err) } @@ -652,14 +652,14 @@ func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Servi fipDeleted := false if !keepFloatingAnnotation { klog.V(4).Infof("Deleting floating IP %v attached to loadbalancer port id %q for internal service %s", floatIP, portID, serviceName) - fipDeleted, err = lbaas.deleteFIPIfCreatedByProvider(floatIP, portID, service) + fipDeleted, err = lbaas.deleteFIPIfCreatedByProvider(ctx, floatIP, portID, service) if err != nil { return "", err } } if !fipDeleted { // if FIP wasn't deleted (because of keep-floatingip annotation or not being created by us) we should still detach it - _, err = lbaas.updateFloatingIP(floatIP, nil) + _, err = lbaas.updateFloatingIP(ctx, floatIP, nil) if err != nil { return "", err } @@ -684,7 +684,7 @@ func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Servi opts := floatingips.ListOpts{ FloatingIP: loadBalancerIP, } - existingIPs, err := openstackutil.GetFloatingIPs(lbaas.network, opts) + existingIPs, err := openstackutil.GetFloatingIPs(ctx, lbaas.network, opts) if err != nil { return "", fmt.Errorf("failed when trying to get existing floating IP %s, error: %v", loadBalancerIP, err) } @@ -693,7 +693,7 @@ func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Servi if len(existingIPs) > 0 { floatingip := existingIPs[0] if len(floatingip.PortID) == 0 { - floatIP, err = lbaas.updateFloatingIP(&floatingip, &portID) + floatIP, err = lbaas.updateFloatingIP(ctx, &floatingip, &portID) if err != nil { return "", err } @@ -714,10 +714,10 @@ func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Servi Description: fmt.Sprintf("Floating IP for Kubernetes external service %s from cluster %s", serviceName, clusterName), } - if loadBalancerIP == "" && svcConf.lbPublicSubnetSpec.MatcherConfigured() { + if loadBalancerIP == "" && svcConf.lbPublicSubnetSpec.matcherConfigured() { var foundSubnet subnets.Subnet // tweak list options for tags - foundSubnets, err := svcConf.lbPublicSubnetSpec.ListSubnetsForNetwork(lbaas, svcConf.lbPublicNetworkID) + foundSubnets, err := svcConf.lbPublicSubnetSpec.listSubnetsForNetwork(ctx, lbaas, svcConf.lbPublicNetworkID) if err != nil { return "", err } @@ -731,7 +731,7 @@ func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Servi svcConf.lbPublicSubnetSpec, svcConf.lbPublicNetworkID) for _, subnet := range foundSubnets { floatIPOpts.SubnetID = subnet.ID - floatIP, err = lbaas.createFloatingIP(fmt.Sprintf("Trying subnet %s for creating", subnet.Name), floatIPOpts) + floatIP, err = lbaas.createFloatingIP(ctx, fmt.Sprintf("Trying subnet %s for creating", subnet.Name), floatIPOpts) if err == nil { foundSubnet = subnet break @@ -748,7 +748,7 @@ func (lbaas *LbaasV2) ensureFloatingIP(clusterName string, service *corev1.Servi floatIPOpts.SubnetID = svcConf.lbPublicSubnetSpec.subnetID } floatIPOpts.FloatingIP = loadBalancerIP - floatIP, err = lbaas.createFloatingIP("Creating", floatIPOpts) + floatIP, err = lbaas.createFloatingIP(ctx, "Creating", floatIPOpts) if err != nil { return "", err } @@ -1046,7 +1046,7 @@ func (lbaas *LbaasV2) buildCreateMemberOpts(port corev1.ServicePort, nodes []*co } // Make sure the listener is created for Service -func (lbaas *LbaasV2) ensureOctaviaListener(lbID string, name string, curListenerMapping map[listenerKey]*listeners.Listener, port corev1.ServicePort, svcConf *serviceConfig, _ *corev1.Service) (*listeners.Listener, error) { +func (lbaas *LbaasV2) ensureOctaviaListener(lbID string, name string, curListenerMapping map[listenerKey]*listeners.Listener, port corev1.ServicePort, svcConf *serviceConfig) (*listeners.Listener, error) { listener, isPresent := curListenerMapping[listenerKey{ Protocol: getListenerProtocol(port.Protocol, svcConf), Port: int(port.Port), @@ -1412,13 +1412,13 @@ func (lbaas *LbaasV2) checkService(ctx context.Context, service *corev1.Service, barbicanUUID := slice[len(slice)-1] barbicanType := slice[len(slice)-2] if barbicanType == "containers" { - container, err := containers.Get(context.TODO(), lbaas.secret, barbicanUUID).Extract() + container, err := containers.Get(ctx, lbaas.secret, barbicanUUID).Extract() if err != nil { return fmt.Errorf("failed to get tls container %q: %v", svcConf.tlsContainerRef, err) } klog.V(4).Infof("Default TLS container %q found", container.ContainerRef) } else if barbicanType == "secrets" { - secret, err := secrets.Get(context.TODO(), lbaas.secret, barbicanUUID).Extract() + secret, err := secrets.Get(ctx, lbaas.secret, barbicanUUID).Extract() if err != nil { return fmt.Errorf("failed to get tls secret %q: %v", svcConf.tlsContainerRef, err) } @@ -1499,7 +1499,7 @@ func (lbaas *LbaasV2) checkService(ctx context.Context, service *corev1.Service, // If there's no annotation and configuration, try to autodetect the FIP network by looking up external nets if floatingNetworkID == "" { - floatingNetworkID, err = openstackutil.GetFloatingNetworkID(lbaas.network) + floatingNetworkID, err = openstackutil.GetFloatingNetworkID(ctx, lbaas.network) if err != nil { msg := "Failed to find floating-network-id for Service %s: %v" lbaas.eventRecorder.Eventf(service, corev1.EventTypeWarning, eventLBExternalNetworkSearchFailed, msg, serviceName, err) @@ -1529,7 +1529,7 @@ func (lbaas *LbaasV2) checkService(ctx context.Context, service *corev1.Service, // check configured subnet belongs to network if floatingNetworkID != "" && floatingSubnet.subnetID != "" { mc := metrics.NewMetricContext("subnet", "get") - subnet, err := subnets.Get(context.TODO(), lbaas.network, floatingSubnet.subnetID).Extract() + subnet, err := subnets.Get(ctx, lbaas.network, floatingSubnet.subnetID).Extract() if mc.ObserveRequest(err) != nil { return fmt.Errorf("failed to find subnet %q: %v", floatingSubnet.subnetID, err) } @@ -1732,14 +1732,14 @@ func (lbaas *LbaasV2) ensureOctaviaLoadBalancer(ctx context.Context, clusterName } } } else { - legacyName := lbaas.getLoadBalancerLegacyName(ctx, clusterName, service) + legacyName := lbaas.getLoadBalancerLegacyName(service) loadbalancer, err = getLoadbalancerByName(lbaas.lb, lbName, legacyName) if err != nil { if err != cpoerrors.ErrNotFound { return nil, fmt.Errorf("error getting loadbalancer for Service %s: %v", serviceName, err) } klog.InfoS("Creating loadbalancer", "lbName", lbName, "service", klog.KObj(service)) - loadbalancer, err = lbaas.createOctaviaLoadBalancer(lbName, clusterName, service, filteredNodes, svcConf) + loadbalancer, err = lbaas.createOctaviaLoadBalancer(ctx, lbName, clusterName, service, filteredNodes, svcConf) if err != nil { return nil, fmt.Errorf("error creating loadbalancer %s: %v", lbName, err) } @@ -1780,7 +1780,7 @@ func (lbaas *LbaasV2) ensureOctaviaLoadBalancer(ctx context.Context, clusterName } for portIndex, port := range service.Spec.Ports { - listener, err := lbaas.ensureOctaviaListener(loadbalancer.ID, cpoutil.Sprintf255(listenerFormat, portIndex, lbName), curListenerMapping, port, svcConf, service) + listener, err := lbaas.ensureOctaviaListener(loadbalancer.ID, cpoutil.Sprintf255(listenerFormat, portIndex, lbName), curListenerMapping, port, svcConf) if err != nil { return nil, err } @@ -1813,7 +1813,7 @@ func (lbaas *LbaasV2) ensureOctaviaLoadBalancer(ctx context.Context, clusterName lbaas.eventRecorder.Eventf(service, corev1.EventTypeWarning, eventLBFloatingIPSkipped, msg, serviceName, addr) klog.Infof(msg, serviceName, addr) } else { - addr, err = lbaas.ensureFloatingIP(clusterName, service, loadbalancer, svcConf, isLBOwner) + addr, err = lbaas.ensureFloatingIP(ctx, clusterName, service, loadbalancer, svcConf, isLBOwner) if err != nil { return nil, err } @@ -1838,14 +1838,14 @@ func (lbaas *LbaasV2) ensureOctaviaLoadBalancer(ctx context.Context, clusterName status := lbaas.createLoadBalancerStatus(service, svcConf, addr) if lbaas.opts.ManageSecurityGroups { - err := lbaas.ensureAndUpdateOctaviaSecurityGroup(clusterName, service, filteredNodes, svcConf) + err := lbaas.ensureAndUpdateOctaviaSecurityGroup(ctx, clusterName, service, filteredNodes, svcConf) if err != nil { return status, fmt.Errorf("failed when reconciling security groups for LB service %v/%v: %v", service.Namespace, service.Name, err) } } else { // Attempt to delete the SG if `manage-security-groups` is disabled. When CPO is reconfigured to enable it we // will reconcile the LB and create the SG. This is to make sure it works the same in the opposite direction. - if err := lbaas.ensureSecurityGroupDeleted(clusterName, service); err != nil { + if err := lbaas.ensureSecurityGroupDeleted(ctx, service); err != nil { return status, err } } @@ -1861,7 +1861,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(ctx context.Context, clusterName string return status, mc.ObserveReconcile(err) } -func (lbaas *LbaasV2) listSubnetsForNetwork(networkID string, tweak ...TweakSubNetListOpsFunction) ([]subnets.Subnet, error) { +func (lbaas *LbaasV2) listSubnetsForNetwork(ctx context.Context, networkID string, tweak ...TweakSubNetListOpsFunction) ([]subnets.Subnet, error) { var opts = subnets.ListOpts{NetworkID: networkID} for _, f := range tweak { if f != nil { @@ -1869,7 +1869,7 @@ func (lbaas *LbaasV2) listSubnetsForNetwork(networkID string, tweak ...TweakSubN } } mc := metrics.NewMetricContext("subnet", "list") - allPages, err := subnets.List(lbaas.network, opts).AllPages(context.TODO()) + allPages, err := subnets.List(lbaas.network, opts).AllPages(ctx) if mc.ObserveRequest(err) != nil { return nil, fmt.Errorf("error listing subnets of network %s: %v", networkID, err) } @@ -1907,7 +1907,7 @@ func (lbaas *LbaasV2) updateOctaviaLoadBalancer(ctx context.Context, clusterName } else { // This is a Service created before shared LB is supported. name := lbaas.GetLoadBalancerName(ctx, clusterName, service) - legacyName := lbaas.getLoadBalancerLegacyName(ctx, clusterName, service) + legacyName := lbaas.getLoadBalancerLegacyName(service) loadbalancer, err = getLoadbalancerByName(lbaas.lb, name, legacyName) if err != nil { return err @@ -1954,7 +1954,7 @@ func (lbaas *LbaasV2) updateOctaviaLoadBalancer(ctx context.Context, clusterName } if lbaas.opts.ManageSecurityGroups { - err := lbaas.ensureAndUpdateOctaviaSecurityGroup(clusterName, service, filteredNodes, svcConf) + err := lbaas.ensureAndUpdateOctaviaSecurityGroup(ctx, clusterName, service, filteredNodes, svcConf) if err != nil { return fmt.Errorf("failed to update Security Group for loadbalancer service %s: %v", serviceName, err) } @@ -1980,7 +1980,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(ctx context.Context, clusterName return mc.ObserveReconcile(err) } -func (lbaas *LbaasV2) deleteFIPIfCreatedByProvider(fip *floatingips.FloatingIP, portID string, service *corev1.Service) (bool, error) { +func (lbaas *LbaasV2) deleteFIPIfCreatedByProvider(ctx context.Context, fip *floatingips.FloatingIP, portID string, service *corev1.Service) (bool, error) { matched, err := regexp.Match("Floating IP for Kubernetes external service", []byte(fip.Description)) if err != nil { return false, err @@ -1992,7 +1992,7 @@ func (lbaas *LbaasV2) deleteFIPIfCreatedByProvider(fip *floatingips.FloatingIP, } klog.InfoS("Deleting floating IP for service", "floatingIP", fip.FloatingIP, "service", klog.KObj(service)) mc := metrics.NewMetricContext("floating_ip", "delete") - err = floatingips.Delete(context.TODO(), lbaas.network, fip.ID).ExtractErr() + err = floatingips.Delete(ctx, lbaas.network, fip.ID).ExtractErr() if mc.ObserveRequest(err) != nil { return false, fmt.Errorf("failed to delete floating IP %s for loadbalancer VIP port %s: %v", fip.FloatingIP, portID, err) } @@ -2079,7 +2079,7 @@ func (lbaas *LbaasV2) deleteLoadBalancer(loadbalancer *loadbalancers.LoadBalance func (lbaas *LbaasV2) ensureLoadBalancerDeleted(ctx context.Context, clusterName string, service *corev1.Service) error { lbName := lbaas.GetLoadBalancerName(ctx, clusterName, service) - legacyName := lbaas.getLoadBalancerLegacyName(ctx, clusterName, service) + legacyName := lbaas.getLoadBalancerLegacyName(service) var err error var loadbalancer *loadbalancers.LoadBalancer isSharedLB := false @@ -2135,14 +2135,14 @@ func (lbaas *LbaasV2) ensureLoadBalancerDeleted(ctx context.Context, clusterName if needDeleteLB && !keepFloatingAnnotation { if loadbalancer.VipPortID != "" { portID := loadbalancer.VipPortID - fip, err := openstackutil.GetFloatingIPByPortID(lbaas.network, portID) + fip, err := openstackutil.GetFloatingIPByPortID(ctx, lbaas.network, portID) if err != nil { return fmt.Errorf("failed to get floating IP for loadbalancer VIP port %s: %v", portID, err) } // Delete the floating IP only if it was created dynamically by the controller manager. if fip != nil { - _, err = lbaas.deleteFIPIfCreatedByProvider(fip, portID, service) + _, err = lbaas.deleteFIPIfCreatedByProvider(ctx, fip, portID, service) if err != nil { return err } @@ -2175,7 +2175,7 @@ func (lbaas *LbaasV2) ensureLoadBalancerDeleted(ctx context.Context, clusterName // Delete the Security Group. We're doing that even if `manage-security-groups` is disabled to make sure we don't // orphan created SGs even if CPO got reconfigured. - if err := lbaas.ensureSecurityGroupDeleted(clusterName, service); err != nil { + if err := lbaas.ensureSecurityGroupDeleted(ctx, service); err != nil { return err } @@ -2207,7 +2207,7 @@ func GetLoadBalancerSourceRanges(service *corev1.Service, preferredIPFamily core val = defaultLoadBalancerSourceRangesIPv4 } } - specs := strings.Split(val, ",") + specs := cpoutil.SplitTrim(val, ',') ipnets, err := netsets.ParseIPNets(specs...) if err != nil { return nil, fmt.Errorf("%s: %s is not valid. Expecting a comma-separated list of source IP ranges. For example, 10.0.0.0/24,192.168.2.0/24", corev1.AnnotationLoadBalancerSourceRangesKey, val) diff --git a/pkg/openstack/loadbalancer_sg.go b/pkg/openstack/loadbalancer_sg.go index 875de31e32..0443c45566 100644 --- a/pkg/openstack/loadbalancer_sg.go +++ b/pkg/openstack/loadbalancer_sg.go @@ -50,7 +50,7 @@ func getSecurityGroupName(service *corev1.Service) string { } // applyNodeSecurityGroupIDForLB associates the security group with the ports being members of the LB on the nodes. -func applyNodeSecurityGroupIDForLB(network *gophercloud.ServiceClient, svcConf *serviceConfig, nodes []*corev1.Node, sg string) error { +func applyNodeSecurityGroupIDForLB(ctx context.Context, network *gophercloud.ServiceClient, svcConf *serviceConfig, nodes []*corev1.Node, sg string) error { for _, node := range nodes { serverID, _, err := instanceIDFromProviderID(node.Spec.ProviderID) if err != nil { @@ -64,7 +64,7 @@ func applyNodeSecurityGroupIDForLB(network *gophercloud.ServiceClient, svcConf * } listOpts := neutronports.ListOpts{DeviceID: serverID} - allPorts, err := openstackutil.GetPorts[PortWithPortSecurity](network, listOpts) + allPorts, err := openstackutil.GetPorts[PortWithPortSecurity](ctx, network, listOpts) if err != nil { return err } @@ -92,7 +92,7 @@ func applyNodeSecurityGroupIDForLB(network *gophercloud.ServiceClient, svcConf * newSGs := append(port.SecurityGroups, sg) updateOpts := neutronports.UpdateOpts{SecurityGroups: &newSGs} mc := metrics.NewMetricContext("port", "update") - res := neutronports.Update(context.TODO(), network, port.ID, updateOpts) + res := neutronports.Update(ctx, network, port.ID, updateOpts) if mc.ObserveRequest(res.Err) != nil { return fmt.Errorf("failed to update security group for port %s: %v", port.ID, res.Err) } @@ -103,10 +103,10 @@ func applyNodeSecurityGroupIDForLB(network *gophercloud.ServiceClient, svcConf * } // disassociateSecurityGroupForLB removes the given security group from the ports -func disassociateSecurityGroupForLB(network *gophercloud.ServiceClient, sg string) error { +func disassociateSecurityGroupForLB(ctx context.Context, network *gophercloud.ServiceClient, sg string) error { // Find all the ports that have the security group associated. listOpts := neutronports.ListOpts{SecurityGroups: []string{sg}} - allPorts, err := openstackutil.GetPorts[neutronports.Port](network, listOpts) + allPorts, err := openstackutil.GetPorts[neutronports.Port](ctx, network, listOpts) if err != nil { return err } @@ -125,7 +125,7 @@ func disassociateSecurityGroupForLB(network *gophercloud.ServiceClient, sg strin // we don't trigger a lost update issue. updateOpts := neutronports.UpdateOpts{SecurityGroups: &newSGs} mc := metrics.NewMetricContext("port", "update") - res := neutronports.Update(context.TODO(), network, port.ID, updateOpts) + res := neutronports.Update(ctx, network, port.ID, updateOpts) if mc.ObserveRequest(res.Err) != nil { return fmt.Errorf("failed to update security group for port %s: %v", port.ID, res.Err) } @@ -134,7 +134,7 @@ func disassociateSecurityGroupForLB(network *gophercloud.ServiceClient, sg strin // so this stays for backward compatibility. It's reasonable to delete it in the future. 404s are ignored. if slices.Contains(port.Tags, sg) { mc = metrics.NewMetricContext("port_tag", "delete") - err := neutrontags.Delete(context.TODO(), network, "ports", port.ID, sg).ExtractErr() + err := neutrontags.Delete(ctx, network, "ports", port.ID, sg).ExtractErr() if mc.ObserveRequest(err) != nil { return fmt.Errorf("failed to remove tag %s to port %s: %v", sg, port.ID, res.Err) } @@ -145,9 +145,9 @@ func disassociateSecurityGroupForLB(network *gophercloud.ServiceClient, sg strin } // group, if it not present. -func (lbaas *LbaasV2) ensureSecurityRule(sgRuleCreateOpts rules.CreateOpts) error { +func (lbaas *LbaasV2) ensureSecurityRule(ctx context.Context, sgRuleCreateOpts rules.CreateOpts) error { mc := metrics.NewMetricContext("security_group_rule", "create") - _, err := rules.Create(context.TODO(), lbaas.network, sgRuleCreateOpts).Extract() + _, err := rules.Create(ctx, lbaas.network, sgRuleCreateOpts).Extract() if err != nil && cpoerrors.IsConflictError(err) { // Conflict means the SG rule already exists, so ignoring that error. klog.Warningf("Security group rule already found when trying to create it. This indicates concurrent "+ @@ -204,7 +204,7 @@ func getRulesToCreateAndDelete(wantedRules []rules.CreateOpts, existingRules []r } // ensureAndUpdateOctaviaSecurityGroup handles the creation and update of the security group and the securiry rules for the octavia load balancer -func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, apiService *corev1.Service, nodes []*corev1.Node, svcConf *serviceConfig) error { +func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(ctx context.Context, clusterName string, apiService *corev1.Service, nodes []*corev1.Node, svcConf *serviceConfig) error { // get service ports ports := apiService.Spec.Ports if len(ports) == 0 { @@ -213,7 +213,7 @@ func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, ap // ensure security group for LB lbSecGroupName := getSecurityGroupName(apiService) - lbSecGroupID, err := secgroups.IDFromName(context.TODO(), lbaas.network, lbSecGroupName) + lbSecGroupID, err := secgroups.IDFromName(ctx, lbaas.network, lbSecGroupName) if err != nil { // If the security group of LB not exist, create it later if cpoerrors.IsNotFound(err) { @@ -230,7 +230,7 @@ func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, ap } mc := metrics.NewMetricContext("security_group", "create") - lbSecGroup, err := groups.Create(context.TODO(), lbaas.network, lbSecGroupCreateOpts).Extract() + lbSecGroup, err := groups.Create(ctx, lbaas.network, lbSecGroupCreateOpts).Extract() if mc.ObserveRequest(err) != nil { return fmt.Errorf("failed to create Security Group for loadbalancer service %s/%s: %v", apiService.Namespace, apiService.Name, err) } @@ -238,7 +238,7 @@ func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, ap } mc := metrics.NewMetricContext("subnet", "get") - subnet, err := subnets.Get(context.TODO(), lbaas.network, svcConf.lbMemberSubnetID).Extract() + subnet, err := subnets.Get(ctx, lbaas.network, svcConf.lbMemberSubnetID).Extract() if mc.ObserveRequest(err) != nil { return fmt.Errorf( "failed to find subnet %s from openstack: %v", svcConf.lbMemberSubnetID, err) @@ -306,7 +306,7 @@ func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, ap // create new rules for _, opts := range toCreate { - err := lbaas.ensureSecurityRule(opts) + err := lbaas.ensureSecurityRule(ctx, opts) if err != nil { return fmt.Errorf("failed to apply security rule (%v), %w", opts, err) } @@ -316,7 +316,7 @@ func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, ap for _, existingRule := range toDelete { klog.Infof("Deleting rule %s from security group %s (%s)", existingRule.ID, existingRule.SecGroupID, lbSecGroupName) mc := metrics.NewMetricContext("security_group_rule", "delete") - err := rules.Delete(context.TODO(), lbaas.network, existingRule.ID).ExtractErr() + err := rules.Delete(ctx, lbaas.network, existingRule.ID).ExtractErr() if err != nil && cpoerrors.IsNotFound(err) { // ignore 404 klog.Warningf("Security group rule %s found missing when trying to delete it. This indicates concurrent "+ @@ -327,17 +327,17 @@ func (lbaas *LbaasV2) ensureAndUpdateOctaviaSecurityGroup(clusterName string, ap } } - if err := applyNodeSecurityGroupIDForLB(lbaas.network, svcConf, nodes, lbSecGroupID); err != nil { + if err := applyNodeSecurityGroupIDForLB(ctx, lbaas.network, svcConf, nodes, lbSecGroupID); err != nil { return err } return nil } // ensureSecurityGroupDeleted deleting security group for specific loadbalancer service. -func (lbaas *LbaasV2) ensureSecurityGroupDeleted(_ string, service *corev1.Service) error { +func (lbaas *LbaasV2) ensureSecurityGroupDeleted(ctx context.Context, service *corev1.Service) error { // Generate Name lbSecGroupName := getSecurityGroupName(service) - lbSecGroupID, err := secgroups.IDFromName(context.TODO(), lbaas.network, lbSecGroupName) + lbSecGroupID, err := secgroups.IDFromName(ctx, lbaas.network, lbSecGroupName) if err != nil { if cpoerrors.IsNotFound(err) { // It is OK when the security group has been deleted by others. @@ -347,12 +347,12 @@ func (lbaas *LbaasV2) ensureSecurityGroupDeleted(_ string, service *corev1.Servi } // Disassociate the security group from the neutron ports on the nodes. - if err := disassociateSecurityGroupForLB(lbaas.network, lbSecGroupID); err != nil { + if err := disassociateSecurityGroupForLB(ctx, lbaas.network, lbSecGroupID); err != nil { return fmt.Errorf("failed to disassociate security group %s: %v", lbSecGroupID, err) } mc := metrics.NewMetricContext("security_group", "delete") - lbSecGroup := groups.Delete(context.TODO(), lbaas.network, lbSecGroupID) + lbSecGroup := groups.Delete(ctx, lbaas.network, lbSecGroupID) if lbSecGroup.Err != nil && !cpoerrors.IsNotFound(lbSecGroup.Err) { return mc.ObserveRequest(lbSecGroup.Err) } diff --git a/pkg/openstack/loadbalancer_subnet_match.go b/pkg/openstack/loadbalancer_subnet_match.go index 790045b51b..8fcc719b52 100644 --- a/pkg/openstack/loadbalancer_subnet_match.go +++ b/pkg/openstack/loadbalancer_subnet_match.go @@ -17,12 +17,14 @@ limitations under the License. package openstack import ( + "context" "fmt" "regexp" "strings" "github.com/gophercloud/gophercloud/v2/openstack/networking/v2/subnets" "gopkg.in/godo.v2/glob" + "k8s.io/cloud-provider-openstack/pkg/util" ) // floatingSubnetSpec contains the specification of the public subnet to use for @@ -119,18 +121,18 @@ func subnetTagMatcher(tags string) matcher { } func (s *floatingSubnetSpec) Configured() bool { - if s != nil && (s.subnetID != "" || s.MatcherConfigured()) { + if s != nil && (s.subnetID != "" || s.matcherConfigured()) { return true } return false } -func (s *floatingSubnetSpec) ListSubnetsForNetwork(lbaas *LbaasV2, networkID string) ([]subnets.Subnet, error) { - matcher, err := s.Matcher(false) +func (s *floatingSubnetSpec) listSubnetsForNetwork(ctx context.Context, lbaas *LbaasV2, networkID string) ([]subnets.Subnet, error) { + matcher, err := s.matcher(false) if err != nil { return nil, err } - list, err := lbaas.listSubnetsForNetwork(networkID, s.tweakListOpts) + list, err := lbaas.listSubnetsForNetwork(ctx, networkID, s.tweakListOpts) if err != nil { return nil, err } @@ -170,7 +172,7 @@ func (s *floatingSubnetSpec) tweakListOpts(opts *subnets.ListOpts) { } } -func (s *floatingSubnetSpec) MatcherConfigured() bool { +func (s *floatingSubnetSpec) matcherConfigured() bool { if s != nil && s.subnetID == "" && (s.subnet != "" || s.subnetTags != "") { return true } @@ -196,8 +198,8 @@ func (s *floatingSubnetSpec) String() string { return addField(pat, "tags", s.subnetTags) } -func (s *floatingSubnetSpec) Matcher(tag bool) (matcher, error) { - if !s.MatcherConfigured() { +func (s *floatingSubnetSpec) matcher(tag bool) (matcher, error) { + if !s.matcherConfigured() { return nil, nil } var match matcher @@ -226,9 +228,5 @@ func tagList(tags string) ([]string, bool, bool) { if all { tags = tags[1:] } - list := strings.Split(tags, ",") - for i := range list { - list[i] = strings.TrimSpace(list[i]) - } - return list, not, all + return util.SplitTrim(tags, ','), not, all } diff --git a/pkg/openstack/loadbalancer_subnet_match_test.go b/pkg/openstack/loadbalancer_subnet_match_test.go index 8293877088..087feb9800 100644 --- a/pkg/openstack/loadbalancer_subnet_match_test.go +++ b/pkg/openstack/loadbalancer_subnet_match_test.go @@ -103,7 +103,7 @@ func runTag(t *testing.T, subnet *subnets.Subnet, spec floatingSubnetSpec, expec } func runMatch(t *testing.T, subnet *subnets.Subnet, spec floatingSubnetSpec, expected bool) { - m, err := spec.Matcher(true) + m, err := spec.matcher(true) assert.NoError(t, err) assert.Equal(t, m(subnet), expected) } diff --git a/pkg/openstack/openstack.go b/pkg/openstack/openstack.go index 0f45ed070a..ef1a7bc57b 100644 --- a/pkg/openstack/openstack.go +++ b/pkg/openstack/openstack.go @@ -456,13 +456,14 @@ func (os *OpenStack) GetZoneByNodeName(ctx context.Context, nodeName types.NodeN func (os *OpenStack) Routes() (cloudprovider.Routes, bool) { klog.V(4).Info("openstack.Routes() called") + ctx := context.TODO() network, err := client.NewNetworkV2(os.provider, os.epOpts) if err != nil { klog.Errorf("Failed to create an OpenStack Network client: %v", err) return nil, false } - netExts, err := openstackutil.GetNetworkExtensions(network) + netExts, err := openstackutil.GetNetworkExtensions(ctx, network) if err != nil { klog.Warningf("Failed to list neutron extensions: %v", err) return nil, false diff --git a/pkg/openstack/routes.go b/pkg/openstack/routes.go index 96bf8e5929..850061750d 100644 --- a/pkg/openstack/routes.go +++ b/pkg/openstack/routes.go @@ -82,7 +82,7 @@ func (r *Routes) ListRoutes(ctx context.Context, clusterName string) ([]*cloudpr } mc := metrics.NewMetricContext("router", "get") - router, err := routers.Get(context.TODO(), r.network, r.os.routeOpts.RouterID).Extract() + router, err := routers.Get(ctx, r.network, r.os.routeOpts.RouterID).Extract() if mc.ObserveRequest(err) != nil { return nil, err } @@ -100,7 +100,7 @@ func (r *Routes) ListRoutes(ctx context.Context, clusterName string) ([]*cloudpr } // detect router's private network ID for further VM ports filtering - r.networkIDs, err = getRouterNetworkIDs(r.network, r.os.routeOpts.RouterID) + r.networkIDs, err = getRouterNetworkIDs(ctx, r.network, r.os.routeOpts.RouterID) if err != nil { return nil, err } @@ -108,12 +108,12 @@ func (r *Routes) ListRoutes(ctx context.Context, clusterName string) ([]*cloudpr return routes, nil } -func getRouterNetworkIDs(network *gophercloud.ServiceClient, routerID string) ([]string, error) { +func getRouterNetworkIDs(ctx context.Context, network *gophercloud.ServiceClient, routerID string) ([]string, error) { opts := ports.ListOpts{ DeviceID: routerID, } mc := metrics.NewMetricContext("port", "list") - pages, err := ports.List(network, opts).AllPages(context.TODO()) + pages, err := ports.List(network, opts).AllPages(ctx) if mc.ObserveRequest(err) != nil { return nil, err } @@ -173,11 +173,11 @@ func getAddrByNodeName(name types.NodeName, needIPv6 bool, nodes []*v1.Node) str return "" } -func updateRoutes(network *gophercloud.ServiceClient, router *routers.Router, newRoutes []routers.Route) (func(), error) { +func updateRoutes(ctx context.Context, network *gophercloud.ServiceClient, router *routers.Router, newRoutes []routers.Route) (func(), error) { origRoutes := router.Routes // shallow copy mc := metrics.NewMetricContext("router", "update") - _, err := routers.Update(context.TODO(), network, router.ID, routers.UpdateOpts{ + _, err := routers.Update(ctx, network, router.ID, routers.UpdateOpts{ Routes: &newRoutes, }).Extract() if mc.ObserveRequest(err) != nil { @@ -187,7 +187,7 @@ func updateRoutes(network *gophercloud.ServiceClient, router *routers.Router, ne unwinder := func() { klog.V(4).Infof("Reverting routes change to router %v", router.ID) mc := metrics.NewMetricContext("router", "update") - _, err := routers.Update(context.TODO(), network, router.ID, routers.UpdateOpts{ + _, err := routers.Update(ctx, network, router.ID, routers.UpdateOpts{ Routes: &origRoutes, }).Extract() if mc.ObserveRequest(err) != nil { @@ -198,9 +198,9 @@ func updateRoutes(network *gophercloud.ServiceClient, router *routers.Router, ne return unwinder, nil } -func addRoute(network *gophercloud.ServiceClient, routerID string, newRoute []routers.Route) (func(), error) { +func addRoute(ctx context.Context, network *gophercloud.ServiceClient, routerID string, newRoute []routers.Route) (func(), error) { mc := metrics.NewMetricContext("router", "update") - _, err := extraroutes.Add(context.TODO(), network, routerID, extraroutes.Opts{ + _, err := extraroutes.Add(ctx, network, routerID, extraroutes.Opts{ Routes: &newRoute, }).Extract() if mc.ObserveRequest(err) != nil { @@ -210,7 +210,7 @@ func addRoute(network *gophercloud.ServiceClient, routerID string, newRoute []ro unwinder := func() { klog.V(4).Infof("Reverting routes change to router %v", routerID) mc := metrics.NewMetricContext("router", "update") - _, err := extraroutes.Remove(context.TODO(), network, routerID, extraroutes.Opts{ + _, err := extraroutes.Remove(ctx, network, routerID, extraroutes.Opts{ Routes: &newRoute, }).Extract() if mc.ObserveRequest(err) != nil { @@ -221,9 +221,9 @@ func addRoute(network *gophercloud.ServiceClient, routerID string, newRoute []ro return unwinder, nil } -func removeRoute(network *gophercloud.ServiceClient, routerID string, oldRoute []routers.Route) (func(), error) { +func removeRoute(ctx context.Context, network *gophercloud.ServiceClient, routerID string, oldRoute []routers.Route) (func(), error) { mc := metrics.NewMetricContext("router", "update") - _, err := extraroutes.Remove(context.TODO(), network, routerID, extraroutes.Opts{ + _, err := extraroutes.Remove(ctx, network, routerID, extraroutes.Opts{ Routes: &oldRoute, }).Extract() if mc.ObserveRequest(err) != nil { @@ -233,7 +233,7 @@ func removeRoute(network *gophercloud.ServiceClient, routerID string, oldRoute [ unwinder := func() { klog.V(4).Infof("Reverting routes change to router %v", routerID) mc := metrics.NewMetricContext("router", "update") - _, err := extraroutes.Add(context.TODO(), network, routerID, extraroutes.Opts{ + _, err := extraroutes.Add(ctx, network, routerID, extraroutes.Opts{ Routes: &oldRoute, }).Extract() if mc.ObserveRequest(err) != nil { @@ -244,11 +244,11 @@ func removeRoute(network *gophercloud.ServiceClient, routerID string, oldRoute [ return unwinder, nil } -func updateAllowedAddressPairs(network *gophercloud.ServiceClient, port *PortWithPortSecurity, newPairs []ports.AddressPair) (func(), error) { +func updateAllowedAddressPairs(ctx context.Context, network *gophercloud.ServiceClient, port *PortWithPortSecurity, newPairs []ports.AddressPair) (func(), error) { origPairs := port.AllowedAddressPairs // shallow copy mc := metrics.NewMetricContext("port", "update") - _, err := ports.Update(context.TODO(), network, port.ID, ports.UpdateOpts{ + _, err := ports.Update(ctx, network, port.ID, ports.UpdateOpts{ AllowedAddressPairs: &newPairs, }).Extract() if mc.ObserveRequest(err) != nil { @@ -258,7 +258,7 @@ func updateAllowedAddressPairs(network *gophercloud.ServiceClient, port *PortWit unwinder := func() { klog.V(4).Infof("Reverting allowed-address-pairs change to port %v", port.ID) mc := metrics.NewMetricContext("port", "update") - _, err := ports.Update(context.TODO(), network, port.ID, ports.UpdateOpts{ + _, err := ports.Update(ctx, network, port.ID, ports.UpdateOpts{ AllowedAddressPairs: &origPairs, }).Extract() if mc.ObserveRequest(err) != nil { @@ -295,7 +295,7 @@ func (r *Routes) CreateRoute(ctx context.Context, clusterName string, nameHint s defer r.Unlock() mc := metrics.NewMetricContext("router", "get") - router, err := routers.Get(context.TODO(), r.network, r.os.routeOpts.RouterID).Extract() + router, err := routers.Get(ctx, r.network, r.os.routeOpts.RouterID).Extract() if mc.ObserveRequest(err) != nil { return err } @@ -314,7 +314,7 @@ func (r *Routes) CreateRoute(ctx context.Context, clusterName string, nameHint s NextHop: addr, }) - unwind, err := updateRoutes(r.network, router, routes) + unwind, err := updateRoutes(ctx, r.network, router, routes) if err != nil { return err } @@ -326,7 +326,7 @@ func (r *Routes) CreateRoute(ctx context.Context, clusterName string, nameHint s DestinationCIDR: route.DestinationCIDR, NextHop: addr, }} - unwind, err := addRoute(r.network, r.os.routeOpts.RouterID, route) + unwind, err := addRoute(ctx, r.network, r.os.routeOpts.RouterID, route) if err != nil { return err } @@ -341,7 +341,7 @@ func (r *Routes) CreateRoute(ctx context.Context, clusterName string, nameHint s } // get the port of addr on target node. - port, err := getPortByIP(r.network, addr, r.networkIDs) + port, err := r.getPortByIP(ctx, addr) if err != nil { return err } @@ -364,7 +364,7 @@ func (r *Routes) CreateRoute(ctx context.Context, clusterName string, nameHint s newPairs := append(port.AllowedAddressPairs, ports.AddressPair{ IPAddress: route.DestinationCIDR, }) - unwind, err := updateAllowedAddressPairs(r.network, port, newPairs) + unwind, err := updateAllowedAddressPairs(ctx, r.network, port, newPairs) if err != nil { return err } @@ -404,7 +404,7 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo defer r.Unlock() mc := metrics.NewMetricContext("router", "get") - router, err := routers.Get(context.TODO(), r.network, r.os.routeOpts.RouterID).Extract() + router, err := routers.Get(ctx, r.network, r.os.routeOpts.RouterID).Extract() if mc.ObserveRequest(err) != nil { return err } @@ -427,7 +427,7 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo routes[index] = routes[len(routes)-1] routes = routes[:len(routes)-1] - unwind, err := updateRoutes(r.network, router, routes) + unwind, err := updateRoutes(ctx, r.network, router, routes) // If this was a blackhole route we are done, there are no ports to update if err != nil || route.Blackhole { return err @@ -444,7 +444,7 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo DestinationCIDR: route.DestinationCIDR, NextHop: addr, }} - unwind, err := removeRoute(r.network, r.os.routeOpts.RouterID, route) + unwind, err := removeRoute(ctx, r.network, r.os.routeOpts.RouterID, route) // If this was a blackhole route we are done, there are no ports to update if err != nil || blackhole { return err @@ -460,7 +460,7 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo } // get the port of addr on target node. - port, err := getPortByIP(r.network, addr, r.networkIDs) + port, err := r.getPortByIP(ctx, addr) if err != nil { return err } @@ -484,7 +484,7 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo addrPairs[index] = addrPairs[len(addrPairs)-1] addrPairs = addrPairs[:len(addrPairs)-1] - unwind, err := updateAllowedAddressPairs(r.network, port, addrPairs) + unwind, err := updateAllowedAddressPairs(ctx, r.network, port, addrPairs) if err != nil { return err } @@ -496,8 +496,8 @@ func (r *Routes) DeleteRoute(ctx context.Context, clusterName string, route *clo return nil } -func getPortByIP(network *gophercloud.ServiceClient, addr string, networkIDs []string) (*PortWithPortSecurity, error) { - for _, networkID := range networkIDs { +func (r *Routes) getPortByIP(ctx context.Context, addr string) (*PortWithPortSecurity, error) { + for _, networkID := range r.networkIDs { opts := ports.ListOpts{ FixedIPs: []ports.FixedIPOpts{ { @@ -506,7 +506,7 @@ func getPortByIP(network *gophercloud.ServiceClient, addr string, networkIDs []s }, NetworkID: networkID, } - ports, err := openstackutil.GetPorts[PortWithPortSecurity](network, opts) + ports, err := openstackutil.GetPorts[PortWithPortSecurity](ctx, r.network, opts) if err != nil { return nil, err } diff --git a/pkg/util/openstack/network.go b/pkg/util/openstack/network.go index d353dbb852..6dccbf660e 100644 --- a/pkg/util/openstack/network.go +++ b/pkg/util/openstack/network.go @@ -33,12 +33,12 @@ import ( ) // GetNetworkExtensions returns an extension map. -func GetNetworkExtensions(client *gophercloud.ServiceClient) (map[string]bool, error) { +func GetNetworkExtensions(ctx context.Context, client *gophercloud.ServiceClient) (map[string]bool, error) { seen := make(map[string]bool) mc := metrics.NewMetricContext("network_extension", "list") pager := extensions.List(client) - err := pager.EachPage(context.TODO(), func(_ context.Context, page pagination.Page) (bool, error) { + err := pager.EachPage(ctx, func(_ context.Context, page pagination.Page) (bool, error) { exts, err := extensions.ExtractExtensions(page) if err != nil { return false, err @@ -53,11 +53,11 @@ func GetNetworkExtensions(client *gophercloud.ServiceClient) (map[string]bool, e } // GetFloatingIPs returns all the filtered floating IPs -func GetFloatingIPs(client *gophercloud.ServiceClient, opts floatingips.ListOpts) ([]floatingips.FloatingIP, error) { +func GetFloatingIPs(ctx context.Context, client *gophercloud.ServiceClient, opts floatingips.ListOpts) ([]floatingips.FloatingIP, error) { var floatingIPList []floatingips.FloatingIP mc := metrics.NewMetricContext("floating_ip", "list") - allPages, err := floatingips.List(client, opts).AllPages(context.TODO()) + allPages, err := floatingips.List(client, opts).AllPages(ctx) if mc.ObserveRequest(err) != nil { return floatingIPList, err } @@ -70,11 +70,11 @@ func GetFloatingIPs(client *gophercloud.ServiceClient, opts floatingips.ListOpts } // GetFloatingIPByPortID get the floating IP of the given port. -func GetFloatingIPByPortID(client *gophercloud.ServiceClient, portID string) (*floatingips.FloatingIP, error) { +func GetFloatingIPByPortID(ctx context.Context, client *gophercloud.ServiceClient, portID string) (*floatingips.FloatingIP, error) { opt := floatingips.ListOpts{ PortID: portID, } - ips, err := GetFloatingIPs(client, opt) + ips, err := GetFloatingIPs(ctx, client, opt) if err != nil { return nil, err } @@ -87,7 +87,7 @@ func GetFloatingIPByPortID(client *gophercloud.ServiceClient, portID string) (*f } // GetFloatingNetworkID returns a floating network ID. -func GetFloatingNetworkID(client *gophercloud.ServiceClient) (string, error) { +func GetFloatingNetworkID(ctx context.Context, client *gophercloud.ServiceClient) (string, error) { type NetworkWithExternalExt struct { networks.Network external.NetworkExternalExt @@ -95,7 +95,7 @@ func GetFloatingNetworkID(client *gophercloud.ServiceClient) (string, error) { var allNetworks []NetworkWithExternalExt mc := metrics.NewMetricContext("network", "list") - page, err := networks.List(client, networks.ListOpts{}).AllPages(context.TODO()) + page, err := networks.List(client, networks.ListOpts{}).AllPages(ctx) if err != nil { return "", mc.ObserveRequest(err) } @@ -108,7 +108,7 @@ func GetFloatingNetworkID(client *gophercloud.ServiceClient) (string, error) { for _, network := range allNetworks { if network.External && len(network.Subnets) > 0 { mc := metrics.NewMetricContext("subnet", "list") - page, err := subnets.List(client, subnets.ListOpts{NetworkID: network.ID}).AllPages(context.TODO()) + page, err := subnets.List(client, subnets.ListOpts{NetworkID: network.ID}).AllPages(ctx) if err != nil { return "", mc.ObserveRequest(err) } @@ -142,9 +142,9 @@ func getSubnet(networkSubnet string, subnetList []subnets.Subnet) *subnets.Subne } // GetPorts gets all the filtered ports. -func GetPorts[PortType interface{}](client *gophercloud.ServiceClient, listOpts neutronports.ListOpts) ([]PortType, error) { +func GetPorts[PortType interface{}](ctx context.Context, client *gophercloud.ServiceClient, listOpts neutronports.ListOpts) ([]PortType, error) { mc := metrics.NewMetricContext("port", "list") - allPages, err := neutronports.List(client, listOpts).AllPages(context.TODO()) + allPages, err := neutronports.List(client, listOpts).AllPages(ctx) if mc.ObserveRequest(err) != nil { return []PortType{}, err }