」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 用Java編寫kooperator

用Java編寫kooperator

發佈於2024-11-04
瀏覽:512

Writing koperator in Java

This tutorial is specifically for developers with Java background who want to learn how to write first kubernetes operator fast. Why operators? There are several advantages:

  • significant maintenance reduction, saving keystrokes
  • resiliency built in into whatever system you are creating
  • fun of learning, getting serious about kubernetes nuts and bolts

I will try to limit theory to minimum and show a fool-proof recipe how to “bake a cake”. I chose Java because it is close to my working experience and to be honest it is easier than Go (but some may disagree).

Lets jump straight to it.

Theory and background

Nobody likes reading lengthy documentation, but let’s get this quickly of our chest, shall we?

What is a pod?

Pod is a group of containers with shared network interface (and given unique IP address) and storage.

What is a replica set?

Replica set controls creation and deleting of pods so that at each instant there is exactly specified number of pods with given template.

What is deployment?

Deployment owns replica set and indirectly owns pods. When you create deployment pods are created, when you delete it pods are gone.

What is service?

Service is SINGLE internet endpoint for bunch of pods (it distributes the load among them equally). You can expose it to be visible from outside the cluster. It automates the creation of endpoint slices.

The problem with kubernetes is that from the inception it was designed to be stateless. Replica sets don’t track the identities of pods, when particular pod is gone new one is just created. There are some use cases that need state like databases and cache clusters. Stateful sets only partially mitigate the problem.

This is why people started writing operators to take off the burden of maintenance. I wont go into the depths of the pattern and various sdks — you can start from here.

Controllers and reconcillation

Everything that works in kubernetes, every tiny gear of machinery is based on simple concept of control loop. So what this control loop does for particular resource type is that it checks what is and what should be (as defined in manifest). If there is mismatch it tries to perform some actions to fix that. This is called reconcillation.

And what operators really are is the same concept but for custom resources. Custom resources are the means of extending kubernetes api to some resource types that are defined by you. If you set up crd in kubernetes then all the actions like get, list, update, delete and so on will be possible on this resource. And what will do the actual work? Thats right — our operator.

Motivating example and java app

As typical for testing technology for the first time you pick the problem that is most basic to do. Because the concept is particularly complex then hello world in this case will be a little bit long. Anyways, in most of the sources I have seen that the simplest use case is setting up static page serving.

So the project is like this : we will define custom resource that represents two pages we want to serve. After applying that resource operator will automatically set up serving application in Spring Boot, create config map with pages content, mount the config map into a volume in apps pod and set up service for that pod. What is fun about this is that if we modify the resource, it will rebind everything on the fly and new page changes will be instantly visible. Second fun thing is that if we delete the resource it will delete everything leaving our cluster clean.

Serving java app

This will be really simple static page server in Spring Boot. You will only need spring-boot-starter-web so go ahead to spring initializer and pick:

  • maven
  • java 21
  • newest stable version (3.3.4 for me)
  • graal vm
  • and spring boot starter web

The app is just this:

@SpringBootApplication
@RestController
public class WebpageServingApplication {

    @GetMapping(value = "/{page}", produces = "text/html")
    public String page(@PathVariable String page) throws IOException {
        return Files.readString(Path.of("/static/" page));
    }

    public static void main(String[] args) {
        SpringApplication.run(WebpageServingApplication.class, args);
    }

}

Whatever we pass as path variable will be fetched from /static directory (in our case page1 and page2). So static directory will be mounted from config map, but about that later.

So now we have to build a native image and push it to the remote repository.

Tip number 1

org.graalvm.buildtoolsnative-maven-plugin-Ob

Configuring GraalVM like so you will have fastest build with lowest memory consumption (around 2GB). For me it was a must as I only have 16GB of memory and lots of stuff installed.

Tip number 2

org.springframework.bootspring-boot-maven-plugintruepaketobuildpacks/builder-jammy-full:latestghcr.io/dgawlik/webpage-serving:1.0.521https://ghcr.io/dgawlikdgawlik${env.GITHUB_TOKEN}
  • use paketobuildpacks/builder-jammy-full:latest while you are testing because -tiny and -base won’t have bash installed and you won’t be able to attach to container. Once you are done you can switch.
  • publish true will cause building image to push it to repository, so go ahead and switch it to your repo
  • BP_JVM_VERSION will be the java version of the builder image, it should be the same as the java of your project. As far as I know the latest java available is 21.

So now you do:

mvn spring-boot:build-image

And that’s it.

Operator with Fabric8

