首页 > 解决方案 > Kubernetes手表的正确使用方法

问题描述

我是 Kubernetes 的新手,我不确定如何继续正确实现手表;特别是我不确定如何处理 resourceVersion 参数。

目标是监视具有特定标签的新 pod,并且在发生错误或与集群断开连接的情况下,能够从发生的最后一个事件重新启动监视。

我正在做这样的事情:

// after setting up the connection and some parameters
String lastResourceVersion = null; // at beginning version is unknown
while (true) {
  try {
    Watch<V1Pod> watcher = Watch.createWatch(
            client,
            api.listNamespacedPodCall(namespace, pretty, fieldSelector, labelSelector, lastResourceVersion, forEver, true, null, null),
            new TypeToken<Watch.Response<V1Pod>>() {}.getType()
    );
    for (Watch.Response<V1Pod> item : watcher) {
      //increment the version
      lastResourceVersion = item.object.getMetadata().getResourceVersion();
      // do some stuff with the pod
    }
  } catch (ApiException apiException) {
    log.error("restarting the watch from "+lastResourceVersion, apiException);
  }
}

使用 Pod 的 resourceVersion 重新初始化 watch 调用是否正确?这个数字是集群中所有事件的一种时间戳,还是不同的 api 会使用不同的序列?

我需要注意特定的例外情况吗?例如。如果 resourceVersion 太旧?

谢谢

标签: kuberneteswatch

解决方案


亚当是对的。

这最好由https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes解释

引用相关部分(强调我的):

在检索资源集合(命名空间或集群范围)时,来自服务器的响应将包含一个 resourceVersion 值,该值可用于启动对服务器的监视。

...剪断...

当请求的监视操作由于该资源的历史版本不可用而失败时,客户端必须通过识别状态码 410 Gone、清除本地缓存、执行列表操作并从该资源返回的 resourceVersion 启动监视来处理这种情况。新的列表操作。

因此,在调用 watch 之前,您应该列出并从列表中提取 resourceVersion(而不是其中的对象)。然后使用该资源版本启动手表。如果手表由于某种原因失败,您将不得不再次列出,然后使用该列表中的 resourceVersion 重新建立手表。


推荐阅读