CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-grafana-backup

A Python-based application to backup Grafana settings using the Grafana API

Pending
Overview
Eval results
Files

api-health.mddocs/

API Health Checking

Comprehensive API validation and feature detection system that ensures compatibility with different Grafana versions and configurations. The health checking system validates connectivity, authentication, and feature availability before performing operations.

Capabilities

Main Health Check Function

The primary API validation function that orchestrates comprehensive health checking and feature detection.

def main(settings):
    """
    Perform comprehensive API health checks and feature detection
    
    Args:
        settings (dict): Configuration settings including API endpoints and credentials
        
    Returns:
        tuple: (status_code, response_data, dashboard_uid_support, 
                datasource_uid_support, paging_support, contact_point_support)
    """

Core Health Check Functions

Located in the grafana_backup.dashboardApi module, these functions provide low-level API validation.

Basic Health Check

def health_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
    """
    Check Grafana server health and availability
    
    Args:
        grafana_url (str): Base URL of Grafana instance
        http_get_headers (dict): HTTP headers for authentication
        verify_ssl (bool): Whether to verify SSL certificates
        client_cert (str): Path to client certificate (optional)
        debug (bool): Enable debug logging
        
    Returns:
        tuple: (status_code, json_response)
    """

Authentication Check

def auth_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
    """
    Verify API token authentication and permissions
    
    Args:
        grafana_url (str): Base URL of Grafana instance
        http_get_headers (dict): HTTP headers with API token
        verify_ssl (bool): Whether to verify SSL certificates
        client_cert (str): Path to client certificate (optional)
        debug (bool): Enable debug logging
        
    Returns:
        tuple: (status_code, json_response)
    """

UID Feature Detection

def uid_feature_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
    """
    Detect if Grafana instance supports UID-based operations
    
    Args:
        grafana_url (str): Base URL of Grafana instance
        http_get_headers (dict): HTTP headers for authentication
        verify_ssl (bool): Whether to verify SSL certificates
        client_cert (str): Path to client certificate (optional)
        debug (bool): Enable debug logging
        
    Returns:
        tuple: (dashboard_uid_support, datasource_uid_support)
    """

Paging Feature Detection

def paging_feature_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
    """
    Detect if Grafana instance supports API paging (v6.2+)
    
    Args:
        grafana_url (str): Base URL of Grafana instance
        http_get_headers (dict): HTTP headers for authentication
        verify_ssl (bool): Whether to verify SSL certificates
        client_cert (str): Path to client certificate (optional)
        debug (bool): Enable debug logging
        
    Returns:
        bool: True if paging is supported, False otherwise
    """

Contact Point Feature Detection

def contact_point_check(grafana_url, http_get_headers, verify_ssl, client_cert, debug):
    """
    Detect if Grafana instance supports unified alerting contact points
    
    Args:
        grafana_url (str): Base URL of Grafana instance
        http_get_headers (dict): HTTP headers for authentication
        verify_ssl (bool): Whether to verify SSL certificates
        client_cert (str): Path to client certificate (optional)
        debug (bool): Enable debug logging
        
    Returns:
        bool: True if contact points are supported, False otherwise
    """

Feature Detection Details

UID Support Detection

The system detects whether the Grafana instance supports UID-based operations:

Dashboard UID Support

  • Detection method: Searches for first dashboard and checks for 'uid' field
  • Fallback behavior: Uses ID-based operations if UIDs not supported
  • Impact: Affects dashboard backup/restore file naming and references

Datasource UID Support

  • Detection method: Retrieves first datasource and checks for 'uid' field
  • Fallback behavior: Uses name-based datasource references
  • Impact: Affects datasource backup/restore and dashboard datasource references

Paging Support Detection

Detects support for API result paging introduced in Grafana 6.2:

  • Detection method: Attempts to use paging parameters in search API
  • Benefits: Enables efficient handling of large datasets
  • Fallback: Uses limit-based search for older versions

Contact Point Support Detection

Detects unified alerting contact point support:

  • Detection method: Attempts to access contact points API endpoint
  • Grafana version: Available in newer Grafana versions with unified alerting
  • Impact: Determines whether contact points can be backed up and restored

Configuration Options

Health Check Controls

Health checking behavior can be controlled through configuration:

# Configuration settings that control health checking
API_HEALTH_CHECK: bool  # Enable/disable basic health checks
API_AUTH_CHECK: bool   # Enable/disable authentication verification
DEBUG: bool            # Enable debug logging for health checks

SSL and Certificate Options

# SSL and certificate configuration
VERIFY_SSL: bool       # Verify SSL certificates
CLIENT_CERT: str       # Path to client certificate file for mutual TLS

