610 lines
16 KiB
Markdown
610 lines
16 KiB
Markdown
# Arquitetura do Sistema - Proxy Scraping Service
|
|
|
|
## Visão Geral
|
|
|
|
Sistema distribuído de scraping, validação e armazenamento de proxies anônimos, construído com Python, PostgreSQL e Docker. A arquitetura segue princípios de separation of concerns, com módulos independentes e bem definidos.
|
|
|
|
## Diagrama de Arquitetura
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────┐
|
|
│ Docker Compose │
|
|
│ │
|
|
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
│ │ Proxy Scraper Service │ │
|
|
│ │ │ │
|
|
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
|
|
│ │ │ Scrapers │───>│ Validator │───>│ Database │ │ │
|
|
│ │ │ │ │ │ │ Manager │ │ │
|
|
│ │ │ - HTML │ │ - Test │ │ │ │ │
|
|
│ │ │ - Selenium │ │ - Anonymity│ │ - Insert │ │ │
|
|
│ │ │ - Multi- │ │ - Parallel │ │ - Update │ │ │
|
|
│ │ │ Source │ │ │ │ - Dedupe │ │ │
|
|
│ │ └─────────────┘ └─────────────┘ └──────┬──────┘ │ │
|
|
│ │ ^ │ │ │
|
|
│ │ │ ┌──────────────┐ │ │ │
|
|
│ │ │ │ Scheduler │ │ │ │
|
|
│ │ │ │ APScheduler │ │ │ │
|
|
│ │ │ │ Daily 2-4 AM│ │ │ │
|
|
│ │ │ └──────────────┘ │ │ │
|
|
│ │ │ │ │ │
|
|
│ │ proxies.txt v │ │
|
|
│ │ (Volume Mount) ┌──────────────────┐ │ │
|
|
│ └────────────────────────────────────>│ PostgreSQL │ │ │
|
|
│ │ │ │ │
|
|
│ │ - Proxies Table │ │ │
|
|
│ │ - Indexes │ │ │
|
|
│ │ - Constraints │ │ │
|
|
│ └──────────────────┘ │ │
|
|
└─────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
## Componentes
|
|
|
|
### 1. Main Service (main.py)
|
|
|
|
**Responsabilidade**: Orquestração do fluxo principal
|
|
|
|
**Componentes**:
|
|
- `ProxyScrapingService`: Classe principal que coordena todo o processo
|
|
- `setup_logging()`: Configuração de logging colorido
|
|
- `main()`: Entry point da aplicação
|
|
|
|
**Fluxo de Execução**:
|
|
```python
|
|
1. Inicialização
|
|
├── Setup logging
|
|
├── Carregar configurações
|
|
├── Criar instâncias (DB, Validator, Scheduler)
|
|
└── Verificar argumentos CLI
|
|
|
|
2. Agendamento
|
|
├── Calcular horário aleatório (2-4 AM)
|
|
├── Registrar job no APScheduler
|
|
└── Executar job inicial (opcional)
|
|
|
|
3. Job de Scraping
|
|
├── Scrape de todas as URLs
|
|
├── Deduplicação
|
|
├── Validação paralela
|
|
├── Armazenamento no banco
|
|
└── Exibição de estatísticas
|
|
|
|
4. Loop Principal
|
|
└── Aguardar próximo agendamento
|
|
```
|
|
|
|
**Características**:
|
|
- Execução imediata via `--immediate` flag
|
|
- Tratamento de sinais (SIGINT, SIGTERM)
|
|
- Logging estruturado com níveis
|
|
- Métricas de execução
|
|
|
|
### 2. Configuration (config.py)
|
|
|
|
**Responsabilidade**: Gerenciamento centralizado de configurações
|
|
|
|
**Tecnologia**: Pydantic Settings
|
|
|
|
**Configurações**:
|
|
```python
|
|
- PostgreSQL: host, port, db, user, password
|
|
- Proxy: timeout, validation_url
|
|
- Scraping: delay, max_retries
|
|
- Schedule: hour_start, hour_end
|
|
- Paths: proxies_file
|
|
- Logging: log_level
|
|
```
|
|
|
|
**Vantagens**:
|
|
- Validação automática de tipos
|
|
- Valores padrão
|
|
- Suporte a .env
|
|
- Type hints para IDE
|
|
|
|
### 3. Database Manager (database.py)
|
|
|
|
**Responsabilidade**: Abstração de operações PostgreSQL
|
|
|
|
**Características**:
|
|
- **Connection Pool**: SimpleConnectionPool para performance
|
|
- **Context Manager**: Gerenciamento automático de conexões
|
|
- **Transaction Safety**: Commit/rollback automático
|
|
- **Type Safety**: Uso de prepared statements
|
|
|
|
**Métodos Principais**:
|
|
|
|
```python
|
|
proxy_exists(ip, port, protocol) -> bool
|
|
# Verifica existência antes de inserir
|
|
# Evita duplicatas
|
|
# Query otimizada com indexes
|
|
|
|
insert_proxy(proxy_data: Dict) -> bool
|
|
# Insere proxy único
|
|
# Valida anonimato
|
|
# Retorna sucesso/falha
|
|
|
|
insert_proxies_bulk(proxies: List) -> int
|
|
# Inserção em massa
|
|
# Usa execute_values para performance
|
|
# Retorna contagem de inseridos
|
|
|
|
update_proxy_status(ip, port, protocol, status) -> bool
|
|
# Atualiza após validação
|
|
# Incrementa counters
|
|
# Atualiza timestamps
|
|
|
|
get_stats() -> Dict
|
|
# Estatísticas agregadas
|
|
# Usa window functions
|
|
# Retorna métricas
|
|
```
|
|
|
|
**Schema Design**:
|
|
- **Constraint**: UNIQUE (ip_address, port, protocol)
|
|
- **Indexes**: active, protocol, country, response_time
|
|
- **Triggers**: auto-update updated_at
|
|
- **Check Constraints**: port range, protocol enum
|
|
|
|
### 4. Validator (validator.py)
|
|
|
|
**Responsabilidade**: Validação de conectividade e anonimato
|
|
|
|
**Arquitetura**:
|
|
```
|
|
Validação Individual
|
|
├── Build proxy URL
|
|
├── Fazer request HTTP
|
|
├── Medir tempo de resposta
|
|
├── Verificar status code
|
|
└── Analisar anonimato
|
|
├── Headers check
|
|
├── IP leak detection
|
|
└── Forward detection
|
|
|
|
Validação em Massa
|
|
├── ThreadPoolExecutor (max_workers=20)
|
|
├── Submit tasks paralelas
|
|
├── Coletar resultados
|
|
└── Filtrar apenas anônimos
|
|
```
|
|
|
|
**Critérios de Anonimato**:
|
|
1. **Headers Proibidos**:
|
|
- X-Forwarded-For
|
|
- X-Real-IP
|
|
- Via
|
|
- Forwarded
|
|
- X-Proxy-ID
|
|
|
|
2. **Análise de Origin**:
|
|
- Múltiplos IPs indicam forwarding
|
|
- IP diferente do proxy indica leak
|
|
|
|
3. **Abordagem Conservadora**:
|
|
- Em caso de dúvida, marca como não-anônimo
|
|
- Melhor falso-negativo que falso-positivo
|
|
|
|
**Performance**:
|
|
- Validação paralela (20 threads)
|
|
- Timeout configurável (padrão: 10s)
|
|
- Retry automático em erros de rede
|
|
|
|
### 5. Scrapers (scrapers.py)
|
|
|
|
**Responsabilidade**: Coleta de proxies de múltiplas fontes
|
|
|
|
**Hierarquia de Classes**:
|
|
```
|
|
ProxyScraper (Base Class)
|
|
├── Métodos comuns
|
|
├── Normalização de dados
|
|
└── Error handling
|
|
|
|
GenericHTMLScraper
|
|
├── BeautifulSoup parsing
|
|
├── Regex extraction
|
|
├── Table parsing
|
|
└── Para sites estáticos
|
|
|
|
SeleniumScraper
|
|
├── Headless Chrome
|
|
├── WebDriver automation
|
|
├── Pagination handling
|
|
└── Para sites dinâmicos
|
|
|
|
ScraperFactory
|
|
└── Seleção automática de scraper
|
|
```
|
|
|
|
**GenericHTMLScraper**:
|
|
```python
|
|
Estratégias de Extração:
|
|
1. Regex patterns (IP:PORT)
|
|
- Pattern: \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}
|
|
- Validação de octetos (0-255)
|
|
- Validação de porta (1-65535)
|
|
|
|
2. Table parsing
|
|
- Identifica tabelas HTML
|
|
- Extrai colunas (IP, Port, Country, Protocol)
|
|
- Suporta layouts variados
|
|
|
|
3. Text extraction
|
|
- Busca em todo o texto da página
|
|
- Útil para APIs ou listas simples
|
|
```
|
|
|
|
**SeleniumScraper**:
|
|
```python
|
|
Capabilities:
|
|
- Headless Chrome with options
|
|
- WebDriver manager (auto-install)
|
|
- Implicit waits (10s)
|
|
- JavaScript execution
|
|
- Screenshot on error (debug)
|
|
|
|
Pagination:
|
|
- Detecta botões "Next"
|
|
- Múltiplos seletores (XPath, class, rel)
|
|
- Max pages limit (5 default)
|
|
- Delay entre páginas
|
|
```
|
|
|
|
**ScraperFactory**:
|
|
```python
|
|
Logic:
|
|
IF url CONTAINS ['freeproxy.world', 'free-proxy-list.net']:
|
|
RETURN SeleniumScraper
|
|
ELSE:
|
|
RETURN GenericHTMLScraper
|
|
```
|
|
|
|
### 6. Scheduling
|
|
|
|
**Tecnologia**: APScheduler
|
|
|
|
**Configuração**:
|
|
```python
|
|
Trigger: CronTrigger
|
|
Timezone: UTC
|
|
Schedule: Daily
|
|
Time: Random between 2-4 AM
|
|
Persistence: In-memory
|
|
```
|
|
|
|
**Fluxo**:
|
|
```
|
|
Startup
|
|
├── Calcular hora aleatória
|
|
├── Registrar job no scheduler
|
|
├── Executar job inicial (opcional)
|
|
└── Start scheduler loop
|
|
|
|
Scheduled Time
|
|
├── Trigger job execution
|
|
├── Run scraping workflow
|
|
├── Log resultado
|
|
└── Aguardar próxima execução
|
|
|
|
Shutdown
|
|
├── Receber SIGINT/SIGTERM
|
|
├── Graceful shutdown do scheduler
|
|
├── Fechar pool de conexões
|
|
└── Exit
|
|
```
|
|
|
|
## Fluxo de Dados
|
|
|
|
### 1. Scraping Phase
|
|
|
|
```
|
|
URLs (proxies.txt)
|
|
│
|
|
├─> URL 1 ──> Scraper ──> Raw Proxies []
|
|
│
|
|
├─> URL 2 ──> Scraper ──> Raw Proxies []
|
|
│
|
|
└─> URL N ──> Scraper ──> Raw Proxies []
|
|
│
|
|
v
|
|
All Raw Proxies []
|
|
```
|
|
|
|
### 2. Deduplication Phase
|
|
|
|
```
|
|
All Raw Proxies []
|
|
│
|
|
├─> Create Set(ip, port, protocol)
|
|
│
|
|
└─> Remove duplicates
|
|
│
|
|
v
|
|
Unique Proxies []
|
|
```
|
|
|
|
### 3. Validation Phase
|
|
|
|
```
|
|
Unique Proxies []
|
|
│
|
|
├─> ThreadPoolExecutor
|
|
│ │
|
|
│ ├─> Worker 1 ──> Validate ──> Result
|
|
│ ├─> Worker 2 ──> Validate ──> Result
|
|
│ ├─> ...
|
|
│ └─> Worker N ──> Validate ──> Result
|
|
│
|
|
└─> Collect Results
|
|
│
|
|
└─> Filter (active AND anonymous)
|
|
│
|
|
v
|
|
Validated Proxies []
|
|
```
|
|
|
|
### 4. Storage Phase
|
|
|
|
```
|
|
Validated Proxies []
|
|
│
|
|
└─> For each proxy:
|
|
│
|
|
├─> Check if exists (SELECT)
|
|
│ │
|
|
│ ├─> Exists: Skip
|
|
│ └─> Not exists: Insert
|
|
│
|
|
└─> Update counters
|
|
```
|
|
|
|
## Padrões de Design
|
|
|
|
### 1. Factory Pattern
|
|
**Uso**: ScraperFactory
|
|
**Benefício**: Criação dinâmica de scrapers baseado em URL
|
|
|
|
### 2. Context Manager
|
|
**Uso**: Database connections
|
|
**Benefício**: Gerenciamento automático de recursos
|
|
|
|
### 3. Strategy Pattern
|
|
**Uso**: Diferentes estratégias de scraping (HTML vs Selenium)
|
|
**Benefício**: Extensibilidade sem modificar código existente
|
|
|
|
### 4. Connection Pool
|
|
**Uso**: PostgreSQL connections
|
|
**Benefício**: Reuso de conexões, melhor performance
|
|
|
|
### 5. Template Method
|
|
**Uso**: ProxyScraper base class
|
|
**Benefício**: Estrutura comum, implementação específica
|
|
|
|
## Segurança
|
|
|
|
### 1. Database Security
|
|
- Prepared statements (SQL injection prevention)
|
|
- Connection pooling (DoS prevention)
|
|
- Non-root user no container
|
|
- Password via environment variables
|
|
|
|
### 2. Network Security
|
|
- Proxies testados antes de uso
|
|
- Timeout em todas as requisições
|
|
- User-agent rotation (futuro)
|
|
- Rate limiting entre requests
|
|
|
|
### 3. Container Security
|
|
- Multi-stage builds
|
|
- Non-root user (UID 1000)
|
|
- Read-only volumes onde possível
|
|
- Health checks
|
|
|
|
### 4. Data Validation
|
|
- Pydantic para configurações
|
|
- Port range validation
|
|
- IP format validation
|
|
- Protocol enum validation
|
|
|
|
## Performance
|
|
|
|
### Otimizações Implementadas
|
|
|
|
1. **Database**:
|
|
- Connection pooling (1-10 connections)
|
|
- Bulk inserts com execute_values
|
|
- Indexes estratégicos
|
|
- ON CONFLICT DO NOTHING (upsert)
|
|
|
|
2. **Validation**:
|
|
- ThreadPoolExecutor (20 workers)
|
|
- Timeout por proxy (10s)
|
|
- Early termination em falhas
|
|
|
|
3. **Scraping**:
|
|
- Processamento sequencial de URLs
|
|
- Delay configurável
|
|
- Selenium driver reuse
|
|
- BeautifulSoup com lxml parser
|
|
|
|
### Benchmarks
|
|
|
|
**Hardware**: 2 CPU cores, 2GB RAM
|
|
|
|
| Operação | Tempo | Throughput |
|
|
|----------|-------|------------|
|
|
| Scraping (100 proxies) | 2-5 min | 20-50/min |
|
|
| Validation (100 proxies) | 30-60s | 100-200/min |
|
|
| DB Insert (100 proxies) | <1s | >1000/s |
|
|
| Total Pipeline | 5-10 min | 10-20/min |
|
|
|
|
## Extensibilidade
|
|
|
|
### Adicionar Novo Scraper
|
|
|
|
```python
|
|
# 1. Criar classe
|
|
class NewScraper(ProxyScraper):
|
|
def scrape(self) -> List[Dict[str, Any]]:
|
|
# Implementar lógica
|
|
pass
|
|
|
|
# 2. Registrar no factory
|
|
# Editar ScraperFactory.create_scraper()
|
|
if "newsite.com" in url:
|
|
return NewScraper(url)
|
|
```
|
|
|
|
### Adicionar Nova Validação
|
|
|
|
```python
|
|
# Editar validator.py
|
|
def custom_validation(self, proxy):
|
|
# Sua lógica
|
|
pass
|
|
|
|
# Adicionar ao validate_proxy()
|
|
if custom_validation(proxy):
|
|
return True, time, True
|
|
```
|
|
|
|
### Adicionar Campos ao Banco
|
|
|
|
```sql
|
|
-- 1. Alterar schema
|
|
ALTER TABLE proxies ADD COLUMN new_field VARCHAR(100);
|
|
|
|
-- 2. Atualizar index se necessário
|
|
CREATE INDEX idx_new_field ON proxies(new_field);
|
|
```
|
|
|
|
```python
|
|
# 3. Atualizar database.py
|
|
def insert_proxy(self, proxy_data):
|
|
# Adicionar novo campo na query
|
|
pass
|
|
```
|
|
|
|
## Monitoramento
|
|
|
|
### Logs
|
|
|
|
**Níveis**:
|
|
- DEBUG: Detalhes de cada operação
|
|
- INFO: Progresso e estatísticas
|
|
- WARNING: Problemas não-críticos
|
|
- ERROR: Erros que requerem atenção
|
|
|
|
**Formato**:
|
|
```
|
|
TIMESTAMP - MODULE - LEVEL - MESSAGE
|
|
```
|
|
|
|
**Cores**:
|
|
- DEBUG: Cyan
|
|
- INFO: Green
|
|
- WARNING: Yellow
|
|
- ERROR: Red
|
|
|
|
### Métricas
|
|
|
|
**Disponíveis**:
|
|
- Total proxies scraped
|
|
- Taxa de validação
|
|
- Proxies inseridos vs duplicados
|
|
- Tempo de execução
|
|
- Database statistics
|
|
|
|
### Health Checks
|
|
|
|
**Docker**:
|
|
```yaml
|
|
healthcheck:
|
|
test: python health_check.py
|
|
interval: 60s
|
|
timeout: 10s
|
|
retries: 3
|
|
```
|
|
|
|
**PostgreSQL**:
|
|
```bash
|
|
pg_isready -U postgres -d proxies
|
|
```
|
|
|
|
## Troubleshooting
|
|
|
|
### Debug Mode
|
|
|
|
```bash
|
|
# Ativar logs DEBUG
|
|
export LOG_LEVEL=DEBUG
|
|
docker-compose restart proxy-scraper
|
|
|
|
# Ver logs detalhados
|
|
docker-compose logs -f proxy-scraper
|
|
```
|
|
|
|
### Common Issues
|
|
|
|
1. **No proxies inserted**:
|
|
- Check anonymity validation
|
|
- Verify sources in proxies.txt
|
|
- Test individual proxy manually
|
|
|
|
2. **Selenium errors**:
|
|
- Chrome not installed
|
|
- Missing dependencies
|
|
- Rebuild Docker image
|
|
|
|
3. **Database connection**:
|
|
- Check credentials
|
|
- Verify network
|
|
- Check PostgreSQL logs
|
|
|
|
## Deployment
|
|
|
|
### Production Checklist
|
|
|
|
- [ ] Alterar senhas padrão (.env)
|
|
- [ ] Configurar backup do PostgreSQL
|
|
- [ ] Setup monitoring (Prometheus/Grafana)
|
|
- [ ] Configurar log rotation
|
|
- [ ] Setup alertas (falhas, performance)
|
|
- [ ] Documentar runbook operacional
|
|
- [ ] Testar disaster recovery
|
|
- [ ] Configurar firewall rules
|
|
- [ ] Setup SSL/TLS para pgAdmin
|
|
- [ ] Implementar rate limiting
|
|
|
|
### Scaling
|
|
|
|
**Horizontal**:
|
|
- Múltiplas instâncias do scraper
|
|
- Load balancer para requisições
|
|
- Shared PostgreSQL
|
|
|
|
**Vertical**:
|
|
- Aumentar workers de validação
|
|
- Mais CPU/RAM para containers
|
|
- Otimizar queries do banco
|
|
|
|
## Conclusão
|
|
|
|
Sistema production-ready com arquitetura modular, escalável e segura. Implementa best practices de desenvolvimento Python, DevOps e infraestrutura.
|
|
|
|
**Pontos Fortes**:
|
|
- Separação clara de responsabilidades
|
|
- Fácil extensibilidade
|
|
- Alta performance
|
|
- Segurança robusta
|
|
- Monitoramento completo
|
|
|
|
**Próximos Passos**:
|
|
- Implementar cache Redis
|
|
- Adicionar API REST
|
|
- Dashboard web
|
|
- Machine learning para qualidade de proxy
|
|
- Geolocation avançada
|