|
|
@@ -0,0 +1,75 @@ |
|
|
|
package com.imitate.web.module.game.service; |
|
|
|
|
|
|
|
|
|
|
|
import com.imitate.common.enums.ErrorCodeEnum; |
|
|
|
import com.imitate.common.exception.BusinessException; |
|
|
|
import com.imitate.common.k8s.service.K8sService; |
|
|
|
import com.imitate.common.k8s.service.PortService; |
|
|
|
import com.imitate.common.k8s.service.RunPodService; |
|
|
|
import com.imitate.common.k8s.util.K8sUtils; |
|
|
|
import com.imitate.common.sys.constant.SysConfigCsts; |
|
|
|
import com.imitate.common.util.TpUtils; |
|
|
|
import lombok.extern.slf4j.Slf4j; |
|
|
|
import org.apache.commons.lang3.StringUtils; |
|
|
|
import org.springframework.beans.factory.annotation.Autowired; |
|
|
|
import org.springframework.stereotype.Service; |
|
|
|
|
|
|
|
import java.util.List; |
|
|
|
|
|
|
|
import static com.imitate.common.k8s.bean.PodCreateStrategy.MAX_CREATE_POD_TIME_LIMIT; |
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
* 代理服务,获取云主机及容器对外映射的端口 |
|
|
|
* |
|
|
|
* @author 威少 |
|
|
|
*/ |
|
|
|
@Slf4j |
|
|
|
@Service |
|
|
|
public class ProxyService { |
|
|
|
@Autowired |
|
|
|
private RunPodService runPodService; |
|
|
|
|
|
|
|
@Autowired |
|
|
|
private K8sService k8sService; |
|
|
|
|
|
|
|
@Autowired |
|
|
|
private PortService portService; |
|
|
|
|
|
|
|
/** |
|
|
|
* 为容器端口创建端口映射,支持外网访问 |
|
|
|
* @param tpiID tpiId |
|
|
|
* @param podType pod类型 |
|
|
|
* @param port 容器端口号 |
|
|
|
* @return 外网端口号 |
|
|
|
*/ |
|
|
|
public int getContainerExternalMappingPort(String tpiID, Integer podType, Integer port) { |
|
|
|
String cluster = runPodService.getRunPodCluster(tpiID, podType); |
|
|
|
String podName = TpUtils.buildEvaPodName(tpiID, podType); |
|
|
|
String serviceName = TpUtils.buildEvaServiceName(tpiID, podType, port); |
|
|
|
|
|
|
|
// 集群或者pod不存在直接报错 |
|
|
|
if (StringUtils.isEmpty(cluster) || k8sService.getRunningPod(cluster, podName, MAX_CREATE_POD_TIME_LIMIT) == null) { |
|
|
|
log.info("openServicePort failed, pod not ready, tpiID: {}, podType: {}, port: {}", tpiID, podType, port); |
|
|
|
throw new BusinessException(ErrorCodeEnum.NOT_CHECK_SVS.getValue(), ErrorCodeEnum.NOT_CHECK_SVS.getDescription()); |
|
|
|
} |
|
|
|
|
|
|
|
// service 存在则直接返回 |
|
|
|
io.fabric8.kubernetes.api.model.Service service = k8sService.getService(cluster, serviceName); |
|
|
|
if (service != null) { |
|
|
|
return K8sUtils.getNodePort(service); |
|
|
|
} else { |
|
|
|
// 否则创建 |
|
|
|
List<io.fabric8.kubernetes.api.model.Service> services = k8sService.getServicesByTpiID(cluster, tpiID); |
|
|
|
if (services.size() >= 10) { |
|
|
|
throw new BusinessException(ErrorCodeEnum.SVC_PORT_MAX.getValue(), ErrorCodeEnum.SVC_PORT_MAX.getDescription()); |
|
|
|
} |
|
|
|
int nodePort = portService.allocatePort(SysConfigCsts.KEY_USABLE_PORT_K8S); |
|
|
|
k8sService.createService(cluster, serviceName, podName, tpiID, port, nodePort); |
|
|
|
return nodePort; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
} |