Настройка базового плагина OpenTelemetry в gRPC Python

1. Введение

В этом практическом занятии вы используете gRPC для создания клиента и сервера, которые составляют основу приложения для построения маршрутов, написанного на Python.

К концу этого урока у вас будет простое gRPC-приложение HelloWorld, оснащенное плагином gRPC OpenTelemetry, и вы сможете увидеть экспортированные метрики наблюдаемости в Prometheus.

Что вы узнаете

  • Как настроить плагин OpenTelemetry для существующего gRPC-приложения на Python
  • Запуск локального экземпляра Prometheus
  • Экспорт метрик в Prometheus
  • Просмотр метрик на панели мониторинга Prometheus

2. Прежде чем начать

Что вам понадобится

  • git
  • локон
  • build-essential
  • Python 3.9 или выше. Инструкции по установке Python для конкретной платформы см. в разделе «Настройка и использование Python» . В качестве альтернативы можно установить Python, не являющийся системным, используя такие инструменты, как uv или pyenv .
  • Для установки пакетов Python требуется pip версии 9.0.1 или выше.
  • venv для создания виртуальных сред Python.

Установите необходимые компоненты:

sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install -y git curl build-essential clang
sudo apt install python3
sudo apt install python3-pip python3-venv

Получите код

Для упрощения обучения в этом практическом занятии предлагается готовый шаблон исходного кода, который поможет вам начать работу. Следующие шаги проведут вас через процесс инструментирования плагина gRPC OpenTelemetry в приложении.

grpc-codelabs

Исходный код для этого практического занятия доступен в этой директории GitHub. Если вы предпочитаете не реализовывать код самостоятельно, готовый исходный код доступен в директории completed .

Сначала клонируйте репозиторий grpc codelab и перейдите в папку grpc-python-opentelemetry:

git clone https://github.com/grpc-ecosystem/grpc-codelabs.git
cd grpc-codelabs/codelabs/grpc-python-opentelemetry/

В качестве альтернативы вы можете скачать ZIP-архив, содержащий только папку codelab, и распаковать его вручную.

Для начала создадим новое виртуальное окружение Python (venv), чтобы изолировать зависимости вашего проекта от системных пакетов:

python3 -m venv --upgrade-deps .venv

Для активации виртуального окружения в оболочке bash/zsh:

source .venv/bin/activate

Для Windows и нестандартных оболочек см. таблицу по адресу https://docs.python.org/3/library/venv.html#how-venvs-work .

Далее установите зависимости в среду выполнения, используя следующую команду:

python -m pip install -r requirements.txt

3. Зарегистрируйте плагин OpenTelemetry.

Нам потребуется gRPC-приложение для добавления плагина gRPC OpenTelemetry. В этом практическом занятии мы будем использовать простой gRPC-клиент и сервер HelloWorld, которые мы будем модифицировать с помощью плагина gRPC OpenTelemetry.

Первым делом зарегистрируйте плагин OpenTelemetry, настроенный с использованием экспортера Prometheus, в клиенте. Откройте start_here/observability_greeter_client.py в вашем любимом редакторе. Сначала добавьте соответствующие зависимости и макросы, чтобы они выглядели следующим образом:

import logging
import time

import grpc
import grpc_observability
import helloworld_pb2
import helloworld_pb2_grpc
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from opentelemetry.sdk.metrics import MeterProvider
from prometheus_client import start_http_server

_SERVER_PORT = "50051"
_PROMETHEUS_PORT = 9465

Затем преобразуйте run() следующим образом:

