使用 client-go 模拟 Pod 准备就绪的"kubectl wait"



在bash脚本中,我通常使用"kubectl wait"来阻止,直到某个pod资源准备就绪,例如类似于以下内容:

kubectl wait --for=condition=Ready --timeout=2m -n mynamespace pod -l myselector

这很有效,因为有时我不知道我需要等待的pod的确切名称,而"kubectl wait"允许我根据选择器定位pod,然后阻止它,直到它准备好。

现在我需要在golang代码中做一些类似的事情。我看到过使用客户端go库进行身份验证并按名称"获取"特定pod的示例。但我有几个问题是如何最好地适应我的需求。。。

  1. 我不知道pod的确切/全名才能"获取(("它,这就是为什么"kubectl wait"是完美的,因为它允许我使用选择器找到pod。我假设我应该使用client go库来代替CoreV1((.Pods((.List((调用,而不是Get((,以便使用选择器找到我想要的pod?

  2. 此外,pod可能不会立即存在,可能只在1分钟左右后创建,这是"kubectl wait"为我处理的。在代码中,我是否需要循环/睡眠并继续执行List((,直到pod存在?

  3. 类似于#2的问题…一旦List((返回了一个pod名称,在golang中"等待"该pod处于"就绪"状态的最佳方式是什么?如果可以避免的话,我不想用睡眠做任何丑陋的民意调查。。。那么,使用golang‘wait’软件包或类似软件有更好的选择吗?你推荐什么?

不如完全按照kubectl的方式来做?基本上,使用List(…(基于字段选择器进行列表,然后使用Watch(...)

代码段:

...
// List with a name field selector to get the current resourceVersion to watch from (not the object's resourceVersion)
gottenObjList, err := o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(context.TODO(), metav1.ListOptions{FieldSelector: nameSelector})
if apierrors.IsNotFound(err) {
return info.Object, true, nil
}
if err != nil {
// TODO this could do something slightly fancier if we wish
return info.Object, false, err
}
if len(gottenObjList.Items) != 1 {
return info.Object, true, nil
}
gottenObj := &gottenObjList.Items[0]
resourceLocation := ResourceLocation{
GroupResource: info.Mapping.Resource.GroupResource(),
Namespace:     gottenObj.GetNamespace(),
Name:          gottenObj.GetName(),
}
if uid, ok := o.UIDMap[resourceLocation]; ok {
if gottenObj.GetUID() != uid {
return gottenObj, true, nil
}
}
watchOptions := metav1.ListOptions{}
watchOptions.FieldSelector = nameSelector
watchOptions.ResourceVersion = gottenObjList.GetResourceVersion()
objWatch, err := o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(context.TODO(), watchOptions)
if err != nil {
return gottenObj, false, err
}
...

✌️

最新更新