python - Python Kubernetes 获得新事件
问题描述
我正在尝试使用 python 在 k8s 中捕获事件。问题是当我运行脚本时,监视进程会向我显示所有事件(当前的和新的)。是否有可能只获得新事件?
我的代码如下所示:
config.load_incluster_config()
v1 = client.CoreV1Api()
w = watch.Watch()
for event in w.stream(v1.list_service_for_all_namespaces, timeout_seconds=0):
service = event['object']
if service.spec.type == 'NodePort':
print(service.metadata.name, service.metadata.namespace, service.spec.type, service.spec.ports[0].node_port, event['type'])
使用上面的代码,我收到当前事件(旧事件)和新事件,但我只想要新事件。提前致谢!!
解决方案
您可以通过添加 if 语句来使用。
if event['type'] == "ADDED" and namespace not in namespaces: print("Event: %s %s %s" % (event['type'],event['object'].kind, namespace)
from kubernetes import client, config, watch
from urllib3.exceptions import ProtocolError
config.load_kube_config()
api_instance = client.CoreV1Api()
all_namespaces = api_instance.list_namespace(watch=False)
namespaces = set()
for namespace in all_namespaces.items:
namespaces.add(namespace.metadata.name)
#print(namespace.metadata.name)
w = watch.Watch()
try:
for event in w.stream(api_instance.list_namespace,timeout_seconds=0):
namespace = event['object'].metadata.name
if event['type'] == "ADDED" and namespace not in namespaces:
print("Event: %s %s %s" % (event['type'],event['object'].kind, namespace))
namespaces.add(namespace)
except ProtocolError:
print("watchPodEvents ProtocolError, continuing..")
推荐阅读
- mysql - SQL 根据另一个表和另一个列值删除一个表中的所有行
- python - python中xaxis(axhspan,matplotlib)上带有日期时间的绘图中的阴影区域
- flutter - Flutter - 从另一个有状态小部件设置一个有状态小部件的变量值
- visual-studio-code - 底部工具栏中的调试按钮导致“启动:程序'[program_name]'不退出。” 使用 CMake 工具
- python - 如何编写一个需要 3 个变量的函数?
- c# - 使用 ASP.NET Core MVC 中的 EF Core 查询获取可为空的关系字段的数据
- oauth-2.0 - 使用 Microsoft Identity Platform 和 MSAL.NET 从 Hotmail 中代表用户流检索电子邮件
- android - 如何模拟成功和错误代码的 API 响应
- javascript - 如何使用 React 钩子过滤状态?
- pycharm - PyCharm 上的 Windows 防御者