Buckets:

download
raw
5.86 kB
#!/usr/bin/env python3
"""
Metrics and Monitoring Module
Provides Prometheus-compatible metrics for the Zen AI Pentest API.
"""
import time
from functools import wraps
from typing import Callable, Optional
# Try to import prometheus_client
try:
from prometheus_client import (
CONTENT_TYPE_LATEST,
Counter,
Gauge,
Histogram,
Info,
generate_latest,
)
PROMETHEUS_AVAILABLE = True
except ImportError:
PROMETHEUS_AVAILABLE = False
# Create dummy classes for when prometheus_client is not installed
class DummyMetric:
def __init__(self, *args, **kwargs):
pass
def inc(self, *args, **kwargs):
pass
def observe(self, *args, **kwargs):
pass
def set(self, *args, **kwargs):
pass
def labels(self, *args, **kwargs):
return self
def time(self):
return DummyTimer()
class DummyTimer:
def __enter__(self):
return self
def __exit__(self, *args):
pass
Counter = Histogram = Gauge = Info = DummyMetric
def generate_latest():
return b""
CONTENT_TYPE_LATEST = "text/plain"
# Request metrics
REQUEST_COUNT = Counter(
"zen_api_requests_total",
"Total API requests",
["method", "endpoint", "status_code"],
)
REQUEST_DURATION = Histogram(
"zen_api_request_duration_seconds",
"API request duration in seconds",
["method", "endpoint"],
buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
)
# Scan metrics
SCAN_COUNT = Counter("zen_scans_total", "Total scans initiated", ["scan_type", "status"])
SCAN_DURATION = Histogram(
"zen_scan_duration_seconds",
"Scan duration in seconds",
["scan_type"],
buckets=[1.0, 5.0, 15.0, 30.0, 60.0, 300.0, 600.0, 1800.0, 3600.0],
)
ACTIVE_SCANS = Gauge("zen_active_scans", "Number of currently active scans")
# Tool metrics
TOOL_EXECUTION_COUNT = Counter(
"zen_tool_executions_total",
"Total tool executions",
["tool_name", "status"],
)
TOOL_EXECUTION_DURATION = Histogram(
"zen_tool_execution_duration_seconds",
"Tool execution duration in seconds",
["tool_name"],
buckets=[0.1, 0.5, 1.0, 5.0, 10.0, 30.0, 60.0, 300.0],
)
# Database metrics
DB_CONNECTIONS = Gauge(
"zen_db_connections",
"Number of database connections",
["state"], # active, idle, total
)
DB_QUERY_DURATION = Histogram(
"zen_db_query_duration_seconds",
"Database query duration in seconds",
["operation"],
buckets=[0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0],
)
# Cache metrics
CACHE_HIT_COUNT = Counter("zen_cache_hits_total", "Total cache hits", ["cache_name"])
CACHE_MISS_COUNT = Counter("zen_cache_misses_total", "Total cache misses", ["cache_name"])
# Agent metrics
AGENT_MESSAGES = Counter(
"zen_agent_messages_total",
"Total agent messages",
["agent_type", "message_type"],
)
AGENT_TASK_DURATION = Histogram(
"zen_agent_task_duration_seconds",
"Agent task execution duration",
["agent_type", "task_type"],
)
# System metrics
SYSTEM_INFO = Info("zen_system", "System information")
# Application info
APP_INFO = Info("zen_app", "Application information")
def init_metrics(app_version: str = "unknown", app_name: str = "zen-ai-pentest"):
"""Initialize metrics with application info"""
if PROMETHEUS_AVAILABLE:
APP_INFO.info(
{
"name": app_name,
"version": app_version,
}
)
SYSTEM_INFO.info(
{
"platform": "linux",
}
)
def track_request(method: str, endpoint: str, status_code: int, duration: float):
"""Track API request metrics"""
REQUEST_COUNT.labels(method=method, endpoint=endpoint, status_code=str(status_code)).inc()
REQUEST_DURATION.labels(method=method, endpoint=endpoint).observe(duration)
def track_scan(scan_type: str, status: str, duration: Optional[float] = None):
"""Track scan metrics"""
SCAN_COUNT.labels(scan_type=scan_type, status=status).inc()
if duration is not None:
SCAN_DURATION.labels(scan_type=scan_type).observe(duration)
def track_tool_execution(tool_name: str, status: str, duration: Optional[float] = None):
"""Track tool execution metrics"""
TOOL_EXECUTION_COUNT.labels(tool_name=tool_name, status=status).inc()
if duration is not None:
TOOL_EXECUTION_DURATION.labels(tool_name=tool_name).observe(duration)
def track_cache_hit(cache_name: str = "default"):
"""Track cache hit"""
CACHE_HIT_COUNT.labels(cache_name=cache_name).inc()
def track_cache_miss(cache_name: str = "default"):
"""Track cache miss"""
CACHE_MISS_COUNT.labels(cache_name=cache_name).inc()
def set_active_scans(count: int):
"""Set number of active scans"""
ACTIVE_SCANS.set(count)
def track_agent_message(agent_type: str, message_type: str):
"""Track agent message"""
AGENT_MESSAGES.labels(agent_type=agent_type, message_type=message_type).inc()
def timing_decorator(metric: Histogram):
"""Decorator to time function execution"""
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
try:
return func(*args, **kwargs)
finally:
duration = time.time() - start
metric.observe(duration)
return wrapper
return decorator
def get_metrics_response():
"""Get metrics in Prometheus format"""
if PROMETHEUS_AVAILABLE:
return generate_latest()
return b"# Metrics not available - prometheus_client not installed"
def get_metrics_content_type():
"""Get content type for metrics response"""
return CONTENT_TYPE_LATEST

Xet Storage Details

Size:
5.86 kB
·
Xet hash:
80002e108a5f57277960a8ce2d95ad1cc3784148ddb5d58c718155563c52952c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.