Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: add load balancer backend pool batch updater #4391

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions pkg/consts/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -535,3 +535,10 @@ const (
const (
VMSSTagForBatchOperation = "aks-managed-coordination"
)

type LoadBalancerBackendPoolUpdateOperation string

const (
LoadBalancerBackendPoolUpdateOperationAdd LoadBalancerBackendPoolUpdateOperation = "add"
LoadBalancerBackendPoolUpdateOperationRemove LoadBalancerBackendPoolUpdateOperation = "remove"
)
6 changes: 3 additions & 3 deletions pkg/provider/azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ type Cloud struct {
KubeClient clientset.Interface
eventBroadcaster record.EventBroadcaster
eventRecorder record.EventRecorder
routeUpdater *delayedRouteUpdater
routeUpdater batchProcessor

vmCache azcache.Resource
lbCache azcache.Resource
Expand Down Expand Up @@ -711,7 +711,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config,
if callFromCCM {
// start delayed route updater.
az.routeUpdater = newDelayedRouteUpdater(az, consts.RouteUpdateInterval)
go az.routeUpdater.run()
go az.routeUpdater.run(ctx)

// Azure Stack does not support zone at the moment
// https://docs.microsoft.com/en-us/azure-stack/user/azure-stack-network-differences?view=azs-2102
Expand All @@ -723,7 +723,7 @@ func (az *Cloud) InitializeCloudFromConfig(ctx context.Context, config *Config,
return err
}

go az.refreshZones(az.syncRegionZonesMap)
go az.refreshZones(ctx, az.syncRegionZonesMap)
}
}

Expand Down
55 changes: 44 additions & 11 deletions pkg/provider/azure_loadbalancer_backendpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,7 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes []
}
}

