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 <grpcpp/ext/csm_observability.h>
20 #include <grpcpp/grpcpp.h>
21 #include <grpcpp/support/string_ref.h>
22 #include <sys/types.h>
23
24 #include <chrono>
25 #include <condition_variable>
26 #include <iostream>
27 #include <memory>
28 #include <optional>
29 #include <string>
30
31 #include "absl/flags/flag.h"
32 #include "absl/flags/parse.h"
33 #include "absl/strings/str_join.h"
34 #include "absl/strings/str_split.h"
35 #include "absl/types/optional.h"
36 #include "opentelemetry/exporters/prometheus/exporter_factory.h"
37 #include "opentelemetry/exporters/prometheus/exporter_options.h"
38 #include "opentelemetry/sdk/metrics/meter_provider.h"
39
40 #ifdef BAZEL_BUILD
41 #include "examples/protos/helloworld.grpc.pb.h"
42 #else
43 #include "helloworld.grpc.pb.h"
44 #endif
45
46 ABSL_FLAG(std::string, target, "xds:///helloworld:50051", "Target string");
47 ABSL_FLAG(std::string, cookie_name, "GSSA", "Cookie name");
48 ABSL_FLAG(uint, delay_s, 5, "Delay between requests");
49
50 using grpc::Channel;
51 using grpc::ClientContext;
52 using grpc::Status;
53 using helloworld::Greeter;
54 using helloworld::HelloReply;
55 using helloworld::HelloRequest;
56
57 namespace {
58
59 struct Cookie {
60 std::string name;
61 std::string value;
62 std::set<std::string> attributes;
63
64 template <typename Sink>
AbslStringify(Sink & sink,const Cookie & cookie)65 friend void AbslStringify(Sink& sink, const Cookie& cookie) {
66 absl::Format(&sink, "(Cookie: %s, value: %s, attributes: {%s})",
67 cookie.name, cookie.value,
68 absl::StrJoin(cookie.attributes, ", "));
69 }
70 };
71
ParseCookie(absl::string_view header)72 Cookie ParseCookie(absl::string_view header) {
73 Cookie cookie;
74 std::pair<absl::string_view, absl::string_view> name_value =
75 absl::StrSplit(header, absl::MaxSplits('=', 1));
76 cookie.name = std::string(name_value.first);
77 std::pair<absl::string_view, absl::string_view> value_attrs =
78 absl::StrSplit(name_value.second, absl::MaxSplits(';', 1));
79 cookie.value = std::string(value_attrs.first);
80 for (absl::string_view segment : absl::StrSplit(value_attrs.second, ';')) {
81 cookie.attributes.emplace(absl::StripAsciiWhitespace(segment));
82 }
83 return cookie;
84 }
85
GetCookies(const std::multimap<grpc::string_ref,grpc::string_ref> & initial_metadata,absl::string_view cookie_name)86 std::vector<Cookie> GetCookies(
87 const std::multimap<grpc::string_ref, grpc::string_ref>& initial_metadata,
88 absl::string_view cookie_name) {
89 std::vector<Cookie> values;
90 auto pair = initial_metadata.equal_range("set-cookie");
91 for (auto it = pair.first; it != pair.second; ++it) {
92 const auto cookie = ParseCookie(it->second.data());
93 if (cookie.name == cookie_name) {
94 values.emplace_back(std::move(cookie));
95 }
96 }
97 return values;
98 }
99
100 class GreeterClient {
101 public:
GreeterClient(std::shared_ptr<Channel> channel,absl::string_view cookie_name)102 GreeterClient(std::shared_ptr<Channel> channel, absl::string_view cookie_name)
103 : stub_(Greeter::NewStub(channel)), cookie_name_(cookie_name) {}
104
105 // Assembles the client's payload, sends it and presents the response back
106 // from the server.
SayHello()107 void SayHello() {
108 // Data we are sending to the server.
109 HelloRequest request;
110 request.set_name("world");
111
112 // Container for the data we expect from the server.
113 HelloReply reply;
114
115 // Context for the client. It could be used to convey extra information to
116 // the server and/or tweak certain RPC behaviors.
117 ClientContext context;
118
119 // The actual RPC.
120 std::mutex mu;
121 std::condition_variable cv;
122 absl::optional<Status> status;
123 // Set the cookie header if we already got a cookie from the server
124 if (cookie_from_server_.has_value()) {
125 context.AddMetadata("cookie",
126 absl::StrFormat("%s=%s", cookie_from_server_->name,
127 cookie_from_server_->value));
128 }
129 std::unique_lock<std::mutex> lock(mu);
130 stub_->async()->SayHello(&context, &request, &reply, [&](Status s) {
131 std::lock_guard<std::mutex> lock(mu);
132 status = std::move(s);
133 cv.notify_one();
134 });
135 while (!status.has_value()) {
136 cv.wait(lock);
137 }
138 if (!status->ok()) {
139 std::cout << "RPC failed" << status->error_code() << ": "
140 << status->error_message() << std::endl;
141 return;
142 }
143 const std::multimap<grpc::string_ref, grpc::string_ref>&
144 server_initial_metadata = context.GetServerInitialMetadata();
145 // Update a cookie after a successful request
146 std::vector<Cookie> cookies =
147 GetCookies(server_initial_metadata, cookie_name_);
148 if (!cookies.empty()) {
149 cookie_from_server_.emplace(std::move(cookies.front()));
150 }
151 std::cout << "Greeter received: " << reply.message() << std::endl;
152 }
153
154 private:
155 std::unique_ptr<Greeter::Stub> stub_;
156 std::string cookie_name_;
157 absl::optional<Cookie> cookie_from_server_;
158 };
159
InitializeObservability()160 absl::StatusOr<grpc::CsmObservability> InitializeObservability() {
161 opentelemetry::exporter::metrics::PrometheusExporterOptions opts;
162 // default was "localhost:9464" which causes connection issue across GKE pods
163 opts.url = "0.0.0.0:9464";
164 opts.without_otel_scope = false;
165 auto prometheus_exporter =
166 opentelemetry::exporter::metrics::PrometheusExporterFactory::Create(opts);
167 auto meter_provider =
168 std::make_shared<opentelemetry::sdk::metrics::MeterProvider>();
169 meter_provider->AddMetricReader(std::move(prometheus_exporter));
170 return grpc::CsmObservabilityBuilder()
171 .SetMeterProvider(std::move(meter_provider))
172 .BuildAndRegister();
173 }
174
175 } // namespace
176
main(int argc,char ** argv)177 int main(int argc, char** argv) {
178 absl::ParseCommandLine(argc, argv);
179 // Setup the observability
180 auto observability = InitializeObservability();
181 if (!observability.ok()) {
182 std::cerr << "CsmObservability::Init() failed: "
183 << observability.status().ToString() << std::endl;
184 return static_cast<int>(observability.status().code());
185 }
186 GreeterClient greeter(grpc::CreateChannel(absl::GetFlag(FLAGS_target),
187 grpc::InsecureChannelCredentials()),
188 absl::GetFlag(FLAGS_cookie_name));
189 while (true) {
190 greeter.SayHello();
191 std::this_thread::sleep_for(
192 std::chrono::seconds(absl::GetFlag(FLAGS_delay_s)));
193 }
194 return 0;
195 }
196