- Add AI engine with OpenAI integration - Anomaly detection - Log analysis with pattern clustering - Capacity prediction - Complete installation manual (Portuguese) - Docker monitoring guide - APM integration guide (Node.js, Python, Go) - Alert configuration guide
1139 lines
27 KiB
Markdown
1139 lines
27 KiB
Markdown
# 🐍 OPHION - Manual Completo
|
|
|
|
## Observability Platform com Inteligência Artificial
|
|
|
|
---
|
|
|
|
# PARTE 1: VISÃO GERAL
|
|
|
|
## O que é o OPHION?
|
|
|
|
OPHION é uma plataforma de observabilidade open-source que combina:
|
|
- **Métricas** - CPU, memória, disco, rede
|
|
- **Logs** - Centralização e análise
|
|
- **Traces** - Rastreamento distribuído
|
|
- **Alertas** - Notificações inteligentes
|
|
- **IA** - Detecção de anomalias e previsões
|
|
|
|
## Arquitetura
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────┐
|
|
│ SEUS SERVIDORES │
|
|
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
|
|
│ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │ Agent N │ │
|
|
│ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │
|
|
└───────┼────────────┼────────────┼────────────┼──────────────────┘
|
|
│ │ │ │
|
|
└────────────┴─────┬──────┴────────────┘
|
|
│ HTTPS/TLS
|
|
▼
|
|
┌─────────────────────────────────────────────────────────────────┐
|
|
│ OPHION CLOUD │
|
|
│ ┌─────────────────────────────────────────────────────────┐ │
|
|
│ │ API Gateway │ │
|
|
│ │ (Rate Limit, Auth, Load Balance) │ │
|
|
│ └─────────────────────────┬───────────────────────────────┘ │
|
|
│ │ │
|
|
│ ┌─────────────┬───────────┼───────────┬─────────────┐ │
|
|
│ │ │ │ │ │ │
|
|
│ ▼ ▼ ▼ ▼ ▼ │
|
|
│ ┌────┐ ┌──────┐ ┌────────┐ ┌──────┐ ┌────────┐ │
|
|
│ │Logs│ │Metrics│ │ Traces │ │Alerts│ │ AI │ │
|
|
│ │Svc │ │ Svc │ │ Svc │ │ Svc │ │ Engine │ │
|
|
│ └──┬─┘ └───┬──┘ └───┬────┘ └──┬───┘ └───┬────┘ │
|
|
│ │ │ │ │ │ │
|
|
│ └───────────┴──────────┴───────────┴────────────┘ │
|
|
│ │ │
|
|
│ ┌──────▼──────┐ │
|
|
│ │ ClickHouse │ (Time-series DB) │
|
|
│ │ PostgreSQL │ (Config/Users) │
|
|
│ │ Redis │ (Cache/Realtime) │
|
|
│ └─────────────┘ │
|
|
│ │
|
|
│ ┌─────────────────────────────────────────────────────────┐ │
|
|
│ │ Dashboard (Next.js) │ │
|
|
│ └─────────────────────────────────────────────────────────┘ │
|
|
└─────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 2: INSTALAÇÃO DO SERVIDOR
|
|
|
|
## 2.1 Requisitos
|
|
|
|
### Hardware Mínimo
|
|
| Componente | Mínimo | Recomendado |
|
|
|------------|--------|-------------|
|
|
| CPU | 2 cores | 4+ cores |
|
|
| RAM | 4 GB | 8+ GB |
|
|
| Disco | 50 GB SSD | 200+ GB SSD |
|
|
| Rede | 100 Mbps | 1 Gbps |
|
|
|
|
### Software
|
|
- Ubuntu 22.04+ ou Debian 12+
|
|
- Docker 24+
|
|
- Docker Compose 2.20+
|
|
|
|
## 2.2 Instalação Rápida
|
|
|
|
```bash
|
|
# Um comando para instalar tudo
|
|
curl -fsSL https://ophion.com.br/install.sh | bash
|
|
```
|
|
|
|
## 2.3 Instalação Manual Detalhada
|
|
|
|
### Passo 1: Instalar Docker
|
|
|
|
```bash
|
|
# Atualizar sistema
|
|
sudo apt update && sudo apt upgrade -y
|
|
|
|
# Instalar Docker
|
|
curl -fsSL https://get.docker.com | sh
|
|
|
|
# Adicionar usuário ao grupo docker
|
|
sudo usermod -aG docker $USER
|
|
newgrp docker
|
|
|
|
# Verificar instalação
|
|
docker --version
|
|
docker compose version
|
|
```
|
|
|
|
### Passo 2: Clonar Repositório
|
|
|
|
```bash
|
|
# Clonar
|
|
git clone https://github.com/bigtux/ophion.git /opt/ophion
|
|
cd /opt/ophion
|
|
|
|
# Ou baixar release
|
|
wget https://github.com/bigtux/ophion/releases/latest/download/ophion-server.tar.gz
|
|
tar -xzf ophion-server.tar.gz
|
|
cd ophion-server
|
|
```
|
|
|
|
### Passo 3: Configurar Ambiente
|
|
|
|
```bash
|
|
# Copiar exemplo
|
|
cp deploy/docker/.env.example deploy/docker/.env
|
|
|
|
# Editar configurações
|
|
nano deploy/docker/.env
|
|
```
|
|
|
|
**Arquivo .env completo:**
|
|
|
|
```env
|
|
#=============================================
|
|
# OPHION - Configurações do Servidor
|
|
#=============================================
|
|
|
|
# === SEGURANÇA (OBRIGATÓRIO - ALTERE!) ===
|
|
JWT_SECRET=gere-uma-chave-de-32-caracteres-minimo
|
|
ENCRYPTION_KEY=outra-chave-secreta-32-chars-min
|
|
|
|
# === POSTGRESQL ===
|
|
POSTGRES_HOST=postgres
|
|
POSTGRES_PORT=5432
|
|
POSTGRES_USER=ophion
|
|
POSTGRES_PASSWORD=SenhaForteAqui123!
|
|
POSTGRES_DB=ophion
|
|
|
|
# === CLICKHOUSE ===
|
|
CLICKHOUSE_HOST=clickhouse
|
|
CLICKHOUSE_PORT=9000
|
|
CLICKHOUSE_USER=default
|
|
CLICKHOUSE_PASSWORD=SenhaClickhouse123!
|
|
CLICKHOUSE_DB=ophion
|
|
|
|
# === REDIS ===
|
|
REDIS_HOST=redis
|
|
REDIS_PORT=6379
|
|
REDIS_PASSWORD=SenhaRedis123!
|
|
|
|
# === SERVIDOR ===
|
|
OPHION_HOST=0.0.0.0
|
|
OPHION_PORT=8080
|
|
OPHION_ENV=production
|
|
OPHION_DEBUG=false
|
|
|
|
# === DASHBOARD ===
|
|
NEXT_PUBLIC_API_URL=https://api.ophion.com.br
|
|
NEXTAUTH_SECRET=chave-nextauth-secreta
|
|
NEXTAUTH_URL=https://app.ophion.com.br
|
|
|
|
# === RETENÇÃO DE DADOS ===
|
|
METRICS_RETENTION_DAYS=30
|
|
LOGS_RETENTION_DAYS=14
|
|
TRACES_RETENTION_DAYS=7
|
|
|
|
# === INTELIGÊNCIA ARTIFICIAL ===
|
|
AI_ENABLED=true
|
|
AI_MODEL=gpt-4o-mini
|
|
OPENAI_API_KEY=sk-your-openai-key
|
|
AI_ANOMALY_DETECTION=true
|
|
AI_LOG_ANALYSIS=true
|
|
AI_PREDICTIONS=true
|
|
|
|
# === ALERTAS ===
|
|
SMTP_HOST=smtp.gmail.com
|
|
SMTP_PORT=587
|
|
SMTP_USER=seu-email@gmail.com
|
|
SMTP_PASSWORD=sua-senha-app
|
|
SMTP_FROM=noreply@ophion.com.br
|
|
|
|
TELEGRAM_BOT_TOKEN=seu-bot-token
|
|
SLACK_WEBHOOK_URL=https://hooks.slack.com/...
|
|
|
|
# === RATE LIMITING ===
|
|
RATE_LIMIT_REQUESTS=1000
|
|
RATE_LIMIT_WINDOW=60
|
|
```
|
|
|
|
### Passo 4: Iniciar Serviços
|
|
|
|
```bash
|
|
cd /opt/ophion/deploy/docker
|
|
|
|
# Iniciar em background
|
|
docker compose up -d
|
|
|
|
# Verificar status
|
|
docker compose ps
|
|
|
|
# Ver logs
|
|
docker compose logs -f
|
|
```
|
|
|
|
### Passo 5: Verificar Instalação
|
|
|
|
```bash
|
|
# Health check da API
|
|
curl http://localhost:8080/health
|
|
# Esperado: {"status":"healthy","version":"1.0.0"}
|
|
|
|
# Health check do Dashboard
|
|
curl http://localhost:3000
|
|
# Esperado: HTML da página
|
|
```
|
|
|
|
## 2.4 Configurar Proxy Reverso (Nginx)
|
|
|
|
```bash
|
|
sudo apt install nginx -y
|
|
|
|
sudo tee /etc/nginx/sites-available/ophion << 'EOF'
|
|
# API
|
|
server {
|
|
listen 80;
|
|
server_name api.ophion.com.br;
|
|
|
|
location / {
|
|
proxy_pass http://localhost:8080;
|
|
proxy_http_version 1.1;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection 'upgrade';
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Real-IP $remote_addr;
|
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
proxy_cache_bypass $http_upgrade;
|
|
}
|
|
}
|
|
|
|
# Dashboard
|
|
server {
|
|
listen 80;
|
|
server_name app.ophion.com.br ophion.com.br www.ophion.com.br;
|
|
|
|
location / {
|
|
proxy_pass http://localhost:3000;
|
|
proxy_http_version 1.1;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection 'upgrade';
|
|
proxy_set_header Host $host;
|
|
proxy_cache_bypass $http_upgrade;
|
|
}
|
|
}
|
|
EOF
|
|
|
|
sudo ln -s /etc/nginx/sites-available/ophion /etc/nginx/sites-enabled/
|
|
sudo nginx -t
|
|
sudo systemctl reload nginx
|
|
```
|
|
|
|
## 2.5 Configurar SSL
|
|
|
|
```bash
|
|
# Instalar Certbot
|
|
sudo apt install certbot python3-certbot-nginx -y
|
|
|
|
# Gerar certificados
|
|
sudo certbot --nginx -d ophion.com.br -d www.ophion.com.br -d app.ophion.com.br -d api.ophion.com.br
|
|
|
|
# Auto-renovação (já configurado automaticamente)
|
|
sudo certbot renew --dry-run
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 3: INSTALAÇÃO DO AGENT
|
|
|
|
## 3.1 O que é o Agent?
|
|
|
|
O Agent é um processo leve que roda em cada servidor monitorado, coletando:
|
|
- Métricas do sistema (CPU, RAM, disco, rede)
|
|
- Métricas de containers Docker
|
|
- Logs do sistema e aplicações
|
|
- Processos em execução
|
|
|
|
## 3.2 Instalação Rápida
|
|
|
|
```bash
|
|
# Defina suas variáveis
|
|
export OPHION_SERVER="https://api.ophion.com.br"
|
|
export OPHION_API_KEY="ophion_sua_chave_aqui"
|
|
|
|
# Instalar
|
|
curl -fsSL https://ophion.com.br/agent.sh | bash
|
|
```
|
|
|
|
## 3.3 Instalação Manual
|
|
|
|
### Download do Binário
|
|
|
|
```bash
|
|
# Linux AMD64
|
|
wget https://github.com/bigtux/ophion/releases/latest/download/ophion-agent-linux-amd64 -O /usr/local/bin/ophion-agent
|
|
|
|
# Linux ARM64
|
|
wget https://github.com/bigtux/ophion/releases/latest/download/ophion-agent-linux-arm64 -O /usr/local/bin/ophion-agent
|
|
|
|
# Dar permissão de execução
|
|
chmod +x /usr/local/bin/ophion-agent
|
|
```
|
|
|
|
### Criar Configuração
|
|
|
|
```bash
|
|
sudo mkdir -p /etc/ophion
|
|
|
|
sudo tee /etc/ophion/agent.yaml << 'EOF'
|
|
# OPHION Agent Configuration
|
|
server:
|
|
url: https://api.ophion.com.br
|
|
api_key: ophion_sua_chave_aqui
|
|
|
|
agent:
|
|
hostname: ${HOSTNAME} # ou nome personalizado
|
|
tags:
|
|
environment: production
|
|
team: infra
|
|
region: brasil
|
|
|
|
# Intervalo de coleta
|
|
interval: 30s
|
|
|
|
# Coletores ativos
|
|
collectors:
|
|
# Métricas do sistema
|
|
cpu:
|
|
enabled: true
|
|
per_core: true
|
|
|
|
memory:
|
|
enabled: true
|
|
|
|
disk:
|
|
enabled: true
|
|
paths:
|
|
- /
|
|
- /var
|
|
- /home
|
|
|
|
network:
|
|
enabled: true
|
|
interfaces:
|
|
- eth0
|
|
- ens3
|
|
|
|
# Processos
|
|
processes:
|
|
enabled: true
|
|
top_n: 10 # Top 10 por CPU/memória
|
|
|
|
# Docker
|
|
docker:
|
|
enabled: true
|
|
socket: /var/run/docker.sock
|
|
collect_logs: true
|
|
log_lines: 100
|
|
|
|
# Logs do sistema
|
|
logs:
|
|
enabled: true
|
|
paths:
|
|
- /var/log/syslog
|
|
- /var/log/auth.log
|
|
- /var/log/nginx/*.log
|
|
|
|
# Buffer local (caso servidor indisponível)
|
|
buffer:
|
|
enabled: true
|
|
path: /var/lib/ophion/buffer
|
|
max_size: 100MB
|
|
|
|
# Logging do agent
|
|
logging:
|
|
level: info
|
|
file: /var/log/ophion-agent.log
|
|
EOF
|
|
```
|
|
|
|
### Criar Serviço Systemd
|
|
|
|
```bash
|
|
sudo tee /etc/systemd/system/ophion-agent.service << 'EOF'
|
|
[Unit]
|
|
Description=OPHION Monitoring Agent
|
|
Documentation=https://docs.ophion.com.br
|
|
After=network-online.target
|
|
Wants=network-online.target
|
|
|
|
[Service]
|
|
Type=simple
|
|
User=root
|
|
ExecStart=/usr/local/bin/ophion-agent --config /etc/ophion/agent.yaml
|
|
Restart=always
|
|
RestartSec=10
|
|
StandardOutput=append:/var/log/ophion-agent.log
|
|
StandardError=append:/var/log/ophion-agent.log
|
|
|
|
# Limites de recursos
|
|
MemoryMax=256M
|
|
CPUQuota=10%
|
|
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
```
|
|
|
|
### Iniciar Serviço
|
|
|
|
```bash
|
|
# Recarregar systemd
|
|
sudo systemctl daemon-reload
|
|
|
|
# Habilitar no boot
|
|
sudo systemctl enable ophion-agent
|
|
|
|
# Iniciar
|
|
sudo systemctl start ophion-agent
|
|
|
|
# Verificar status
|
|
sudo systemctl status ophion-agent
|
|
|
|
# Ver logs
|
|
sudo journalctl -u ophion-agent -f
|
|
```
|
|
|
|
## 3.4 Verificar Funcionamento
|
|
|
|
```bash
|
|
# No servidor do Agent
|
|
curl -s localhost:9100/metrics | head -20
|
|
|
|
# No servidor OPHION (verificar se dados chegam)
|
|
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
|
https://api.ophion.com.br/api/v1/hosts
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 4: MONITORAMENTO DE DOCKER
|
|
|
|
## 4.1 Configuração Básica
|
|
|
|
O Agent detecta automaticamente containers Docker se tiver acesso ao socket.
|
|
|
|
```bash
|
|
# Verificar se o socket existe
|
|
ls -la /var/run/docker.sock
|
|
|
|
# Agent precisa de permissão
|
|
sudo usermod -aG docker root
|
|
```
|
|
|
|
## 4.2 Docker Compose - Adicionar Agent
|
|
|
|
Adicione ao seu `docker-compose.yml`:
|
|
|
|
```yaml
|
|
version: '3.8'
|
|
|
|
services:
|
|
# Seus serviços existentes...
|
|
app:
|
|
image: minha-app:latest
|
|
# ...
|
|
|
|
# Agent OPHION
|
|
ophion-agent:
|
|
image: ophion/agent:latest
|
|
container_name: ophion-agent
|
|
restart: unless-stopped
|
|
environment:
|
|
- OPHION_SERVER=https://api.ophion.com.br
|
|
- OPHION_API_KEY=${OPHION_API_KEY}
|
|
- OPHION_HOSTNAME=${HOSTNAME:-docker-host}
|
|
volumes:
|
|
# Socket do Docker (obrigatório para métricas de containers)
|
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
|
# Sistema de arquivos do host (para métricas de disco)
|
|
- /proc:/host/proc:ro
|
|
- /sys:/host/sys:ro
|
|
- /:/host/root:ro
|
|
network_mode: host
|
|
pid: host
|
|
privileged: true
|
|
```
|
|
|
|
## 4.3 Labels para Organização
|
|
|
|
Adicione labels aos seus containers para melhor visualização:
|
|
|
|
```yaml
|
|
services:
|
|
api:
|
|
image: minha-api:latest
|
|
labels:
|
|
# Labels do OPHION
|
|
ophion.monitor: "true"
|
|
ophion.service: "api"
|
|
ophion.environment: "production"
|
|
ophion.team: "backend"
|
|
ophion.alert.cpu: "80" # Alertar se CPU > 80%
|
|
ophion.alert.memory: "90" # Alertar se memória > 90%
|
|
|
|
database:
|
|
image: postgres:16
|
|
labels:
|
|
ophion.monitor: "true"
|
|
ophion.service: "database"
|
|
ophion.type: "postgresql"
|
|
```
|
|
|
|
## 4.4 Métricas Coletadas
|
|
|
|
| Métrica | Descrição | Tipo |
|
|
|---------|-----------|------|
|
|
| `container.cpu.usage_percent` | Uso de CPU | gauge |
|
|
| `container.memory.usage_bytes` | Memória usada | gauge |
|
|
| `container.memory.limit_bytes` | Limite de memória | gauge |
|
|
| `container.memory.percent` | % memória usada | gauge |
|
|
| `container.network.rx_bytes` | Bytes recebidos | counter |
|
|
| `container.network.tx_bytes` | Bytes enviados | counter |
|
|
| `container.disk.read_bytes` | Leitura de disco | counter |
|
|
| `container.disk.write_bytes` | Escrita de disco | counter |
|
|
| `container.status` | Status (1=running) | gauge |
|
|
| `container.restart_count` | Número de restarts | counter |
|
|
| `container.uptime_seconds` | Tempo online | gauge |
|
|
|
|
---
|
|
|
|
# PARTE 5: APM - MONITORAMENTO DE APLICAÇÕES
|
|
|
|
## 5.1 Node.js / Express
|
|
|
|
### Instalação
|
|
|
|
```bash
|
|
npm install @ophion/apm
|
|
```
|
|
|
|
### Configuração
|
|
|
|
```javascript
|
|
// PRIMEIRA LINHA do seu app - antes de qualquer import
|
|
const ophion = require('@ophion/apm');
|
|
|
|
ophion.init({
|
|
serverUrl: process.env.OPHION_SERVER || 'https://api.ophion.com.br',
|
|
apiKey: process.env.OPHION_API_KEY,
|
|
serviceName: 'minha-api',
|
|
environment: process.env.NODE_ENV || 'development',
|
|
|
|
// Opções avançadas
|
|
sampleRate: 1.0, // 100% das requisições (reduzir em produção)
|
|
captureBody: true, // Capturar body das requisições
|
|
captureHeaders: true, // Capturar headers
|
|
captureErrors: true, // Capturar exceções automaticamente
|
|
|
|
// Instrumentações automáticas
|
|
instrumentations: {
|
|
http: true,
|
|
express: true,
|
|
mongodb: true,
|
|
postgresql: true,
|
|
redis: true,
|
|
axios: true
|
|
}
|
|
});
|
|
|
|
// Agora seus imports normais
|
|
const express = require('express');
|
|
const app = express();
|
|
|
|
// Middleware de erro (para capturar exceções)
|
|
app.use(ophion.errorHandler());
|
|
|
|
app.listen(3000);
|
|
```
|
|
|
|
### Traces Customizados
|
|
|
|
```javascript
|
|
const { trace, context } = require('@ophion/apm');
|
|
|
|
app.get('/api/users/:id', async (req, res) => {
|
|
// Criar span customizado
|
|
const span = trace.startSpan('fetch-user');
|
|
|
|
try {
|
|
span.setAttribute('user.id', req.params.id);
|
|
|
|
const user = await db.users.findById(req.params.id);
|
|
|
|
span.setAttribute('user.found', !!user);
|
|
span.setStatus({ code: 'OK' });
|
|
|
|
res.json(user);
|
|
} catch (error) {
|
|
span.recordException(error);
|
|
span.setStatus({ code: 'ERROR', message: error.message });
|
|
throw error;
|
|
} finally {
|
|
span.end();
|
|
}
|
|
});
|
|
```
|
|
|
|
## 5.2 Python / Flask / Django
|
|
|
|
### Instalação
|
|
|
|
```bash
|
|
pip install ophion-apm
|
|
```
|
|
|
|
### Flask
|
|
|
|
```python
|
|
# PRIMEIRA LINHA - antes de qualquer import
|
|
import ophion_apm
|
|
|
|
ophion_apm.init(
|
|
server_url='https://api.ophion.com.br',
|
|
api_key='YOUR_API_KEY',
|
|
service_name='minha-api',
|
|
environment='production'
|
|
)
|
|
|
|
# Imports normais
|
|
from flask import Flask
|
|
app = Flask(__name__)
|
|
|
|
# Instrumentação automática já está ativa
|
|
@app.route('/api/users/<id>')
|
|
def get_user(id):
|
|
return {'id': id}
|
|
```
|
|
|
|
### Django
|
|
|
|
```python
|
|
# settings.py
|
|
|
|
INSTALLED_APPS = [
|
|
'ophion_apm.django',
|
|
# ... outros apps
|
|
]
|
|
|
|
OPHION_APM = {
|
|
'SERVER_URL': 'https://api.ophion.com.br',
|
|
'API_KEY': 'YOUR_API_KEY',
|
|
'SERVICE_NAME': 'minha-api',
|
|
'ENVIRONMENT': 'production',
|
|
}
|
|
```
|
|
|
|
## 5.3 Go
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"github.com/bigtux/ophion/sdk/go/apm"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func main() {
|
|
// Inicializar APM
|
|
apm.Init(apm.Config{
|
|
ServerURL: "https://api.ophion.com.br",
|
|
APIKey: "YOUR_API_KEY",
|
|
ServiceName: "minha-api",
|
|
Environment: "production",
|
|
})
|
|
defer apm.Close()
|
|
|
|
r := gin.Default()
|
|
|
|
// Middleware de tracing
|
|
r.Use(apm.GinMiddleware())
|
|
|
|
r.GET("/api/users/:id", func(c *gin.Context) {
|
|
// Span automático criado pelo middleware
|
|
|
|
// Span customizado
|
|
ctx, span := apm.StartSpan(c.Request.Context(), "fetch-user")
|
|
defer span.End()
|
|
|
|
// Sua lógica...
|
|
c.JSON(200, gin.H{"id": c.Param("id")})
|
|
})
|
|
|
|
r.Run(":8080")
|
|
}
|
|
```
|
|
|
|
## 5.4 OpenTelemetry (Universal)
|
|
|
|
OPHION é 100% compatível com OpenTelemetry:
|
|
|
|
```bash
|
|
# Variáveis de ambiente
|
|
export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.ophion.com.br"
|
|
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_API_KEY"
|
|
export OTEL_SERVICE_NAME="minha-api"
|
|
export OTEL_RESOURCE_ATTRIBUTES="environment=production,team=backend"
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 6: INTELIGÊNCIA ARTIFICIAL
|
|
|
|
## 6.1 Funcionalidades de IA
|
|
|
|
### Detecção de Anomalias
|
|
- Identifica automaticamente comportamentos anormais
|
|
- Aprende o padrão normal da sua infraestrutura
|
|
- Alerta antes que problemas ocorram
|
|
|
|
### Análise de Logs com IA
|
|
- Agrupa logs similares automaticamente
|
|
- Identifica padrões de erro
|
|
- Sugere causas raiz de problemas
|
|
|
|
### Previsão de Capacidade
|
|
- Prevê quando recursos vão acabar
|
|
- Sugere escalonamento proativo
|
|
- Identifica tendências
|
|
|
|
### Correlação de Eventos
|
|
- Relaciona eventos de diferentes fontes
|
|
- Identifica cascatas de falhas
|
|
- Reduz ruído de alertas
|
|
|
|
## 6.2 Configuração da IA
|
|
|
|
### No arquivo .env:
|
|
|
|
```env
|
|
# Habilitar IA
|
|
AI_ENABLED=true
|
|
|
|
# Modelo a usar (recomendado: gpt-4o-mini por custo/benefício)
|
|
AI_MODEL=gpt-4o-mini
|
|
OPENAI_API_KEY=sk-your-key-here
|
|
|
|
# Funcionalidades específicas
|
|
AI_ANOMALY_DETECTION=true
|
|
AI_LOG_ANALYSIS=true
|
|
AI_PREDICTIONS=true
|
|
AI_ROOT_CAUSE=true
|
|
|
|
# Limites de custo
|
|
AI_MAX_TOKENS_PER_DAY=100000
|
|
AI_MAX_REQUESTS_PER_HOUR=60
|
|
```
|
|
|
|
### Via API:
|
|
|
|
```bash
|
|
# Habilitar análise de IA para um host
|
|
curl -X POST "https://api.ophion.com.br/api/v1/hosts/{host_id}/ai" \
|
|
-H "Authorization: Bearer YOUR_API_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"anomaly_detection": true,
|
|
"log_analysis": true,
|
|
"predictions": true,
|
|
"sensitivity": "medium"
|
|
}'
|
|
```
|
|
|
|
## 6.3 Como Funciona a Detecção de Anomalias
|
|
|
|
```
|
|
1. APRENDIZADO (primeiras 24-48h)
|
|
- IA observa padrões normais
|
|
- Aprende ciclos diários/semanais
|
|
- Identifica baselines
|
|
|
|
2. DETECÇÃO (contínuo)
|
|
- Compara métricas atuais com baseline
|
|
- Detecta desvios significativos
|
|
- Considera contexto (dia, hora, eventos)
|
|
|
|
3. ALERTA INTELIGENTE
|
|
- Classifica severidade automaticamente
|
|
- Agrupa alertas relacionados
|
|
- Sugere ações de correção
|
|
```
|
|
|
|
## 6.4 Exemplos de Alertas com IA
|
|
|
|
**Alerta Tradicional:**
|
|
```
|
|
⚠️ CPU > 80% no servidor web-01
|
|
```
|
|
|
|
**Alerta com IA:**
|
|
```
|
|
🤖 ANOMALIA DETECTADA - web-01
|
|
|
|
📊 Situação:
|
|
- CPU em 85% (normal para este horário: 40-50%)
|
|
- Memória em 72% (normal: 60%)
|
|
- Conexões: 1.2k (normal: 300-400)
|
|
|
|
🔍 Análise:
|
|
O aumento de CPU e conexões coincide com um pico de
|
|
requisições na API /api/products. O padrão sugere
|
|
possível ataque ou campanha de marketing não planejada.
|
|
|
|
💡 Sugestões:
|
|
1. Verificar origem das requisições (possível bot)
|
|
2. Considerar escalar horizontalmente
|
|
3. Verificar se há campanha ativa
|
|
|
|
🔗 Eventos relacionados:
|
|
- 14:32 - Deploy da v2.3.1 no web-02
|
|
- 14:45 - Aumento de latência no database
|
|
```
|
|
|
|
## 6.5 Análise de Logs com IA
|
|
|
|
### Agrupamento Automático
|
|
|
|
A IA agrupa logs similares:
|
|
|
|
```
|
|
📋 Cluster de Erros #1 (847 ocorrências)
|
|
|
|
Padrão: "Connection refused to database"
|
|
|
|
Exemplos:
|
|
- [14:32:01] Error: Connection refused to postgres:5432
|
|
- [14:32:03] Error: Cannot connect to database server
|
|
- [14:32:05] Error: Database connection timeout
|
|
|
|
🤖 Análise:
|
|
Múltiplas falhas de conexão com banco de dados.
|
|
Possível causa: limite de conexões atingido ou
|
|
banco de dados indisponível.
|
|
|
|
💡 Sugestões:
|
|
1. Verificar status do PostgreSQL
|
|
2. Verificar pool de conexões
|
|
3. Aumentar max_connections se necessário
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 7: ALERTAS E NOTIFICAÇÕES
|
|
|
|
## 7.1 Canais Suportados
|
|
|
|
| Canal | Configuração |
|
|
|-------|-------------|
|
|
| Telegram | Bot Token + Chat ID |
|
|
| Slack | Webhook URL |
|
|
| Discord | Webhook URL |
|
|
| Email | SMTP |
|
|
| SMS | Twilio |
|
|
| PagerDuty | Integration Key |
|
|
| OpsGenie | API Key |
|
|
| Webhook | URL customizada |
|
|
|
|
## 7.2 Configurar Telegram
|
|
|
|
```bash
|
|
# 1. Criar bot no @BotFather
|
|
# 2. Obter token: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz
|
|
|
|
# 3. Descobrir seu Chat ID
|
|
curl "https://api.telegram.org/bot{TOKEN}/getUpdates"
|
|
|
|
# 4. Configurar no OPHION
|
|
curl -X POST "https://api.ophion.com.br/api/v1/integrations/telegram" \
|
|
-H "Authorization: Bearer YOUR_API_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"bot_token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz",
|
|
"chat_id": "-1001234567890",
|
|
"name": "Alertas Infra"
|
|
}'
|
|
```
|
|
|
|
## 7.3 Criar Alertas
|
|
|
|
### Via Dashboard
|
|
|
|
1. Acesse **Alertas** → **Novo Alerta**
|
|
2. Configure a condição
|
|
3. Escolha canais de notificação
|
|
4. Salvar
|
|
|
|
### Via API
|
|
|
|
```bash
|
|
curl -X POST "https://api.ophion.com.br/api/v1/alerts/rules" \
|
|
-H "Authorization: Bearer YOUR_API_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"name": "CPU Alta",
|
|
"description": "Alerta quando CPU ultrapassa 80%",
|
|
"enabled": true,
|
|
"condition": {
|
|
"metric": "system.cpu.usage",
|
|
"operator": ">",
|
|
"threshold": 80,
|
|
"duration": "5m",
|
|
"aggregation": "avg"
|
|
},
|
|
"filters": {
|
|
"host": "*",
|
|
"environment": "production"
|
|
},
|
|
"notifications": [
|
|
{
|
|
"channel": "telegram",
|
|
"integration_id": "tel_123"
|
|
},
|
|
{
|
|
"channel": "email",
|
|
"to": ["admin@empresa.com"]
|
|
}
|
|
],
|
|
"severity": "warning",
|
|
"ai_analysis": true
|
|
}'
|
|
```
|
|
|
|
## 7.4 Escalação
|
|
|
|
```yaml
|
|
# Configurar política de escalação
|
|
escalation:
|
|
name: "Crítico Produção"
|
|
steps:
|
|
- delay: 0m
|
|
notify:
|
|
- channel: telegram
|
|
target: grupo-infra
|
|
- channel: slack
|
|
target: "#alerts"
|
|
|
|
- delay: 15m
|
|
notify:
|
|
- channel: telegram
|
|
target: tech-lead
|
|
- channel: sms
|
|
target: "+5511999999999"
|
|
|
|
- delay: 30m
|
|
notify:
|
|
- channel: phone
|
|
target: "+5511999999999"
|
|
- channel: email
|
|
target: cto@empresa.com
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 8: DASHBOARDS
|
|
|
|
## 8.1 Dashboards Pré-configurados
|
|
|
|
- **System Overview** - Visão geral de todos os hosts
|
|
- **Docker Containers** - Métricas de containers
|
|
- **Application Performance** - APM e traces
|
|
- **Logs Explorer** - Busca e análise de logs
|
|
- **Alerts History** - Histórico de alertas
|
|
|
|
## 8.2 Criar Dashboard Customizado
|
|
|
|
### Via Interface
|
|
|
|
1. **Dashboards** → **Novo Dashboard**
|
|
2. Arraste widgets da biblioteca
|
|
3. Configure queries
|
|
4. Salvar
|
|
|
|
### Via API
|
|
|
|
```bash
|
|
curl -X POST "https://api.ophion.com.br/api/v1/dashboards" \
|
|
-H "Authorization: Bearer YOUR_API_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"name": "Meu Dashboard",
|
|
"widgets": [
|
|
{
|
|
"type": "timeseries",
|
|
"title": "CPU por Host",
|
|
"query": "system.cpu.usage",
|
|
"groupBy": "host",
|
|
"position": {"x": 0, "y": 0, "w": 6, "h": 4}
|
|
},
|
|
{
|
|
"type": "gauge",
|
|
"title": "Memória Total",
|
|
"query": "avg(system.memory.percent)",
|
|
"position": {"x": 6, "y": 0, "w": 3, "h": 4}
|
|
}
|
|
]
|
|
}'
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 9: API REFERENCE
|
|
|
|
## 9.1 Autenticação
|
|
|
|
```bash
|
|
# Header de autorização
|
|
Authorization: Bearer YOUR_API_KEY
|
|
```
|
|
|
|
## 9.2 Endpoints Principais
|
|
|
|
| Método | Endpoint | Descrição |
|
|
|--------|----------|-----------|
|
|
| GET | `/api/v1/hosts` | Listar hosts |
|
|
| GET | `/api/v1/hosts/{id}/metrics` | Métricas de um host |
|
|
| GET | `/api/v1/containers` | Listar containers |
|
|
| GET | `/api/v1/logs` | Buscar logs |
|
|
| GET | `/api/v1/traces` | Buscar traces |
|
|
| GET | `/api/v1/alerts` | Listar alertas |
|
|
| POST | `/api/v1/alerts/rules` | Criar regra de alerta |
|
|
| GET | `/api/v1/dashboards` | Listar dashboards |
|
|
|
|
## 9.3 Exemplos
|
|
|
|
```bash
|
|
# Buscar métricas de CPU das últimas 6 horas
|
|
curl "https://api.ophion.com.br/api/v1/metrics?metric=system.cpu.usage&from=-6h" \
|
|
-H "Authorization: Bearer YOUR_API_KEY"
|
|
|
|
# Buscar logs com filtro
|
|
curl "https://api.ophion.com.br/api/v1/logs?query=error&host=web-01&from=-1h" \
|
|
-H "Authorization: Bearer YOUR_API_KEY"
|
|
|
|
# Ingerir métricas customizadas
|
|
curl -X POST "https://api.ophion.com.br/api/v1/metrics" \
|
|
-H "Authorization: Bearer YOUR_API_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"metrics": [
|
|
{
|
|
"name": "app.orders.count",
|
|
"value": 150,
|
|
"tags": {"region": "brasil"}
|
|
}
|
|
]
|
|
}'
|
|
```
|
|
|
|
---
|
|
|
|
# PARTE 10: TROUBLESHOOTING
|
|
|
|
## 10.1 Agent não conecta
|
|
|
|
```bash
|
|
# Verificar DNS
|
|
nslookup api.ophion.com.br
|
|
|
|
# Verificar conectividade
|
|
curl -v https://api.ophion.com.br/health
|
|
|
|
# Verificar API Key
|
|
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
|
https://api.ophion.com.br/api/v1/status
|
|
|
|
# Verificar logs do agent
|
|
journalctl -u ophion-agent -f
|
|
```
|
|
|
|
## 10.2 Métricas não aparecem
|
|
|
|
1. Verificar se agent está rodando
|
|
2. Verificar API Key
|
|
3. Aguardar 60 segundos
|
|
4. Verificar filtros no dashboard
|
|
|
|
## 10.3 Docker não monitora
|
|
|
|
```bash
|
|
# Verificar socket
|
|
ls -la /var/run/docker.sock
|
|
|
|
# Testar acesso
|
|
docker ps
|
|
|
|
# Verificar se agent tem acesso
|
|
docker exec ophion-agent docker ps
|
|
```
|
|
|
|
## 10.4 Logs de Debug
|
|
|
|
```bash
|
|
# Aumentar nível de log do agent
|
|
echo "logging:\n level: debug" >> /etc/ophion/agent.yaml
|
|
systemctl restart ophion-agent
|
|
journalctl -u ophion-agent -f
|
|
```
|
|
|
|
---
|
|
|
|
# SUPORTE
|
|
|
|
- 📧 **Email:** suporte@ophion.com.br
|
|
- 💬 **Telegram:** [@ophion_suporte](https://t.me/ophion_suporte)
|
|
- 📖 **Docs:** https://docs.ophion.com.br
|
|
- 🐙 **GitHub:** https://github.com/bigtux/ophion
|
|
- 🐛 **Issues:** https://github.com/bigtux/ophion/issues
|
|
|
|
---
|
|
|
|
*🐍 OPHION - Observability Made Simple*
|
|
*Made with 🖤 in Brazil*
|