11 KiB
🐍 Ophion - Guia de Instrumentação OpenTelemetry
Este guia explica como adicionar auto-instrumentação OpenTelemetry a qualquer container Docker, enviando traces, métricas e logs para o Ophion.
📋 Índice
- Arquitetura
- Setup Rápido
- Variáveis de Ambiente
- Instrumentação por Linguagem
- Instrumentação de Containers Existentes
- Troubleshooting
🏗️ Arquitetura
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Your App 1 │ │ Your App 2 │ │ Your App N │
│ (Node.js/Python/│ │ (Java/Go/.NET) │ │ (Any language) │
│ etc.) │ │ │ │ │
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
│ OTLP (gRPC/HTTP) │ │
│ │ │
└───────────────────────┼───────────────────────┘
│
┌────────────▼────────────┐
│ OpenTelemetry │
│ Collector │
│ (otel-collector) │
│ :4317 (gRPC) │
│ :4318 (HTTP) │
└────────────┬────────────┘
│
┌────────────▼────────────┐
│ Ophion Server │
│ (server:8080) │
│ │
│ Traces │ Metrics │ │
│ Logs │ Alerts │
└─────────────────────────┘
🚀 Setup Rápido
1. Inicie o Ophion com o Collector
cd ~/projetos_jarvis/ophion
docker-compose up -d
O otel-collector estará disponível em:
- gRPC:
otel-collector:4317 - HTTP:
otel-collector:4318
2. Configure seu container
Adicione estas variáveis de ambiente ao seu serviço:
environment:
- OTEL_SERVICE_NAME=meu-servico
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_TRACES_EXPORTER=otlp
- OTEL_METRICS_EXPORTER=otlp
- OTEL_LOGS_EXPORTER=otlp
3. Conecte à rede do Ophion
networks:
- ophion
🔧 Variáveis de Ambiente
Essenciais
| Variável | Descrição | Exemplo |
|---|---|---|
OTEL_SERVICE_NAME |
Nome do seu serviço | api-gateway |
OTEL_EXPORTER_OTLP_ENDPOINT |
Endpoint do collector | http://otel-collector:4318 |
OTEL_TRACES_EXPORTER |
Exporter de traces | otlp |
Opcionais (Recomendadas)
| Variável | Descrição | Default |
|---|---|---|
OTEL_SERVICE_VERSION |
Versão do serviço | - |
OTEL_EXPORTER_OTLP_PROTOCOL |
Protocolo OTLP | http/protobuf |
OTEL_METRICS_EXPORTER |
Exporter de métricas | none |
OTEL_LOGS_EXPORTER |
Exporter de logs | none |
OTEL_RESOURCE_ATTRIBUTES |
Atributos extras | env=prod |
OTEL_TRACES_SAMPLER |
Tipo de sampler | parentbased_always_on |
OTEL_TRACES_SAMPLER_ARG |
Argumento do sampler | 1.0 |
OTEL_PROPAGATORS |
Formatos de propagação | tracecontext,baggage |
Exemplo Completo
environment:
# Identificação
- OTEL_SERVICE_NAME=meu-servico
- OTEL_SERVICE_VERSION=1.2.3
# Endpoint
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# Exporters
- OTEL_TRACES_EXPORTER=otlp
- OTEL_METRICS_EXPORTER=otlp
- OTEL_LOGS_EXPORTER=otlp
# Recursos
- OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production,team=backend
# Sampling (100% em dev, ajuste em prod)
- OTEL_TRACES_SAMPLER=parentbased_traceidratio
- OTEL_TRACES_SAMPLER_ARG=1.0
# Propagação (trace context para outros serviços)
- OTEL_PROPAGATORS=tracecontext,baggage,b3multi
📦 Instrumentação por Linguagem
Node.js
Auto-instrumentação sem alterar código:
- Instale os pacotes:
npm install @opentelemetry/auto-instrumentations-node @opentelemetry/api
- Configure no docker-compose.yml:
environment:
- OTEL_SERVICE_NAME=minha-api-node
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_TRACES_EXPORTER=otlp
- NODE_OPTIONS=--require @opentelemetry/auto-instrumentations-node/register
Instrumentações automáticas incluídas:
- HTTP/Express/Fastify
- MongoDB/PostgreSQL/MySQL
- Redis/Memcached
- gRPC
- AWS SDK
Python
Auto-instrumentação sem alterar código:
- Instale os pacotes:
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install
- Execute com o wrapper:
CMD ["opentelemetry-instrument", "python", "app.py"]
- Configure no docker-compose.yml:
environment:
- OTEL_SERVICE_NAME=minha-api-python
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_TRACES_EXPORTER=otlp
- OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
Instrumentações automáticas incluídas:
- Flask/Django/FastAPI
- Requests/HTTPX/aiohttp
- SQLAlchemy/psycopg2
- Redis/Celery
- boto3/botocore
Java
Auto-instrumentação via Java Agent:
- Baixe o agent no Dockerfile:
RUN wget https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar \
-O /opt/opentelemetry-javaagent.jar
- Configure no docker-compose.yml:
environment:
- OTEL_SERVICE_NAME=minha-api-java
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_TRACES_EXPORTER=otlp
- JAVA_TOOL_OPTIONS=-javaagent:/opt/opentelemetry-javaagent.jar
Instrumentações automáticas incluídas:
- Spring Boot/Spring MVC
- JAX-RS/Jersey
- Hibernate/JPA
- JDBC (PostgreSQL, MySQL, etc.)
- Kafka/RabbitMQ
- gRPC
Go
Go requer instrumentação explícita no código, mas é simples:
import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/sdk/trace"
)
func initTracer() (*trace.TracerProvider, error) {
exporter, err := otlptracehttp.New(context.Background())
if err != nil {
return nil, err
}
tp := trace.NewTracerProvider(
trace.WithBatcher(exporter),
trace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(os.Getenv("OTEL_SERVICE_NAME")),
)),
)
otel.SetTracerProvider(tp)
return tp, nil
}
.NET
Auto-instrumentação via .NET OpenTelemetry:
- Adicione os pacotes:
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
- Configure no Program.cs:
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddOtlpExporter());
- Configure no docker-compose.yml:
environment:
- OTEL_SERVICE_NAME=minha-api-dotnet
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
🔄 Instrumentação de Containers Existentes
Método 1: Modificar docker-compose.yml
Adicione ao seu serviço existente:
services:
meu-servico-existente:
# ... configuração existente ...
environment:
# Adicione estas linhas:
- OTEL_SERVICE_NAME=meu-servico
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_TRACES_EXPORTER=otlp
# Para Node.js:
- NODE_OPTIONS=--require @opentelemetry/auto-instrumentations-node/register
# Para Java:
# - JAVA_TOOL_OPTIONS=-javaagent:/opt/opentelemetry-javaagent.jar
networks:
- ophion
networks:
ophion:
external: true
Método 2: Docker Compose Override
Crie um arquivo docker-compose.otel.yml:
version: '3.8'
services:
meu-servico:
environment:
- OTEL_SERVICE_NAME=meu-servico
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_TRACES_EXPORTER=otlp
networks:
- ophion
networks:
ophion:
external: true
Execute com:
docker-compose -f docker-compose.yml -f docker-compose.otel.yml up -d
Método 3: Sidecar Pattern
Para aplicações que não suportam modificação:
services:
meu-servico:
# Aplicação original sem modificação
otel-proxy:
image: otel/opentelemetry-collector-contrib:latest
command: ["--config=/etc/otel-config.yaml"]
volumes:
- ./otel-proxy-config.yaml:/etc/otel-config.yaml
depends_on:
- meu-servico
🔍 Troubleshooting
Traces não aparecem no Ophion
- Verifique conectividade:
docker exec -it seu-container wget -q -O- http://otel-collector:13133/health
- Verifique logs do collector:
docker logs ophion-otel-collector
- Verifique se as env vars estão corretas:
docker exec -it seu-container env | grep OTEL
Erros de conexão
- Certifique-se que o container está na rede
ophion - Use
otel-collector(nome do serviço) e nãolocalhost - Porta 4318 para HTTP, 4317 para gRPC
Muitos traces (custo alto)
Ajuste o sampling:
environment:
- OTEL_TRACES_SAMPLER=parentbased_traceidratio
- OTEL_TRACES_SAMPLER_ARG=0.1 # 10% dos traces
Traces incompletos
Verifique propagação entre serviços:
environment:
- OTEL_PROPAGATORS=tracecontext,baggage,b3multi
📚 Exemplos
Veja os exemplos completos em:
examples/docker/nodejs-instrumented/- Node.jsexamples/docker/python-instrumented/- Pythonexamples/docker/java-instrumented/- Java
🆘 Suporte
- Documentação OpenTelemetry: https://opentelemetry.io/docs/
- Ophion Issues: Abra uma issue no repositório
- Collector Debug: Use
debugexporter para troubleshooting