Now the fun starts. First you will need this in your pom:

io.fabric8kubernetes-client6.13.4io.fabric8crd-generator-apt6.13.4provided

crd-generator-apt is a plugin that scans a project, detects CRD pojos and generates the manifest.

Since I mentioned it, these resources are:

@Group("com.github.webserving")
@Version("v1alpha1")
@ShortNames("websrv")
public class WebServingResource extends CustomResource implements Namespaced {
}
public record WebServingSpec(String page1, String page2) {
}
public record WebServingStatus (String status) {
}

What is common in all resource manifests in Kubernetes is that most of them has spec and status. So you can see that the spec will consist of two pages pasted in heredoc format. Now, the proper way to handle things would be to manipulate status to reflect whatever operator is doing. If for example it is waiting on deployment to finish it would have status = “Processing”, on everything done it would patch the status to “Ready” and so on. But we will skip that because this is just simple demo.

Good news is that the logic of the operator is all in main class and really short. So step by step here it is:

KubernetesClient client = new KubernetesClientBuilder()
    .withTaskExecutor(executor).build();

var crdClient = client.resources(WebServingResource.class)
    .inNamespace("default");


var handler = new GenericResourceEventHandler(update -> {
   synchronized (changes) {
       changes.notifyAll();
   }
});

crdClient.inform(handler).start();

client.apps().deployments().inNamespace("default")
     .withName("web-serving-app-deployment").inform(handler).start();

client.services().inNamespace("default")
   .withName("web-serving-app-svc").inform(handler).start();

client.configMaps().inNamespace("default")
    .withName("web-serving-app-config").inform(handler).start();

So the heart of the program is of course Fabric8 Kuberenetes client built in first line. It is convenient to customize it with own executor. I used famous virtual threads, so when waiting on blocking io java will suspend the logic and move to main.

How here is a new part. The most basic version would be to run forever the loop and put Thread.sleep(1000) in it or so. But there is more clever way - kubernetes informers. Informer is websocket connection to kubernetes api server and it informs the client each time the subscribed resource changes. There is more to it you can read on the internet for example how to use various caches which fetch updates all at once in batch. But here it just subscribes directly per resource. The handler is a little bit bloated so I wrote a helper class GenericResourceEventHandler.

public class GenericResourceEventHandler implements ResourceEventHandler {

    private final Consumer handler;

    public GenericResourceEventHandler(Consumer handler) {
        this.handler = handler;
    }


    @Override
    public void onAdd(T obj) {
        this.handler.accept(obj);
    }

    @Override
    public void onUpdate(T oldObj, T newObj) {
        this.handler.accept(newObj);
    }

    @Override
    public void onDelete(T obj, boolean deletedFinalStateUnknown) {
        this.handler.accept(null);
    }
}

Since we only need to wake up the loop in all of the cases then we pass it a generic lambda. The idea for the loop is to wait on lock in the end and then the informer callback releases the lock each time the changes are detected.

Next:

