使用kubernetes手表的正确方法

时间:2018-10-09 09:20:37

标签: kubernetes watch

我是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重新初始化监视调用是否正确?这个数字是集群中所有事件的时间戳,还是不同的api使用不同的序列?

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

谢谢

1 个答案:

答案 0 :(得分:3)

亚当是对的。

最好用 https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes

来解释

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

  

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

...片段...

  

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

因此,在调用watch之前,应该列出资源版本并将其从列表中拉出(而不是其中的对象)。然后从该resourceVersion开始监视。如果手表由于某种原因而失败,则必须再次列出,然后使用该列表中的resourceVersion重新建立手表。