From d58ac37e39f8643c6a64babedac288be25058790 Mon Sep 17 00:00:00 2001 From: bigtux Date: Thu, 5 Feb 2026 22:45:05 -0300 Subject: [PATCH] feat: Add AI engine and complete documentation - 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 --- docs/MANUAL_COMPLETO.md | 1138 +++++++++++++++++++++++++++++++++++++++ internal/ai/engine.go | 336 ++++++++++++ web/index.html | 211 ++++++++ 3 files changed, 1685 insertions(+) create mode 100644 docs/MANUAL_COMPLETO.md create mode 100644 internal/ai/engine.go create mode 100644 web/index.html diff --git a/docs/MANUAL_COMPLETO.md b/docs/MANUAL_COMPLETO.md new file mode 100644 index 0000000..13869aa --- /dev/null +++ b/docs/MANUAL_COMPLETO.md @@ -0,0 +1,1138 @@ +# 🐍 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/') +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* diff --git a/internal/ai/engine.go b/internal/ai/engine.go new file mode 100644 index 0000000..d145669 --- /dev/null +++ b/internal/ai/engine.go @@ -0,0 +1,336 @@ +package ai + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "time" +) + +// AIEngine é o motor de inteligência artificial do OPHION +type AIEngine struct { + apiKey string + model string + baseURL string + client *http.Client + enabled bool +} + +// Config configuração do AI Engine +type Config struct { + APIKey string + Model string + Enabled bool +} + +// AnomalyResult resultado da detecção de anomalias +type AnomalyResult struct { + IsAnomaly bool `json:"is_anomaly"` + Confidence float64 `json:"confidence"` + Severity string `json:"severity"` + Description string `json:"description"` + Suggestions []string `json:"suggestions"` + RelatedEvents []string `json:"related_events"` +} + +// LogAnalysisResult resultado da análise de logs +type LogAnalysisResult struct { + Clusters []LogCluster `json:"clusters"` + RootCause string `json:"root_cause"` + Suggestions []string `json:"suggestions"` +} + +// LogCluster agrupamento de logs similares +type LogCluster struct { + Pattern string `json:"pattern"` + Count int `json:"count"` + Severity string `json:"severity"` + Examples []string `json:"examples"` + Description string `json:"description"` +} + +// PredictionResult resultado de previsões +type PredictionResult struct { + Metric string `json:"metric"` + CurrentValue float64 `json:"current_value"` + PredictedValue float64 `json:"predicted_value"` + TimeToThreshold string `json:"time_to_threshold"` + Confidence float64 `json:"confidence"` + Recommendation string `json:"recommendation"` +} + +// NewAIEngine cria nova instância do AI Engine +func NewAIEngine(config Config) *AIEngine { + return &AIEngine{ + apiKey: config.APIKey, + model: config.Model, + baseURL: "https://api.openai.com/v1", + client: &http.Client{ + Timeout: 30 * time.Second, + }, + enabled: config.Enabled, + } +} + +// NewFromEnv cria AI Engine a partir de variáveis de ambiente +func NewFromEnv() *AIEngine { + return NewAIEngine(Config{ + APIKey: os.Getenv("OPENAI_API_KEY"), + Model: getEnvOrDefault("AI_MODEL", "gpt-4o-mini"), + Enabled: os.Getenv("AI_ENABLED") == "true", + }) +} + +func getEnvOrDefault(key, defaultValue string) string { + if value := os.Getenv(key); value != "" { + return value + } + return defaultValue +} + +// DetectAnomaly detecta anomalias em métricas +func (e *AIEngine) DetectAnomaly(ctx context.Context, metrics MetricsData) (*AnomalyResult, error) { + if !e.enabled { + return nil, fmt.Errorf("AI engine is disabled") + } + + prompt := fmt.Sprintf(`Analise as seguintes métricas de servidor e detecte anomalias: + +Host: %s +Período: últimas %d horas +Métricas atuais: +- CPU: %.2f%% (baseline: %.2f%%) +- Memória: %.2f%% (baseline: %.2f%%) +- Disco: %.2f%% (baseline: %.2f%%) +- Conexões de rede: %d (baseline: %d) + +Histórico recente (últimas 24h): +%s + +Responda em JSON com o formato: +{ + "is_anomaly": boolean, + "confidence": 0.0-1.0, + "severity": "low|medium|high|critical", + "description": "descrição da anomalia", + "suggestions": ["sugestão 1", "sugestão 2"], + "related_events": ["evento relacionado 1"] +}`, + metrics.Hostname, + metrics.PeriodHours, + metrics.CPU.Current, metrics.CPU.Baseline, + metrics.Memory.Current, metrics.Memory.Baseline, + metrics.Disk.Current, metrics.Disk.Baseline, + metrics.Network.Connections, metrics.Network.BaselineConnections, + metrics.History, + ) + + response, err := e.chat(ctx, prompt) + if err != nil { + return nil, err + } + + var result AnomalyResult + if err := json.Unmarshal([]byte(response), &result); err != nil { + return nil, fmt.Errorf("failed to parse AI response: %w", err) + } + + return &result, nil +} + +// AnalyzeLogs analisa logs e identifica padrões +func (e *AIEngine) AnalyzeLogs(ctx context.Context, logs []LogEntry) (*LogAnalysisResult, error) { + if !e.enabled { + return nil, fmt.Errorf("AI engine is disabled") + } + + // Preparar logs para análise + logText := "" + for i, log := range logs { + if i >= 100 { // Limitar a 100 logs + break + } + logText += fmt.Sprintf("[%s] %s: %s\n", log.Timestamp, log.Level, log.Message) + } + + prompt := fmt.Sprintf(`Analise os seguintes logs de aplicação e identifique padrões, erros e possíveis causas raiz: + +Logs: +%s + +Responda em JSON com o formato: +{ + "clusters": [ + { + "pattern": "padrão identificado", + "count": 10, + "severity": "error|warning|info", + "examples": ["exemplo 1", "exemplo 2"], + "description": "descrição do cluster" + } + ], + "root_cause": "possível causa raiz dos problemas", + "suggestions": ["sugestão de correção 1", "sugestão 2"] +}`, logText) + + response, err := e.chat(ctx, prompt) + if err != nil { + return nil, err + } + + var result LogAnalysisResult + if err := json.Unmarshal([]byte(response), &result); err != nil { + return nil, fmt.Errorf("failed to parse AI response: %w", err) + } + + return &result, nil +} + +// PredictCapacity prevê capacidade futura +func (e *AIEngine) PredictCapacity(ctx context.Context, data CapacityData) (*PredictionResult, error) { + if !e.enabled { + return nil, fmt.Errorf("AI engine is disabled") + } + + prompt := fmt.Sprintf(`Analise os dados históricos e preveja quando o recurso atingirá o limite: + +Recurso: %s +Valor atual: %.2f%% +Limite crítico: %.2f%% +Dados históricos (últimos 30 dias): +%s + +Responda em JSON com o formato: +{ + "metric": "nome da métrica", + "current_value": 75.5, + "predicted_value": 95.0, + "time_to_threshold": "em 7 dias", + "confidence": 0.85, + "recommendation": "recomendação de ação" +}`, data.Metric, data.CurrentValue, data.Threshold, data.History) + + response, err := e.chat(ctx, prompt) + if err != nil { + return nil, err + } + + var result PredictionResult + if err := json.Unmarshal([]byte(response), &result); err != nil { + return nil, fmt.Errorf("failed to parse AI response: %w", err) + } + + return &result, nil +} + +// chat envia mensagem para a API da OpenAI +func (e *AIEngine) chat(ctx context.Context, prompt string) (string, error) { + requestBody := map[string]interface{}{ + "model": e.model, + "messages": []map[string]string{ + { + "role": "system", + "content": "Você é um especialista em observabilidade e monitoramento de infraestrutura. Analise os dados fornecidos e forneça insights acionáveis. Sempre responda em JSON válido.", + }, + { + "role": "user", + "content": prompt, + }, + }, + "temperature": 0.3, + "max_tokens": 2000, + } + + jsonBody, err := json.Marshal(requestBody) + if err != nil { + return "", err + } + + req, err := http.NewRequestWithContext(ctx, "POST", e.baseURL+"/chat/completions", bytes.NewBuffer(jsonBody)) + if err != nil { + return "", err + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+e.apiKey) + + resp, err := e.client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + var result struct { + Choices []struct { + Message struct { + Content string `json:"content"` + } `json:"message"` + } `json:"choices"` + Error struct { + Message string `json:"message"` + } `json:"error"` + } + + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return "", err + } + + if result.Error.Message != "" { + return "", fmt.Errorf("OpenAI error: %s", result.Error.Message) + } + + if len(result.Choices) == 0 { + return "", fmt.Errorf("no response from AI") + } + + return result.Choices[0].Message.Content, nil +} + +// IsEnabled verifica se o AI Engine está habilitado +func (e *AIEngine) IsEnabled() bool { + return e.enabled +} + +// === Tipos de dados auxiliares === + +// MetricsData dados de métricas para análise +type MetricsData struct { + Hostname string + PeriodHours int + CPU MetricValue + Memory MetricValue + Disk MetricValue + Network NetworkMetric + History string +} + +// MetricValue valor de métrica com baseline +type MetricValue struct { + Current float64 + Baseline float64 +} + +// NetworkMetric métricas de rede +type NetworkMetric struct { + Connections int + BaselineConnections int +} + +// LogEntry entrada de log +type LogEntry struct { + Timestamp string + Level string + Message string + Source string +} + +// CapacityData dados para previsão de capacidade +type CapacityData struct { + Metric string + CurrentValue float64 + Threshold float64 + History string +} diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..40ac7ba --- /dev/null +++ b/web/index.html @@ -0,0 +1,211 @@ + + + + + + OPHION - Open Source Observability Platform + + + + + + + + + + + +
+
+ 🎉 Open Source & Self-Hosted Available +
+

