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 <grpcpp/grpcpp.h>
20
21 #include <condition_variable>
22 #include <iostream>
23 #include <memory>
24 #include <mutex>
25 #include <string>
26
27 #include "absl/flags/flag.h"
28 #include "absl/flags/parse.h"
29
30 #ifdef BAZEL_BUILD
31 #include "examples/protos/helloworld.grpc.pb.h"
32 #include "src/proto/grpc/health/v1/health.grpc.pb.h"
33 #else
34 #include "health.grpc.pb.h"
35 #include "helloworld.grpc.pb.h"
36 #endif
37
38 ABSL_FLAG(std::string, target, "localhost:50051", "Server address");
39
40 using grpc::Channel;
41 using grpc::ClientContext;
42 using grpc::Status;
43 using grpc::health::v1::Health;
44 using grpc::health::v1::HealthCheckRequest;
45 using grpc::health::v1::HealthCheckResponse;
46 using helloworld::Greeter;
47 using helloworld::HelloReply;
48 using helloworld::HelloRequest;
49
50 class GreeterClient {
51 public:
GreeterClient(std::shared_ptr<Channel> channel)52 GreeterClient(std::shared_ptr<Channel> channel)
53 : stub_(Greeter::NewStub(channel)),
54 health_stub_(Health::NewStub(channel)) {}
55
56 // Assembles the client's payload, sends it and presents the response back
57 // from the server.
SayHello(const std::string & user)58 std::string SayHello(const std::string& user) {
59 // Data we are sending to the server.
60 HelloRequest request;
61 request.set_name(user);
62
63 // Container for the data we expect from the server.
64 HelloReply reply;
65
66 // Context for the client. It could be used to convey extra information to
67 // the server and/or tweak certain RPC behaviors.
68 ClientContext context;
69
70 // The actual RPC.
71 std::mutex mu;
72 std::condition_variable cv;
73 bool done = false;
74 Status status;
75 stub_->async()->SayHello(&context, &request, &reply,
76 [&mu, &cv, &done, &status](Status s) {
77 status = std::move(s);
78 std::lock_guard<std::mutex> lock(mu);
79 done = true;
80 cv.notify_one();
81 });
82
83 std::unique_lock<std::mutex> lock(mu);
84 while (!done) {
85 cv.wait(lock);
86 }
87
88 // Act upon its status.
89 if (status.ok()) {
90 return reply.message();
91 } else {
92 std::cout << status.error_code() << ": " << status.error_message()
93 << std::endl;
94 return "RPC failed";
95 }
96 }
97
CheckHealth(const std::string & message)98 void CheckHealth(const std::string& message) {
99 ClientContext context;
100 HealthCheckResponse response;
101 Status status = health_stub_->Check(
102 &context, HealthCheckRequest::default_instance(), &response);
103 if (!status.ok()) {
104 std::cerr << "Failed to check service health: " << status.error_code()
105 << ": " << status.error_message() << "\n";
106 return;
107 }
108 std::cout << message << ": " << response.DebugString();
109 }
110
111 private:
112 std::unique_ptr<Greeter::Stub> stub_;
113 std::unique_ptr<Health::Stub> health_stub_;
114 };
115
main(int argc,char ** argv)116 int main(int argc, char** argv) {
117 absl::ParseCommandLine(argc, argv);
118 // Instantiate the client. It requires a channel, out of which the actual RPCs
119 // are created. This channel models a connection to an endpoint specified by
120 // the argument "--target=" which is the only expected argument.
121 std::string target_str = absl::GetFlag(FLAGS_target);
122 // We indicate that the channel isn't authenticated (use of
123 // InsecureChannelCredentials()).
124 grpc::ChannelArguments args;
125 args.SetServiceConfigJSON(
126 "{\"healthCheckConfig\": "
127 "{\"serviceName\": \"\"}}");
128 GreeterClient greeter(grpc::CreateCustomChannel(
129 target_str, grpc::InsecureChannelCredentials(), args));
130 std::string user = "world";
131 greeter.CheckHealth("Before call");
132 std::string reply = greeter.SayHello(user);
133 std::cout << "Greeter received: " << reply << std::endl;
134 greeter.CheckHealth("After call");
135 reply = greeter.SayHello(user);
136 std::cout << "Greeter received: " << reply << std::endl;
137 greeter.CheckHealth("After second call");
138 return 0;
139 }
140