Forráskód Böngészése

创建 pod 前先创建 ns

martin 2 éve
szülő
commit
5d0ed06560

+ 31 - 16
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/util/KubernetesUtil.java

@@ -58,26 +58,41 @@ public class KubernetesUtil {
      * 创建 namespace 命名空间
      *
      * @param apiClient     客户端
-     * @param namespaceName 命名空间名称
+     * @param nsName 命名空间名称
      * @return 命名空间对象
-     * @throws ApiException 异常
      */
-    public static V1Namespace createNamespace(ApiClient apiClient, String namespaceName) throws ApiException {
-        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
-        V1Namespace yaml = new V1Namespace();
-        //1 apiVersion
-        yaml.setApiVersion("v1");
-
-        //2 kind
-        yaml.setKind("Namespace");
+    @SneakyThrows
+    public static V1Namespace createNs(ApiClient apiClient, String nsName) {
+        if (!getNs(apiClient).contains(nsName)) {
+            CoreV1Api coreV1Api = new CoreV1Api(apiClient);
+            V1Namespace yaml = new V1Namespace();
+            //1 apiVersion
+            yaml.setApiVersion("v1");
+            //2 kind
+            yaml.setKind("Namespace");
+            //3 metadata
+            V1ObjectMeta metadata = new V1ObjectMeta();
+            metadata.setName(nsName);
+            metadata.setLabels(null);
+            yaml.setMetadata(metadata);
+            return coreV1Api.createNamespace(yaml, null, null, null, null);
+        } else {
+            return null;
+        }
+    }
 
-        //3 metadata
-        V1ObjectMeta metadata = new V1ObjectMeta();
-        metadata.setName(namespaceName);
-        metadata.setLabels(null);
-        yaml.setMetadata(metadata);
 
-        return coreV1Api.createNamespace(yaml, null, null, null, null);
+    /**
+     * 获取 namespace 列表
+     *
+     * @param apiClient api 客户端
+     * @return pod 名称列表
+     */
+    @SneakyThrows
+    public static List<String> getNs(ApiClient apiClient) {
+        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
+        V1NamespaceList v1NamespaceList = coreV1Api.listNamespace(null, null, null, null, null, null, null, null, null, null);
+        return v1NamespaceList.getItems().stream().map(ns -> Objects.requireNonNull(ns.getMetadata()).getName()).collect(Collectors.toList());
     }
 
     public static List<String> getPod(ApiClient apiClient, String namespaceName) throws ApiException {

+ 1 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/util/ProjectUtil.java

@@ -106,6 +106,7 @@ public class ProjectUtil {
         String podYamlName = podName + ".yaml";     // 模板文件名称
         String podYamlPath = podYamlDirectory + podYamlName;
         FileUtil.writeStringToLocalFile(podYamlContent, podYamlPath);
+        KubernetesUtil.createNs(apiClient, kubernetesNamespace);
         KubernetesUtil.applyYaml(hostname, username, password, podYamlPath);
 //        下面这种执行方法报错
 //        V1Pod v1Pod = (V1Pod) Yaml.load(nextPodString);