正确使用kubernetes手表的方法

G. *_*oni 9 watch 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

使用Pod的resourceVersion重新初始化观看调用是否正确?此数字是群集中所有事件的时间戳,还是不同的api将使用不同的序列?

我是否需要注意特定的例外情况?例如.如果资源版本是旧的?

谢谢

kro*_*sey 10

亚当是对的。

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

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

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

……剪……

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

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