var nodeIPsToBeAdded []string
nodePrivateIPsSet := sets.New[string]()
for _, node := range nodes {
if isControlPlaneNode(node) {
Expand All @@ -444,21 +445,12 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(service *v1.Service, nodes []

if !existingIPs.Has(privateIP) {
name := node.Name
if utilnet.IsIPv6String(privateIP) {
name = fmt.Sprintf("%s-%s", name, v6Suffix)
}

klog.V(6).Infof("bi.EnsureHostsInPool: adding %s with ip address %s", name, privateIP)
*backendPool.LoadBalancerBackendAddresses = append(*backendPool.LoadBalancerBackendAddresses, network.LoadBalancerBackendAddress{
Name: pointer.String(name),
LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{
IPAddress: pointer.String(privateIP),
},
})
nodeIPsToBeAdded = append(nodeIPsToBeAdded, privateIP)
numOfAdd++
changed = true
}
}
changed = bi.addNodeIPAddressesToBackendPool(&backendPool, nodeIPsToBeAdded)

var nodeIPsToBeDeleted []string
for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses {
Expand Down Expand Up @@ -772,6 +764,47 @@ func newBackendPool(lb *network.LoadBalancer, isBackendPoolPreConfigured bool, p
return isBackendPoolPreConfigured
}

func (az *Cloud) addNodeIPAddressesToBackendPool(backendPool *network.BackendAddressPool, nodeIPAddresses []string) bool {
if backendPool.LoadBalancerBackendAddresses == nil {
lbBackendPoolAddresses := make([]network.LoadBalancerBackendAddress, 0)
backendPool.LoadBalancerBackendAddresses = &lbBackendPoolAddresses
}

var changed bool
addresses := *backendPool.LoadBalancerBackendAddresses
for _, ipAddress := range nodeIPAddresses {
if !hasIPAddressInBackendPool(backendPool, ipAddress) {
name := az.nodePrivateIPToNodeNameMap[ipAddress]
klog.V(4).Infof("bi.addNodeIPAddressesToBackendPool: adding %s to the backend pool %s", ipAddress, pointer.StringDeref(backendPool.Name, ""))
addresses = append(addresses, network.LoadBalancerBackendAddress{
Name: pointer.String(name),
LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{
IPAddress: pointer.String(ipAddress),
},
})
changed = true
}
}
backendPool.LoadBalancerBackendAddresses = &addresses
return changed
}

func hasIPAddressInBackendPool(backendPool *network.BackendAddressPool, ipAddress string) bool {
if backendPool.LoadBalancerBackendAddresses == nil {
return false
}

addresses := *backendPool.LoadBalancerBackendAddresses
for _, address := range addresses {
if address.LoadBalancerBackendAddressPropertiesFormat != nil &&
pointer.StringDeref(address.IPAddress, "") == ipAddress {
return true
}
}

return false
}

func removeNodeIPAddressesFromBackendPool(
backendPool network.BackendAddressPool,
nodeIPAddresses []string,
Expand Down
12 changes: 10 additions & 2 deletions pkg/provider/azure_loadbalancer_backendpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) {

az := GetTestCloud(ctrl)
az.LoadBalancerSku = consts.LoadBalancerSkuStandard
az.nodePrivateIPToNodeNameMap = map[string]string{
"10.0.0.2": "vmss-0",
"2001::2": "vmss-0",
"10.0.0.1": "vmss-1",
"2001::1": "vmss-1",
"10.0.0.4": "vmss-2",
"2001::4": "vmss-2",
}
bi := newBackendPoolTypeNodeIP(az)

nodes := []*v1.Node{
Expand Down Expand Up @@ -182,13 +190,13 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) {
},
},
{
Name: pointer.String("vmss-0-IPv6"),
Name: pointer.String("vmss-0"),
LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{
IPAddress: pointer.String("2001::2"),
},
},
{
Name: pointer.String("vmss-2-IPv6"),
Name: pointer.String("vmss-2"),
LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{
IPAddress: pointer.String("2001::4"),
},
Expand Down
220 changes: 220 additions & 0 deletions pkg/provider/azure_local_services.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/*
Copyright 2023 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package provider

import (
"context"
"fmt"
"strings"
"sync"
"time"

"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
"k8s.io/utils/pointer"

"sigs.k8s.io/cloud-provider-azure/pkg/consts"
"sigs.k8s.io/cloud-provider-azure/pkg/retry"
)

// batchProcessor collects operations in a certain interval and then processes them in batches.
type batchProcessor interface {
// run starts the batchProcessor, and stops if the context exits.
run(ctx context.Context)

// addOperation adds an operation to the batchProcessor.
addOperation(operation batchOperation) batchOperation
}

// batchOperation is an operation that can be added to a batchProcessor.
type batchOperation interface {
wait() batchOperationResult
}

// loadBalancerBackendPoolUpdateOperation is an operation that updates the backend pool of a load balancer.
type loadBalancerBackendPoolUpdateOperation struct {
loadBalancerName string
backendPoolName string
kind consts.LoadBalancerBackendPoolUpdateOperation
nodeIPs []string
result chan batchOperationResult
}

func (op *loadBalancerBackendPoolUpdateOperation) wait() batchOperationResult {
return <-op.result
}

// loadBalancerBackendPoolUpdater is a batchProcessor that updates the backend pool of a load balancer.
type loadBalancerBackendPoolUpdater struct {
az *Cloud
interval time.Duration
lock sync.Mutex
operations []batchOperation
}

// newLoadBalancerBackendPoolUpdater creates a new loadBalancerBackendPoolUpdater.
func newLoadBalancerBackendPoolUpdater(az *Cloud, interval time.Duration) *loadBalancerBackendPoolUpdater {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add two new configurations for the batch updater intervals (LB and route)? we may need to tune the intervals from time to time (this could be done in a following PR).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure.

return &loadBalancerBackendPoolUpdater{
az: az,
interval: interval,
operations: make([]batchOperation, 0),
}
}

// run starts the loadBalancerBackendPoolUpdater, and stops if the context exits.
func (updater *loadBalancerBackendPoolUpdater) run(ctx context.Context) {
err := wait.PollUntilContextCancel(ctx, updater.interval, false, func(ctx context.Context) (bool, error) {
updater.process()
return false, nil
})
if err != nil {
klog.Infof("loadBalancerBackendPoolUpdater.run: stopped due to %s", err.Error())
}
}

// getAddIPsToBackendPoolOperation creates a new loadBalancerBackendPoolUpdateOperation
// that adds nodeIPs to the backend pool.
func getAddIPsToBackendPoolOperation(loadBalancerName, backendPoolName string, nodeIPs []string) *loadBalancerBackendPoolUpdateOperation {
return &loadBalancerBackendPoolUpdateOperation{
loadBalancerName: loadBalancerName,
backendPoolName: backendPoolName,
kind: consts.LoadBalancerBackendPoolUpdateOperationAdd,
nodeIPs: nodeIPs,
result: make(chan batchOperationResult),
}
}

// getRemoveIPsFromBackendPoolOperation creates a new loadBalancerBackendPoolUpdateOperation
// that removes nodeIPs from the backend pool.
func getRemoveIPsFromBackendPoolOperation(loadBalancerName, backendPoolName string, nodeIPs []string) *loadBalancerBackendPoolUpdateOperation {
return &loadBalancerBackendPoolUpdateOperation{
loadBalancerName: loadBalancerName,
backendPoolName: backendPoolName,
kind: consts.LoadBalancerBackendPoolUpdateOperationRemove,
nodeIPs: nodeIPs,
result: make(chan batchOperationResult),
}
}

// addOperation adds an operation to the loadBalancerBackendPoolUpdater.
func (updater *loadBalancerBackendPoolUpdater) addOperation(operation batchOperation) batchOperation {
updater.lock.Lock()
defer updater.lock.Unlock()

updater.operations = append(updater.operations, operation)
return operation
}

// process processes all operations in the loadBalancerBackendPoolUpdater.
// It merges operations that have the same loadBalancerName and backendPoolName,
// and then processes them in batches. If an operation fails, it will be retried
// if it is retriable, otherwise all operations in the batch targeting to
// this backend pool will fail.
func (updater *loadBalancerBackendPoolUpdater) process() {
updater.lock.Lock()
defer updater.lock.Unlock()

if len(updater.operations) == 0 {
klog.V(4).Infof("loadBalancerBackendPoolUpdater.process: no operations to process")
return
}

// Group operations by loadBalancerName:backendPoolName
groups := make(map[string][]batchOperation)
for _, op := range updater.operations {
lbOp := op.(*loadBalancerBackendPoolUpdateOperation)
key := fmt.Sprintf("%s:%s", lbOp.loadBalancerName, lbOp.backendPoolName)
groups[key] = append(groups[key], op)
}

// Clear all jobs.
updater.operations = make([]batchOperation, 0)

for key, ops := range groups {
parts := strings.Split(key, ":")
lbName, poolName := parts[0], parts[1]
operationName := fmt.Sprintf("%s/%s", lbName, poolName)
bp, rerr := updater.az.LoadBalancerClient.GetLBBackendPool(context.Background(), updater.az.ResourceGroup, lbName, poolName, "")
if rerr != nil {
updater.processError(rerr, operationName, ops...)
continue
}

var changed bool
for _, op := range ops {
lbOp := op.(*loadBalancerBackendPoolUpdateOperation)
switch lbOp.kind {
case consts.LoadBalancerBackendPoolUpdateOperationRemove:
changed = removeNodeIPAddressesFromBackendPool(bp, lbOp.nodeIPs, false, true)
case consts.LoadBalancerBackendPoolUpdateOperationAdd:
changed = updater.az.addNodeIPAddressesToBackendPool(&bp, lbOp.nodeIPs)
default:
panic("loadBalancerBackendPoolUpdater.process: unknown operation type")
}
}
// To keep the code clean, ignore the case when `changed` is true
// but the backend pool object is not changed after multiple times of removal and re-adding.
if changed {
rerr = updater.az.LoadBalancerClient.CreateOrUpdateBackendPools(context.Background(), updater.az.ResourceGroup, lbName, poolName, bp, pointer.StringDeref(bp.Etag, ""))
if rerr != nil {
updater.processError(rerr, operationName, ops...)
continue
}
}
notify(newBatchOperationResult(operationName, true, nil), ops...)
}
}

// processError mark the operations as retriable if the error is retriable,
// and fail all operations if the error is not retriable.
func (updater *loadBalancerBackendPoolUpdater) processError(
rerr *retry.Error,
operationName string,
operations ...batchOperation,
) {
if rerr.Retriable {
// Retry if retriable.
updater.operations = append(updater.operations, operations...)
} else {
// Fail all operations if not retriable.
notify(newBatchOperationResult(operationName, false, rerr.Error()), operations...)
}
}

// notify notifies the operations with the result.
func notify(res batchOperationResult, operations ...batchOperation) {
for _, op := range operations {
lbOp := op.(*loadBalancerBackendPoolUpdateOperation)
lbOp.result <- res
}
}

// batchOperationResult is the result of a batch operation.
type batchOperationResult struct {
name string
success bool
err error
}

// newBatchOperationResult creates a new batchOperationResult.
func newBatchOperationResult(name string, success bool, err error) batchOperationResult {
return batchOperationResult{
name: name,
success: success,
err: err,
}
}