aula-12: Victoria Metrics + Grafana via GitOps
Stack completo de observabilidade: - Victoria Metrics (vmsingle, vmagent, vmalert) - Grafana com dashboards built-in - Alertas customizados (PVC, pods, nodes, deployments) - pvc-autoresizer para expansão automática de volumes - Queries PromQL documentadas Instalação via ArgoCD seguindo padrão GitOps da aula-11.
This commit is contained in:
446
aula-12/README.md
Normal file
446
aula-12/README.md
Normal file
@@ -0,0 +1,446 @@
|
||||
# Aula 12 - Victoria Metrics (Observabilidade)
|
||||
|
||||
Stack completo de monitoramento com Victoria Metrics, Grafana e alertas, instalado via **GitOps com ArgoCD**.
|
||||
|
||||
## Por que Victoria Metrics?
|
||||
|
||||
### Alternativa ao Prometheus
|
||||
|
||||
Victoria Metrics oferece **compatibilidade total** com Prometheus, mas com vantagens:
|
||||
|
||||
| Feature | Prometheus | Victoria Metrics |
|
||||
|---------|------------|------------------|
|
||||
| Consumo de RAM | Alto | ~7x menor |
|
||||
| Compressão | Básica | ~10x melhor |
|
||||
| Velocidade | Normal | ~2-3x mais rápido |
|
||||
| Setup HA | Complexo (Thanos) | Simples |
|
||||
| API | PromQL | PromQL + extensões |
|
||||
|
||||
### Diferença da Aula-05
|
||||
|
||||
| Aula-05 (KEDA) | Aula-12 (Observabilidade) |
|
||||
|----------------|---------------------------|
|
||||
| Foco: Auto-scaling | Foco: Monitoramento |
|
||||
| VM básico (sem Grafana) | VM + Grafana completo |
|
||||
| Queries para KEDA | Queries para operações |
|
||||
| Ambiente local | Cluster Hetzner + GitOps |
|
||||
|
||||
## Arquitetura
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Victoria Metrics Stack │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
|
||||
│ │ vmagent │ │ vmsingle │ │ Grafana │ │
|
||||
│ │ (coleta) │──│ (storage) │──│ (visualização) │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ ┌──────┴──────┐ ┌─────┴─────┐ ┌─────┴─────┐ │
|
||||
│ │ node-export │ │ vmalert │ │ Dashboards│ │
|
||||
│ │ kube-state │ │ (alertas) │ │ pré-config│ │
|
||||
│ └─────────────┘ └───────────┘ └───────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Componentes
|
||||
|
||||
| Componente | Função |
|
||||
|------------|--------|
|
||||
| **vmsingle** | Armazena métricas (modo single-node) |
|
||||
| **vmagent** | Coleta métricas via scrape |
|
||||
| **vmalert** | Avalia regras e dispara alertas |
|
||||
| **Grafana** | Interface de visualização |
|
||||
| **kube-state-metrics** | Métricas de objetos K8s (pods, deployments) |
|
||||
| **node-exporter** | Métricas de nodes (CPU, RAM, disco) |
|
||||
|
||||
## Pré-requisitos
|
||||
|
||||
- Cluster Kubernetes Hetzner (aula-08)
|
||||
- ArgoCD instalado (aula-11)
|
||||
- GitLab com grupo `factory` (aula-11)
|
||||
|
||||
## Estrutura
|
||||
|
||||
```
|
||||
aula-12/
|
||||
├── README.md # Este arquivo
|
||||
├── setup.sh # Instalação automatizada
|
||||
├── cleanup.sh # Remoção via ArgoCD
|
||||
│
|
||||
├── gitops/ # Conteúdo para GitLab
|
||||
│ └── apps/
|
||||
│ └── victoria-metrics/
|
||||
│ ├── Chart.yaml # Helm chart wrapper
|
||||
│ ├── values.yaml # Configurações do stack
|
||||
│ └── templates/
|
||||
│ └── alerts.yaml # VMRule customizado
|
||||
│
|
||||
├── argocd/
|
||||
│ └── application.yaml # ArgoCD Application CRD
|
||||
│
|
||||
├── alerts/
|
||||
│ └── vmalert-rules.yaml # Referência (aplicada via gitops/)
|
||||
│
|
||||
└── queries/
|
||||
└── useful-queries.md # Queries PromQL úteis
|
||||
```
|
||||
|
||||
## Instalação (GitOps)
|
||||
|
||||
### 1. Executar Setup
|
||||
|
||||
```bash
|
||||
cd aula-12
|
||||
./setup.sh
|
||||
```
|
||||
|
||||
O script:
|
||||
1. Cria projeto `factory/monitoring` no GitLab
|
||||
2. Faz push dos manifests GitOps
|
||||
3. Cria namespace `monitoring`
|
||||
4. Aplica ArgoCD Application
|
||||
5. Aguarda sincronização
|
||||
|
||||
### 2. Fluxo GitOps
|
||||
|
||||
```
|
||||
┌──────────────────┐ push ┌──────────────────┐
|
||||
│ aula-12/ │ ──────────► │ factory/monitoring│
|
||||
│ gitops/ │ │ (GitLab) │
|
||||
└──────────────────┘ └────────┬─────────┘
|
||||
│
|
||||
sync │
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ ArgoCD │
|
||||
└────────┬─────────┘
|
||||
│
|
||||
apply │
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ Kubernetes │
|
||||
│ ns: monitoring │
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
### 3. Verificar Instalação
|
||||
|
||||
```bash
|
||||
# Status do ArgoCD Application
|
||||
kubectl get application monitoring -n argocd
|
||||
|
||||
# Pods rodando
|
||||
kubectl get pods -n monitoring
|
||||
|
||||
# Serviços
|
||||
kubectl get svc -n monitoring
|
||||
```
|
||||
|
||||
## Configuração de DNS
|
||||
|
||||
Antes de acessar o Grafana, configure o DNS:
|
||||
|
||||
```bash
|
||||
# Obter IP do Load Balancer
|
||||
kubectl get svc -n ingress-nginx ingress-nginx-controller -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
|
||||
```
|
||||
|
||||
Configure o registro DNS:
|
||||
- **grafana.kube.quest** → IP do Load Balancer (ex: 49.13.44.102)
|
||||
|
||||
## Acessar Grafana
|
||||
|
||||
### Via Ingress (Recomendado)
|
||||
|
||||
Após configurar o DNS:
|
||||
- **URL**: https://grafana.kube.quest
|
||||
- Certificado TLS via Let's Encrypt (automático)
|
||||
|
||||
### Credenciais
|
||||
|
||||
- **Usuário**: admin
|
||||
- **Senha**: (gerada automaticamente)
|
||||
|
||||
```bash
|
||||
# Obter senha do Grafana
|
||||
kubectl get secret monitoring-grafana -n monitoring \
|
||||
-o jsonpath='{.data.admin-password}' | base64 -d; echo
|
||||
```
|
||||
|
||||
### Via Port-Forward (Alternativa)
|
||||
|
||||
Se não tiver DNS configurado:
|
||||
|
||||
```bash
|
||||
# Port-forward Grafana
|
||||
kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80
|
||||
|
||||
# Acessar
|
||||
open http://localhost:3000
|
||||
```
|
||||
|
||||
## Dashboards Incluídos
|
||||
|
||||
O chart `victoria-metrics-k8s-stack` já inclui **20+ dashboards** via Grafana sidecar:
|
||||
|
||||
### Dashboards Principais
|
||||
|
||||
| Dashboard | Descrição |
|
||||
|-----------|-----------|
|
||||
| **Kubernetes / Views / Global** | Visão geral do cluster |
|
||||
| **Kubernetes / Views / Namespaces** | Recursos por namespace |
|
||||
| **Kubernetes / Views / Nodes** | CPU, memória, disco por node |
|
||||
| **Kubernetes / Views / Pods** | Métricas detalhadas de pods |
|
||||
| **Node Exporter / Nodes** | Métricas de sistema operacional |
|
||||
| **Node Exporter / USE Method / Node** | Utilização, Saturação, Erros |
|
||||
| **VictoriaMetrics / vmagent** | Status da coleta de métricas |
|
||||
| **VictoriaMetrics / vmsingle** | Status do storage de métricas |
|
||||
|
||||
### Ver Todos os Dashboards
|
||||
|
||||
No Grafana:
|
||||
1. Menu lateral → **Dashboards**
|
||||
2. Ou acesse: https://grafana.kube.quest/dashboards
|
||||
|
||||
## Alertas Configurados
|
||||
|
||||
| Alerta | Condição | Severidade |
|
||||
|--------|----------|------------|
|
||||
| PVCAlmostFull | PVC > 80% | warning |
|
||||
| PVCFull | PVC > 95% | critical |
|
||||
| PodCrashLooping | Restarts > 5/hora | warning |
|
||||
| PodNotReady | Pod não Ready > 5min | warning |
|
||||
| NodeHighCPU | CPU > 90% por 5min | warning |
|
||||
| NodeLowMemory | RAM livre < 10% | warning |
|
||||
| NodeDiskFull | Disco > 85% | critical |
|
||||
|
||||
### Verificar Alertas
|
||||
|
||||
```bash
|
||||
# Ver alertas ativos
|
||||
kubectl get vmrule -n monitoring
|
||||
|
||||
# Ver status no VMAlert
|
||||
kubectl port-forward -n monitoring svc/vmalert 8880:8880
|
||||
open http://localhost:8880/alerts
|
||||
```
|
||||
|
||||
## Queries PromQL Úteis
|
||||
|
||||
### Uso de Storage
|
||||
|
||||
```promql
|
||||
# Uso de PVC em porcentagem
|
||||
kubelet_volume_stats_used_bytes / kubelet_volume_stats_capacity_bytes * 100
|
||||
|
||||
# PVCs acima de 80%
|
||||
(kubelet_volume_stats_used_bytes / kubelet_volume_stats_capacity_bytes) > 0.8
|
||||
|
||||
# Espaço disponível por PVC
|
||||
kubelet_volume_stats_available_bytes
|
||||
```
|
||||
|
||||
### CPU e Memória
|
||||
|
||||
```promql
|
||||
# CPU por pod (cores)
|
||||
sum(rate(container_cpu_usage_seconds_total{container!=""}[5m])) by (pod, namespace)
|
||||
|
||||
# Memória por namespace
|
||||
sum(container_memory_working_set_bytes{container!=""}) by (namespace)
|
||||
|
||||
# CPU por node (%)
|
||||
100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
|
||||
```
|
||||
|
||||
### Pods e Containers
|
||||
|
||||
```promql
|
||||
# Pods restartando na última hora
|
||||
sum(increase(kube_pod_container_status_restarts_total[1h])) by (pod, namespace) > 0
|
||||
|
||||
# Pods não Ready
|
||||
kube_pod_status_ready{condition="false"}
|
||||
|
||||
# Pods em CrashLoopBackOff
|
||||
kube_pod_container_status_waiting_reason{reason="CrashLoopBackOff"}
|
||||
```
|
||||
|
||||
### Network
|
||||
|
||||
```promql
|
||||
# Bytes recebidos por pod
|
||||
sum(rate(container_network_receive_bytes_total[5m])) by (pod)
|
||||
|
||||
# Bytes enviados por pod
|
||||
sum(rate(container_network_transmit_bytes_total[5m])) by (pod)
|
||||
```
|
||||
|
||||
## Integrações
|
||||
|
||||
### Com KEDA (Aula-05)
|
||||
|
||||
Victoria Metrics pode alimentar KEDA para auto-scaling:
|
||||
|
||||
```yaml
|
||||
triggers:
|
||||
- type: prometheus
|
||||
metadata:
|
||||
serverAddress: http://vmsingle-vm.monitoring:8429
|
||||
query: sum(kube_deployment_status_replicas_unavailable{deployment="myapp"})
|
||||
threshold: '1'
|
||||
```
|
||||
|
||||
### Com Alertmanager
|
||||
|
||||
Para notificações (Slack, Email, PagerDuty):
|
||||
|
||||
```yaml
|
||||
# values.yaml
|
||||
vmalert:
|
||||
alertmanager:
|
||||
url: http://alertmanager.monitoring:9093
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Grafana não carrega dashboards
|
||||
|
||||
```bash
|
||||
# Verificar configmap de dashboards
|
||||
kubectl get configmap -n monitoring | grep dashboard
|
||||
|
||||
# Verificar logs do sidecar
|
||||
kubectl logs -n monitoring -l app.kubernetes.io/name=grafana -c sc-dashboard
|
||||
```
|
||||
|
||||
### Métricas não aparecem
|
||||
|
||||
```bash
|
||||
# Verificar targets do vmagent
|
||||
kubectl port-forward -n monitoring svc/vmagent 8429:8429
|
||||
open http://localhost:8429/targets
|
||||
|
||||
# Verificar scrape configs
|
||||
kubectl get configmap -n monitoring vmagent-config -o yaml
|
||||
```
|
||||
|
||||
### VMAlert não dispara alertas
|
||||
|
||||
```bash
|
||||
# Verificar regras carregadas
|
||||
kubectl port-forward -n monitoring svc/vmalert 8880:8880
|
||||
open http://localhost:8880/rules
|
||||
|
||||
# Verificar logs
|
||||
kubectl logs -n monitoring -l app=vmalert
|
||||
```
|
||||
|
||||
### ArgoCD mostra OutOfSync
|
||||
|
||||
```bash
|
||||
# Ver diff
|
||||
argocd app diff monitoring
|
||||
|
||||
# Forçar sync
|
||||
argocd app sync monitoring --prune
|
||||
```
|
||||
|
||||
## Auto-Resize de PVC (Opcional)
|
||||
|
||||
Expansão automática de volumes quando atingirem 80% da capacidade.
|
||||
|
||||
### Instalar pvc-autoresizer
|
||||
|
||||
```bash
|
||||
# Adicionar repo Helm
|
||||
helm repo add pvc-autoresizer https://topolvm.github.io/pvc-autoresizer/
|
||||
|
||||
# Instalar com Victoria Metrics como fonte de métricas
|
||||
helm install pvc-autoresizer pvc-autoresizer/pvc-autoresizer \
|
||||
--namespace pvc-autoresizer \
|
||||
--create-namespace \
|
||||
--set controller.args.prometheusURL=http://vmsingle-monitoring-victoria-metrics-k8s-stack.monitoring:8429
|
||||
|
||||
# Habilitar auto-resize no StorageClass
|
||||
kubectl annotate storageclass hcloud-volumes resize.topolvm.io/enabled="true"
|
||||
```
|
||||
|
||||
### Anotar PVCs para Auto-Resize
|
||||
|
||||
```bash
|
||||
# Anotar um PVC específico
|
||||
kubectl annotate pvc <nome-pvc> -n <namespace> \
|
||||
resize.topolvm.io/storage_limit="50Gi" \
|
||||
resize.topolvm.io/threshold="20%" \
|
||||
resize.topolvm.io/increase="10Gi"
|
||||
|
||||
# Anotar TODOS os PVCs
|
||||
kubectl get pvc -A --no-headers | awk '{print $1, $2}' | \
|
||||
xargs -n2 sh -c 'kubectl annotate pvc "$1" -n "$0" \
|
||||
resize.topolvm.io/storage_limit="50Gi" \
|
||||
resize.topolvm.io/threshold="20%" \
|
||||
resize.topolvm.io/increase="10Gi" --overwrite'
|
||||
```
|
||||
|
||||
### Configuração das Annotations
|
||||
|
||||
| Annotation | Valor | Descrição |
|
||||
|------------|-------|-----------|
|
||||
| `storage_limit` | `10Ti` | Limite máximo (10TB = max Hetzner) |
|
||||
| `threshold` | `20%` | Expandir quando free < 20% (usado > 80%) |
|
||||
| `increase` | `10Gi` | Quanto aumentar por vez |
|
||||
|
||||
### Alerta de Notificação
|
||||
|
||||
Quando um PVC é redimensionado, o alerta **PVCAutoResized** é disparado automaticamente (severity: info).
|
||||
|
||||
### Verificar Funcionamento
|
||||
|
||||
```bash
|
||||
# Logs do controller
|
||||
kubectl logs -n pvc-autoresizer deployment/pvc-autoresizer-controller
|
||||
|
||||
# Ver PVCs com auto-resize habilitado
|
||||
kubectl get pvc -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}: {.metadata.annotations.resize\.topolvm\.io/storage_limit}{"\n"}{end}'
|
||||
```
|
||||
|
||||
### Referência
|
||||
|
||||
- [pvc-autoresizer GitHub](https://github.com/topolvm/pvc-autoresizer)
|
||||
|
||||
---
|
||||
|
||||
## Retenção de Dados
|
||||
|
||||
Configuração padrão: **14 dias**
|
||||
|
||||
Para alterar:
|
||||
|
||||
```yaml
|
||||
# gitops/apps/victoria-metrics/values.yaml
|
||||
vmsingle:
|
||||
retentionPeriod: "30d"
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
```bash
|
||||
./cleanup.sh
|
||||
```
|
||||
|
||||
O script remove:
|
||||
1. ArgoCD Application
|
||||
2. Namespace `monitoring`
|
||||
3. Projeto GitLab (opcional)
|
||||
|
||||
**Nota**: Dados de métricas serão perdidos!
|
||||
|
||||
## Referências
|
||||
|
||||
- [Victoria Metrics Docs](https://docs.victoriametrics.com/)
|
||||
- [victoria-metrics-k8s-stack Chart](https://github.com/VictoriaMetrics/helm-charts/tree/master/charts/victoria-metrics-k8s-stack)
|
||||
- [Grafana Dashboards](https://grafana.com/grafana/dashboards/)
|
||||
- [PromQL Cheat Sheet](https://promlabs.com/promql-cheat-sheet/)
|
||||
- [pvc-autoresizer](https://github.com/topolvm/pvc-autoresizer) - Auto-resize de volumes
|
||||
Reference in New Issue
Block a user