from kubernetes import client, config
from grpc_health.v1 import health_pb2, health_pb2_grpc
import grpc.experimental.aio as aio
import asyncio
async def check_grpc_health(ip, port):
try:
channel = aio.insecure_channel(f"{ip}:{port}")
stub = health_pb2_grpc.HealthStub(channel)
response = await stub.Check(health_pb2.HealthCheckRequest(service=""), timeout=1)
await channel.close()
return response.status == health_pb2.HealthCheckResponse.SERVING
except Exception as e:
print(f"Error checking health of gRPC service at {ip}:{port}: {e}")
return False
async def check_pod_health(pod):
ip = pod.status.pod_ip
port = None
if pod.spec.containers and pod.spec.containers[0].ports:
port = pod.spec.containers[0].ports[0].container_port
if ip is not None and await check_grpc_health(ip, port):
print(f"Pod {pod.metadata.name} is healthy.")
else:
print(f"Pod {pod.metadata.name} is unhealthy, consider restarting.")
async def main():
config.load_kube_config()
v1 = client.CoreV1Api()
namespace = "apple-engine"
label_selector = "grpc-health-check"
print("finding...")
pods = await v1.list_namespaced_pod(namespace=namespace, watch=False)
print(len(pods.items))
tasks = [check_pod_health(pod) for pod in pods.items]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
字符串
我正在使用kubernetes API编写这个健康检查python代码,但不考虑proto文件。
如果我使用这个健康检查代码,是否需要proto文件?只是想检查与proto的连接,不完全考虑命名空间和标签选择器
1条答案
按热度按时间5t7ly7z51#
gRPC项目提供了gRPC Health Checking protocol的PyPI实现,称为
grpcio-health-checking
,您可以使用。