使用Kubernetes API检查gRPC服务健康是否需要proto文件?
关于gRPC健康检查代码是否需要proto文件的疑问
以下是你编写的代码:
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健康检查代码,用于检测Pod中的gRPC服务健康状态,但未考虑proto文件的使用。
请问使用该代码时是否需要proto文件?我仅需基于proto完成连接检查,暂不关注namespace和label selector的设置。
不需要额外准备proto文件,原因如下:
- 你代码中导入的
grpc_health.v1.health_pb2和health_pb2_grpc是gRPC官方标准健康检查接口对应的Python生成代码,这些代码已经包含在grpcio-health-checking依赖包中。 - 只要你安装了
grpcio-health-checking,这些pb2文件会自动被放置到Python的依赖目录里,不需要你手动编写或编译proto文件。
你只需要确保安装了所需依赖:
pip install kubernetes grpcio grpcio-health-checking grpcio-aio
补充说明:只有当你使用自定义的非标准gRPC健康检查proto时,才需要自己编写proto并编译生成对应的pb2文件;而你的代码调用的是gRPC官方统一的健康检查接口,完全不需要额外的proto文件就能正常工作。
内容的提问来源于stack exchange,提问作者Tae In Kim
相关产品推荐
相关产品推荐

