问题描述
如何使用Node.js和Bazel为gRPC设置GRPC Health Checking?
解决方法
1。将grpc-health-probe二进制文件添加到Bazel
在您的WORKSPACE
文件中添加
load("@bazel_tools//tools/build_defs/repo:http.bzl","http_file")
http_file(
name = "grpc_health_check_bin",downloaded_file_path = "grpc_health_probe",urls = ["https://github.com/grpc-ecosystem/grpc-health-probe/releases/download/v0.3.2/grpc_health_probe-linux-amd64"],)
下载可执行二进制文件。
2。实施服务
选项1:使用grpc-health-check npm模块
- 只需阅读文档即可:)
选项2 自己实施卫生服务
- 转到this页并复制
health-checking.proto
文件,该文件当前如下所示:syntax = "proto3"; package grpc.health.v1; message HealthCheckRequest { string service = 1; } message HealthCheckResponse { enum ServingStatus { UNKNOWN = 0; SERVING = 1; NOT_SERVING = 2; SERVICE_UNKNOWN = 3; // Used only by the Watch method. } ServingStatus status = 1; } service Health { rpc Check(HealthCheckRequest) returns (HealthCheckResponse); rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse); }
- 在您的BUILD.bazel文件中,创建带有proto文件的文件组,以便我们以后可以将其添加到NodeJs映像中
filegroup( name = "health_checking_proto",srcs = ["health-checking.proto"],)
- 实施卫生服务
import * as protoLoader from '@grpc/proto-loader' import * as grpc from '@grpc/grpc-js' async function main() { const packageDefinition = await protoLoader.load('health-checking.proto') const grpcObject = grpc.loadPackageDefinition(packageDefinition) const {service} = (grpcObject.grpc as any).health.v1.Health const server = new grpc.Server() const implementation = { // status can be on of UNKNOWN,SERVING,NOT_SERVING Check: (_call: any,callback: any) => callback(null,{status: 'SERVING'}),} server.addService(service,implementation) server.bindAsync('0.0.0.0:9090',grpc.ServerCredentials.createInsecure(),() => server.start()) } main()
3。使用Bazel构建和部署NodeJs映像
最终的BUILD
文件可能如下所示:
load("@npm//@bazel/typescript:index.bzl","ts_library")
load("@k8s_deploy//:defaults.bzl","k8s_deploy")
load("@io_bazel_rules_docker//nodejs:image.bzl","nodejs_image")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "lib",srcs = glob(include = ["**/*.ts"]),deps = [
"@npm//@grpc/grpc-js","@npm//@grpc/proto-loader","@npm//@types/node",],)
filegroup(
name = "health_checking_proto",)
nodejs_image(
name = "image",data = [
# nodejs application
":lib",# health-checking.proto file
":health_checking_proto",# grpc-health-probe executable binary
"@grpc_health_check_bin//file",entry_point = ":index.ts",)
k8s_deploy(
name = "k8s",images = {"k8s:placeholder_name": ":image"},template = ":k8s.yaml",)
4。向Kubernetes添加活跃性和就绪性探针
spec:
containers:
- name: server
image: "[YOUR-DOCKER-IMAGE]"
ports:
- containerPort: 9090
readinessProbe:
exec:
command: ["/app/<path to dir with BUILD file>/image.binary.runfiles/grpc_health_check_bin/file/grpc_health_probe","-addr=:9090"]
initialDelaySeconds: 5
livenessProbe:
exec:
command: ["/app/<path to dir with BUILD file>/image.binary.runfiles/grpc_health_check_bin/file/grpc_health_probe","-addr=:9090"]
initialDelaySeconds: 10