func main()

in cmd/grpc-health-probe/main.go [74:140]


func main() {
	ctx, cancel := context.WithCancel(context.Background())

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		sig := <-c
		if sig == os.Interrupt {
			log.Infof("cancellation received")
			cancel()
			return
		}
	}()

	opts := []grpc.DialOption{
		grpc.WithUserAgent(userAgent),
		grpc.WithBlock(),
		grpc.WithNoProxy()}

	opts = append(opts, grpc.WithInsecure())

	if verbose {
		log.Info("establishing connection")
	}
	connStart := time.Now()
	dialCtx, cancel2 := context.WithTimeout(ctx, connTimeoutDur)
	defer cancel2()
	conn, err := grpc.DialContext(dialCtx, remoteURL, opts...)
	if err != nil {
		if err == context.DeadlineExceeded {
			log.Infof("timeout: failed to connect service %q within %v", remoteURL, connTimeoutDur)
		} else {
			log.Infof("error: failed to connect service at %q: %+v", remoteURL, err)
		}
		os.Exit(StatusConnectionFailure)
	}
	connDuration := time.Since(connStart)
	defer conn.Close()
	if verbose {
		log.Infof("connection established (took %v)", connDuration)
	}

	rpcStart := time.Now()
	rpcCtx, rpcCancel := context.WithTimeout(ctx, rpcTimeoutDur)
	defer rpcCancel()
	resp, err := healthpb.NewHealthClient(conn).Check(rpcCtx, &healthpb.HealthCheckRequest{Service: serviceName})
	if err != nil {
		if stat, ok := status.FromError(err); ok && stat.Code() == codes.Unimplemented {
			log.Infof("error: this server does not implement the grpc health protocol (grpc.health.v1.Health)")
		} else if stat, ok := status.FromError(err); ok && stat.Code() == codes.DeadlineExceeded {
			log.Infof("timeout: health rpc did not complete within %v", rpcTimeoutDur)
		} else {
			log.Infof("error: health rpc failed: %+v", err)
		}
		os.Exit(StatusRPCFailure)
	}
	rpcDuration := time.Since(rpcStart)

	if resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {
		log.Infof("service unhealthy (responded with %q)", resp.GetStatus().String())
		os.Exit(StatusUnhealthy)
	}
	if verbose {
		log.Infof("time elapsed: connect=%v rpc=%v", connDuration, rpcDuration)
	}
	log.Infof("status: %v", resp.GetStatus().String())
}