为了账号安全,请及时绑定邮箱和手机立即绑定

观察 pod 状态的所有变化

观察 pod 状态的所有变化

Go
至尊宝的传说 2022-07-18 17:09:59
我正在尝试编写行为类似于 kubectl get pods --watch. 这样,每当 pod 的状态发生变化时,我都会被触发。我创建了一个go项目(在集群中运行)并添加了以下代码:podsWatcher, err := restAPIClient.CoreV1().Pods("").Watch(globalHTTPContext, metav1.ListOptions{Watch: true})if err != nil {    // do something}podsChan := podsWatcher.ResultChan()for event := range podsChan {    switch event.Type {    case watch.Added:        // do something    case watch.Modified:        // do something    case watch.Deleted:        // do something    case watch.Bookmark:        // do something    case watch.Error:        // do something    }}每次对 pod 进行重大更改时,我都会收到一个事件,但不是针对所有事件。(事件)。如何触发 Pod 状态中发生的每一个变化(如--watch标志)?
查看完整描述

1 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

显然,手表是由每次更改(在 pod describe 中进行的)触发的,我正在查看pod.status.phase而不是查看pod.Status.ContainerStatuses,这就是为什么我认为我没有收到每个事件。


我添加了一个函数来处理以下事件:


// get ContainerStatuses. If there is no containerStatus, return the pod phase

func getPodStatus(pod *core.Pod) string {

    containerStatuses := pod.Status.ContainerStatuses

    status := ""

    if len(containerStatuses) > 0 {

        for i := range containerStatuses {

            if containerStatuses[i].State.Terminated != nil {

                status = containerStatuses[i].State.Terminated.Reason

            }

            if containerStatuses[i].State.Waiting != nil {

                status = containerStatuses[i].State.Waiting.Reason

            }

            if containerStatuses[i].State.Running != nil {

                if status == "" { // if none of the containers report an error

                    status = "Running"

                }

            }

        }

    }

    if status == "" {

        status = string(pod.Status.Phase)

    }

    return status

}


// PodWatch watch pod changes in all namespaces

func PodWatch() error {

    podsWatcher, err := restAPIClient.CoreV1().Pods("").Watch(globalHTTPContext, metav1.ListOptions{Watch: true})

    if err != nil {

        return err

    }

    podsChan := podsWatcher.ResultChan()

    for event := range podsChan {

        pod, err := event.Object.(*core.Pod)

        if err != nil {

            return err

        }

        switch event.Type {

        case watch.Added:

            fmt.Println(getPodStatus(pod))

        case watch.Modified:

            fmt.Println(getPodStatus(pod))

        case watch.Deleted:

            fmt.Println(getPodStatus(pod))

        case watch.Bookmark:

            fmt.Println(getPodStatus(pod))

        case watch.Error:

            fmt.Println(getPodStatus(pod))

        }

    }

}

这个解决方案适合我的需要,如果你想实现--watch类似 kubectl,你可以在这里找到实现。


查看完整回答
反对 回复 2022-07-18
  • 1 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信