From 65dda9373373a32aafa49748d3e14bdb759b5616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=90=AF=E8=88=AA?= <101104760+ZhangSetSail@users.noreply.github.com> Date: Fri, 6 Dec 2024 16:18:22 +0800 Subject: [PATCH] fix: create tcp outer svc failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张启航 <101104760+ZhangSetSail@users.noreply.github.com> --- .../apigateway/api_gateway_route.go | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/api/controller/apigateway/api_gateway_route.go b/api/controller/apigateway/api_gateway_route.go index 458f5ff32..c2ab66ccb 100644 --- a/api/controller/apigateway/api_gateway_route.go +++ b/api/controller/apigateway/api_gateway_route.go @@ -437,11 +437,28 @@ func (g Struct) CreateTCPRoute(w http.ResponseWriter, r *http.Request) { }, Spec: spec, } - _, err = k.Services(tenant.Namespace).Create(r.Context(), service, v1.CreateOptions{}) - if err != nil { - logrus.Errorf("create tcp rule func, create svc failure: %s", err.Error()) - httputil.ReturnBcodeError(r, w, bcode.ErrPortExists) - return + for { + // 设置服务的 NodePort + nodePort := service.Spec.Ports[0].NodePort + // 创建服务 + _, err = k.Services(tenant.Namespace).Create(r.Context(), service, v1.CreateOptions{}) + if err != nil { + if strings.Contains(err.Error(), "provided port is already allocated") { + // 如果端口已被占用,增加端口号并重新尝试 + logrus.Infof("NodePort %d is already allocated, trying next port...", nodePort) + nodePort++ + continue // 重新尝试创建服务 + } else { + // 其他错误,返回失败 + logrus.Errorf("create tcp rule func, create svc failure: %s", err.Error()) + httputil.ReturnBcodeError(r, w, bcode.ErrPortExists) + return + } + } + apisixRouteStream.Match.IngressPort = nodePort + // 如果创建成功,退出循环 + logrus.Infof("Service created successfully with NodePort %d", nodePort) + break } } else { // Service exists, update it