+ Observability
+ Made Simple +

+

+ Métricas, logs, traces e alertas em uma única plataforma. + Alternativa open source ao Datadog por 1/10 do preço. +

+ +

Setup em 5 minutos • Não precisa de cartão

+
+ + +
+
+
+
10TB+
+
Métricas/dia
+
+
+
99.9%
+
Uptime
+
+
+
<100ms
+
Latência
+
+
+
+
Usuários
+
+
+
+ + +
+

Tudo que você precisa

+
+
+
📊
+

Infrastructure Monitoring

+

CPU, memória, disco e rede em tempo real. Suporte a Docker, K8s e cloud.

+
+
+
📝
+

Log Management

+

Centralize todos os seus logs. Busca poderosa e alertas por padrões.

+
+
+
🔍
+

Distributed Tracing

+

Rastreie requests entre serviços. Identifique gargalos rapidamente.

+
+
+
📈
+

Custom Dashboards

+

Crie dashboards personalizados. Drag-and-drop, widgets flexíveis.

+
+
+
🚨
+

Smart Alerts

+

Telegram, Slack, Email, PagerDuty. Escalação e silenciamento inteligente.

+
+
+
🔐
+

Enterprise Security

+

SSO, RBAC, audit logs. Compliance com LGPD e SOC2.