Usage Examples

Basic Health Check

from grafana_backup.api_checks import main as check_api
from grafana_backup.grafanaSettings import main as load_config

# Load configuration
settings = load_config('/path/to/grafanaSettings.json')

# Perform comprehensive health check
(status, response, dashboard_uid, datasource_uid, 
 paging, contact_points) = check_api(settings)

if status == 200:
    print("API is healthy and authenticated")
    print(f"Dashboard UID support: {dashboard_uid}")
    print(f"Datasource UID support: {datasource_uid}")
    print(f"Paging support: {paging}")
    print(f"Contact point support: {contact_points}")
else:
    print(f"API check failed: {response}")

Individual Feature Checks

from grafana_backup.dashboardApi import (
    health_check, auth_check, uid_feature_check, 
    paging_feature_check, contact_point_check
)

# Extract settings
grafana_url = settings['GRAFANA_URL']
headers = settings['HTTP_GET_HEADERS']
verify_ssl = settings['VERIFY_SSL']
client_cert = settings['CLIENT_CERT']
debug = settings['DEBUG']

# Individual health checks
health_status, health_response = health_check(
    grafana_url, headers, verify_ssl, client_cert, debug
)

auth_status, auth_response = auth_check(
    grafana_url, headers, verify_ssl, client_cert, debug
)

dashboard_uid, datasource_uid = uid_feature_check(
    grafana_url, headers, verify_ssl, client_cert, debug
)

paging_supported = paging_feature_check(
    grafana_url, headers, verify_ssl, client_cert, debug
)

contact_points_supported = contact_point_check(
    grafana_url, headers, verify_ssl, client_cert, debug
)

Integration with Operations

Health checking is automatically integrated into all major operations:

# Example from backup operation
from grafana_backup.save import main as save_backup

# Health checks are performed automatically before backup
save_args = {
    'save': True,
    '--components': None,
    '--no-archive': False,
    '--config': None
}

# This call will automatically:
# 1. Perform health checks
# 2. Detect feature support
# 3. Adapt backup behavior based on detected features
# 4. Exit gracefully if health checks fail
save_backup(save_args, settings)

Health Check Results

Successful Health Check Response

When all health checks pass, the system configures feature flags:

# Features are added to settings for use by other modules
settings.update({
    'DASHBOARD_UID_SUPPORT': True,
    'DATASOURCE_UID_SUPPORT': True,
    'PAGING_SUPPORT': True,
    'CONTACT_POINT_SUPPORT': False
})

Failed Health Check Handling

When health checks fail, operations are prevented:

  • Connection failures: Network connectivity or URL configuration issues
  • Authentication failures: Invalid API tokens or insufficient permissions
  • SSL errors: Certificate validation failures or expired certificates
  • Version incompatibility: Unsupported Grafana versions or configurations

Error Handling and Diagnostics

Debug Information

When debug mode is enabled, health checks provide detailed diagnostic information:

# Debug output includes:
# - HTTP request/response details
# - Authentication header validation
# - SSL certificate information
# - API endpoint availability
# - Feature detection results

Common Issues and Solutions

Connection Issues

  • Symptom: Health check returns non-200 status
  • Solutions: Verify URL, check network connectivity, validate SSL configuration

Authentication Issues

  • Symptom: Auth check fails with 401/403 status
  • Solutions: Verify API token, check token permissions, validate admin credentials

Feature Detection Issues

  • Symptom: Features detected incorrectly
  • Solutions: Check Grafana version, verify API access, review debug output

Best Practices

Health Check Configuration

{
  "general": {
    "api_health_check": true,
    "api_auth_check": true,
    "debug": false,
    "verify_ssl": true
  }
}

Production Considerations

  • SSL verification: Always enable SSL verification in production
  • Debug logging: Disable debug logging in production for security
  • Health check timing: Health checks add minimal overhead but can be disabled if needed
  • Certificate management: Ensure SSL certificates are valid and up-to-date

Troubleshooting

  • Enable debug mode: Set DEBUG=true for detailed diagnostic information
  • Check network connectivity: Verify Grafana instance is accessible
  • Validate credentials: Confirm API token has required permissions
  • Review Grafana logs: Check Grafana server logs for additional context

The API health checking system provides robust validation and feature detection to ensure reliable operation across different Grafana versions and configurations.

Install with Tessl CLI

npx tessl i tessl/pypi-grafana-backup

docs

admin-tools.md

api-health.md

archive-management.md

backup-operations.md

cloud-storage.md

configuration.md

delete-operations.md

index.md

monitoring.md

restore-operations.md

tile.json