client-go gin的简单整合二(list列表相关进一步操作)

Posted saynaihe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了client-go gin的简单整合二(list列表相关进一步操作)相关的知识,希望对你有一定的参考价值。

背景

上一步完成了client-go gin的简单整合一(list列表相关操作),实现了简单的namespace deployment service的name的输出!现在我想输出更多的内容,也当时深入一下kubernetes这些基础!

1. client-go gin的简单整合二(list列表相关进一步操作)

1. 从namespace开始

[root@zhangpeng ~]# kubectl get ns -o wide


首先我想输出namespace的STATUS状态和AGE!
以develop为例看一下还有什么想输出的信息

[root@zhangpeng ~]# kubectl get ns develop -o yaml


creationTimestamp labels status状态在这里也是可以体现的!
动手吧
src/service/Namespace.go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"time"
)

type Time struct 
	time.Time `protobuf:"-"`

type Namespace struct 
	Name       string
	CreateTime Time `json:"CreateTime"`
	Status     string
	Labels     map[string]string


func ListNamespace(g *gin.Context) 
	ns, err := K8sClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions)
	if err != nil 
		g.Error(err)
		return
	
	ret := make([]*Namespace, 0)
	for _, item := range ns.Items 
		ret = append(ret, &Namespace
			Name:       item.Name,
			CreateTime: Time(item.CreationTimestamp),
			Status:     string(item.Status.Phase),
			Labels:     item.Labels,
		)

	
	g.JSON(200, ret)
	return

注:毕竟新手不太会处理数据,就做了如下处理,先能展现出自己先要的数据。后面再作深入的学习!


同理status

但是我这里偷懒了…直接搞了一个string。短期来看应该没有什么问题吧?

同理labels map[string]string


运行main.go,main.go依然是原来的没有进行其他修改如下:

package main

import (
	"github.com/gin-gonic/gin"
	"k8s-demo1/src/service"
)

func main() 
	r := gin.Default()
	r.GET("/", func(context *gin.Context) 
		context.JSON(200, "hello")
	)
	r.GET("/namespaces", service.ListNamespace)
	r.GET("/deployments", service.ListDeployment)
	r.GET("/service", service.ListService)
	r.Run()



浏览器访问:http://127.0.0.1:8080/namespaces,如下

基本完成,AGE还没有想好怎么展现,是不是要算时间戳减去CreateTime?后面再去研究吧…

2.继续deployment的进一步深入

[root@zhangpeng ~]# kubectl get deployment -o wide


恩 起码的是要把这些基本输出的:READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR!
详细看一眼nginx deployment 看一眼还有什么要输出的:

[root@zhangpeng ~]# kubectl get deployment nginx -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2022-05-01T13:47:52Z"
  generation: 1
  labels:
    app: nginx
    env: dev
  name: nginx
  namespace: default
  resourceVersion: "16449910"
  uid: ec1423a5-1268-40ea-bbf5-15576a332755
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: nginx
      env: dev
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
        env: dev
      name: nginx
    spec:
      containers:
      - image: nginx:1.16.1
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
          name: http
          protocol: TCP
        resources: 
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: 
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: "2022-05-01T13:48:10Z"
    lastUpdateTime: "2022-05-01T13:48:10Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2022-05-01T13:47:52Z"
    lastUpdateTime: "2022-05-01T13:48:10Z"
    message: ReplicaSet "nginx-7b5d9df6b8" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 1
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1

这还没有想好需要什么,就先按照kubectl get deployment -o wide的输出整一下了

src/service/Deployment.go

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Deployment struct 
	Name                string
	Replicas            int32
	AvailableReplicas   int32
	UnavailableReplicas int32
	Images              string
	Labels              map[string]string


func ListDeployment(g *gin.Context) 
	ns := g.Query("ns")

	dps, err := K8sClient.AppsV1().Deployments(ns).List(context.Background(), metav1.ListOptions)
	if err != nil 
		g.Error(err)
	
	ret := make([]*Deployment, 0)
	for _, item := range dps.Items 

		ret = append(ret, &Deployment
			Name:                item.Name,
			Replicas:            item.Status.Replicas,
			AvailableReplicas:   item.Status.AvailableReplicas,
			UnavailableReplicas: item.Status.UnavailableReplicas,
			Images:              item.Spec.Template.Spec.Containers[0].Image,
			Labels:              item.Labels,
		)

	
	g.JSON(200, ret)
	return


Images也没有考虑其他的,多个镜像或者其他状况,READY CONTAINERS还没有想好怎么展现!
go run main.go
http://127.0.0.1:8080/deployments

http://127.0.0.1:8080/deployments?ns=kube-system

3.同理service

[root@zhangpeng .kube]# kubectl get svc -o wide
NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE   SELECTOR
kubernetes   ClusterIP   192.168.0.1   <none>        443/TCP   55d   <none>

基本就输出NAME TYPE CLUSTER-IP EXTERNAL-IP PORTS SELECTOR

package service

import (
	"context"
	"github.com/gin-gonic/gin"
	. "k8s-demo1/src/lib"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type Service struct 
	Name       string
	Type       string
	ClusterIp  string
	ExternalIp []string
	Ports      []string
	Select     map[string]string


func ListService(g *gin.Context) 
	ns := g.Query("ns")
	svc, err := K8sClient.CoreV1().Services(ns).List(context.Background(), metav1.ListOptions)
	if err != nil 
		g.Error(err)
		return
	
	ret := make([]*Service, 0)
	for _, item := range svc.Items 
		ret = append(ret, &Service
			Name:       item.Name,
			Type:       string(item.Spec.Type),
			ClusterIp:  item.Spec.ClusterIP,
			ExternalIp: item.Spec.ExternalIPs,
			Select:     item.Spec.Selector,
		)

	
	g.JSON(200, ret)
	return

注意:ExternalIp貌似会有问题 都是null还没有先好怎么取数据Type 偷懒了直接string了!ports也没有想到怎么取得
go run main.go
http://127.0.0.1:8080/service

http://127.0.0.1:8080/service?ns=default

第一部分list总算能看一下了…除了没有实现的…

总结

  1. 算是基本上实现了list接口的自定义显示?
  2. goland神器是不错,查看源码,可惜还不能深入读懂
  3. service ports ExternalIp,**deployment **READY CONTAINERS展现,还有image多镜像的处理?
  4. AGE的计算

以上是关于client-go gin的简单整合二(list列表相关进一步操作)的主要内容,如果未能解决你的问题,请参考以下文章

client-go gin的简单整合三(list列表相关再进阶关于Pods)

client-go gin的简单整合六-list-watch二(关于Rs与Pod以及Deployment的完善)

client-go gin的简单整合六-list-watch二(关于Rs与Pod以及Deployment的完善)

client-go gin的简单整合六-list-watch二(关于Rs与Pod以及Deployment的完善)

client-go gin的简单整合三(list列表相关再进阶关于Pods)

client-go gin的简单整合三(list列表相关再进阶关于Pods)