for (; ; ) {

    var crdList = crdClient.list().getItems();
    var crd = Optional.ofNullable(crdList.isEmpty() ? null : crdList.get(0));


    var skipUpdate = false;
    var reload = false;

    if (!crd.isPresent()) {
        System.out.println("No WebServingResource found, reconciling disabled");
        currentCrd = null;
        skipUpdate = true;
    } else if (!crd.get().getSpec().equals(
            Optional.ofNullable(currentCrd)
                    .map(WebServingResource::getSpec).orElse(null))) {
        currentCrd = crd.orElse(null);
        System.out.println("Crd changed, Reconciling ConfigMap");
        reload = true;
    }

If there is no crd then there is nothing to be done. And if the crd changed then we have to reload everything.

var currentConfigMap = client.configMaps().inNamespace("default")
        .withName("web-serving-app-config").get();

if(!skipUpdate && (reload || desiredConfigMap(currentCrd).equals(currentConfigMap))) {
    System.out.println("New configmap, reconciling WebServingResource");
    client.configMaps().inNamespace("default").withName("web-serving-app-config")
            .createOrReplace(desiredConfigMap(currentCrd));
    reload = true;
}

This is for the case that ConfigMap is changed in between the iterations. Since it is mounted in pod then we have to reload the deployment.

var currentServingDeploymentNullable = client.apps().deployments().inNamespace("default")
        .withName("web-serving-app-deployment").get();
var currentServingDeployment = Optional.ofNullable(currentServingDeploymentNullable);

if(!skipUpdate && (reload || !desiredWebServingDeployment(currentCrd).getSpec().equals(
        currentServingDeployment.map(Deployment::getSpec).orElse(null)))) {

    System.out.println("Reconciling Deployment");
    client.apps().deployments().inNamespace("default").withName("web-serving-app-deployment")
            .createOrReplace(desiredWebServingDeployment(currentCrd));
}

var currentServingServiceNullable = client.services().inNamespace("default")
            .withName("web-serving-app-svc").get();
var currentServingService = Optional.ofNullable(currentServingServiceNullable);

if(!skipUpdate && (reload || !desiredWebServingService(currentCrd).getSpec().equals(
        currentServingService.map(Service::getSpec).orElse(null)))) {

    System.out.println("Reconciling Service");
    client.services().inNamespace("default").withName("web-serving-app-svc")
            .createOrReplace(desiredWebServingService(currentCrd));
}

If any of the service or deployment differs from the defaults we will replace them with the defaults.

synchronized (changes) {
    changes.wait();
}

Then the aforementioned lock.

So now the only thing is to define the desired configmap, service and deployment.

private static Deployment desiredWebServingDeployment(WebServingResource crd) {
    return new DeploymentBuilder()
            .withNewMetadata()
            .withName("web-serving-app-deployment")
            .withNamespace("default")
            .addToLabels("app", "web-serving-app")
            .withOwnerReferences(createOwnerReference(crd))
            .endMetadata()
            .withNewSpec()
            .withReplicas(1)
            .withNewSelector()
            .addToMatchLabels("app", "web-serving-app")
            .endSelector()
            .withNewTemplate()
            .withNewMetadata()
            .addToLabels("app", "web-serving-app")
            .endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("web-serving-app-container")
            .withImage("ghcr.io/dgawlik/webpage-serving:1.0.5")
            .withVolumeMounts(new VolumeMountBuilder()
                    .withName("web-serving-app-config")
                    .withMountPath("/static")
                    .build())
            .addNewPort()
            .withContainerPort(8080)
            .endPort()
            .endContainer()
            .withVolumes(new VolumeBuilder()
                    .withName("web-serving-app-config")
                    .withConfigMap(new ConfigMapVolumeSourceBuilder()
                            .withName("web-serving-app-config")
                            .build())
                    .build())
            .withImagePullSecrets(new LocalObjectReferenceBuilder()
                    .withName("regcred").build())
            .endSpec()
            .endTemplate()
            .endSpec()
            .build();
}

private static Service desiredWebServingService(WebServingResource crd) {
    return new ServiceBuilder()
            .editMetadata()
            .withName("web-serving-app-svc")
            .withOwnerReferences(createOwnerReference(crd))
            .withNamespace(crd.getMetadata().getNamespace())
            .endMetadata()
            .editSpec()
            .addNewPort()
            .withPort(8080)
            .withTargetPort(new IntOrString(8080))
            .endPort()
            .addToSelector("app", "web-serving-app")
            .endSpec()
            .build();
}

private static ConfigMap desiredConfigMap(WebServingResource crd) {
    return new ConfigMapBuilder()
            .withMetadata(
                    new ObjectMetaBuilder()
                            .withName("web-serving-app-config")
                            .withNamespace(crd.getMetadata().getNamespace())
                            .withOwnerReferences(createOwnerReference(crd))
                            .build())
            .withData(Map.of("page1", crd.getSpec().page1(),
                    "page2", crd.getSpec().page2()))
            .build();
}

private static OwnerReference createOwnerReference(WebServingResource crd) {
    return new OwnerReferenceBuilder()
            .withApiVersion(crd.getApiVersion())
            .withKind(crd.getKind())
            .withName(crd.getMetadata().getName())
            .withUid(crd.getMetadata().getUid())
            .withController(true)
            .build();
}

The magic of the OwnerReference is that you mark the resource which is it’s parent. Whenever you delete the parent k8s will delete automatically all the dependant resources.

But you can’t run it yet. You need a docker credentials in kubernetes:

kubectl delete secret regcred

kubectl create secret docker-registry regcred \
  --docker-server=ghcr.io \
  --docker-username=dgawlik \
  --docker-password=$GITHUB_TOKEN

Run this script once. Then we also need to set up the ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: demo-ingress
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web-serving-app-svc
                port:
                  number: 8080

The workflow

So first you build the operator project. Then you take target/classes/META-INF/fabric8/webservingresources.com.github.webserving-v1.yml and apply it. From now on the kubernetes is ready to accept your crd. Here it is:

apiVersion: com.github.webserving/v1alpha1
kind: WebServingResource
metadata:
  name: example-ws
  namespace: default
spec:
  page1: |
    

Hola amigos!

Buenos dias!

page2: |

Hello my friend

Good evening

You apply the crd kubectl apply -f src/main/resources/crd-instance.yaml. And then you run Main of the operator.

Then monitor the pod if it is up. Next just take the ip of the cluster:

minikube ip

And in your browser navigate to /page1 and /page2.

Then try to change the crd and apply it again. After a second you should see the changes.

The end.

Conclusion

A bright observer will notice that the code has some concurrency issues. A lot can happen in between the start and the end of the loop. But there are a lot of cases to consider and tried to keep it simple. You can do it as aftermath.

Like wise for the deployment. Instead of running it in IDE you can build the image the same way as for serving app and write deployment of it. That’s basically demystification of the operator — it is just a pod like every other.

I hope you found it useful.

Thanks for reading.

I almost forgot - here is the repo:

https://github.com/dgawlik/operator-hello-world

版本聲明 本文轉載於:https://dev.to/dominik_gawlik_431ca4cb96/writing-k8s-operator-in-java-33ao?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何在 Serp 中排名 4
    如何在 Serp 中排名 4
    搜索引擎排名页面 (SERP) 是网站争夺可见性和流量的地方。到 2024 年,在 Google 和其他搜索引擎上的高排名仍然对在线成功至关重要。然而,SEO(搜索引擎优化)多年来已经发生了变化,并将继续发展。如果您想知道如何在 2024 年提高 SERP 排名,这里有一个简单的指南可以帮助您了解最...
    程式設計 發佈於2024-11-05
  • 如何使用多處理在 Python 進程之間共享鎖
    如何使用多處理在 Python 進程之間共享鎖
    在Python 中的進程之間共享鎖定當嘗試使用pool.map() 來定位具有多個參數(包括Lock() 物件)的函數時,它是對於解決子進程之間共享鎖的問題至關重要。由於 pickling 限制,傳統的 multiprocessing.Lock() 無法直接傳遞給 Pool 方法。 選項 1:使用 ...
    程式設計 發佈於2024-11-05
  • Type Script 中 readonly 和 const 的區別
    Type Script 中 readonly 和 const 的區別
    這兩個功能的相似之處在於它們都是不可分配的。 能具體解釋一下嗎? 在這篇文章中,我將分享它們之間的差異。 const 防止重新分配給變數。 在這種情況下,hisName 是一個不能重新分配的變數。 const hisName = 'Michael Scofield' hisN...
    程式設計 發佈於2024-11-05
  • 如何使用 Range 函式在 Python 中複製 C/C++ 循環語法?
    如何使用 Range 函式在 Python 中複製 C/C++ 循環語法?
    Python 中的 for 迴圈:擴展 C/C 迴圈語法在程式設計中,for 迴圈是迭代序列的基本結構。雖然 C/C 採用特定的循環初始化語法,但 Python 提供了更簡潔的方法。不過,Python 中有一種模仿 C/C 循環風格的方法。 實作循環運算:for (int k = 1; k <...
    程式設計 發佈於2024-11-05
  • TechEazy Consulting 推出全面的 Java、Spring Boot 和 AWS 培訓計畫並提供免費實習機會
    TechEazy Consulting 推出全面的 Java、Spring Boot 和 AWS 培訓計畫並提供免費實習機會
    TechEazy Consulting 很高興地宣布推出我們的綜合培訓計劃,專為希望轉向後端開發使用Java、Spring Boot的初學者、新手和專業人士而設計,以及AWS。 此4個月的帶薪培訓計劃之後是2個月的無薪實習,您可以在實際專案中應用您的新技能—無需任何額外的培訓費用。對於那些希望填補...
    程式設計 發佈於2024-11-05
  • Polyfills-填充物還是縫隙? (第 1 部分)
    Polyfills-填充物還是縫隙? (第 1 部分)
    幾天前,我們在組織的 Teams 聊天中收到一條優先訊息,內容如下:發現安全漏洞 - 偵測到 Polyfill JavaScript - HIGH。 舉個例子,我在一家大型銀行公司工作,你必須知道,銀行和安全漏洞就像主要的敵人。因此,我們開始深入研究這個問題,並在幾個小時內解決了這個問題,我將在下...
    程式設計 發佈於2024-11-05
  • 移位運算子與位元簡寫賦值
    移位運算子與位元簡寫賦值
    1。移位運算子 :向右移動。 >>>:無符號右移(零填充)。 2.移位運算子的一般語法 value > num-bits:將值位向右移動,保留符號位。 value >>> num-bits:透過在左側插入零將值位向右移動。 3.左移 每次左移都會導致該值的所有位元向左移動一位。 右側插入0...
    程式設計 發佈於2024-11-05
  • 如何使用 VBA 從 Excel 建立與 MySQL 資料庫的連線?
    如何使用 VBA 從 Excel 建立與 MySQL 資料庫的連線?
    VBA如何在Excel中連接到MySQL資料庫? 使用VBA連接到MySQL資料庫嘗試連接使用 VBA 在 Excel 中存取 MySQL 資料庫有時可能具有挑戰性。在您的情況下,您在嘗試建立連線時遇到錯誤。 若要使用 VBA 成功連線至 MySQL 資料庫,請依照下列步驟操作:Sub Connec...
    程式設計 發佈於2024-11-05
  • 測試自動化:使用 Java 和 TestNG 進行 Selenium 指南
    測試自動化:使用 Java 和 TestNG 進行 Selenium 指南
    测试自动化已成为软件开发过程中不可或缺的一部分,使团队能够提高效率、减少手动错误并以更快的速度交付高质量的产品。 Selenium 是一个用于自动化 Web 浏览器的强大工具,与 Java 的多功能性相结合,为构建可靠且可扩展的自动化测试套件提供了一个强大的框架。使用 Selenium Java 进...
    程式設計 發佈於2024-11-05
  • 我對 DuckDuckGo 登陸頁面的看法
    我對 DuckDuckGo 登陸頁面的看法
    「為什麼不穀歌一下呢?」是我在對話中得到的常見答案。谷歌的無所不在甚至催生了新的動詞「Google」。但是我寫的程式碼越多,我就越質疑我每天使用的數位工具。也許我對谷歌使用我的個人資訊的方式不再感到滿意。或者我們很多人依賴谷歌進行互聯網搜索和其他應用程序,說實話,我厭倦了在搜索某個主題或產品後彈出的...
    程式設計 發佈於2024-11-05
  • 為什麼 Turbo C++ 的「cin」只讀取第一個字?
    為什麼 Turbo C++ 的「cin」只讀取第一個字?
    Turbo C 的「cin」限制:僅讀取第一個單字在Turbo C 中,「cin」輸入運算符有一個處理字元數組時的限制。具體來說,它只會讀取直到遇到空白字元(例如空格或換行符)。嘗試讀取多字輸入時,這可能會導致意外行為。 請考慮以下 Turbo C 代碼:#include <iostream....
    程式設計 發佈於2024-11-05
  • 使用 Buildpack 建立 Spring Boot 應用程式的 Docker 映像
    使用 Buildpack 建立 Spring Boot 應用程式的 Docker 映像
    介绍 您已经创建了一个 Spring Boot 应用程序。它在您的本地计算机上运行良好,现在您需要将该应用程序部署到其他地方。在某些平台上,您可以直接提交jar文件,它将被部署。在某些地方,您可以启动虚拟机,下载源代码,构建并运行它。但是,大多数时候您需要使用容器来部署应用程序。大...
    程式設計 發佈於2024-11-05
  • 如何保護 PHP 程式碼免於未經授權的存取?
    如何保護 PHP 程式碼免於未經授權的存取?
    保護PHP 代碼免於未經授權的訪問保護PHP 軟體背後的智慧財產權對於防止其濫用或盜竊至關重要。為了解決這個問題,可以使用多種方法來混淆和防止未經授權的存取您的程式碼。 一個有效的方法是利用 PHP 加速器。這些工具透過快取頻繁執行的部分來增強程式碼的效能。第二個好處是,它們使反編譯和逆向工程程式碼...
    程式設計 發佈於2024-11-05
  • React:了解 React 的事件系統
    React:了解 React 的事件系統
    Overview of React's Event System What is a Synthetic Event? Synthetic events are an event-handling mechanism designed by React to ach...
    程式設計 發佈於2024-11-05
  • 為什麼在使用 Multipart/Form-Data POST 請求時會收到 301 Moved Permanently 錯誤?
    為什麼在使用 Multipart/Form-Data POST 請求時會收到 301 Moved Permanently 錯誤?
    Multipart/Form-Data POSTsMultipart/Form-Data POSTs嘗試使用multipart/form-data POST 資料時,可能會出現類似所提供的錯誤訊息遭遇。理解問題需要檢視問題的構成。遇到的錯誤是 301 Moved Permanently 回應,表示資...
    程式設計 發佈於2024-11-05

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3