Browse Source

NamespaceApi定义

raledong 7 years ago
parent
commit
de436b1724

+ 46 - 1
src/main/java/nju/seec/SEECdemo/logic/api/k8s/NamespaceApi.java

@@ -1,9 +1,11 @@
 package nju.seec.SEECdemo.logic.api.k8s;
 
-import io.kubernetes.client.models.V1Namespace;
 import nju.seec.SEECdemo.logic.api.k8s.vo.ApiResult;
 import nju.seec.SEECdemo.logic.api.k8s.vo.Namespace;
 
+import java.util.List;
+import java.util.Map;
+
 /**
  * author: rale
  * createdAt: 12/22/18
@@ -16,4 +18,47 @@ public interface NamespaceApi {
      * @return
      */
     ApiResult<Void> create(Namespace namespace);
+
+    /**
+     * 异步新建一个命名空间
+     * @param namespace
+     * @return
+     */
+    ApiResult<Void> createAsync(Namespace namespace);
+
+
+    /**
+     * 删除命名空间
+     * @param name
+     * @return
+     */
+    ApiResult<Void> deleteByName(String name);
+
+    /**
+     * 获得名称为name的命名空间
+     * @param name
+     * @return
+     */
+    ApiResult<Namespace> getByName(String name);
+
+    /**
+     * 获得所有命名空间
+     * @return
+     */
+    ApiResult<List<Namespace>> getAll();
+
+    /**
+     * 获取匹配labels标签的namespace
+     * @param labels
+     * @return
+     */
+    ApiResult<List<Namespace>> getByLabels(Map<String, String> labels);
+
+    /**
+     * 获取匹配了label标签的namespace
+     * @param key
+     * @param value
+     * @return
+     */
+    ApiResult<List<Namespace>> getByLabel(String key, String value);
 }

+ 69 - 5
src/main/java/nju/seec/SEECdemo/logic/api/k8s/impl/NamespaceApiImpl.java

@@ -2,7 +2,10 @@ package nju.seec.SEECdemo.logic.api.k8s.impl;
 
 import io.kubernetes.client.ApiException;
 import io.kubernetes.client.apis.CoreV1Api;
+import io.kubernetes.client.models.V1DeleteOptions;
+import io.kubernetes.client.models.V1DeleteOptionsBuilder;
 import io.kubernetes.client.models.V1Namespace;
+import io.kubernetes.client.models.V1NamespaceList;
 import nju.seec.SEECdemo.logic.api.k8s.NamespaceApi;
 import nju.seec.SEECdemo.logic.api.k8s.vo.ApiResult;
 import nju.seec.SEECdemo.logic.api.k8s.vo.Namespace;
@@ -10,7 +13,12 @@ import nju.seec.SEECdemo.util.LoggerUtil;
 import org.slf4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
