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

1. Введение

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

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

Чему вы научитесь

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

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

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

  • мерзавец
  • завиток
  • сборка-необходима
  • Python 3.9 или выше. Инструкции по установке Python для конкретных платформ см. в разделе «Настройка и использование Python» . Также можно установить несистемный Python с помощью таких инструментов, как uv или pyenv .
  • pip версии 9.0.1 или выше для установки пакетов Python.
  • 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

Исходный код scaffold для этой лабораторной работы доступен в этом каталоге 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 OpenTelemetry нам понадобится приложение gRPC. В этой лабораторной работе мы будем использовать простой клиент и сервер 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

Это позволит настроить считывание показателей из клиентских и серверных процессов кодовой лаборатории каждые 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-запросов, не дожидаясь завершения предыдущих. (Решение этой проблемы пока не предоставлено.)