使用 client-go 模拟“kubectl wait”以等待 Pod 准备就绪

Dav*_*eUK 6 go kubernetes client-go

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

kubectl wait --for=condition=Ready --timeout=2m -n mynamespace pod -l myselector
Run Code Online (Sandbox Code Playgroud)

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

现在我需要在 golang 代码中做类似的事情。我见过使用client-go库进行身份验证并按名称“获取”特定 pod 的示例。但我有一些关于如何最好地使这个例子适应我的需要的问题......

  1. 我不知道能够“Get()”它的 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' 包或类似的?你有什么建议吗?

Ric*_*ico 6

完全按照它的方式去做怎么样kubectl?基本上,使用List(...)根据字段选择器列出,然后Watch(...)

\n

片段:

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

\xe2\x9c\x8c\xef\xb8\x8f

\n