+
+
+
+ + +
+

Preços Transparentes

+

Sem surpresas. Sem cobrança por usuário.

+
+
+

Community

+
Grátis
+

Self-hosted

+
    +
  • ✓ Todas as features
  • +
  • ✓ Usuários ilimitados
  • +
  • ✓ Hosts ilimitados
  • +
  • ✓ 7 dias retenção
  • +
  • ✓ Comunidade
  • +
+ Download +
+
+

Starter

+
R$ 97/mês
+

Para pequenas equipes

+
    +
  • ✓ 5 hosts
  • +
  • ✓ 10GB logs/mês
  • +
  • ✓ 14 dias retenção
  • +
  • ✓ Alertas Telegram
  • +
  • ✓ Suporte email
  • +
+ Começar +
+
+
POPULAR
+

Pro

+
R$ 297/mês
+

Para empresas

+
    +
  • ✓ 20 hosts
  • +
  • ✓ 50GB logs/mês
  • +
  • ✓ 30 dias retenção
  • +
  • ✓ APM completo
  • +
  • ✓ Suporte prioritário
  • +
+ Começar +
+
+

Enterprise

+
Custom
+

Para grandes empresas

+
    +
  • ✓ Hosts ilimitados
  • +
  • ✓ Retenção custom
  • +
  • ✓ SSO / SAML
  • +
  • ✓ On-premise
  • +
  • ✓ SLA 99.99%
  • +
+ Contato +
+
+
+ + +
+
+

Pronto para começar?

+

Setup em 5 minutos. Cancele quando quiser.

+ + Criar Conta Grátis → + +
+
+ + + + +