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

对你无可奈何

背景:

紧接client-go gin的简单整合二(list列表相关进一步操作),namespace deployment service 都list列表展现了,总觉得还少点什么?比如显示集群中所有运行的pod列表?根据namespace显示pod列表?按照deployment名称查询所包含的pod?总而言之这一部分就围绕着pod列表的展现展开了!

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

1. 展现命名空间的pod相关信息

先确认一下需要获取的信息:
kubectl get pods -o wide

[root@zhangpeng ~]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE     IP          NODE                       NOMINATED NODE   READINESS GATES
nginx-7b5d9df6b8-dsx8j   1/1     Running   0          5d19h   10.31.0.4   cn-beijing.172.25.84.228   <none>           <none>

name status restarts ip node这几个肯定三要搞上的 输出一下pod的yaml看还有什么要输出的

[root@zhangpeng ~]# kubectl get pods nginx-7b5d9df6b8-dsx8j -o yaml

image.png
createtime lables image也添加一下!
基本copy了一下Namespace.go 里面func ListNamespace过来:
src/service/Pod.go

package service

import (
    "context"
    "github.com/gin-gonic/gin"
    . "k8s-demo1/src/lib"
package service

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

type Pod struct {
    Namespace  string
    Status     string
    Images     string
    NodeName   string
    CreateTime string
    Labels     map[string]string
}

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

    pods, err := K8sClient.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})
    if err != nil {
        g.Error(err)
    }
    ret := make([]*Pod, 0)
    for _, item := range pods.Items {

        ret = append(ret, &Pod{
        Namespace:  item.Namespace,
            Name:       item.Name,
            Status:     string(item.Status.Phase),
            Labels:     item.Labels,
            NodeName:   item.Spec.NodeName,
            Images:     item.Spec.Containers[0].Image,
            CreateTime: item.CreationTimestamp.Format("2006-01-02 15:04:05"),
        })

    }
    g.JSON(200, ret)
    return
}

Status取了Phase的值应该是没有问题的吧?Images跟deployment取值一样。本来开始准备搞上restart的次数......但是kube-system下pod有异常输出就先忽略了!
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.GET("pods", service.ListallPod)
    r.Run()
}

增加r.GET("pods", service.ListallPod)路由! 运行main.go
http://127.0.0.1:8080/pods
image.png
http://127.0.0.1:8080/pods?ns...
image.png
基本完成!

2. 按照deployment为条件显示对应pod列表

按照namespace命名空间区分排序pod列表还是很简单的,如何按照deployment 名字去显示pod列表呢?
这边是照抄的沈老师的课程,自己还没有转过弯来......
image.png
deployment是通过selector标签去匹配的pod labels,我就先那么理解了......
写一个方法GetPodsByDep根据namespace depoyment名称获取pod相关信息:
src/service/Deployment.go文件中:

func GetPodsByDep(ns string, dep *v1.Deployment) []*Pod {
    ctx := context.Background()
    listopt := metav1.ListOptions{
        LabelSelector: GetLabels(dep.Spec.Selector.MatchLabels),
    }
    list, err := K8sClient.CoreV1().Pods(ns).List(ctx, listopt)
    if err != nil {
        panic(err.Error())
    }
    pods := make([]*Pod, len(list.Items))
    for i, pod := range list.Items {
        pods[i] = &Pod{
            Namespace:  pod.Namespace,
            Name:       pod.Name, //获取 pod名称
            Status:     string(pod.Status.Phase),
            Images:     pod.Spec.Containers[0].Image,
            NodeName:   pod.Spec.NodeName, //所属节点
            Labels:     pod.Labels,
            CreateTime: pod.CreationTimestamp.Format("2006-01-02 15:04:05"), //创建时间
        }
    }

    return pods

}

src/service/Deployment.go最终如下:

package service

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

type Deployment struct {
    Namespace           string
    Name                string
    Replicas            int32
    AvailableReplicas   int32
    UnavailableReplicas int32
    Images              string
    CreateTime          string
    Labels              map[string]string
    Pods                []*Pod
}

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.GetLabels(),
        })

    }
    g.JSON(200, ret)
    return
}
func GetPodsByDep(ns string, dep *v1.Deployment) []*Pod {
    ctx := context.Background()
    listopt := metav1.ListOptions{
        LabelSelector: GetLabels(dep.Spec.Selector.MatchLabels),
    }
    list, err := K8sClient.CoreV1().Pods(ns).List(ctx, listopt)
    if err != nil {
        panic(err.Error())
    }
    pods := make([]*Pod, len(list.Items))
    for i, pod := range list.Items {
        pods[i] = &Pod{
            Namespace:  pod.Namespace,
            Name:       pod.Name, //获取 pod名称
            Status:     string(pod.Status.Phase),
            Images:     pod.Spec.Containers[0].Image,
            NodeName:   pod.Spec.NodeName, //所属节点
            Labels:     pod.Labels,
            CreateTime: pod.CreationTimestamp.Format("2006-01-02 15:04:05"), //创建时间
        }
    }

    return pods

}
func GetDeployment(g *gin.Context) {
    ns := g.Query("ns")
    name := g.Query("name")
    ctx := context.Background()
    getopt := metav1.GetOptions{}
    dps, err := K8sClient.AppsV1().Deployments(ns).Get(ctx, name, getopt)
    if err != nil {
        g.Error(err)
    }
    ret := make([]*Deployment, 0)
    ret = append(ret, &Deployment{
        Namespace:           dps.Namespace,
        Name:                dps.Name,
        Replicas:            dps.Status.Replicas,
        AvailableReplicas:   dps.Status.AvailableReplicas,
        UnavailableReplicas: dps.Status.UnavailableReplicas,
        Images:              dps.Spec.Template.Spec.Containers[0].Image,
        CreateTime:          dps.CreationTimestamp.Format("2006-01-02 15:03:04"),
        Labels:              dps.Labels,
        Pods:                GetPodsByDep(ns, dps),
    })
    g.JSON(200, ret)
    return
}

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.GET("/deployment", service.GetDeployment)
    r.GET("pods", service.ListallPod)
    r.Run()
}

运行 main.go
http://127.0.0.1:8080/deploym...
image.png

后记:

  1. GetPodsByDep还是有点懵
  2. 指针还是迷惑
  3. map啥的数据格式啥的还是蒙懵阿......
  4. 这一周好好消化一下list......
  5. 后面貌似还有informer? list watch机制啥的......一步一步来吧!
  6. 最近工作有点杂,更新会慢一些。但是会持续更新ing......
阅读 254

19 声望
5 粉丝
0 条评论
19 声望
5 粉丝
文章目录
宣传栏