def run():
    # Start Prometheus client
    start_http_server(port=_PROMETHEUS_PORT, addr="0.0.0.0")
    meter_provider = MeterProvider(metric_readers=[PrometheusMetricReader()])

    otel_plugin = grpc_observability.OpenTelemetryPlugin(
        meter_provider=meter_provider
    )
    otel_plugin.register_global()

    with grpc.insecure_channel(target=f"localhost:{_SERVER_PORT}") as channel:
        stub = helloworld_pb2_grpc.GreeterStub(channel)
        # Continuously send RPCs every second.
        while True:
            try:
                response = stub.SayHello(helloworld_pb2.HelloRequest(name="You"))
                print(f"Greeter client received: {response.message}")
                time.sleep(1)
            except grpc.RpcError as rpc_error:
                print("Call failed with code: ", rpc_error.code())

    # Deregister is not called in this example, but this is required to clean up.
    otel_plugin.deregister_global()

Следующий шаг — добавление плагина OpenTelemetry на сервер. Откройте start_here/observability_greeter_server.py и добавьте соответствующие зависимости и макросы, чтобы они выглядели следующим образом:

from concurrent import futures
import logging
import time

import grpc
import grpc_observability
import helloworld_pb2
import helloworld_pb2_grpc
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from prometheus_client import start_http_server

_SERVER_PORT = "50051"
_PROMETHEUS_PORT = 9464

Затем преобразуйте run() следующим образом:

def serve():
    # Start Prometheus client
    start_http_server(port=_PROMETHEUS_PORT, addr="0.0.0.0")

    meter_provider = MeterProvider(metric_readers=[PrometheusMetricReader()])

    otel_plugin = grpc_observability.OpenTelemetryPlugin(
        meter_provider=meter_provider
    )
    otel_plugin.register_global()

    server = grpc.server(
        thread_pool=futures.ThreadPoolExecutor(max_workers=10),
    )
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port("[::]:" + _SERVER_PORT)
    server.start()
    print("Server started, listening on " + _SERVER_PORT)

    server.wait_for_termination()

    # Deregister is not called in this example, but this is required to clean up.
    otel_plugin.deregister_global()

4. Запуск примера и просмотр метрик.

Для запуска сервера выполните команду:

cd start_here
python -m observability_greeter_server

После успешной настройки вы увидите следующий вывод для сервера:

Server started, listening on 50051

Пока сервер работает, на другом терминале запустите клиент.

# Run the below commands to cd to the working directory and activate virtual environment in the new terminal
cd grpc-codelabs/codelabs/grpc-python-opentelemetry/
source .venv/bin/activate

cd start_here
python -m observability_greeter_client

Успешный забег будет выглядеть следующим образом:

Greeter client received: Hello You
Greeter client received: Hello You
Greeter client received: Hello You

Поскольку мы настроили плагин gRPC OpenTelemetry для экспорта метрик с помощью Prometheus, эти метрики будут доступны на localhost:9464 для сервера и localhost:9465 для клиента.

Чтобы просмотреть показатели клиента -

curl localhost:9465/metrics

В результате получится следующее:

