pyATS Genie Health Checks

26.3 · active · verified Thu Apr 16

genie-libs-health is a Python library within the pyATS framework, providing a robust mechanism for monitoring network device health status. It allows users to define custom health checks using YAML files, which are then executed against devices configured in a pyATS testbed. This library is part of the `genie` ecosystem and is primarily used for automated network device validation and troubleshooting. It is currently at version `26.3` and follows the `genie` release cadence, which typically aligns with `pyATS` monthly releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define health checks using a YAML structure, initialize the `Health` object with a device (mocked for this example), and execute the checks. In a real scenario, `my_device` would be an actual connected device loaded from a pyATS testbed file. The example uses `unittest.mock` to make the code runnable without requiring actual device connectivity.

import yaml
from unittest.mock import Mock # For a truly runnable example without a real device
from genie.libs.health.health import Health

# --- 1. Create a mock device and testbed for demonstration ---
# In a real scenario, you would load a testbed from a file:
# from pyats.topology import loader
# testbed = loader.load('path/to/testbed.yaml')
# my_device = testbed.devices['your_device_name']

# Mock a device and its connection/execution methods
mock_device = Mock()
mock_device.name = "my_mock_device"
mock_device.os = "iosxe"
mock_device.connected = False
mock_device.api.execute.return_value = {
    "show version": "Cisco IOS XE Software, Version 17.3.4",
    "show processes cpu sorted": "CPU utilization for five seconds: 5%/1%; one minute: 4%; five minutes: 3%"
}

# Define connect/disconnect behavior for the mock
def mock_connect():
    print(f"Attempting to connect to {mock_device.name} (mocked)...")
    mock_device.connected = True
    print(f"Successfully connected to {mock_device.name} (mocked).")
mock_device.connect.side_effect = mock_connect

def mock_disconnect():
    print(f"Disconnecting from {mock_device.name} (mocked)...")
    mock_device.connected = False
mock_device.disconnect.side_effect = mock_disconnect

# Create a mock testbed containing our mock device
mock_testbed = Mock()
mock_testbed.devices = {'my_mock_device': mock_device}
mock_testbed.name = "mock_testbed"

# --- 2. Define a simple health check YAML in-memory ---
health_yaml_content = """
health_check_sections:
  section_version_check:
    commands:
      show version:
        - '.*Cisco IOS XE Software.*' # Checks for IOS XE in 'show version' output
  section_cpu_usage_check:
    commands:
      show processes cpu sorted:
        - 'CPU utilization for five seconds: [0-9]{1,2}%/' # Checks if CPU is valid percentage
"""
health_data = yaml.safe_load(health_yaml_content)

# --- 3. Initialize and run Health checks ---
try:
    # Use the mock device (in a real scenario, this would be from testbed.devices)
    my_device = mock_testbed.devices['my_mock_device']
    my_device.connect() # This will call our mock_connect function

    # Create Health object with the device and parsed health data
    health = Health(device=my_device, health_data=health_data)

    # Run all defined health checks
    print(f"\nRunning health checks on {my_device.name}...")
    health_result = health.check_all()

    # Print results
    print("\nHealth Check Results Summary:")
    for section, result in health_result.items():
        print(f"  Section: '{section}' -> Status: {result['status']}")
        if result['status'] == 'Fail':
            print(f"    Reason: {result.get('reason', 'No specific reason provided.')}")
            for command, cmd_result in result.get('commands', {}).items():
                if cmd_result.get('status') == 'Fail':
                    print(f"      Command '{command}' failed: {cmd_result.get('reason', 'N/A')}")

except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    if my_device and my_device.connected:
        my_device.disconnect()

view raw JSON →