-import nju.seec.SEECdemo.logic.api.k8s.vo.ApiResult;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static nju.seec.SEECdemo.logic.api.k8s.util.Constants.PRETTY_FORMAT;
 
 /**
  * author: rale
@@ -21,6 +29,7 @@ public class NamespaceApiImpl implements NamespaceApi{
 
     private Logger logger = LoggerUtil.getLogger(NamespaceApi.class);
 
+    private static final String BACKGROUND_PROPAGATION_POLICY = "Background";
     @Autowired
     private CoreV1Api coreV1Api;
 
@@ -37,14 +46,69 @@ public class NamespaceApiImpl implements NamespaceApi{
             coreV1Api.createNamespace(v1Namespace, "true");
         } catch (ApiException e) {
             LoggerUtil.error(logger, e, "Namespace创建失败,namespace={}, v1Namespace={}", namespace, v1Namespace);
-            ApiResult<Void> result = new ApiResult<>();
-            result.setSuccess(false);
-            result.setErrorCode(e.getCode());
-            return result;
+            return new ApiResult<>(e.getCode(), e.getMessage());
         }
         ApiResult<Void> result = new ApiResult<>();
         result.setSuccess(true);
         return result;
     }
 
+    @Override
+    public ApiResult<Void> createAsync(Namespace namespace) {
+        return null;
+    }
+
+    @Override
+    public ApiResult<Void> deleteByName(String name) {
+        try {
+            V1DeleteOptions v1DeleteOptions = new V1DeleteOptionsBuilder()
+                    .withApiVersion(Namespace.VERSION)
+                    .withPropagationPolicy(BACKGROUND_PROPAGATION_POLICY)
+                    .build();
+            coreV1Api.deleteNamespace(name, v1DeleteOptions, PRETTY_FORMAT,
+                    null, null, BACKGROUND_PROPAGATION_POLICY);
+        } catch (ApiException e) {
+            LoggerUtil.error(logger, e, "Namespace删除失败,name={}, response={}", name , e.getResponseBody());
+            return new ApiResult<>(e.getCode(), e.getMessage());
+        }
+        return new ApiResult<>(null);
+    }
+
+    @Override
+    public ApiResult<Namespace> getByName(String name) {
+        return null;
+    }
+
+    @Override
+    public ApiResult<List<Namespace>> getAll() {
+        try {
+            V1NamespaceList v1NamespaceList = coreV1Api.listNamespace(PRETTY_FORMAT, null, null,
+                    true, null, null, null, null, null);
+            List<Namespace> namespaces =  v1NamespaceList.getItems().stream().map(Namespace::new).collect(Collectors.toList());
+            LoggerUtil.info(logger,"result={}", namespaces);
+            return new ApiResult<>(namespaces);
+        } catch (ApiException e) {
+            LoggerUtil.error(logger, e, "获取全部Namespace异常, response={}", e.getResponseBody());
+            return new ApiResult<>(e.getCode(), e.getMessage());
+        }
+    }
+
+    @Override
+    public ApiResult<List<Namespace>> getByLabels(Map<String, String> labels) {
+        return null;
+    }
+
+    @Override
+    public ApiResult<List<Namespace>> getByLabel(String key, String value) {
+        try {
+            V1NamespaceList v1NamespaceList = coreV1Api.listNamespace(PRETTY_FORMAT, null, null, true,key+":"+value, null, null, null, null);
+            List<Namespace> namespaces =  v1NamespaceList.getItems().stream().map(Namespace::new).collect(Collectors.toList());
+            LoggerUtil.info(logger,"result={}", namespaces);
+            return new ApiResult<>(namespaces);
+        } catch (ApiException e) {
+            LoggerUtil.error(logger, e, "根据标签获取Namespace异常, key={}, value={}", key, value);
+            return new ApiResult<>(e.getCode(), e.getMessage());
+        }
+    }
+
 }

+ 34 - 0
src/main/java/nju/seec/SEECdemo/logic/api/k8s/util/Constants.java

@@ -0,0 +1,34 @@
+package nju.seec.SEECdemo.logic.api.k8s.util;
+
+public abstract class Constants {
+
+	//标签域名前缀
+	private static final String LABEL_PREFIX = "demo.seec.nju.cn";
+	//课程前缀
+	public static final String TYPE_LABEL = LABEL_PREFIX + "/type";
+
+	public static final String DESCRIPTION_LABEL = LABEL_PREFIX + "/description";
+
+	public static final String APPLICATION_LABEL = LABEL_PREFIX + "/app";
+	// 用户namespace的label
+	public static final String USERSPACE_LABEL = LABEL_PREFIX +"/userspace";
+	// pod的label
+	public static final String SELECTOR_LABEL = LABEL_PREFIX + "/app";
+	// 非对外service的label
+	public static final String INTERNAL_LABEL = LABEL_PREFIX + "/internal";
+	// 对外service的label
+	public static final String EXTERNAL_LABEL = LABEL_PREFIX + "/external";
+	// 持久卷访问模式
+	public static final String STORAGE_ACCESS_MODE = "ReadWriteMany";
+	// 持久卷存储类型
+	public static final String STORAGE_CLASS = "glusterfs";
+
+	public static final String RESOURCE_STORAGE = "storage";
+
+	public static final String NAME_PATTERN = "^[0-9a-zA-Z-]{8,}$";
+
+	public static final String PRETTY_FORMAT = "false";
+
+	static final String NAMESPACE_API_VERSION = "v1";
+
+}

+ 13 - 1
src/main/java/nju/seec/SEECdemo/logic/api/k8s/vo/ApiResult.java

@@ -1,6 +1,7 @@
 package nju.seec.SEECdemo.logic.api.k8s.vo;
 
 import lombok.Data;
+import lombok.NoArgsConstructor;
 import org.springframework.data.annotation.ReadOnlyProperty;
 
 /**
@@ -9,9 +10,9 @@ import org.springframework.data.annotation.ReadOnlyProperty;
  */
 
 @Data
