In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use Go to build Kubernetes applications". In the daily operation, I believe many people have doubts about how to use Go to build Kubernetes applications. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to use Go to build Kubernetes applications"! Next, please follow the editor to study!
The Kubernetes project is written in the go language, and native support for Go api is very convenient. This article describes how to use kubernetes client-go to practice a simple interaction with K8s.
Kubernetes's Go Client Project (client-go)
Go client is the oldest of the K8s client, with many features. Instead of using the Swagger generator, Client-go uses a source code generation tool from the K8s project, which is designed to generate K8s-style objects and serializers.
The project is a collection of packages that can meet different programming needs, from REST-style primitives to complex client.
RESTClient is a base package that uses types from the api-machinery library as a set of REST primitives to provide access to API. As an abstraction on top of RESTClient, _ clientset_ will be your starting point for creating the K8s client tool. It exposes exposed API resources and their corresponding serialization.
Note: packages such as discovery, dynamic, and scale are also included in client-go. Although these packages are not introduced this time, it is important to understand their capabilities.
A simple k8s client tool
Let's review the tool we are going to build again to illustrate the use of go client. Pvcwatch is a simple command-line tool that listens to the declared PVC capacity in the cluster. When the total reaches a threshold, he takes an action (in this case, the notification is displayed on the screen)
You can find complete examples on github.
The purpose of this example is to show the following aspects of k8s go client:-how to connect-resource list retrieval and traversal-object listening
Setup
Client-go supports Godep and dep as hypervisors for vendor, and I find dep easy to use, so I continue to use dep. For example, the following is the minimum Gopkg.toml required for client-go v6.0 and k8s API v1.9.
[[constraint]] name = "k8s.io/api" version = "kubernetes-1.9.0" [[constraint]] name = "k8s.io/apimachinery" version = "kubernetes-1.9.0" [[constraint]] name = "k8s.io/client-go" version = "6.0.0"
Run dep ensure to ensure the rest of the work.
Connect API Server
The first step in our Go client is to establish a connection to API Server. To do this, we will use the clientcmd in the entity package, as shown in the following code:
Import (... "k8s.io/client-go/tools/clientcmd") func main () {kubeconfig: = filepath.Join (os.Getenv ("HOME"), ".kube", "config",) config, err: = clientcmd.BuildConfigFromFlags ("", kubeconfig) if err! = nil {log.Fatal (err)}.}
_ Client-go_ makes it an unimportant task by providing entity functionality to get your configuration from different contexts.
From config fil
As the example above does, you can launch the configuration from the kubeconfig file to connect to API server. This is an ideal solution when your code is running outside the cluster. Clientcmd.BuildConfigFromFlags ("", configFile)
From the cluster
When your code runs in this cluster, you can use the above function without any arguments, and this function will connect to api server through the cluster information.
Clientcmd.BuildConfigFromFlags (",")
Or we can use the rest package to create one that uses the information in the cluster to configure startup. (note: all Pod in K8s will automatically mount the default ServiceAccount in K8s as Volume, so the default ServiceAccount authorization information will be used), as follows:
Import "k8s.io/client-go/rest"... Rest.InClusterConfig ()
Create a clientset
We need to create a serialized client so that we can get the API object. The Clientset type definition in the kubernetes package provides a serialized client to access the exposed API object, as follows:
Type Clientset struct {* authenticationv1beta1.AuthenticationV1beta1Client * authorizationv1.AuthorizationV1Client... * corev1.CoreV1Client}
Once we have the correct configuration connection, we can use this configuration to initialize a clientset, as follows:
Func main () {config, err: = clientcmd.BuildConfigFromFlags (", kubeconfig)... Clientset, err: = kubernetes.NewForConfig (config) if err! = nil {log.Fatal (err)}}
For our example, we are using the v1 API object. Next, we will use clientset to access the core api resources through CoreV1 (), as follows:
Func main () {... Clientset, err: = kubernetes.NewForConfig (config) if err! = nil {log.Fatal (err)} api: = clientset.CoreV1 ()}
You can see here that you can get clientsets.
Get the PVC list of the cluster
One of the most basic operations we perform on clientset gets a list of stored API objects. In our example, we are going to get a list of pvc under namespace, as follows:
Import (... Metav1 "k8s.io/apimachinery/pkg/apis/meta/v1") func main () {var ns, label, field string flag.StringVar (& ns, "namespace", "", "namespace") flag.StringVar (& label, "l", "", "Label selector") flag.StringVar (& field, "f", "," Field selector "). Api: = clientset.CoreV1 () / / setup list options listOptions: = metav1.ListOptions {LabelSelector: label, FieldSelector: field,} pvcs, err: = api.PersistentVolumeClaims (ns) .List (listOptions) if err! = nil {log.Fatal (err)} printPVCs (pvcs).}
In the above code, we use ListOptions to specify label and field selectors (and namespace) to narrow the pvc list, and the return type for this result is v1.PeristentVolumeClaimList. The following code shows how we can traverse and print the list of pvc obtained from api server.
Func printPVCs (pvcs * v1.PersistentVolumeClaimList) {template: = "%-32s%-8s%-8s\ n" fmt.Printf (template, "NAME", "STATUS", "CAPACITY") for _, pvc: = range pvcs.Items {quant: = pvc.Spec.Resources.Requests [v1.ResourceStorage] fmt.Printf (template, pvc.Name String (pvc.Status.Phase), quant.String ()}}
Listen for pvc in the cluster
The Go client framework of K8s supports the ability to listen for specified API objects in their lifecycle events, including CREATED,MODIFIED,DELETED events triggered when a specified object is created, updated, and deleted. For our command-line tools, we will listen to the total amount of PVC that has been declared in the cluster.
For a certain namespace, when the capacity of the pvc reaches a certain threshold (such as 200Gi), we will take some action. For simplicity, we are going to print a notice on the screen. But in a more complex implementation, you can use the same method to trigger an automatic operation.
Start the monitoring function
Now let's create a listener through Watch for the PersistentVolumeClaim resource. The listener then accesses event notifications from go's channel via ResultChan.
Func main () {... Api: = clientset.CoreV1 () listOptions: = metav1.ListOptions {LabelSelector: label, FieldSelector: field,} watcher, err: = api.PersistentVolumeClaims (ns). Watch (listOptions) if err! = nil {log.Fatal (err)} ch: = watcher.ResultChan ()...}
Cyclic event
Next we will deal with resource events. But before we deal with the event, let's declare that the two variables of type resource.Quantity are maxClaimsQuant and totalClaimQuant to represent our application resource threshold and the total number of PVC applications running in a ns cluster, respectively.
Import ("k8s.io/apimachinery/pkg/api/resource"...) Func main () {var maxClaims string flag.StringVar (& maxClaims, "max-claims", "200Gi", "Maximum total claims to watch") var totalClaimedQuant resource.Quantity maxClaimedQuant: = resource.MustParse (maxClaims). Ch: = watcher.ResultChan () for event: = range ch {pvc, ok: = event.Object. (* v1.PersistentVolumeClaim) if! ok {log.Fatal ("unexpected type")}.}}
In the for-range loop above, the channel of watcher is used to process incoming notifications from the server. Each event is assigned to the variable event, and the type of event.Object is declared as PersistentVolumeClaim, so we can extract it from it.
Handling ADDED events
When a new PVC is created, the value of event.Type is set to watch.Added. Then we use the following code to get the new declared capacity (quant) and add it to the total running capacity (totalClaimedQuant). Finally, we check to see if the current total capacity is greater than the maximum value set (maxClaimedQuant), and if so, we trigger an event.
Import ("k8s.io/apimachinery/pkg/watch"...) Func main () {... For event: = range ch {pvc Ok: = event.Object. (* v1.PersistentVolumeClaim) if! ok {log.Fatal ("unexpected type")} quant: = pvc.Spec.Resources.Requests [v1.ResourceStorage] switch event.Type {case watch.Added: totalClaimedQuant.Add (quant) log.Printf ("PVC% s added, claim size% s\ n" Pvc.Name, quant.String () if totalClaimedQuant.Cmp (maxClaimedQuant) = 1 {log.Printf ("\ nClaim overage reached: max% s at% s", maxClaimedQuant.String () TotalClaimedQuant.String () / / trigger action log.Println ("* Taking action * *")}}...}
Handling DELETED events
The code also reacts when the PVC is deleted, performing the opposite logic and subtracting the capacity of the deleted PVC application from the total value of the running capacity.
Func main () {... For event: = range ch {... Switch event.Type {case watch.Deleted: quant: = pvc.Spec.Resources.Requests [v1.ResourceStorage] totalClaimedQuant.Sub (quant) log.Printf ("PVC% s removed, size% s\ n", pvc.Name Quant.String () if totalClaimedQuant.Cmp (maxClaimedQuant). / pvcwatch Using kubeconfig: / Users/vladimir/.kube/config-PVCs-NAME STATUS CAPACITY my-redis-redis Bound 50Gi my-redis2-redis Bound 100Gi -Total capacity claimed: 150Gi-PVC Watch (max claims 200Gi)-2018-02-13 21:55:03 PVC my-redis2-redis added Claim size 100Gi 2018-02-13 21:55:03 At 50.0% claim capcity (100Gi/200Gi) 2018-02-13 21:55:03 PVC my-redis-redis added, claim size 50Gi 2018-02-13 21:55:03 At 75.0% claim capcity (150Gi/200Gi)
Let's deploy an application to the cluster that will apply for 75Gi capacity storage. (for example, let's deploy an instance influxdb through helm).
Helm install-- name my-influx\-- set persistence.enabled=true,persistence.size=75Gi stable/influxdb
As you can see below, our tool immediately responded with a new announcement and a warning because the total number of claims currently running has exceeded the threshold we set.
-PVC Watch (max claims 200Gi)-2018-02-13 21:55:03 At 75.0% claim capcity (150Gi/200Gi) 2018-02-13 22:01:29 PVC my-influx-influxdb added, claim size 75Gi 2018-02-13 22:01:29 Claim overage reached: max 200Gi at 225Gi 2018-02-13 22:01:29 * Taking action * * 2018-02-13 22:01:29 At 112.5% claim capcity (225Gi/200Gi)
Instead, when you delete a PVC from a cluster, the tool displays a prompt accordingly.
... At 112.5% claim capcity (225Gi/200Gi) 11:30:36 PVC my-redis2-redis removed on 2018-02-14, size 100Gi 2018-02-14 11:30:36 Claim usage normal: max 200Gi at 125Gi 2018-02-14 11:30:36 * Taking action * *
Summary
This article is part of an ongoing series that uses the official K8s client in the go language to interact with API server. As before, this code gradually implements a command-line tool to listen for the size of the PVC under the specified namespace. This code implements a simple listener list to trigger resource events returned from the server.
At this point, the study on "how to use Go to build Kubernetes applications" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.