main
黄海 10 months ago
parent 3c41ef4ca6
commit 712c1a2da1

@ -1,175 +0,0 @@
package Util;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.apis.NetworkingV1Api;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
public class K8sClient {
private static final Logger log = LoggerFactory.getLogger(K8sClient.class);
/**
* k8s-api
*/
private ApiClient apiClient;
/**
* PODSA访
* loading the in-cluster config, including:
* 1. service-account CA
* 2. service-account bearer-token
* 3. service-account namespace
* 4. master endpoints(ip, port) from pre-set environment variables
*/
public K8sClient() {
try {
this.apiClient = ClientBuilder.cluster().build();
} catch (IOException e) {
log.error("构建K8s-Client异常", e);
throw new RuntimeException("构建K8s-Client异常");
}
}
/**
* UA访
* loading the out-of-cluster config, a kubeconfig from file-system
*
* @param kubeConfigPath kube
*/
public K8sClient(String kubeConfigPath) {
try {
this.apiClient = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
} catch (IOException e) {
log.error("读取kubeConfigPath异常", e);
throw new RuntimeException("读取kubeConfigPath异常");
} catch (Exception e) {
log.error("构建K8s-Client异常", e);
throw new RuntimeException("构建K8s-Client异常");
}
}
/**
* Pod
*
* @return podList
*/
public V1PodList getAllPodList() {
// new a CoreV1Api
CoreV1Api api = new CoreV1Api(apiClient);
// invokes the CoreV1Api client
try {
V1PodList list = api.listPodForAllNamespaces().execute();
return list;
} catch (ApiException e) {
log.error("获取podlist异常:" + e.getResponseBody(), e);
}
return null;
}
/**
* k8s service
*
* @param namespace
* @param serviceName
* @param port pod
* @param selector pod
* @return service
*/
public V1Service createService(String namespace, String serviceName, Integer port, Map<String, String> selector) {
//构建service的yaml对象
V1Service svc = new V1ServiceBuilder()
.withNewMetadata()
.withName(serviceName)
.endMetadata()
.withNewSpec()
.addNewPort()
.withProtocol("TCP")
.withPort(port)
.withTargetPort(new IntOrString(port))
.endPort()
.withSelector(selector)
.endSpec()
.build();
// Deployment and StatefulSet is defined in apps/v1, so you should use AppsV1Api instead of CoreV1API
CoreV1Api api = new CoreV1Api(apiClient);
V1Service v1Service = null;
try {
v1Service = api.createNamespacedService(namespace, svc).execute();
} catch (ApiException e) {
log.error("创建service异常:" + e.getResponseBody(), e);
} catch (Exception e) {
log.error("创建service系统异常:", e);
}
return v1Service;
}
/**
* k8s V1Ingress
*
* @param namespace
* @param ingressName ingress
* @param annotations ingress
* @param path
* @param serviceName
* @param servicePort
* @return ingress
*/
public V1Ingress createV1Ingress(String namespace, String ingressName, Map<String, String> annotations, String path,
String serviceName, Integer servicePort) {
//构建ingress的yaml对象
V1Ingress ingress = new V1IngressBuilder()
.withNewMetadata()
.withName(ingressName)
.withAnnotations(annotations)
.endMetadata()
.withNewSpec()
.addNewRule()
.withHttp(new V1HTTPIngressRuleValueBuilder().addToPaths(new V1HTTPIngressPathBuilder()
.withPath(path)
.withPathType("Prefix")
.withBackend(new V1IngressBackendBuilder()
.withService(new V1IngressServiceBackendBuilder()
.withName(serviceName)
.withPort(new V1ServiceBackendPortBuilder()
.withNumber(servicePort).build()).build()).build()).build()).build())
.endRule()
.endSpec()
.build();
//调用对应的API执行创建ingress的操作
NetworkingV1Api api = new NetworkingV1Api(apiClient);
V1Ingress v1Ingress = null;
try {
v1Ingress = api.createNamespacedIngress(namespace, ingress).execute();
} catch (ApiException e) {
log.error("创建ingress异常:" + e.getResponseBody(), e);
} catch (Exception e) {
log.error("创建ingress系统异常:", e);
}
return v1Ingress;
}
}

@ -1,23 +1,64 @@
package Util;
import com.jfinal.kit.PathKit;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class K8sClientTest {
public static void main(String[] args) {
public static void testGetAllPodList() throws IOException, ApiException {
//Master /root/.kube/config文件拷贝过来
String kubeConfigPath = PathKit.getRootClassPath()+ "\\.kube\\config";
String kubeConfigPath = PathKit.getRootClassPath() + "\\.kube\\config";
if (!new File(kubeConfigPath).exists()) {
System.out.println("kubeConfig不存在跳过");
return;
}
K8sClient k8sClient = new K8sClient(kubeConfigPath);
V1PodList podList = k8sClient.getAllPodList();
ApiClient apiClient = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
// new a CoreV1Api
CoreV1Api api = new CoreV1Api(apiClient);
// invokes the CoreV1Api client
V1PodList podList = api.listPodForAllNamespaces().execute();
for (V1Pod item : podList.getItems()) {
System.out.println(item.getMetadata().getNamespace() + ":" + item.getMetadata().getName());
String result = removePrefixAndLastTwoDashes(item.getMetadata().getName());
if (result.equals("ds-base-web")) {
System.out.println(result);
}
}
}
/**
* -
*
* @param input
* @return
*/
public static String removePrefixAndLastTwoDashes(String input) {
// 去掉开头的default:
String trimmed = input.replaceFirst("^default:", "");
// 去掉最后两个以-开头的字符串
Pattern pattern = Pattern.compile("-[^-]+(-[^-]+)?$");
Matcher matcher = pattern.matcher(trimmed);
if (matcher.find()) {
return trimmed.substring(0, trimmed.length() - matcher.group().length());
}
return trimmed;
}
public static void main(String[] args) throws IOException, ApiException {
testGetAllPodList();
}
}

Loading…
Cancel
Save