Kubernetes fabric8 JavaAPI
Kubernetes fabric8 JavaAPI
一、依赖准备
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>4.9.0</version>
</dependency>
下列展示代码中可能包含演示需要的依赖包,需要手动导入。全文手动原创,非其他博客及官方转载。
二、代码例子及分析
1.客户端的创建
Kubernetes 的资源默认是对内部是可见并可以访问的,我们可以通过以下方式去访问Kubernetes 获取我们想要的资源。
- 对于Kubernetes 可以通过 JavaAPI 通过安全证书文件、Token或admin.conf配置外部访问
- 同样也可以配置这些配置文件通过HTTP访问apiService访问
- 内部也可以通过kube-proxy将内部数据暴露出来进行访问的方式。
JavaAPI访问
1.1 通过安全证书访问
需要安全证书文件:apiserver-kubelet-client.crt、apiserver-kubelet-client.key、ca.crt
//创建 Config 用于创建 Client
Config config = new ConfigBuilder()
.withMasterUrl("ip")
.withCaCertData("ca.crt内容")
.withClientCertData("apiserver-kubelet-client.crt内容")
.withClientKeyData("apiserver-kubelet-client.key内容")
.build();
// 创建Client
KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);
1.2 通过配置文件访问
需要配置文件:admin.conf
config = Config.fromKubeconfig("admin.conf内容");
KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);
1.3 kube-proxy 配置后通过 HTTP 直接访问
首先在服务器中开启kube-proxy代理暴露8080端口:nohup kubectl proxy –port=8080 &
config = new ConfigBuilder().withMasterUrl("http://127.0.0.1:8080").build();
KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);
//通过http访问k8s中的路径资源
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/apis/devices.kubeedge.io/v1alpha1/devices");
HttpResponse response = null;
response = httpClient.execute(httpGet);
HttpEntity responseEntity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int code = statusLine.getStatusCode();
String result = EntityUtils.toString(responseEntity);
1.4 http浏览器直接访问K8S资源的,这里暂不讲解。
2.访问操作pod、nodeSpace等基础资源
//查看Pod
MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> operation = client.pods();
//创建Pod,获取资源处理类,在传入组装号的Pod类
NonNamespaceOperation pods =client.pods().inNamespace("default");
//配置Pod,还可以通过 pod 类组装,想要运行 这里的参数是不够的,仅作演示
Pod pod1 =new PodBuilder().withNewMetadata().withName("pod1").withNamespace("default").and().build();
pods.create(pod1);
//删除同上
pods.delete(pod1);
3.访问操作复杂管理器Deployment控制器
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentSpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author wanchen.chen
* @ClassName K8sDeploymentConf
* @Despriction: 用于组合 Deployment
* @date 2020/5/17 23:40
* @Version 1.0
**/
public class K8sDeploymentConf {
/**
*
* @param appName
* @param image
* @param nodeName
* @return
*/
public static Deployment getDepandDeployment(String appName,String image,String nodeName){
//参数传递
String appGroup = "appGroup";
//参数
Map<String,String> labels = new HashMap<String,String>();
labels.put("app",appGroup);
Map<String,String> nodeSelector = new HashMap<String,String>();
nodeSelector.put("name",nodeName);
//mataData 数据组装
ObjectMeta mataData = new ObjectMeta();
mataData.setName(appName);
mataData.setLabels(labels);
//镜像设置
Container container = new Container();
container.setName(appName);
container.setImage(image);
container.setImagePullPolicy("IfNotPresent");
SecurityContext sc = new SecurityContext();
sc.setPrivileged(true);
container.setSecurityContext(sc);
List<Container> containers = new ArrayList<>();
containers.add(container);
//Spec 数据组装
//1.selector
LabelSelector ls =new LabelSelector();
ls.setMatchLabels(labels);
//2.template
ObjectMeta empMataData = new ObjectMeta();
empMataData.setLabels(labels);
PodSpec pods = new PodSpec();
pods.setHostNetwork(true);
pods.setNodeSelector(nodeSelector);
pods.setContainers(containers);
//2.2 组装
PodTemplateSpec pt = new PodTemplateSpec();
pt.setMetadata(empMataData);
pt.setSpec(pods);
//3.spec 组合
DeploymentSpec ds = new DeploymentSpec();
ds.setReplicas(1);
ds.setSelector(ls);
ds.setTemplate(pt);
//Deployment 设置
Deployment deployment =new Deployment();
deployment.setApiVersion("apps/v1");
deployment.setKind("Deployment");
deployment.setMetadata(mataData);
deployment.setSpec(ds);
return deployment;
}
}
Deployment操作:
//将基础Client转换为AppsAPIGroupClient,用于操作deployment
AppsAPIGroupClient oclient =client.adapt(AppsAPIGroupClient.class);
MixedOperation<Deployment, DeploymentList, DoneableDeployment, RollableScalableResource<Deployment, DoneableDeployment>> operation1
=oclient.deployments();
//将资源转换为JSON 查看
DeploymentList deploymentList =operation1.list();
List<Deployment> deployments = deploymentList.getItems();
JSONArray jsonArray=JSON.parseArray(JSON.toJSONString(deployments));
//创建Deployment,返回创建好的Deployment文件
oclient.deployments().create(K8sDeploymentConf.getDepandDeployment("appName","image","nodeName"));
//删除同上,返回结果为boolean类型数据
oclient.deployments().delete(K8sDeploymentConf.getDepandDeployment("appName","image","nodeName"));
三、博客参考及持续更新
感谢以下博客作业的辛苦创作,参考博客: