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 <string>
29
30 #include "absl/flags/flag.h"
31 #include "absl/flags/parse.h"
32 #include "absl/types/optional.h"
33 #include "examples/cpp/otel/util.h"
34 #include "opentelemetry/exporters/prometheus/exporter_factory.h"
35 #include "opentelemetry/exporters/prometheus/exporter_options.h"
36 #include "opentelemetry/sdk/metrics/meter_provider.h"
37
38 ABSL_FLAG(std::string, target, "xds:///helloworld:50051", "Target string");
39 ABSL_FLAG(std::string, prometheus_endpoint, "localhost:9464",
40 "Prometheus exporter endpoint");
41
42 namespace {
43
InitializeObservability()44 absl::StatusOr<grpc::CsmObservability> InitializeObservability() {
45 opentelemetry::exporter::metrics::PrometheusExporterOptions opts;
46 // default was "localhost:9464" which causes connection issue across GKE pods
47 opts.url = "0.0.0.0:9464";
48 opts.without_otel_scope = false;
49 auto prometheus_exporter =
50 opentelemetry::exporter::metrics::PrometheusExporterFactory::Create(opts);
51 auto meter_provider =
52 std::make_shared<opentelemetry::sdk::metrics::MeterProvider>();
53 // The default histogram boundaries are not granular enough for RPCs. Override
54 // the "grpc.client.attempt.duration" view as recommended by
55 // https://github.com/grpc/proposal/blob/master/A66-otel-stats.md.
56 AddLatencyView(meter_provider.get(), "grpc.client.attempt.duration", "s");
57 meter_provider->AddMetricReader(std::move(prometheus_exporter));
58 return grpc::CsmObservabilityBuilder()
59 .SetMeterProvider(std::move(meter_provider))
60 .BuildAndRegister();
61 }
62
63 } // namespace
64
main(int argc,char ** argv)65 int main(int argc, char** argv) {
66 absl::ParseCommandLine(argc, argv);
67 // Setup CSM observability
68 auto observability = InitializeObservability();
69 if (!observability.ok()) {
70 std::cerr << "CsmObservability::Init() failed: "
71 << observability.status().ToString() << std::endl;
72 return static_cast<int>(observability.status().code());
73 }
74
75 // Continuously send RPCs every second.
76 RunClient(absl::GetFlag(FLAGS_target));
77
78 return 0;
79 }
80