feat: add total calls and available websites status
Some checks failed
Deploy / deploy (push) Has been cancelled

This commit is contained in:
2026-03-04 17:58:49 -03:00
parent e1102420a8
commit 0920c1f5c5
9 changed files with 381 additions and 15 deletions

View File

@@ -26,6 +26,7 @@ Isso iniciará automaticamente:
- 🐍 API Python Flask (porta 5000) - 🐍 API Python Flask (porta 5000)
- 📊 Grafana (porta 3000) - 📊 Grafana (porta 3000)
- 🔥 Prometheus (porta 9090) - 🔥 Prometheus (porta 9090)
- 🌐 Blackbox Exporter (porta 9115)
## 4️⃣ Acesse os serviços ## 4️⃣ Acesse os serviços
@@ -34,6 +35,7 @@ Isso iniciará automaticamente:
| Grafana | http://localhost:3000 | admin / admin | | Grafana | http://localhost:3000 | admin / admin |
| API | http://localhost:5000 | - | | API | http://localhost:5000 | - |
| Prometheus | http://localhost:9090 | - | | Prometheus | http://localhost:9090 | - |
| Blackbox Exporter | http://localhost:9115 | - |
## 5️⃣ Teste a API ## 5️⃣ Teste a API
```bash ```bash
@@ -78,6 +80,16 @@ curl http://localhost:5000/api/summary
- Data Source: Prometheus - Data Source: Prometheus
- Metrics: `ticket_duration_seconds` - 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? ## ❓ Problemas?
```bash ```bash

View File

@@ -42,6 +42,7 @@ Isso irá iniciar:
- **Api (Flask)** em `http://localhost:5000` - **Api (Flask)** em `http://localhost:5000`
- **Grafana** em `http://localhost:3000` (admin/admin) - **Grafana** em `http://localhost:3000` (admin/admin)
- **Prometheus** em `http://localhost:9090` - **Prometheus** em `http://localhost:9090`
- **Blackbox Exporter** em `http://localhost:9115`
### 4. Verificar saúde da API ### 4. Verificar saúde da API
```bash ```bash
@@ -135,6 +136,34 @@ curl http://localhost:5000/api/summary
3. **Metrics**: Selecione `ticket_duration_seconds` 3. **Metrics**: Selecione `ticket_duration_seconds`
4. **Visualization**: Selecione `Stat` ou `Time series` 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 ## 🐛 Troubleshooting
### Erro: "Failed to authenticate with API" ### Erro: "Failed to authenticate with API"

9
blackbox.yml Normal file
View File

@@ -0,0 +1,9 @@
modules:
http_2xx:
prober: http
timeout: 5s
http:
preferred_ip_protocol: ip4
valid_status_codes: []
method: GET
follow_redirects: true

View File

@@ -65,6 +65,21 @@ services:
restart: unless-stopped restart: unless-stopped
depends_on: depends_on:
- monitoring-api - 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: volumes:
grafana-storage: grafana-storage:

View File

@@ -71,10 +71,76 @@
}, },
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 5, "w": 4,
"x": 0, "x": 0,
"y": 4 "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, "id": 5,
"options": { "options": {
"colorMode": "background", "colorMode": "background",
@@ -137,8 +203,8 @@
}, },
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 5, "w": 4,
"x": 5, "x": 8,
"y": 4 "y": 4
}, },
"id": 6, "id": 6,
@@ -203,8 +269,8 @@
}, },
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 5, "w": 4,
"x": 10, "x": 12,
"y": 4 "y": 4
}, },
"id": 7, "id": 7,
@@ -316,8 +382,8 @@
}, },
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 9, "w": 8,
"x": 15, "x": 16,
"y": 4 "y": 4
}, },
"id": 8, "id": 8,
@@ -477,7 +543,7 @@
"type": "prometheus", "type": "prometheus",
"uid": "PBFA97CFB590B2093" "uid": "PBFA97CFB590B2093"
}, },
"expr": "ticket_duration_milliseconds{status=\"group\"}", "expr": "max by (contact_name, group_tag) (ticket_duration_milliseconds{status=\"group\"})",
"format": "table", "format": "table",
"instant": true, "instant": true,
"refId": "A" "refId": "A"
@@ -531,6 +597,9 @@
"type": "auto" "type": "auto"
}, },
"filterable": false, "filterable": false,
"footer": {
"reducers": []
},
"inspect": false "inspect": false
}, },
"mappings": [], "mappings": [],
@@ -539,7 +608,7 @@
"steps": [ "steps": [
{ {
"color": "green", "color": "green",
"value": null "value": 0
}, },
{ {
"color": "red", "color": "red",
@@ -615,7 +684,7 @@
"type": "prometheus", "type": "prometheus",
"uid": "PBFA97CFB590B2093" "uid": "PBFA97CFB590B2093"
}, },
"expr": "ticket_duration_milliseconds{status!=\"group\"}", "expr": "max by (contact_name, tag) (ticket_duration_milliseconds{status!=\"group\"})",
"format": "table", "format": "table",
"instant": true, "instant": true,
"refId": "A" "refId": "A"
@@ -659,6 +728,146 @@
} }
], ],
"type": "table" "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, "preload": false,
@@ -680,5 +889,5 @@
"timezone": "", "timezone": "",
"title": "Monitoramento de Atendimento", "title": "Monitoramento de Atendimento",
"uid": "monitoring-tickets", "uid": "monitoring-tickets",
"version": 1 "version": 6
} }

