1 // Copyright 2023 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <chrono>
16 #include <condition_variable>
17 #include <iostream>
18 #include <memory>
19 #include <string>
20 #include <thread>
21 #include <vector>
22
23 #include "absl/flags/flag.h"
24 #include "absl/flags/parse.h"
25 #include "absl/strings/match.h"
26 #include "absl/strings/str_format.h"
27
28 #include <grpcpp/grpcpp.h>
29
30 #ifdef BAZEL_BUILD
31 #include "examples/protos/helloworld.grpc.pb.h"
32 #else
33 #include "helloworld.grpc.pb.h"
34 #endif
35
36 ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
37
38 using grpc::CallbackServerContext;
39 using grpc::Channel;
40 using grpc::ClientContext;
41
42 using grpc::Server;
43 using grpc::ServerBidiReactor;
44 using grpc::ServerBuilder;
45 using grpc::ServerUnaryReactor;
46 using grpc::Status;
47 using helloworld::Greeter;
48 using helloworld::HelloReply;
49 using helloworld::HelloRequest;
50
51 // Logic behind the server's behavior.
52 class GreeterServiceImpl final : public Greeter::CallbackService {
53 public:
GreeterServiceImpl(const std::string & self_address)54 GreeterServiceImpl(const std::string& self_address) {
55 self_channel_ =
56 grpc::CreateChannel(self_address, grpc::InsecureChannelCredentials());
57 }
58
59 private:
SayHello(CallbackServerContext * context,const HelloRequest * request,HelloReply * reply)60 ServerUnaryReactor* SayHello(CallbackServerContext* context,
61 const HelloRequest* request,
62 HelloReply* reply) override {
63 if (absl::StartsWith(request->name(), "[propagate me]")) {
64 std::unique_ptr<Greeter::Stub> stub = Greeter::NewStub(self_channel_);
65 std::this_thread::sleep_for(std::chrono::milliseconds(800));
66 // Forwarding this call to the self as a different call
67 HelloRequest new_request;
68 new_request.set_name(request->name().substr(14));
69 std::unique_ptr<ClientContext> new_context =
70 ClientContext::FromCallbackServerContext(*context);
71 std::mutex mu;
72 std::condition_variable cv;
73 bool done = false;
74 Status status;
75 stub->async()->SayHello(new_context.get(), &new_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 std::unique_lock<std::mutex> lock(mu);
83 while (!done) {
84 cv.wait(lock);
85 }
86 ServerUnaryReactor* reactor = context->DefaultReactor();
87 reactor->Finish(status);
88 return reactor;
89 }
90
91 if (request->name() == "delay") {
92 // Intentionally delay for 1.5 seconds so that
93 // the client will see deadline_exceeded.
94 std::this_thread::sleep_for(std::chrono::milliseconds(1500));
95 }
96
97 reply->set_message(request->name());
98
99 ServerUnaryReactor* reactor = context->DefaultReactor();
100 reactor->Finish(Status::OK);
101 return reactor;
102 }
103
104 std::shared_ptr<Channel> self_channel_;
105 };
106
RunServer(uint16_t port)107 void RunServer(uint16_t port) {
108 std::string server_address = absl::StrFormat("0.0.0.0:%d", port);
109 GreeterServiceImpl service(server_address);
110
111 ServerBuilder builder;
112 // Listen on the given address without any authentication mechanism.
113 builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
114 // Register "service" as the instance through which we'll communicate with
115 // clients. In this case it corresponds to an *synchronous* service.
116 builder.RegisterService(&service);
117 // Finally assemble the server.
118 std::unique_ptr<Server> server(builder.BuildAndStart());
119 std::cout << "Server listening on " << server_address << std::endl;
120
121 // Wait for the server to shutdown. Note that some other thread must be
122 // responsible for shutting down the server for this call to ever return.
123 server->Wait();
124 }
125
main(int argc,char ** argv)126 int main(int argc, char** argv) {
127 absl::ParseCommandLine(argc, argv);
128 RunServer(absl::GetFlag(FLAGS_port));
129 return 0;
130 }
131