My latest and most complete articles are in the pumpkin slow say www.pkslow.com, welcome to tea!

1 Kubernetes Java client

For Kubernetes cluster operations, the official command line tool Kubectl, which is the most commonly used and must master the way. Through Kubectl to achieve add, delete, change and check operations, convenient and direct. But there are always more complex scenarios that are difficult to satisfy, such as when I want to trigger a Kubernetes Job to handle a task after a value in the database reaches 100,000. Even if shell programming seems manageable, wouldn’t it be better to integrate it into existing code for project maintenance?

As you can see from the Kubernetes architecture diagram, all we need to do is interact with the API server. In fact, Kubectl does the same. Then we can use any language to manipulate Kubernetes.

Fabric8io/Kubernetes-Client is one of the most useful client libraries for Java. It supports Kubernetes and OpenShift, and is used by many projects such as Spring Cloud, Spark and Istio Java API. You can see its excellence.

2 How to Use it

This article demonstrates some common operations through code.

2.1 Importing Dependencies

The latest version is 5.0.0, and the latest dependencies introduced via Maven are as follows:

<dependency>
  <groupId>io.fabric8</groupId>
  <artifactId>kubernetes-client</artifactId>
  <version>5.0.0</version>
</dependency>
Copy the code

This dependency includes the associated core classes, model classes, Json, okHttp3, and so on.

Look at its dependencies to learn how good projects are organized and managed.

2.2 Creating a Client

The easiest way to create a client is to use the default configuration:

KubernetesClient client = new DefaultKubernetesClient();
Copy the code

It reads configuration files from the directory ~/.kube/config. If you want to modify the configuration, you can configure the following Settings:

  • System Properties
  • Environment Variables
  • Kube configuration file
  • Of ServiceAccountTokenAnd the loaded CA certificate

A list of system attributes and environment variables can be found on the official website.

Of course, you can customize the configuration via Java:

Config config = new ConfigBuilder()
  .withMasterUrl("https://localhost:6443")
  .build();
KubernetesClient client = new DefaultKubernetesClient(config);
Copy the code

2.3 Creating Resources

This Java library uses a number of Builder patterns to create objects, creating the command space as follows:

Namespace namespace = new NamespaceBuilder()
  .withNewMetadata()
  .withName("pkslow")
  .addToLabels("reason"."pkslow-sample")
  .endMetadata()
  .build();
client.namespaces().createOrReplace(namespace);
Copy the code

Very flexible, the above example adds a name and tag, and finally creates a new one using the createOrReplace method, which can be replaced if one exists.

The same is true for pods:

Pod pod = new PodBuilder()
  .withNewMetadata()
  .withName("nginx")
  .addToLabels("app"."nginx")
  .endMetadata()
  .withNewSpec()
  .addNewContainer()
  .withName("nginx")
  .withImage("Nginx: 1.19.5")
  .endContainer()
  .endSpec()
  .build();
client.pods().inNamespace("pkslow").createOrReplace(pod);
Copy the code

After specifying the name, label, and image, it is ready to create.

2.4 Viewing Resources

To view resources, you can query all of them, or filter them by conditional options. The code is as follows:

// View the namespace
NamespaceList namespaceList = client.namespaces().list();
namespaceList.getItems()
  .forEach(namespace ->
           System.out.println(namespace.getMetadata().getName() + ":" + namespace.getStatus().getPhase()));

/ / check the Pod
ListOptions options = new ListOptions();
options.setLabelSelector("app=nginx");
Pod nginx = client.pods().inNamespace("pkslow")
  .list(options)
  .getItems()
  .get(0);
System.out.println(nginx);
Copy the code

2.5 Modifying Resources

Modifying a resource is done using the Edit method, which locates the resource by namespace and name and then modifies it. Example code is as follows:

// Modify the namespace
client.namespaces().withName("pkslow")
  .edit(n -> new NamespaceBuilder(n)
        .editMetadata()
        .addToLabels("project"."pkslow")
        .endMetadata()
        .build()
       );

/ / modify Pod
client.pods().inNamespace("pkslow").withName("nginx")
  .edit(p -> new PodBuilder(p)
        .editMetadata()
        .addToLabels("app-version"."1.0.1")
        .endMetadata()
        .build()
       );
Copy the code

2.6 Deleting a Resource

Deleting a resource is similar. Locate the resource first and then operate:

client.pods().inNamespace("pkslow")
  .withName("nginx")
  .delete();
Copy the code

2.7 Operations Using YAML Files

We can also describe resources directly in yamL files rather than in Java, which is more intuitive and convenient. After compiling yamL files, Load into corresponding objects, and then perform various add, delete, change and check operations, as shown in the following example:

The YAML file defines a Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    myapp: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      myapp: nginx
  template:
    metadata:
      labels:
        myapp: nginx
    spec:
      containers:
        - name: nginx
          image: Nginx: 1.7.9
          ports:
            - containerPort: 80
Copy the code

The Java code is as follows:

Deployment deployment = client.apps().deployments()
  .load(Fabric8KubernetesClientSamples.class.getResourceAsStream("/deployment.yaml"))
  .get();
client.apps().deployments().inNamespace("pkslow")
  .createOrReplace(deployment);
Copy the code

2.8 Listening Events

We can also listen to resource events, to the corresponding response, such as someone deleted the Pod log to the database, this function is very useful. Example code is as follows:

client.pods().inAnyNamespace().watch(new Watcher<Pod>() {
  @Override
  public void eventReceived(Action action, Pod pod) {
    System.out.println("event " + action.name() + "" + pod.toString());
  }

  @Override
  public void onClose(WatcherException e) {
    System.out.println("Watcher close due to "+ e); }});Copy the code

A Watcher listens for all Pod action events, and then prints the action name and the corresponding Pod. The output logs are as follows:

event ADDED Pod(apiVersion=v1, kind=Pod, metadata=ObjectMeta(
event MODIFIED Pod(apiVersion=v1, kind=Pod, metadata=ObjectMeta(
event DELETED Pod(apiVersion=v1, kind=Pod, metadata=ObjectMeta(
event MODIFIED Pod(apiVersion=v1, kind=Pod, metadata=ObjectMeta(
Copy the code

If the log is too long, it is not fully displayed.

3 summary

The Kubernetes Java client is really easy to use, the API is easy to use, even without documentation can be determined by method name. Best of all, there are plenty of excellent examples that are not too friendly.

Using this API, you can manage and use Kubernetes applications more flexibly in your projects.

Please check the code: github.com/LarryDpk/pk…