Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Kubernetes API in GO language

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to use Kubernetes API in the GO language. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

As Kubernetes becomes more and more popular, so does the number of integration and monitoring around it. The key component of all such functionality written by Golang is kubernetes / client-go--, a software package for communicating with the Kubernetes cluster API. In this article, we will discuss the basics used by client-go and how to save developers the time they need to write actual application logic. We will also demonstrate best practices for using the package and share what we have learned from the perspective of developers who integrate with Kubernetes every day. The content will include:

Client authentication vs. ● cluster. Client authentication outside the cluster

● basic list, using client-go to create and delete Kubernetes objects

How ● monitors and reacts to K8s events using ListWatch and Informers

How ● manages package dependencies

Kubernetes is a platform

Kubernetes has many popular places. Users like its rich features, stability and performance. For contributors, the Kubernetes open source community is not only large, but also easy to use and quick feedback. What really makes Kubernetes attractive to third-party developers is its extensibility. The project provides many ways to add new functionality and extend existing functionality without disrupting the main code base. It is these that make Kubernetes a platform.

Here are some ways to extend Kubernetes:

As shown in the figure above, you can see that each Kubernetes cluster component, whether Kubelet or API server, can be extended in some way. Today we will focus on a "custom controller" approach, which I will call a Kubernetes controller (Kubernetes Controller) from now on, or simply a controller (Controller).

What on earth is the Kubernetes controller?

The most common definition of a controller is the code that makes the current state of the system reach the desired state. But what on earth does that mean? Let's take the Ingress controller as an example. Ingress is a Kubernetes resource that can define external access to services in a cluster. HTTP is usually used and load balancing is supported. However, there is no implementation of ingress in the core code of Kubernetes. The implementation of the third-party controller will include:

Events that monitor ingress/services/endpoint resources (create, update, delete)

Load balancers inside or outside the program

Update Ingress with the address of the load balancer

"desired state" in the case of Ingress means that the IP address points to the running load balancer, which is implemented by the user according to the rules defined by the ingress specification. And the external Ingress controller is responsible for transferring ingress resources to this state.

The implementation of controllers and the way they are deployed may also vary for the same resources. You can select the nginx controller and deploy it to each node in the cluster as a daemon set (Daemon Set), or you can choose to run the ingress controller outside the Kubernetes cluster and program F5 as a load balancer. There are no strict rules here, and Kubernetes is so flexible.

Client-go

There are several ways to get information about Kubernetes clusters and their resources, which you can do using Dashboard, kubectl, or programmatic access to Kubernetes API. Client-go is the most widely used library of all tools written in the go language, as well as many other language versions (java, python, etc.). If you haven't written your own controller, I recommend you try go/client-go first.

Kubernetes is written in Go, and I find it more convenient to develop plug-ins in the same language as the main project.

Let's build it...

To be familiar with the relevant platforms and tools, the best way is to practice, to achieve something. Let's start with simplicity and implement a controller as follows:

Monitoring Kubernetes nod

Alerts when mirrors on nodes take up storage space and can be changed

The source code for the implementation of this part can be found here: https://github.com/alena1108/kubecon2017

Basic process

Configure the project

As a developer, my colleagues at Rancher Labs and I prefer to use lightweight tools, and here I will share three of my favorite tools that will help us with our first project.

MicroService skeleton for the go-skel-Go language, simply execute run. / skel.sh test123, which creates a skeleton for the new go project test123.

Supplier management tool for trash-Go language. There are actually a lot of dependency management tools here, but trash is excellent and simple to use when it comes to temporary dependency management.

Dapper-A tool that encapsulates any existing build tool in a consistent environment

Add client-go as a dependency

In order to make it easier to use client-go 's code, we must set it as a dependency of the project. Add it to the vendor.conf file:

Then run trash. It pulls all dependencies defined in vendor.conf into the vendor folder of the project. Here you need to verify that client-go is compatible with the Kubernetes version of your cluster.

Create a client

Before we can create a client that communicates with Kubernetes API, we must first decide how to run our tool: inside or outside the Kubetnetes cluster. When the application runs within the cluster, it is containerized and deployed as Kubernetes pod. It also provides some additional features: you can choose how to deploy it (Deamon set runs on each node, or as a deployment of n copies), configure checks for it, and so on. When the application runs outside the cluster, you need to manage it yourself. The following configuration makes our tools more flexible and supports two ways to define clients based on config flag:

We will run outside the cluster when debugging the application so that you do not need to build the image and redeploy it to Kubernetes pod every time. After testing the application, we can build the image and deploy it to the cluster.

As you can see in the screenshot, the configuration is being built and passed to kubernetes.NewForConfig to generate the client.

Use basic CRUDs

Our tools need to monitor nodes. Before implementing the logical process, let's familiarize ourselves with performing CRUD operations using client-go:

The screenshot above shows:

List node minikube, which is implemented by FieldSelector filter

Update the node with a new dimension

Delete a node using the gracePerios=10 second instruction-meaning that the delete operation will not be performed until 10 seconds after the execution of the command

All of the above steps are done using the user set (clientset) we created earlier.

We also need information about the image on the node; it can be retrieved by accessing the appropriate fields:

Use Informer for monitoring / notification

Now we know how to get the node from Kubernetes APIs and get the mirror information from it. So how do we monitor changes in the size of the image? The easiest way is to poll the node periodically, calculate the current mirror storage capacity, and compare it with the results of the previous poll. The drawback here is that the list calls we perform get all nodes regardless of whether the nodes change or not, which can be resource-intensive-especially if the polling interval is short. What we really want to achieve is to be notified when the node changes, and only after that does our logical process execute. This is what client-go 's Informer does.

In this example, we use the watchList instruction to create an Informer for the node object to monitor the node, and set the object type to api.Node and a synchronization period of 30 seconds to poll the node periodically, regardless of whether the node has changed or not-- this way it can be withdrawn when the update event terminates for some reason. In the last argument, we pass two callback functions-- handleNodeAdd and handleNodeUpdate. These callback functions have practical logic and are triggered when the storage occupied by the mirror on the node changes. NewInformer returns two objects-- controller and store. Once controller is started, monitoring of node.update and node.add will be started, and callback functions will be called. The storage area of this part of the code is located in the memory cache, which is updated by informer. In addition, you can get the node object in the cache without calling Kubernetes APIs directly:

There is only one controller in our project, so using regular Informer is sufficient. However, if your project ends up with multiple controllers for the same object in the future, I suggest you use SharedInformer. In this way, instead of adding Informer to each controller, you only need to register a Shared informer, and let each controller register its own set of callback functions and return the shared cache, which reduces the memory footprint:

Deployment time

It's time to deploy and test the code! For the first run, we just need to create a go binary and run it in out-of-cluster mode:

If you want to change the message output, deploy a pod using an image, which is not displayed on the current node.

After the basic functionality passes the test, the next step is to try to run it in cluster mode. To do this, we must first create an image and define its Dockerfile:

And use docker build to create an image, which will generate an image that can be used to deploy pod in Kubernetes. Now your application can run on the Kubernetes cluster as a pod. Here is an example of a deployment definition that I used to deploy our application in the previous screenshot:

In this paper, we have done the following work:

Create a go project

Add dependencies of the client-go package to the project

Create a client for communicating with Kubernetes api

Define an Informer that monitors node object changes and executes callback functions as soon as they occur

Implement a practical logic in the callback function

Run binaries outside the cluster to test the code and deploy it to the cluster

On how to use Kubernetes API in the GO language to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report