xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/health/health_client.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 /*
2  *
3  * Copyright 2024 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #include <condition_variable>
20 #include <iostream>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 
25 #include "absl/flags/flag.h"
26 #include "absl/flags/parse.h"
27 
28 #include <grpcpp/grpcpp.h>
29 
30 #ifdef BAZEL_BUILD
31 #include "examples/protos/helloworld.grpc.pb.h"
32 
33 #include "src/proto/grpc/health/v1/health.grpc.pb.h"
34 #else
35 #include "health.grpc.pb.h"
36 #include "helloworld.grpc.pb.h"
37 #endif
38 
39 ABSL_FLAG(std::string, target, "localhost:50051", "Server address");
40 
41 using grpc::Channel;
42 using grpc::ClientContext;
43 using grpc::Status;
44 using grpc::health::v1::Health;
45 using grpc::health::v1::HealthCheckRequest;
46 using grpc::health::v1::HealthCheckResponse;
47 using helloworld::Greeter;
48 using helloworld::HelloReply;
49 using helloworld::HelloRequest;
50 
51 class GreeterClient {
52  public:
GreeterClient(std::shared_ptr<Channel> channel)53   GreeterClient(std::shared_ptr<Channel> channel)
54       : stub_(Greeter::NewStub(channel)),
55         health_stub_(Health::NewStub(channel)) {}
56 
57   // Assembles the client's payload, sends it and presents the response back
58   // from the server.
SayHello(const std::string & user)59   std::string SayHello(const std::string& user) {
60     // Data we are sending to the server.
61     HelloRequest request;
62     request.set_name(user);
63 
64     // Container for the data we expect from the server.
65     HelloReply reply;
66 
67     // Context for the client. It could be used to convey extra information to
68     // the server and/or tweak certain RPC behaviors.
69     ClientContext context;
70 
71     // The actual RPC.
72     std::mutex mu;
73     std::condition_variable cv;
74     bool done = false;
75     Status status;
76     stub_->async()->SayHello(&context, &request, &reply,
77                              [&mu, &cv, &done, &status](Status s) {
78                                status = std::move(s);
79                                std::lock_guard<std::mutex> lock(mu);
80                                done = true;
81                                cv.notify_one();
82                              });
83 
84     std::unique_lock<std::mutex> lock(mu);
85     while (!done) {
86       cv.wait(lock);
87     }
88 
89     // Act upon its status.
90     if (status.ok()) {
91       return reply.message();
92     } else {
93       std::cout << status.error_code() << ": " << status.error_message()
94                 << std::endl;
95       return "RPC failed";
96     }
97   }
98 
CheckHealth(const std::string & message)99   void CheckHealth(const std::string& message) {
100     ClientContext context;
101     HealthCheckResponse response;
102     Status status = health_stub_->Check(
103         &context, HealthCheckRequest::default_instance(), &response);
104     if (!status.ok()) {
105       std::cerr << "Failed to check service health: " << status.error_code()
106                 << ": " << status.error_message() << "\n";
107       return;
108     }
109     std::cout << message << ": " << response.DebugString();
110   }
111 
112  private:
113   std::unique_ptr<Greeter::Stub> stub_;
114   std::unique_ptr<Health::Stub> health_stub_;
115 };
116 
main(int argc,char ** argv)117 int main(int argc, char** argv) {
118   absl::ParseCommandLine(argc, argv);
119   // Instantiate the client. It requires a channel, out of which the actual RPCs
120   // are created. This channel models a connection to an endpoint specified by
121   // the argument "--target=" which is the only expected argument.
122   std::string target_str = absl::GetFlag(FLAGS_target);
123   // We indicate that the channel isn't authenticated (use of
124   // InsecureChannelCredentials()).
125   grpc::ChannelArguments args;
126   args.SetServiceConfigJSON(
127       "{\"healthCheckConfig\": "
128       "{\"serviceName\": \"\"}}");
129   GreeterClient greeter(grpc::CreateCustomChannel(
130       target_str, grpc::InsecureChannelCredentials(), args));
131   std::string user = "world";
132   greeter.CheckHealth("Before call");
133   std::string reply = greeter.SayHello(user);
134   std::cout << "Greeter received: " << reply << std::endl;
135   greeter.CheckHealth("After call");
136   reply = greeter.SayHello(user);
137   std::cout << "Greeter received: " << reply << std::endl;
138   greeter.CheckHealth("After second call");
139   return 0;
140 }
141