From 21449f3586147f947131cb9d8e954422e9d80ad7 Mon Sep 17 00:00:00 2001 From: kon3m Date: Tue, 19 Mar 2024 12:33:16 +0530 Subject: [PATCH] added error handling in port allocation helper Signed-off-by: kon3m --- controllers/slicegateway/slicegateway.go | 7 +++++-- controllers/slicegateway/utils.go | 11 ++++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/controllers/slicegateway/slicegateway.go b/controllers/slicegateway/slicegateway.go index fa6b190a3..155d3a47e 100644 --- a/controllers/slicegateway/slicegateway.go +++ b/controllers/slicegateway/slicegateway.go @@ -1377,10 +1377,13 @@ func (r *SliceGwReconciler) ReconcileGatewayDeployments(ctx context.Context, sli // It is valid only if the list of remoteNodePorts in the slicegw object contains the portInUse. if !checkIfNodePortIsValid(sliceGw.Status.Config.SliceGatewayRemoteNodePorts, nodePortInUse) { // Get a valid port number for this deployment - portNumToUpdate := allocateNodePortToClient(sliceGw.Status.Config.SliceGatewayRemoteNodePorts, &gwClientToRemotePortMap) + portNumToUpdate, err := allocateNodePortToClient(sliceGw.Status.Config.SliceGatewayRemoteNodePorts, deployment.Name, &gwClientToRemotePortMap) + if err != nil { + return ctrl.Result{}, err, true + } // Update the port map gwClientToRemotePortMap.Store(deployment.Name, portNumToUpdate) - err := r.updateGatewayDeploymentNodePort(ctx, r.Client, sliceGw, &deployment, portNumToUpdate) + err = r.updateGatewayDeploymentNodePort(ctx, r.Client, sliceGw, &deployment, portNumToUpdate) if err != nil { return ctrl.Result{}, err, true } diff --git a/controllers/slicegateway/utils.go b/controllers/slicegateway/utils.go index 41c2d7e0e..e6243374b 100644 --- a/controllers/slicegateway/utils.go +++ b/controllers/slicegateway/utils.go @@ -460,7 +460,7 @@ func containsWithIndex[T comparable](s []T, e T) (bool, int) { } // a helper to assign distinct port to each client deployment -func allocateNodePortToClient(correctNodePorts []int, nodePortsMap *sync.Map) int { +func allocateNodePortToClient(correctNodePorts []int, depName string, nodePortsMap *sync.Map) (int, error) { nodePortsMap.Range(func(k, v interface{}) bool { if ok, index := containsWithIndex(correctNodePorts, v.(int)); ok { correctNodePorts = append(correctNodePorts[:index], correctNodePorts[index+1:]...) @@ -468,7 +468,12 @@ func allocateNodePortToClient(correctNodePorts []int, nodePortsMap *sync.Map) in return true }) if len(correctNodePorts) > 0 { - return correctNodePorts[0] + return correctNodePorts[0], nil + } else { + port, ok := nodePortsMap.Load(depName) + if ok { + return port.(int), nil + } + return 0, errors.New("could not allocate a port") } - return 0 }