xref: /aosp_15_r20/external/grpc-grpc/examples/python/observability/observability_greeter_server.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1# Copyright 2024 gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""The Python implementation of the GRPC helloworld.Greeter server with observability enabled."""
15
16from collections import defaultdict
17from concurrent import futures
18import logging
19import time
20
21import grpc
22import grpc_observability
23import helloworld_pb2
24import helloworld_pb2_grpc
25import open_telemetry_exporter
26from opentelemetry.sdk.metrics import MeterProvider
27from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
28
29_OTEL_EXPORT_INTERVAL_S = 0.5
30_SERVER_PORT = "50051"
31
32
33class Greeter(helloworld_pb2_grpc.GreeterServicer):
34    def SayHello(self, request, context):
35        message = request.name
36        return helloworld_pb2.HelloReply(message=f"Hello {message}")
37
38
39def serve():
40    all_metrics = defaultdict(list)
41    otel_exporter = open_telemetry_exporter.OTelMetricExporter(
42        all_metrics, print_live=False
43    )
44    reader = PeriodicExportingMetricReader(
45        exporter=otel_exporter,
46        export_interval_millis=_OTEL_EXPORT_INTERVAL_S * 1000,
47    )
48    provider = MeterProvider(metric_readers=[reader])
49
50    otel_plugin = grpc_observability.OpenTelemetryPlugin(
51        meter_provider=provider
52    )
53    otel_plugin.register_global()
54
55    server = grpc.server(
56        thread_pool=futures.ThreadPoolExecutor(max_workers=10),
57    )
58    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
59    server.add_insecure_port("[::]:" + _SERVER_PORT)
60    server.start()
61    print("Server started, listening on " + _SERVER_PORT)
62
63    # Sleep to make sure client made RPC call and all metrics are exported.
64    time.sleep(10)
65    print("Metrics exported on Server side:")
66    for metric in all_metrics:
67        print(metric)
68
69    server.stop(0)
70    otel_plugin.deregister_global()
71
72
73if __name__ == "__main__":
74    logging.basicConfig()
75    serve()
76