1 /*
2 *
3 * Copyright 2021 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 // Explicitly define HAVE_ABSEIL to avoid conflict with OTel's Abseil
20 // version. Refer
21 // https://github.com/open-telemetry/opentelemetry-cpp/issues/1042.
22 #ifndef HAVE_ABSEIL
23 #define HAVE_ABSEIL
24 #endif
25
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/strings/str_format.h"
33 #include "opentelemetry/exporters/prometheus/exporter_factory.h"
34 #include "opentelemetry/exporters/prometheus/exporter_options.h"
35 #include "opentelemetry/sdk/metrics/meter_provider.h"
36
37 #include <grpcpp/ext/otel_plugin.h>
38
39 #ifdef BAZEL_BUILD
40 #include "examples/cpp/otel/util.h"
41 #else
42 #include "util.h"
43 #endif
44
45 ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
46 ABSL_FLAG(std::string, prometheus_endpoint, "localhost:9464",
47 "Prometheus exporter endpoint");
48
main(int argc,char ** argv)49 int main(int argc, char** argv) {
50 absl::ParseCommandLine(argc, argv);
51 // Register a global gRPC OpenTelemetry plugin configured with a prometheus
52 // exporter.
53 opentelemetry::exporter::metrics::PrometheusExporterOptions opts;
54 opts.url = absl::GetFlag(FLAGS_prometheus_endpoint);
55 auto prometheus_exporter =
56 opentelemetry::exporter::metrics::PrometheusExporterFactory::Create(opts);
57 auto meter_provider =
58 std::make_shared<opentelemetry::sdk::metrics::MeterProvider>();
59 // The default histogram boundaries are not granular enough for RPCs. Override
60 // the "grpc.server.call.duration" view as recommended by
61 // https://github.com/grpc/proposal/blob/master/A66-otel-stats.md.
62 AddLatencyView(meter_provider.get(), "grpc.server.call.duration", "s");
63 meter_provider->AddMetricReader(std::move(prometheus_exporter));
64 auto status = grpc::OpenTelemetryPluginBuilder()
65 .SetMeterProvider(std::move(meter_provider))
66 .BuildAndRegisterGlobal();
67 if (!status.ok()) {
68 std::cerr << "Failed to register gRPC OpenTelemetry Plugin: "
69 << status.ToString() << std::endl;
70 return static_cast<int>(status.code());
71 }
72 RunServer(absl::GetFlag(FLAGS_port));
73 return 0;
74 }
75