diff --git a/QUICKSTART.md b/QUICKSTART.md index 2b86165..3f5b21c 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -26,6 +26,7 @@ Isso iniciará automaticamente: - 🐍 API Python Flask (porta 5000) - 📊 Grafana (porta 3000) - 🔥 Prometheus (porta 9090) +- 🌐 Blackbox Exporter (porta 9115) ## 4️⃣ Acesse os serviços @@ -34,6 +35,7 @@ Isso iniciará automaticamente: | Grafana | http://localhost:3000 | admin / admin | | API | http://localhost:5000 | - | | Prometheus | http://localhost:9090 | - | +| Blackbox Exporter | http://localhost:9115 | - | ## 5️⃣ Teste a API ```bash @@ -78,6 +80,16 @@ curl http://localhost:5000/api/summary - Data Source: Prometheus - Metrics: `ticket_duration_seconds` +## 8️⃣ Monitorar apps externas (Nome / Disponível) + +- O dashboard já vem com o painel **Aplicações Externas - Disponibilidade**. +- Para incluir suas aplicações, edite o job `blackbox-http` no arquivo `prometheus.yml` (campo `targets` e `app_name`). +- Aplique com: + +```bash +docker-compose restart prometheus blackbox-exporter +``` + ## ❓ Problemas? ```bash diff --git a/README.md b/README.md index b3e0adc..e4427d3 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ Isso irá iniciar: - **Api (Flask)** em `http://localhost:5000` - **Grafana** em `http://localhost:3000` (admin/admin) - **Prometheus** em `http://localhost:9090` +- **Blackbox Exporter** em `http://localhost:9115` ### 4. Verificar saúde da API ```bash @@ -135,6 +136,34 @@ curl http://localhost:5000/api/summary 3. **Metrics**: Selecione `ticket_duration_seconds` 4. **Visualization**: Selecione `Stat` ou `Time series` +### Painel com Disponibilidade de Aplicações Externas + +Este projeto já provisiona um painel de tabela chamado **Aplicações Externas - Disponibilidade** usando a métrica Prometheus `probe_success` do Blackbox Exporter. + +Para adicionar/remover aplicações monitoradas, edite `prometheus.yml` no job `blackbox-http`: + +```yaml +- job_name: 'blackbox-http' + metrics_path: /probe + params: + module: [http_2xx] + static_configs: + - targets: + - https://seu-app-1.com + labels: + app_name: Meu App 1 + - targets: + - https://seu-app-2.com/health + labels: + app_name: Meu App 2 +``` + +Depois disso, aplique: + +```bash +docker-compose restart prometheus blackbox-exporter +``` + ## 🐛 Troubleshooting ### Erro: "Failed to authenticate with API" diff --git a/blackbox.yml b/blackbox.yml new file mode 100644 index 0000000..7572033 --- /dev/null +++ b/blackbox.yml @@ -0,0 +1,9 @@ +modules: + http_2xx: + prober: http + timeout: 5s + http: + preferred_ip_protocol: ip4 + valid_status_codes: [] + method: GET + follow_redirects: true diff --git a/docker-compose.yml b/docker-compose.yml index 57bf1ee..9f2ad80 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -65,6 +65,21 @@ services: restart: unless-stopped depends_on: - monitoring-api + - blackbox-exporter + + # Blackbox exporter for monitoring external applications + blackbox-exporter: + image: prom/blackbox-exporter:latest + container_name: blackbox-exporter + ports: + - "9115:9115" + volumes: + - ./blackbox.yml:/etc/blackbox_exporter/config.yml:ro + command: + - '--config.file=/etc/blackbox_exporter/config.yml' + networks: + - monitoring + restart: unless-stopped volumes: grafana-storage: diff --git a/grafana/provisioning/dashboards/monitoring-dashboard.json b/grafana/provisioning/dashboards/monitoring-dashboard.json index 42a9dee..a6f1b2d 100644 --- a/grafana/provisioning/dashboards/monitoring-dashboard.json +++ b/grafana/provisioning/dashboards/monitoring-dashboard.json @@ -71,10 +71,76 @@ }, "gridPos": { "h": 7, - "w": 5, + "w": 4, "x": 0, "y": 4 }, + "id": 12, + "options": { + "colorMode": "background", + "graphMode": "none", + "justifyMode": "center", + "orientation": "auto", + "percentChangeColorMode": "standard", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "text": { + "valueSize": 150 + }, + "textMode": "value", + "wideLayout": true + }, + "pluginVersion": "12.3.2", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "PBFA97CFB590B2093" + }, + "expr": "chamados_total", + "format": "time_series", + "instant": true, + "refId": "A" + } + ], + "title": "Chamados Total", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "PBFA97CFB590B2093" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 7, + "w": 4, + "x": 4, + "y": 4 + }, "id": 5, "options": { "colorMode": "background", @@ -137,8 +203,8 @@ }, "gridPos": { "h": 7, - "w": 5, - "x": 5, + "w": 4, + "x": 8, "y": 4 }, "id": 6, @@ -203,8 +269,8 @@ }, "gridPos": { "h": 7, - "w": 5, - "x": 10, + "w": 4, + "x": 12, "y": 4 }, "id": 7, @@ -316,8 +382,8 @@ }, "gridPos": { "h": 7, - "w": 9, - "x": 15, + "w": 8, + "x": 16, "y": 4 }, "id": 8, @@ -477,7 +543,7 @@ "type": "prometheus", "uid": "PBFA97CFB590B2093" }, - "expr": "ticket_duration_milliseconds{status=\"group\"}", + "expr": "max by (contact_name, group_tag) (ticket_duration_milliseconds{status=\"group\"})", "format": "table", "instant": true, "refId": "A" @@ -531,6 +597,9 @@ "type": "auto" }, "filterable": false, + "footer": { + "reducers": [] + }, "inspect": false }, "mappings": [], @@ -539,7 +608,7 @@ "steps": [ { "color": "green", - "value": null + "value": 0 }, { "color": "red", @@ -615,7 +684,7 @@ "type": "prometheus", "uid": "PBFA97CFB590B2093" }, - "expr": "ticket_duration_milliseconds{status!=\"group\"}", + "expr": "max by (contact_name, tag) (ticket_duration_milliseconds{status!=\"group\"})", "format": "table", "instant": true, "refId": "A" @@ -659,6 +728,146 @@ } ], "type": "table" + }, + { + "datasource": { + "type": "prometheus", + "uid": "PBFA97CFB590B2093" + }, + "fieldConfig": { + "defaults": { + "custom": { + "align": "center", + "cellOptions": { + "type": "auto" + }, + "footer": { + "reducers": [] + }, + "inspect": false + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": 0 + }, + { + "color": "green", + "value": 1 + } + ] + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "options": { + "0": { + "color": "red", + "text": "Indisponível" + }, + "1": { + "color": "green", + "text": "Disponível" + } + }, + "type": "value" + } + ] + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "custom.width", + "value": 860 + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Nome" + }, + "properties": [ + { + "id": "custom.width", + "value": 860 + } + ] + } + ] + }, + "gridPos": { + "h": 5, + "w": 24, + "x": 0, + "y": 23 + }, + "id": 11, + "options": { + "cellHeight": "sm", + "showHeader": true, + "sortBy": [ + { + "desc": false, + "displayName": "Nome" + } + ] + }, + "pluginVersion": "12.3.2", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "PBFA97CFB590B2093" + }, + "expr": "probe_success{job=\"blackbox-http\"}", + "format": "table", + "instant": true, + "refId": "A" + } + ], + "title": "Aplicações Externas - Disponibilidade", + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "app_name": true, + "instance": true, + "job": true, + "module": true, + "target": true + }, + "indexByName": { + "Value": 1, + "app": 0 + }, + "renameByName": { + "Value": "Disponível", + "app": "Nome" + } + } + } + ], + "type": "table" } ], "preload": false, @@ -680,5 +889,5 @@ "timezone": "", "title": "Monitoramento de Atendimento", "uid": "monitoring-tickets", - "version": 1 -} + "version": 6 +} \ No newline at end of file diff --git a/prometheus.yml b/prometheus.yml index 3d9d8e1..4cecaf7 100644 --- a/prometheus.yml +++ b/prometheus.yml @@ -9,3 +9,28 @@ scrape_configs: metrics_path: '/metrics' scrape_interval: 5s scrape_timeout: 4s + + - job_name: 'blackbox-http' + metrics_path: /probe + params: + module: [http_2xx] + static_configs: + - targets: + - https://www.google.com + labels: + app_name: Google + - targets: + - https://meu-app-2.com + labels: + app_name: Meu App 2 + relabel_configs: + - source_labels: [__address__] + target_label: __param_target + - source_labels: [app_name] + target_label: app + - action: labeldrop + regex: app_name + - source_labels: [__param_target] + target_label: instance + - target_label: __address__ + replacement: blackbox-exporter:9115 diff --git a/src/api_client.py b/src/api_client.py index 3a36bd6..2100d59 100644 --- a/src/api_client.py +++ b/src/api_client.py @@ -277,3 +277,57 @@ class APIClient: logger.error(f"Error fetching open tickets: {str(e)}") return all_tickets + + def get_total_open_tickets(self) -> int: + """ + Fetch total number of open tickets using showAll=true + + Returns: + int: Total number of open tickets + """ + if not self.token: + logger.error("Not authenticated. Please login first.") + return 0 + + try: + import json + + queue_ids = Config.get_queue_ids_list() + tickets_url = f"{self.base_url}{Config.API_TICKETS_ENDPOINT}" + + params = { + 'pageNumber': 1, + 'status': 'open', + 'showAll': 'true', + 'queueIds': json.dumps(queue_ids), + 'tagIds': '[]', + 'isGroup': 'false', + 'sortDir': 'DESC', + 'isSearching': 'false' + } + + logger.info(f"Fetching total open tickets from {tickets_url} with params: {params}") + response = self.session.get( + tickets_url, + params=params, + timeout=15 + ) + + if response.status_code == 200: + result = response.json() + total = result.get('count') + if isinstance(total, int): + logger.info(f"Fetched total open tickets: {total}") + return total + + tickets = result.get('tickets', []) + fallback_total = len(tickets) if isinstance(tickets, list) else 0 + logger.info(f"Open tickets count field not found, fallback total: {fallback_total}") + return fallback_total + + logger.error(f"Failed to fetch total open tickets: {response.status_code} - {response.text}") + return 0 + + except requests.exceptions.RequestException as e: + logger.error(f"Error fetching total open tickets: {str(e)}") + return 0 diff --git a/src/app.py b/src/app.py index 51330c1..2de6245 100644 --- a/src/app.py +++ b/src/app.py @@ -23,6 +23,7 @@ cached_json = None cached_metrics = None cached_dashboard_resume = None cached_longest_tickets = None +cached_total_open_tickets = 0 last_tickets_update = None last_dashboard_update = None background_thread = None @@ -30,7 +31,7 @@ stop_background_thread = False def background_data_updater(): """Background thread that updates data continuously""" - global cached_tickets, cached_json, cached_metrics, cached_dashboard_resume, cached_longest_tickets + global cached_tickets, cached_json, cached_metrics, cached_dashboard_resume, cached_longest_tickets, cached_total_open_tickets global last_tickets_update, last_dashboard_update, stop_background_thread tickets_interval = max(1, Config.TICKETS_REFRESH_INTERVAL) @@ -83,6 +84,7 @@ def background_data_updater(): } open_tickets = client.get_open_tickets() + cached_total_open_tickets = client.get_total_open_tickets() cached_longest_tickets = DataFormatter.format_longest_tickets(open_tickets, limit=5) last_dashboard_update = datetime.now() logger.info("Background updater: Successfully updated dashboard metrics") @@ -183,7 +185,8 @@ def metrics(): dashboard_metrics = DataFormatter.format_dashboard_metrics( resume_today, resume_month, - cached_longest_tickets + cached_longest_tickets, + cached_total_open_tickets ) if dashboard_metrics: all_metrics.append(dashboard_metrics) diff --git a/src/data_formatter.py b/src/data_formatter.py index acdd45c..b2bc295 100644 --- a/src/data_formatter.py +++ b/src/data_formatter.py @@ -213,7 +213,12 @@ class DataFormatter: return "\n".join(metrics) @staticmethod - def format_dashboard_metrics(resume_today: Dict[str, Any], resume_month: Dict[str, Any], longest_tickets: List[Dict[str, Any]]) -> str: + def format_dashboard_metrics( + resume_today: Dict[str, Any], + resume_month: Dict[str, Any], + longest_tickets: List[Dict[str, Any]], + chamados_total: int = 0 + ) -> str: """ Format dashboard data as Prometheus metrics @@ -221,6 +226,7 @@ class DataFormatter: resume_today: Dashboard resume data for today from API resume_month: Dashboard resume data for the month from API longest_tickets: List of longest tickets + chamados_total: Total number of open tickets (showAll=true) Returns: str: Prometheus format metrics @@ -236,6 +242,10 @@ class DataFormatter: metrics.append("# HELP chamados_abertos_hoje Number of tickets currently open") metrics.append("# TYPE chamados_abertos_hoje gauge") metrics.append(f"chamados_abertos_hoje {chamados_abertos}") + + metrics.append("\n# HELP chamados_total Total number of open tickets") + metrics.append("# TYPE chamados_total gauge") + metrics.append(f"chamados_total {chamados_total}") metrics.append("\n# HELP chamados_do_mes Total tickets this month") metrics.append("# TYPE chamados_do_mes gauge")