View File

@@ -9,3 +9,28 @@ scrape_configs:
metrics_path: '/metrics' metrics_path: '/metrics'
scrape_interval: 5s scrape_interval: 5s
scrape_timeout: 4s 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

View File

@@ -277,3 +277,57 @@ class APIClient:
logger.error(f"Error fetching open tickets: {str(e)}") logger.error(f"Error fetching open tickets: {str(e)}")
return all_tickets 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

View File

@@ -23,6 +23,7 @@ cached_json = None
cached_metrics = None cached_metrics = None
cached_dashboard_resume = None cached_dashboard_resume = None
cached_longest_tickets = None cached_longest_tickets = None
cached_total_open_tickets = 0
last_tickets_update = None last_tickets_update = None
last_dashboard_update = None last_dashboard_update = None
background_thread = None background_thread = None
@@ -30,7 +31,7 @@ stop_background_thread = False
def background_data_updater(): def background_data_updater():
"""Background thread that updates data continuously""" """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 global last_tickets_update, last_dashboard_update, stop_background_thread
tickets_interval = max(1, Config.TICKETS_REFRESH_INTERVAL) tickets_interval = max(1, Config.TICKETS_REFRESH_INTERVAL)
@@ -83,6 +84,7 @@ def background_data_updater():
} }
open_tickets = client.get_open_tickets() 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) cached_longest_tickets = DataFormatter.format_longest_tickets(open_tickets, limit=5)
last_dashboard_update = datetime.now() last_dashboard_update = datetime.now()
logger.info("Background updater: Successfully updated dashboard metrics") logger.info("Background updater: Successfully updated dashboard metrics")
@@ -183,7 +185,8 @@ def metrics():
dashboard_metrics = DataFormatter.format_dashboard_metrics( dashboard_metrics = DataFormatter.format_dashboard_metrics(
resume_today, resume_today,
resume_month, resume_month,
cached_longest_tickets cached_longest_tickets,
cached_total_open_tickets
) )
if dashboard_metrics: if dashboard_metrics:
all_metrics.append(dashboard_metrics) all_metrics.append(dashboard_metrics)

View File

@@ -213,7 +213,12 @@ class DataFormatter:
return "\n".join(metrics) return "\n".join(metrics)
@staticmethod @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 Format dashboard data as Prometheus metrics
@@ -221,6 +226,7 @@ class DataFormatter:
resume_today: Dashboard resume data for today from API resume_today: Dashboard resume data for today from API
resume_month: Dashboard resume data for the month from API resume_month: Dashboard resume data for the month from API
longest_tickets: List of longest tickets longest_tickets: List of longest tickets
chamados_total: Total number of open tickets (showAll=true)
Returns: Returns:
str: Prometheus format metrics str: Prometheus format metrics
@@ -237,6 +243,10 @@ class DataFormatter:
metrics.append("# TYPE chamados_abertos_hoje gauge") metrics.append("# TYPE chamados_abertos_hoje gauge")
metrics.append(f"chamados_abertos_hoje {chamados_abertos}") 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("\n# HELP chamados_do_mes Total tickets this month")
metrics.append("# TYPE chamados_do_mes gauge") metrics.append("# TYPE chamados_do_mes gauge")
metrics.append(f"chamados_do_mes {chamados_mes}") metrics.append(f"chamados_do_mes {chamados_mes}")