java操作k8s-api创建容器、获取pod容器信息
k8s平台上使用kubectl命令可以对K8s的Deployment、pod、Service等资源进行增删改查,但在java后端代码调用接口如何实现上述操作呢?本文将给出自己的部分探索
导入依赖:
<dependency>
<groupId>io.kubernetes</groupId>
<artifactId>client-java</artifactId>
<version>7.0.0</version>
</dependency>
<dependency>
<groupId>io.kubernetes</groupId>
<artifactId>client-java-api</artifactId>
<version>7.0.0</version>
</dependency>
配置连接k8s
把在K8s集群master节点的config配置文件复制到我们项目路径下,该文件在节点的~/.kube路径下
获取客户端
其他方法中会用到此方法返回的client对象
package com;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.FileReader;
import java.io.IOException;
public class Config {
// 返回client,默认使用这个方法
public static ApiClient defaultClient() throws IOException {
String kubeConfigPath = "config";
ApiClient client =
ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
return client;
}
}
创建容器部署
package com;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.models.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Deployment {
/**
* 创建容器部署
* @param name 容器名
* @author bryou
*/
public static void createNamespacedDeployment(String name) throws IOException {
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
AppsV1Api apiInstance = new AppsV1Api(client);
String namespace = "default"; // 选择在那个namespace下创建部署
//端口暴露服务的对应的是 Service.Spec.Selector下的值
Map<String,String> selectLabels = new HashMap<>();
selectLabels.put("select-name",name);
V1Deployment body = new V1DeploymentBuilder()
.withMetadata(new V1ObjectMetaBuilder()
.withName(name)
.withNamespace(namespace)
.withLabels(selectLabels)
.build())
.withSpec(new V1DeploymentSpecBuilder()
//设置默认副本数
.withReplicas(1)
//设置选择器
.withSelector(new V1LabelSelectorBuilder()
.withMatchLabels(selectLabels)
.build())
//设置docker模板
.withTemplate(new V1PodTemplateSpecBuilder()
.withMetadata(new V1ObjectMetaBuilder()
.withLabels(selectLabels)
.build())
.withSpec(new V1PodSpecBuilder()
.withContainers(new V1ContainerBuilder()
.withName("tb-vm")//设置docker名
.withImage("myvmnet:v4")//设置 docker镜像名
.withImagePullPolicy("IfNotPresent")//镜像本地拉去策略
.withCommand("/bin/bash",
"-ce",
"tail -f /dev/null")//命令
.build())
.build())
.build())
.build())
.build(); // V1Deployment |
String pretty = null; // 是否会漂亮输出
String dryRun = null; //
String fieldManager = null; //
try {
V1Deployment result = apiInstance.createNamespacedDeployment(namespace, body, pretty, dryRun, fieldManager);//调用createNamespacedDeployment方法创建容器部署
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AppsV1Api#createNamespacedDeployment");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
/**
* 删除对应的容器部署
* @param name
* @author bryou
*/
public static void deleteDeploymentByYaml(String name) throws ApiException, IOException {
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
AppsV1Api apiInstance = new AppsV1Api(client);
//ExtensionsV1beta1Api apiInstance = new ExtensionsV1beta1Api(client);
// 传入deployment的名字,命名空间,就可以删除deployment以及所有的pod了
V1Status v1Status = apiInstance.deleteNamespacedDeployment(name,"default",null,null,null,null,null,null);
System.out.println(v1Status.getCode()+"删除完毕");
}
}
获取容器名、容器ip、所属主机、创建时间、所属namespace等信息
package com;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import org.joda.time.DateTime;
import java.io.IOException;
/**
* 获取容器名、容器ip、所属主机、创建时间、所属namespace等信息
* @author bryou
*/
public class ListPod {
public static void listPod() throws IOException, ApiException {
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
CoreV1Api api = new CoreV1Api(client);
//打印所有的pod
V1PodList list = api.listNamespacedPod("default",null,null,null,null,null,null,null,null,null);
for (V1Pod item : list.getItems()) {
String pod_name = item.getMetadata().getName(); //获取 pod name
String pod_ip = item.getStatus().getPodIP(); //获取 pod ip
String host_ip = item.getStatus().getHostIP(); //获取 host ip,pod所属节点的ip
String which_namespace = item.getMetadata().getNamespace(); //获取namespace名称
DateTime pod_creatime = item.getMetadata().getCreationTimestamp();
//List<V1ContainerStatus> container_status = item.getStatus().getContainerStatuses(); //获取容器状态
//V1ContainerStatus container_id = container_status.get(1);
System.out.println(pod_name);
System.out.println(pod_ip);
System.out.println(host_ip);
System.out.println(which_namespace);
System.out.println(pod_creatime);
//System.out.println(container_status);
}
}
}