# HELP python_gc_objects_collected_total Objects collected during gc
# TYPE python_gc_objects_collected_total counter
python_gc_objects_collected_total{generation="0"} 241.0
python_gc_objects_collected_total{generation="1"} 163.0
python_gc_objects_collected_total{generation="2"} 0.0
# HELP python_gc_objects_uncollectable_total Uncollectable objects found during GC
# TYPE python_gc_objects_uncollectable_total counter
python_gc_objects_uncollectable_total{generation="0"} 0.0
python_gc_objects_uncollectable_total{generation="1"} 0.0
python_gc_objects_uncollectable_total{generation="2"} 0.0
# HELP python_gc_collections_total Number of times this generation was collected
# TYPE python_gc_collections_total counter
python_gc_collections_total{generation="0"} 78.0
python_gc_collections_total{generation="1"} 7.0
python_gc_collections_total{generation="2"} 0.0
# HELP python_info Python platform information
# TYPE python_info gauge
python_info{implementation="CPython",major="3",minor="10",patchlevel="9",version="3.10.9"} 1.0
# HELP process_virtual_memory_bytes Virtual memory size in bytes.
# TYPE process_virtual_memory_bytes gauge
process_virtual_memory_bytes 1.868988416e+09
# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes 4.1680896e+07
# TYPE process_resident_memory_bytes gauge                                                                                                                                                                                                                                                                21:20:16 [154/966]
process_resident_memory_bytes 4.1680896e+07
# HELP process_start_time_seconds Start time of the process since unix epoch in seconds.
# TYPE process_start_time_seconds gauge
process_start_time_seconds 1.72375679833e+09
# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.
# TYPE process_cpu_seconds_total counter
process_cpu_seconds_total 0.38
# HELP process_open_fds Number of open file descriptors.
# TYPE process_open_fds gauge
process_open_fds 9.0
# HELP process_max_fds Maximum number of open file descriptors.
# TYPE process_max_fds gauge
process_max_fds 4096.0
# HELP target_info Target metadata
# TYPE target_info gauge
target_info{service_name="unknown_service",telemetry_sdk_language="python",telemetry_sdk_name="opentelemetry",telemetry_sdk_version="1.26.0"} 1.0
# HELP grpc_client_attempt_started_total Number of client call attempts started
# TYPE grpc_client_attempt_started_total counter
grpc_client_attempt_started_total{grpc_method="other",grpc_target="localhost:50051"} 18.0
# HELP grpc_client_attempt_sent_total_compressed_message_size_bytes Compressed message bytes sent per client call attempt
# TYPE grpc_client_attempt_sent_total_compressed_message_size_bytes histogram
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="0.0"} 0.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="5.0"} 18.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="10.0"} 18.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="25.0"} 18.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="50.0"} 18.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="75.0"} 18.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="100.0"} 18.0
grpc_client_attempt_sent_total_compressed_message_size_bytes_bucket{grpc_method="other",grpc_status="OK",grpc_target="localhost:50051",le="250.0"} 18.0

Аналогично и для метрик на стороне сервера -

curl localhost:9464/metrics

5. Просмотр метрик в Prometheus

Здесь мы настроим экземпляр Prometheus, который будет собирать метрики с нашего примера gRPC-клиента и сервера, экспортирующих метрики с помощью Prometheus.

Загрузите последнюю версию Prometheus для вашей платформы, используя указанную ссылку, или воспользуйтесь следующей командой:

curl -sLO https://github.com/prometheus/prometheus/releases/download/v3.7.3/prometheus-3.7.3.linux-amd64.tar.gz

Затем извлеките и запустите его, используя следующую команду:

tar xvfz prometheus-*.tar.gz
cd prometheus-*

Создайте конфигурационный файл Prometheus со следующим содержимым:

cat > grpc_otel_python_prometheus.yml <<EOF
scrape_configs:
  - job_name: "prometheus"
    scrape_interval: 5s
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: "grpc-otel-python"
    scrape_interval: 5s
    static_configs:
      - targets: ["localhost:9464", "localhost:9465"]
EOF

Запустите Prometheus с новой конфигурацией.

./prometheus --config.file=grpc_otel_python_prometheus.yml

Это позволит настроить сбор метрик из процессов Codelab на стороне клиента и сервера таким образом, чтобы они собирались каждые 5 секунд.

Для просмотра метрик перейдите по адресу http://localhost:9090/graph . Например, запрос -

histogram_quantile(0.5, rate(grpc_client_attempt_duration_seconds_bucket[1m]))

Будет показан график со средним временем задержки попытки, используя 1 минуту в качестве временного окна для расчета квантилей.

Частота запросов -

increase(grpc_client_attempt_duration_seconds_bucket[1m])

6. (Необязательное) Упражнение для пользователя

На панелях мониторинга Prometheus вы заметите, что показатель QPS низкий. Попробуйте определить в примере какой-нибудь подозрительный код, который ограничивает показатель QPS.

Для энтузиастов: клиентский код ограничивается выполнением только одного ожидающего RPC-вызова в данный момент. Это можно изменить, чтобы клиент отправлял больше RPC-вызовов, не дожидаясь завершения предыдущих. (Решение для этого пока не предложено.)