first commit
This commit is contained in:
319
TECHNICAL.md
Normal file
319
TECHNICAL.md
Normal file
@@ -0,0 +1,319 @@
|
||||
# 📚 Referência Técnica
|
||||
|
||||
## Stack de Tecnologias
|
||||
|
||||
| Componente | Tecnologia | Versão | Função |
|
||||
|-----------|-----------|--------|---------|
|
||||
| API | Python Flask | 2.3.3 | Servidor HTTP |
|
||||
| Web Server | Gunicorn | 21.2.0 | WSGI HTTP Server |
|
||||
| HTTP Client | Requests | 2.31.0 | Cliente HTTP |
|
||||
| Configuration | python-dotenv | 1.0.0 | Gerenciar variáveis de env |
|
||||
| Metrics | prometheus-client | 0.17.1 | Exporte de métricas |
|
||||
| Container | Docker | latest | Containerização |
|
||||
| Orchestration | Docker Compose | 3.8 | Orquestração |
|
||||
| Monitoring | Prometheus | latest | Time series DB |
|
||||
| Visualization | Grafana | latest | Dashboards |
|
||||
|
||||
## Arquitetura de Arquivos
|
||||
|
||||
```
|
||||
monitoramento_atendimento/
|
||||
├── src/
|
||||
│ ├── app.py # Flask app principal
|
||||
│ ├── api_client.py # Cliente PersonalizeIT API
|
||||
│ ├── data_formatter.py # Formatting dados em 3 formatos
|
||||
│ └── config.py # Gerenciar configurações
|
||||
│
|
||||
├── config/
|
||||
│ └── .env.example # Template de env vars
|
||||
│
|
||||
├── grafana/
|
||||
│ └── provisioning/
|
||||
│ ├── datasources/ # Config datasources
|
||||
│ │ └── datasources.yml
|
||||
│ └── dashboards/ # Config dashboards
|
||||
│ ├── dashboard-provider.yml
|
||||
│ └── monitoring-dashboard.json
|
||||
│
|
||||
├── docker-compose.yml # Orquestração 3 containers
|
||||
├── Dockerfile # Build da app Python
|
||||
├── prometheus.yml # Config Prometheus
|
||||
├── requirements.txt # Dependências Python
|
||||
├── .gitignore # Git ignore config
|
||||
├── .env.local # Variaveis locais (exemplo)
|
||||
│
|
||||
├── README.md # Documentação principal
|
||||
├── QUICKSTART.md # Início rápido 3 passos
|
||||
├── INSTALL.md # Guia de instalação
|
||||
├── ARCHITECTURE.md # Explicação arquitetura
|
||||
├── EXAMPLES.md # Exemplos de uso
|
||||
└── TROUBLESHOOTING.md # Debug & FAQ
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```env
|
||||
# API Configuration
|
||||
API_BASE_URL=https://api-personalizeit.zapplataforma.chat
|
||||
API_LOGIN_ENDPOINT=/auth/login
|
||||
API_TICKETS_ENDPOINT=/tickets
|
||||
|
||||
# Credentials (REQUIRED)
|
||||
API_USERNAME=seu_email@exemplo.com
|
||||
API_PASSWORD=sua_senha
|
||||
|
||||
# Flask Config
|
||||
FLASK_PORT=5000
|
||||
FLASK_HOST=0.0.0.0
|
||||
DEBUG=False
|
||||
|
||||
# Refresh interval (seconds)
|
||||
REFRESH_INTERVAL=30
|
||||
|
||||
# Queue IDs (comma-separated)
|
||||
QUEUE_IDS=-1,1,2,3,4,5,7
|
||||
```
|
||||
|
||||
## Endpoints REST
|
||||
|
||||
| Método | Path | Resposta | Uso |
|
||||
|--------|------|----------|-----|
|
||||
| GET | / | JSON status | Verificar app |
|
||||
| GET | /health | JSON health | Health check |
|
||||
| GET | /api/tickets | JSON tickets | Grafana JSON DS |
|
||||
| GET | /api/summary | JSON stats | Resumo dados |
|
||||
| GET | /api/timeseries | JSON time series | Time series |
|
||||
| GET | /metrics | Text Prometheus | Prometheus scrape |
|
||||
|
||||
## Fluxo de Requisição
|
||||
|
||||
```
|
||||
1. Cliente HTTP (Grafana/curl)
|
||||
↓
|
||||
2. Flask app.py
|
||||
- Recebe GET request
|
||||
- Chama update_tickets()
|
||||
↓
|
||||
3. APIClient.login()
|
||||
- POST /auth/login
|
||||
- Recebe bearer token
|
||||
- Configura header Authorization
|
||||
↓
|
||||
4. APIClient.get_all_tickets()
|
||||
- GET /tickets com params
|
||||
- Loop por páginas
|
||||
- Junta resultados
|
||||
↓
|
||||
5. DataFormatter.*()
|
||||
- Formata conforme tipo
|
||||
- JSON / Prometheus / TimeSeries
|
||||
↓
|
||||
6. Flask app.py
|
||||
- Retorna response formatada
|
||||
- Content-Type apropriado
|
||||
↓
|
||||
7. Cliente recebe dados
|
||||
- JSON → Parse browser/Grafana
|
||||
- Prometheus → Prometheus scrape
|
||||
```
|
||||
|
||||
## Cache Strategy
|
||||
|
||||
```python
|
||||
# Em app.py
|
||||
last_update = None
|
||||
cached_tickets = []
|
||||
cached_json = None
|
||||
cached_metrics = None
|
||||
CACHE_DURATION = timedelta(seconds=Config.REFRESH_INTERVAL)
|
||||
|
||||
# Lógica:
|
||||
if last_update is None or (now - last_update) > CACHE_DURATION:
|
||||
# Atualizar do servidor
|
||||
# Refrescar cache
|
||||
last_update = now
|
||||
else:
|
||||
# Retornar cache
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
try:
|
||||
# Fazer algo
|
||||
response = requests.get(url)
|
||||
except requests.exceptions.RequestException as e:
|
||||
# Log erro
|
||||
logger.error(f"Error: {str(e)}")
|
||||
except Exception as e:
|
||||
# Log error genérico
|
||||
logger.error(f"Unexpected error: {str(e)}")
|
||||
finally:
|
||||
# Cleanup if needed
|
||||
```
|
||||
|
||||
## Docker Compose Services
|
||||
|
||||
```yaml
|
||||
services:
|
||||
monitoring-api:
|
||||
image: Python 3.11
|
||||
ports: 5000:5000
|
||||
env_file: .env
|
||||
networks: monitoring
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:latest
|
||||
ports: 3000:3000
|
||||
volumes: grafana-storage
|
||||
networks: monitoring
|
||||
depends_on: monitoring-api
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:latest
|
||||
ports: 9090:9090
|
||||
volumes: prometheus-storage
|
||||
networks: monitoring
|
||||
depends_on: monitoring-api
|
||||
```
|
||||
|
||||
## Prometheus Scrape Config
|
||||
|
||||
```yaml
|
||||
scrape_configs:
|
||||
- job_name: 'monitoring-api'
|
||||
static_configs:
|
||||
- targets: ['monitoring-api:5000']
|
||||
metrics_path: '/metrics'
|
||||
scrape_interval: 30s
|
||||
```
|
||||
|
||||
## Métricas Prometheus Expostas
|
||||
|
||||
```
|
||||
ticket_duration_seconds{ticket_id="...", contact_name="...", status="...", queue="..."} <valor>
|
||||
tickets_total <número>
|
||||
ticket_duration_seconds_avg <número>
|
||||
```
|
||||
|
||||
## Grafana Datasources
|
||||
|
||||
### JSON API
|
||||
- Type: JSON API
|
||||
- URL: http://monitoring-api:5000
|
||||
- Method: GET
|
||||
- Query format: JSON
|
||||
|
||||
### Prometheus
|
||||
- Type: Prometheus
|
||||
- URL: http://prometheus:9090
|
||||
- Access: Server
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
| Métrica | Valor | Notas |
|
||||
|---------|-------|-------|
|
||||
| Latência API | < 500ms | Com cache |
|
||||
| Atualização dados | 30s | Configurável |
|
||||
| Consumo memória | ~150MB | Grafana + API |
|
||||
| Espaço storage | Mínimo | Sem DB persistência |
|
||||
| Concorrência | 4 workers | Gunicorn configurável |
|
||||
| Max tickets | 1000+ | Depende de endpoints |
|
||||
|
||||
## Segurança
|
||||
|
||||
### HTTPS/TLS
|
||||
- SSL verificado em api_client.py
|
||||
- Adicionar proxy reverso para Grafana
|
||||
|
||||
### Authentication
|
||||
- Bearer token na API PersonalizeIT
|
||||
- Admin credentials Grafana (alterar padrão)
|
||||
|
||||
### Data Protection
|
||||
- .env não versionado
|
||||
- Variáveis de ambiente isoladas
|
||||
- Logs não expõem senhas
|
||||
|
||||
## Logging
|
||||
|
||||
### Nível INFO (padrão)
|
||||
```
|
||||
2026-02-09 12:30:00,000 - api_client - INFO - Successfully authenticated
|
||||
2026-02-09 12:30:01,000 - api_client - INFO - Successfully fetched tickets
|
||||
```
|
||||
|
||||
### Nível DEBUG (com DEBUG=True)
|
||||
```
|
||||
2026-02-09 12:30:00,000 - api_client - DEBUG - Request URL: ...
|
||||
2026-02-09 12:30:00,500 - api_client - DEBUG - Response: {"tickets": [...]}
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
# Unit test exemplo
|
||||
import unittest
|
||||
from api_client import APIClient
|
||||
|
||||
class TestAPIClient(unittest.TestCase):
|
||||
def test_login(self):
|
||||
client = APIClient()
|
||||
assert client.login() == True
|
||||
assert client.token is not None
|
||||
```
|
||||
|
||||
## CI/CD
|
||||
|
||||
### GitHub Actions (exemplo)
|
||||
```yaml
|
||||
name: Test
|
||||
on: [push]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Run tests
|
||||
run: python -m pytest
|
||||
- name: Build Docker
|
||||
run: docker build .
|
||||
```
|
||||
|
||||
## Backup & Recovery
|
||||
|
||||
### Dados Grafana
|
||||
```bash
|
||||
# Backup
|
||||
docker-compose exec grafana grafana-cli admin export-dashboard --file /backup/dashboard.json
|
||||
|
||||
# Restore
|
||||
docker-compose exec grafana grafana-cli admin import-dashboard --from /backup/dashboard.json
|
||||
```
|
||||
|
||||
### Dados Prometheus
|
||||
```bash
|
||||
# Backup
|
||||
docker cp prometheus:/prometheus /backup/prometheus-data
|
||||
|
||||
# Restore
|
||||
docker cp /backup/prometheus-data prometheus:/prometheus
|
||||
```
|
||||
|
||||
## Troubleshooting Checklist
|
||||
|
||||
- [ ] Docker rodando (`docker ps`)
|
||||
- [ ] .env configurado
|
||||
- [ ] API PersonalizeIT acessível
|
||||
- [ ] Credenciais válidas
|
||||
- [ ] Portas não em uso (3000, 5000, 9090)
|
||||
- [ ] Volumes com espaço
|
||||
- [ ] Network docker criada
|
||||
- [ ] Logs sem erros críticos
|
||||
|
||||
## Referências
|
||||
|
||||
- [Dockerfile best practices](https://docs.docker.com/develop/dev-best-practices/dockerfile_best-practices/)
|
||||
- [Flask production deployment](https://flask.palletsprojects.com/en/2.3.x/deploying/)
|
||||
- [Prometheus integration](https://prometheus.io/docs/instrumenting/writing_exporters/)
|
||||
- [Grafana data sources](https://grafana.com/docs/grafana/latest/datasources/)
|
||||
Reference in New Issue
Block a user