1 /*
2 *
3 * Copyright 2015 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 <iostream>
20 #include <memory>
21 #include <string>
22 #include <thread>
23
24 #include "absl/flags/flag.h"
25 #include "absl/flags/parse.h"
26 #include "absl/strings/str_format.h"
27
28 #include <grpc/support/log.h>
29 #include <grpcpp/grpcpp.h>
30
31 #ifdef BAZEL_BUILD
32 #include "examples/protos/helloworld.grpc.pb.h"
33 #else
34 #include "helloworld.grpc.pb.h"
35 #endif
36
37 ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
38
39 using grpc::Server;
40 using grpc::ServerAsyncResponseWriter;
41 using grpc::ServerBuilder;
42 using grpc::ServerCompletionQueue;
43 using grpc::ServerContext;
44 using grpc::Status;
45 using helloworld::Greeter;
46 using helloworld::HelloReply;
47 using helloworld::HelloRequest;
48
49 class ServerImpl final {
50 public:
~ServerImpl()51 ~ServerImpl() {
52 server_->Shutdown();
53 // Always shutdown the completion queue after the server.
54 cq_->Shutdown();
55 }
56
57 // There is no shutdown handling in this code.
Run(uint16_t port)58 void Run(uint16_t port) {
59 std::string server_address = absl::StrFormat("0.0.0.0:%d", port);
60
61 ServerBuilder builder;
62 // Listen on the given address without any authentication mechanism.
63 builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
64 // Register "service_" as the instance through which we'll communicate with
65 // clients. In this case it corresponds to an *asynchronous* service.
66 builder.RegisterService(&service_);
67 // Get hold of the completion queue used for the asynchronous communication
68 // with the gRPC runtime.
69 cq_ = builder.AddCompletionQueue();
70 // Finally assemble the server.
71 server_ = builder.BuildAndStart();
72 std::cout << "Server listening on " << server_address << std::endl;
73
74 // Proceed to the server's main loop.
75 HandleRpcs();
76 }
77
78 private:
79 // Class encompasing the state and logic needed to serve a request.
80 class CallData {
81 public:
82 // Take in the "service" instance (in this case representing an asynchronous
83 // server) and the completion queue "cq" used for asynchronous communication
84 // with the gRPC runtime.
CallData(Greeter::AsyncService * service,ServerCompletionQueue * cq)85 CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq)
86 : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) {
87 // Invoke the serving logic right away.
88 Proceed();
89 }
90
Proceed()91 void Proceed() {
92 if (status_ == CREATE) {
93 // Make this instance progress to the PROCESS state.
94 status_ = PROCESS;
95
96 // As part of the initial CREATE state, we *request* that the system
97 // start processing SayHello requests. In this request, "this" acts are
98 // the tag uniquely identifying the request (so that different CallData
99 // instances can serve different requests concurrently), in this case
100 // the memory address of this CallData instance.
101 service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
102 this);
103 } else if (status_ == PROCESS) {
104 // Spawn a new CallData instance to serve new clients while we process
105 // the one for this CallData. The instance will deallocate itself as
106 // part of its FINISH state.
107 new CallData(service_, cq_);
108
109 // The actual processing.
110 std::string prefix("Hello ");
111 reply_.set_message(prefix + request_.name());
112
113 // And we are done! Let the gRPC runtime know we've finished, using the
114 // memory address of this instance as the uniquely identifying tag for
115 // the event.
116 status_ = FINISH;
117 responder_.Finish(reply_, Status::OK, this);
118 } else {
119 GPR_ASSERT(status_ == FINISH);
120 // Once in the FINISH state, deallocate ourselves (CallData).
121 delete this;
122 }
123 }
124
125 private:
126 // The means of communication with the gRPC runtime for an asynchronous
127 // server.
128 Greeter::AsyncService* service_;
129 // The producer-consumer queue where for asynchronous server notifications.
130 ServerCompletionQueue* cq_;
131 // Context for the rpc, allowing to tweak aspects of it such as the use
132 // of compression, authentication, as well as to send metadata back to the
133 // client.
134 ServerContext ctx_;
135
136 // What we get from the client.
137 HelloRequest request_;
138 // What we send back to the client.
139 HelloReply reply_;
140
141 // The means to get back to the client.
142 ServerAsyncResponseWriter<HelloReply> responder_;
143
144 // Let's implement a tiny state machine with the following states.
145 enum CallStatus { CREATE, PROCESS, FINISH };
146 CallStatus status_; // The current serving state.
147 };
148
149 // This can be run in multiple threads if needed.
HandleRpcs()150 void HandleRpcs() {
151 // Spawn a new CallData instance to serve new clients.
152 new CallData(&service_, cq_.get());
153 void* tag; // uniquely identifies a request.
154 bool ok;
155 while (true) {
156 // Block waiting to read the next event from the completion queue. The
157 // event is uniquely identified by its tag, which in this case is the
158 // memory address of a CallData instance.
159 // The return value of Next should always be checked. This return value
160 // tells us whether there is any kind of event or cq_ is shutting down.
161 GPR_ASSERT(cq_->Next(&tag, &ok));
162 GPR_ASSERT(ok);
163 static_cast<CallData*>(tag)->Proceed();
164 }
165 }
166
167 std::unique_ptr<ServerCompletionQueue> cq_;
168 Greeter::AsyncService service_;
169 std::unique_ptr<Server> server_;
170 };
171
main(int argc,char ** argv)172 int main(int argc, char** argv) {
173 absl::ParseCommandLine(argc, argv);
174 ServerImpl server;
175 server.Run(absl::GetFlag(FLAGS_port));
176
177 return 0;
178 }
179