+@NoArgsConstructor
 public class ApiResult<T> {
 
-    @ReadOnlyProperty
     private boolean success;
 
     private int errorCode;
@@ -23,4 +24,15 @@ public class ApiResult<T> {
     public static final int CONFLICT = 409;//命名冲突
 
     public static final int NOT_EXIST = 800; //资源不存在
+
+    public ApiResult(T t){
+        this.value = t;
+        this.success = true;
+    }
+
+    public ApiResult(int errorCode, String errorDescription) {
+        this.success = false;
+        this.errorCode = errorCode;
+        this.errorDescription = errorDescription;
+    }
 }

+ 0 - 32
src/main/java/nju/seec/SEECdemo/logic/api/k8s/vo/Constants.java

@@ -1,32 +0,0 @@
-package nju.seec.SEECdemo.logic.api.k8s.vo;
-
-public abstract class Constants {
-
-	//标签域名前缀
-	private static final String LABEL_PREFIX = "demo.seec.nju.cn";
-	//课程前缀
-	static final String TYPE_LABEL = LABEL_PREFIX + "/type";
-
-	static final String DESCRIPTION_LABEL = LABEL_PREFIX + "/description";
-
-	static final String APPLICATION_LABEL = LABEL_PREFIX + "/app";
-	// 用户namespace的label
-	static final String USERSPACE_LABEL = LABEL_PREFIX +"/userspace";
-	// pod的label
-	static final String SELECTOR_LABEL = LABEL_PREFIX + "/app";
-	// 非对外service的label
-	static final String INTERNAL_LABEL = LABEL_PREFIX + "/internal";
-	// 对外service的label
-	static final String EXTERNAL_LABEL = LABEL_PREFIX + "/external";
-	// 持久卷访问模式
-	static final String STORAGE_ACCESS_MODE = "ReadWriteMany";
-	// 持久卷存储类型
-	static final String STORAGE_CLASS = "glusterfs";
-
-	static final String RESOURCE_STORAGE = "storage";
-
-	static final String NAME_PATTERN = "^[0-9a-zA-Z-]{8,}$";
-
-	static final String NAMESPACE_API_VERSION = "v1";
-
-}

+ 27 - 23
src/main/java/nju/seec/SEECdemo/logic/api/k8s/vo/Namespace.java

@@ -1,12 +1,18 @@
 package nju.seec.SEECdemo.logic.api.k8s.vo;
 
 import io.kubernetes.client.models.*;
+import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
+import lombok.NoArgsConstructor;
 import lombok.ToString;
+import nju.seec.SEECdemo.util.DateUtil;
+import org.springframework.data.annotation.ReadOnlyProperty;
 import org.springframework.util.CollectionUtils;
 
 import javax.validation.constraints.NotNull;
+import java.time.LocalDateTime;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.Map;
 
 /**
@@ -15,24 +21,39 @@ import java.util.Map;
  */
 @ToString
 @Data
+@NoArgsConstructor
 public class Namespace {
 
     private static final String KIND = "Namespace";
 
-    private static final String VERSION = "v1";
+    public static final String VERSION = "v1";
+
+    //@todo 添加一个label标记该Namespace为seec创建的
+    //获取时只获取seec创建的label
+
     @NotNull
     private String name;
 
-    private String description;
+    private Map<String, String> labels = new HashMap<>();
+
+    private Map<String, String> annotations = new HashMap<>();
+
+    @ApiModelProperty(readOnly = true)
+    private LocalDateTime createdAt;
 
-    @NotNull
-    private String type;
+
+    public Namespace(V1Namespace v1Namespace) {
+        this.name = v1Namespace.getMetadata().getName();
+        this.labels = v1Namespace.getMetadata().getLabels();
+        this.annotations = v1Namespace.getMetadata().getAnnotations();
+        this.createdAt = DateUtil.fromJodaDateTime(v1Namespace.getMetadata().getCreationTimestamp());
+    }
 
     public V1Namespace toV1Namespace(){
         V1ObjectMeta v1ObjectMeta = new V1ObjectMetaBuilder()
                 .withName(name)
-                .withLabels(Collections.singletonMap(Constants.TYPE_LABEL, type))
-                .addToAnnotations(Constants.DESCRIPTION_LABEL, description == null ? name : description)
+                .withLabels(labels)
+                .withAnnotations(annotations)
                 .build();
         V1NamespaceSpec v1NamespaceSpec = new V1NamespaceSpecBuilder()
                 .build();
@@ -45,21 +66,4 @@ public class Namespace {
         return v1Namespace;
 
     }
-
-    public Namespace fromV1Namespace(V1Namespace v1Namespace) {
-        Namespace namespace = new Namespace();
-        V1ObjectMeta v1ObjectMeta = v1Namespace.getMetadata();
-        if (v1ObjectMeta != null) {
-            namespace.setName(v1Namespace.getMetadata().getName());
-            Map<String, String> annotations = v1ObjectMeta.getAnnotations();
-            if (!CollectionUtils.isEmpty(annotations)) {
-                namespace.setDescription(annotations.get(Constants.DESCRIPTION_LABEL));
-            }
-            Map<String, String> labels = v1ObjectMeta.getLabels();
-            if (!CollectionUtils.isEmpty(labels)) {
-                namespace.setType(labels.get(Constants.TYPE_LABEL));
-            }
-        }
-        return namespace;
-    }
 }