1 回答
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,你可以在这里找到实现。
- 1 回答
- 0 关注
- 164 浏览
添加回答
举报