Translate README.md to English

This commit is contained in:
2025-09-26 19:12:57 -03:00
parent 0a5b8a03c6
commit cfe3d3006e

303
README.md
View File

@@ -1,201 +1,201 @@
# OpenShift Resource Governance Tool # OpenShift Resource Governance Tool
Uma ferramenta de governança de recursos para clusters OpenShift que vai além do que o Metrics Server e VPA oferecem, fornecendo validações, relatórios e recomendações consolidadas. A resource governance tool for OpenShift clusters that goes beyond what Metrics Server and VPA offer, providing validations, reports and consolidated recommendations.
## 🚀 Características ## 🚀 Features
- **Coleta Automática**: Coleta requests/limits de todos os pods/containers no cluster - **Automatic Collection**: Collects requests/limits from all pods/containers in the cluster
- **Validações Red Hat**: Valida best practices de capacity management - **Red Hat Validations**: Validates capacity management best practices
- **Integração VPA**: Consome recomendações do VPA em modo Off - **VPA Integration**: Consumes VPA recommendations in Off mode
- **Integração Prometheus**: Coleta métricas reais de consumo - **Prometheus Integration**: Collects real consumption metrics
- **Relatórios Consolidados**: Gera relatórios em JSON, CSV e PDF - **Consolidated Reports**: Generates reports in JSON, CSV and PDF
- **UI Web**: Interface simples para visualização e interação - **Web UI**: Simple interface for visualization and interaction
- **Aplicação de Recomendações**: Permite aprovar e aplicar recomendações - **Recommendation Application**: Allows approving and applying recommendations
## 📋 Requisitos ## 📋 Requirements
- OpenShift 4.x - OpenShift 4.x
- Prometheus (nativo no OCP) - Prometheus (native in OCP)
- VPA (opcional, para recomendações) - VPA (optional, for recommendations)
- Python 3.11+ - Python 3.11+
- Docker - Docker
- OpenShift CLI (oc) - OpenShift CLI (oc)
## 🛠️ Instalação ## 🛠️ Installation
### 🚀 Deploy Rápido (Recomendado) ### 🚀 Quick Deploy (Recommended)
```bash ```bash
# 1. Clone o repositório # 1. Clone the repository
git clone <repository-url> git clone <repository-url>
cd RequestsAndLimits cd RequestsAndLimits
# 2. Faça login no OpenShift # 2. Login to OpenShift
oc login <cluster-url> oc login <cluster-url>
# 3. Deploy completo (cria tudo automaticamente) # 3. Complete deploy (creates everything automatically)
./scripts/deploy-complete.sh ./scripts/deploy-complete.sh
``` ```
### 📋 Deploy Manual ### 📋 Manual Deploy
#### 1. Build da Imagem #### 1. Image Build
```bash ```bash
# Build local # Local build
./scripts/build.sh ./scripts/build.sh
# Build com tag específica # Build with specific tag
./scripts/build.sh v1.0.0 ./scripts/build.sh v1.0.0
# Build para registry específico # Build for specific registry
./scripts/build.sh latest seu-usuario ./scripts/build.sh latest your-username
``` ```
#### 2. Deploy no OpenShift #### 2. Deploy to OpenShift
```bash ```bash
# Aplicar todos os recursos # Apply all resources
oc apply -f k8s/ oc apply -f k8s/
# Aguardar deployment # Wait for deployment
oc rollout status deployment/resource-governance -n resource-governance oc rollout status deployment/resource-governance -n resource-governance
``` ```
#### 🚀 CI/CD Automático (Recomendado para Produção) #### 🚀 Automatic CI/CD (Recommended for Production)
```bash ```bash
# 1. Configurar secrets do GitHub # 1. Configure GitHub secrets
./scripts/setup-github-secrets.sh ./scripts/setup-github-secrets.sh
# 2. Fazer commit e push # 2. Commit and push
git add . git add .
git commit -m "Nova funcionalidade" git commit -m "New feature"
git push origin main git push origin main
# 3. GitHub Actions fará deploy automático! # 3. GitHub Actions will do automatic deploy!
``` ```
**Fluxo Automático:** **Automatic Flow:**
-**Push para main** → GitHub Actions detecta mudança -**Push to main** → GitHub Actions detects change
-**Build automático** → Nova imagem no Docker Hub -**Automatic build** → New image on Docker Hub
-**Deploy automático** → OpenShift atualiza deployment -**Automatic deploy** → OpenShift updates deployment
-**Rolling Update** → Zero downtime -**Rolling Update** → Zero downtime
-**Health Checks**Validação automática -**Health Checks**Automatic validation
#### 🔧 Deploy Manual (Desenvolvimento) #### 🔧 Manual Deploy (Development)
```bash ```bash
# Deploy com estratégia Blue-Green # Deploy with Blue-Green strategy
./scripts/blue-green-deploy.sh ./scripts/blue-green-deploy.sh
# Deploy com tag específica # Deploy with specific tag
./scripts/blue-green-deploy.sh v1.2.0 ./scripts/blue-green-deploy.sh v1.2.0
# Testar fluxo CI/CD localmente # Test CI/CD flow locally
./scripts/test-ci-cd.sh ./scripts/test-ci-cd.sh
``` ```
**Scripts para Desenvolvimento:** **Development Scripts:**
-**Controle total** sobre o processo -**Full control** over the process
-**Iteração rápida** durante desenvolvimento -**Fast iteration** during development
-**Debugging** mais fácil -**Easier debugging**
-**Testes locais** antes de fazer push -**Local tests** before pushing
#### Deploy Completo (Inicial) #### Complete Deploy (Initial)
```bash ```bash
# Deploy completo com ImagePullSecret (primeira vez) # Complete deploy with ImagePullSecret (first time)
./scripts/deploy-complete.sh ./scripts/deploy-complete.sh
``` ```
Este script irá: This script will:
- ✅ Criar namespace e RBAC - ✅ Create namespace and RBAC
- ✅ Configurar ImagePullSecret para Docker Hub - ✅ Configure ImagePullSecret for Docker Hub
- ✅ Deploy da aplicação - ✅ Deploy application
- ✅ Configurar Service e Route - ✅ Configure Service and Route
- ✅ Verificar se tudo está funcionando - ✅ Verify everything is working
#### Deploy Manual #### Manual Deploy
```bash ```bash
# Deploy padrão # Default deploy
./scripts/deploy.sh ./scripts/deploy.sh
# Deploy com tag específica # Deploy with specific tag
./scripts/deploy.sh v1.0.0 ./scripts/deploy.sh v1.0.0
# Deploy para registry específico # Deploy to specific registry
./scripts/deploy.sh latest seu-usuario ./scripts/deploy.sh latest your-username
``` ```
#### Undeploy #### Undeploy
```bash ```bash
# Remover completamente a aplicação # Completely remove application
./scripts/undeploy-complete.sh ./scripts/undeploy-complete.sh
``` ```
### 3. Acesso à Aplicação ### 3. Application Access
Após o deploy, acesse a aplicação através da rota criada: After deploy, access the application through the created route:
```bash ```bash
# Obter URL da rota # Get route URL
oc get route resource-governance-route -n resource-governance oc get route resource-governance-route -n resource-governance
# Acessar via browser # Access via browser
# https://resource-governance-route-resource-governance.apps.openshift.local # https://resource-governance-route-resource-governance.apps.openshift.local
``` ```
## 🔧 Configuração ## 🔧 Configuration
### ConfigMap ### ConfigMap
A aplicação é configurada através do ConfigMap `resource-governance-config`: The application is configured through the ConfigMap `resource-governance-config`:
```yaml ```yaml
data: data:
CPU_LIMIT_RATIO: "3.0" # Ratio padrão limit:request para CPU CPU_LIMIT_RATIO: "3.0" # Default limit:request ratio for CPU
MEMORY_LIMIT_RATIO: "3.0" # Ratio padrão limit:request para memória MEMORY_LIMIT_RATIO: "3.0" # Default limit:request ratio for memory
MIN_CPU_REQUEST: "10m" # Mínimo de CPU request MIN_CPU_REQUEST: "10m" # Minimum CPU request
MIN_MEMORY_REQUEST: "32Mi" # Mínimo de memória request MIN_MEMORY_REQUEST: "32Mi" # Minimum memory request
CRITICAL_NAMESPACES: | # Namespaces críticos para VPA CRITICAL_NAMESPACES: | # Critical namespaces for VPA
openshift-monitoring openshift-monitoring
openshift-ingress openshift-ingress
openshift-apiserver openshift-apiserver
PROMETHEUS_URL: "http://prometheus.openshift-monitoring.svc.cluster.local:9090" PROMETHEUS_URL: "http://prometheus.openshift-monitoring.svc.cluster.local:9090"
``` ```
### Variáveis de Ambiente ### Environment Variables
- `KUBECONFIG`: Caminho para kubeconfig (usado em desenvolvimento) - `KUBECONFIG`: Path to kubeconfig (used in development)
- `PROMETHEUS_URL`: URL do Prometheus - `PROMETHEUS_URL`: Prometheus URL
- `CPU_LIMIT_RATIO`: Ratio CPU limit:request - `CPU_LIMIT_RATIO`: CPU limit:request ratio
- `MEMORY_LIMIT_RATIO`: Ratio memória limit:request - `MEMORY_LIMIT_RATIO`: Memory limit:request ratio
- `MIN_CPU_REQUEST`: Mínimo de CPU request - `MIN_CPU_REQUEST`: Minimum CPU request
- `MIN_MEMORY_REQUEST`: Mínimo de memória request - `MIN_MEMORY_REQUEST`: Minimum memory request
## 📊 Uso ## 📊 Usage
### API Endpoints ### API Endpoints
#### Status do Cluster #### Cluster Status
```bash ```bash
GET /api/v1/cluster/status GET /api/v1/cluster/status
``` ```
#### Status de Namespace #### Namespace Status
```bash ```bash
GET /api/v1/namespace/{namespace}/status GET /api/v1/namespace/{namespace}/status
``` ```
#### Validações #### Validations
```bash ```bash
GET /api/v1/validations?namespace=default&severity=error GET /api/v1/validations?namespace=default&severity=error
``` ```
#### Recomendações VPA #### VPA Recommendations
```bash ```bash
GET /api/v1/vpa/recommendations?namespace=default GET /api/v1/vpa/recommendations?namespace=default
``` ```
#### Exportar Relatório #### Export Report
```bash ```bash
POST /api/v1/export POST /api/v1/export
Content-Type: application/json Content-Type: application/json
@@ -208,55 +208,55 @@ Content-Type: application/json
} }
``` ```
### Exemplos de Uso ### Usage Examples
#### 1. Verificar Status do Cluster #### 1. Check Cluster Status
```bash ```bash
curl https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/cluster/status curl https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/cluster/status
``` ```
#### 2. Exportar Relatório CSV #### 2. Export CSV Report
```bash ```bash
curl -X POST https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/export \ curl -X POST https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/export \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{"format": "csv", "includeVPA": true}' -d '{"format": "csv", "includeVPA": true}'
``` ```
#### 3. Ver Validações Críticas #### 3. View Critical Validations
```bash ```bash
curl "https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/validations?severity=critical" curl "https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/validations?severity=critical"
``` ```
## 🔍 Validações Implementadas ## 🔍 Implemented Validations
### 1. Requests Obrigatórios ### 1. Required Requests
- **Problema**: Pods sem requests definidos - **Problem**: Pods without defined requests
- **Severidade**: Error - **Severity**: Error
- **Recomendação**: Definir requests de CPU e memória - **Recommendation**: Define CPU and memory requests
### 2. Limits Recomendados ### 2. Recommended Limits
- **Problema**: Pods sem limits definidos - **Problem**: Pods without defined limits
- **Severidade**: Warning - **Severity**: Warning
- **Recomendação**: Definir limits para evitar consumo excessivo - **Recommendation**: Define limits to avoid excessive consumption
### 3. Ratio Limit:Request ### 3. Limit:Request Ratio
- **Problema**: Ratio muito alto ou baixo - **Problem**: Ratio too high or low
- **Severidade**: Warning/Error - **Severity**: Warning/Error
- **Recomendação**: Ajustar para ratio 3:1 - **Recommendation**: Adjust to 3:1 ratio
### 4. Valores Mínimos ### 4. Minimum Values
- **Problema**: Requests muito baixos - **Problem**: Requests too low
- **Severidade**: Warning - **Severity**: Warning
- **Recomendação**: Aumentar para valores mínimos - **Recommendation**: Increase to minimum values
### 5. Overcommit ### 5. Overcommit
- **Problema**: Requests excedem capacidade do cluster - **Problem**: Requests exceed cluster capacity
- **Severidade**: Critical - **Severity**: Critical
- **Recomendação**: Reduzir requests ou adicionar nós - **Recommendation**: Reduce requests or add nodes
## 📈 Relatórios ## 📈 Reports
### Formato JSON ### JSON Format
```json ```json
{ {
"timestamp": "2024-01-15T10:30:00Z", "timestamp": "2024-01-15T10:30:00Z",
@@ -274,16 +274,16 @@ curl "https://resource-governance-route-resource-governance.apps.openshift.local
} }
``` ```
### Formato CSV ### CSV Format
```csv ```csv
Pod Name,Namespace,Container Name,Validation Type,Severity,Message,Recommendation Pod Name,Namespace,Container Name,Validation Type,Severity,Message,Recommendation
pod-1,default,nginx,missing_requests,error,Container sem requests definidos,Definir requests de CPU e memória pod-1,default,nginx,missing_requests,error,Container without defined requests,Define CPU and memory requests
``` ```
## 🔐 Segurança ## 🔐 Security
### RBAC ### RBAC
A aplicação usa um ServiceAccount dedicado com permissões mínimas: The application uses a dedicated ServiceAccount with minimal permissions:
- **Pods**: get, list, watch, patch, update - **Pods**: get, list, watch, patch, update
- **Namespaces**: get, list, watch - **Namespaces**: get, list, watch
@@ -292,93 +292,92 @@ A aplicação usa um ServiceAccount dedicado com permissões mínimas:
- **Deployments/ReplicaSets**: get, list, watch, patch, update - **Deployments/ReplicaSets**: get, list, watch, patch, update
### Security Context ### Security Context
- Executa como usuário não-root (UID 1000) - Runs as non-root user (UID 1000)
- Usa SecurityContext com runAsNonRoot: true - Uses SecurityContext with runAsNonRoot: true
- Limita recursos com requests/limits - Limits resources with requests/limits
## 🐛 Troubleshooting ## 🐛 Troubleshooting
### Verificar Logs ### Check Logs
```bash ```bash
oc logs -f daemonset/resource-governance -n resource-governance oc logs -f daemonset/resource-governance -n resource-governance
``` ```
### Verificar Status dos Pods ### Check Pod Status
```bash ```bash
oc get pods -n resource-governance oc get pods -n resource-governance
oc describe pod <pod-name> -n resource-governance oc describe pod <pod-name> -n resource-governance
``` ```
### Verificar RBAC ### Check RBAC
```bash ```bash
oc auth can-i get pods --as=system:serviceaccount:resource-governance:resource-governance-sa oc auth can-i get pods --as=system:serviceaccount:resource-governance:resource-governance-sa
``` ```
### Testar Conectividade ### Test Connectivity
```bash ```bash
# Health check # Health check
curl https://resource-governance-route-resource-governance.apps.openshift.local/health curl https://resource-governance-route-resource-governance.apps.openshift.local/health
# Teste de API # API test
curl https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/cluster/status curl https://resource-governance-route-resource-governance.apps.openshift.local/api/v1/cluster/status
``` ```
## 🚀 Desenvolvimento ## 🚀 Development
### Executar Localmente ### Run Locally
```bash ```bash
# Instalar dependências # Install dependencies
pip install -r requirements.txt pip install -r requirements.txt
# Executar aplicação # Run application
python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8080 python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8080
``` ```
### Executar com Docker ### Run with Docker
```bash ```bash
# Build # Build
docker build -t resource-governance . docker build -t resource-governance .
# Executar # Run
docker run -p 8080:8080 resource-governance docker run -p 8080:8080 resource-governance
``` ```
### Testes ### Tests
```bash ```bash
# Testar importação # Test import
python -c "import app.main; print('OK')" python -c "import app.main; print('OK')"
# Testar API # Test API
curl http://localhost:8080/health curl http://localhost:8080/health
``` ```
## 📝 Roadmap ## 📝 Roadmap
### Próximas Versões ### Upcoming Versions
- [ ] UI Web com gráficos interativos - [ ] Web UI with interactive charts
- [ ] Relatórios PDF com gráficos - [ ] PDF reports with charts
- [ ] Regras customizadas por namespace - [ ] Custom rules per namespace
- [ ] Integração com GitOps (ArgoCD) - [ ] GitOps integration (ArgoCD)
- [ ] Notificações via Slack/Teams - [ ] Slack/Teams notifications
- [ ] Métricas customizadas do Prometheus - [ ] Custom Prometheus metrics
- [ ] Suporte a múltiplos clusters - [ ] Multi-cluster support
## 🤝 Contribuição ## 🤝 Contributing
1. Fork o projeto 1. Fork the project
2. Crie uma branch para sua feature (`git checkout -b feature/AmazingFeature`) 2. Create a branch for your feature (`git checkout -b feature/AmazingFeature`)
3. Commit suas mudanças (`git commit -m 'Add some AmazingFeature'`) 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push para a branch (`git push origin feature/AmazingFeature`) 4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Abra um Pull Request 5. Open a Pull Request
## 📄 Licença ## 📄 License
Este projeto está sob a licença MIT. Veja o arquivo [LICENSE](LICENSE) para detalhes. This project is under the MIT license. See the [LICENSE](LICENSE) file for details.
## 📞 Suporte ## 📞 Support
Para suporte e dúvidas: For support and questions:
- Abra uma issue no GitHub - Open an issue on GitHub
- Consulte a documentação do OpenShift - Consult OpenShift documentation
- Verifique os logs da aplicação - Check application logs
# Teste das secrets do GitHub Actions