Python kubernetes pod 监视状态

Python kubernetes pod watch state

当 Pod 改变状态时,我没有成功获取 Pod 的实际状态。从我下面的代码来看,它卡在 waiting 中,在我的终端中 ContainerCreating 卡在无限循环中。

    for event in watch.stream(func=v1.list_namespaced_pod, namespace=ns, timeout_seconds=120):
      response = event['object'].status
      pod_data = {
          "name": data.container_statuses[0].name,
          "status": data.container_statuses[0].state,
          "phase": data.phase,
      }
      if f'{pod_name}' in data[0]['name']:
        running = data[0]['status'].running
        wait = data[0]['status'].waiting
        while wait != None:
          print(f"waiting for {pod_name} state to Running...")
          print(wait.reason)
          time.sleep(10)
        if running.started_at != None:
          print("State has changed to Running. Pod has been created and started... ' ")
          watch.stop()

获取 Pod 当前状态的最佳方法是什么?我有一个复制操作,当状态从 Pending 变为 Running 时触发。

ContainerCreating
ContainerCreating
ContainerCreating
ContainerCreating
ContainerCreating
ContainerCreating
ContainerCreating
ContainerCreating
ContainerCreating

我也尝试过使用 event['object'].status.phase。但它仍然卡在循环中。

 'container_statuses': [{'container_id': 'container-xxx',
                         'image': 'image-xxx',
                         'image_id': 'image-xxxx',
                         'last_state': {'running': None,
                                        'terminated': None,
                                        'waiting': None},
                         'name': 'hub',
                         'ready': True,
                         'restart_count': 0,
                         'state': {'running': {'started_at': datetime.datetime(2020, 4, 11, 8, 15, 53, tzinfo=tzutc())},
                                   'terminated': None,
                                   'waiting': None}}],
 'host_ip': 'xx.xx.xx.xxx',
 'init_container_statuses': None,
 'message': None,
 'nominated_node_name': None,
 'phase': 'Running',
 'pod_ip': 'x.xx.xx.xxx',
 'qos_class': 'Burstable',
 'reason': None,
 'start_time': datetime.datetime(2020, 4, 11, 23, 48, 1, tzinfo=tzutc())}

我可能在 python 调用中做错了什么或使用了错误的 kubernetes 方法。我现在没主意了!

我想你可以使用 watch.stop():

watch = kubernetes.watch.Watch()
core_v1 = k8s.CoreV1Api()
for event in watch.stream(func=core_v1.list_namespaced_pod,
                          namespace=namespace,
                          label_selector=label,
                          timeout_seconds=60):
    if event["object"].status.phase == "Running":
        watch.stop()
        end_time = time.time()
        logger.info("%s started in %0.2f sec", full_name, end_time-start_time)
        return
    # event.type: ADDED, MODIFIED, DELETED
    if event["type"] == "DELETED":
        # Pod was deleted while we were waiting for it to start.
        logger.debug("%s deleted before it started", full_name)
        watch.stop()
        return