xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/csm/csm_greeter_server.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 /*
2  *
3  * Copyright 2023 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 
23 #include "absl/flags/flag.h"
24 #include "absl/flags/parse.h"
25 #include "absl/strings/str_cat.h"
26 #include "opentelemetry/exporters/prometheus/exporter_factory.h"
27 #include "opentelemetry/exporters/prometheus/exporter_options.h"
28 #include "opentelemetry/sdk/metrics/meter_provider.h"
29 
30 #include <grpcpp/ext/admin_services.h>
31 #include <grpcpp/ext/csm_observability.h>
32 #include <grpcpp/ext/proto_server_reflection_plugin.h>
33 #include <grpcpp/grpcpp.h>
34 #include <grpcpp/health_check_service_interface.h>
35 #include <grpcpp/xds_server_builder.h>
36 
37 #include "src/core/lib/iomgr/gethostname.h"
38 
39 #ifdef BAZEL_BUILD
40 #include "examples/protos/helloworld.grpc.pb.h"
41 #else
42 #include "helloworld.grpc.pb.h"
43 #endif
44 
45 ABSL_FLAG(int32_t, port, 50051, "Server port for service.");
46 
47 using grpc::CallbackServerContext;
48 using grpc::Server;
49 using grpc::ServerBuilder;
50 using grpc::ServerUnaryReactor;
51 using grpc::Status;
52 using helloworld::Greeter;
53 using helloworld::HelloReply;
54 using helloworld::HelloRequest;
55 
56 // Logic and data behind the server's behavior.
57 class GreeterServiceImpl final : public Greeter::CallbackService {
SayHello(CallbackServerContext * context,const HelloRequest * request,HelloReply * reply)58   ServerUnaryReactor* SayHello(CallbackServerContext* context,
59                                const HelloRequest* request,
60                                HelloReply* reply) override {
61     std::string prefix("Hello from ");
62     prefix += my_name + " ";
63     reply->set_message(prefix + request->name());
64 
65     ServerUnaryReactor* reactor = context->DefaultReactor();
66     reactor->Finish(Status::OK);
67     return reactor;
68   }
69 
70  public:
GreeterServiceImpl(const std::string & my_hostname)71   GreeterServiceImpl(const std::string& my_hostname) : my_name(my_hostname) {}
72 
73  private:
74   const std::string my_name;
75 };
76 
RunServer(const char * hostname)77 void RunServer(const char* hostname) {
78   grpc::EnableDefaultHealthCheckService(true);
79   grpc::reflection::InitProtoReflectionServerBuilderPlugin();
80   int port = absl::GetFlag(FLAGS_port);
81   grpc::XdsServerBuilder xds_builder;
82   std::unique_ptr<Server> xds_enabled_server;
83 
84   std::string my_hostname(hostname);
85   GreeterServiceImpl service(my_hostname);
86   // Register "service" as the instance through which we'll communicate with
87   // clients. In this case it corresponds to an *synchronous* service.
88   xds_builder.RegisterService(&service);
89   // Listen on the given address with XdsServerCredentials and a fallback of
90   // InsecureServerCredentials
91   xds_builder.AddListeningPort(absl::StrCat("0.0.0.0:", port),
92                                grpc::InsecureServerCredentials());
93   xds_enabled_server = xds_builder.BuildAndStart();
94   gpr_log(GPR_INFO, "Server starting on 0.0.0.0:%d", port);
95 
96   // Wait for the server to shutdown. Note that some other thread must be
97   // responsible for shutting down the server for this call to ever return.
98   xds_enabled_server->Wait();
99 }
100 
main(int argc,char ** argv)101 int main(int argc, char** argv) {
102   absl::ParseCommandLine(argc, argv);
103   opentelemetry::exporter::metrics::PrometheusExporterOptions opts;
104   // default was "localhost:9464" which causes connection issue across GKE pods
105   opts.url = "0.0.0.0:9464";
106   auto prometheus_exporter =
107       opentelemetry::exporter::metrics::PrometheusExporterFactory::Create(opts);
108   auto meter_provider =
109       std::make_shared<opentelemetry::sdk::metrics::MeterProvider>();
110   meter_provider->AddMetricReader(std::move(prometheus_exporter));
111   auto observability = grpc::CsmObservabilityBuilder()
112                            .SetMeterProvider(std::move(meter_provider))
113                            .BuildAndRegister();
114   if (!observability.ok()) {
115     std::cerr << "CsmObservability::Init() failed: "
116               << observability.status().ToString() << std::endl;
117     return static_cast<int>(observability.status().code());
118   }
119   const char* hostname = grpc_gethostname();
120   if (hostname == nullptr) {
121     std::cout << "Failed to get hostname, terminating" << std::endl;
122     return 1;
123   }
124   RunServer(hostname);
125   return 0;
126 }
127