API Reference - fleXRPL/datadog-monitor-deployer GitHub Wiki

API Reference

This document provides detailed information about the Python API provided by the DataDog Monitor Deployer.

Core Classes

Monitor Class

The base class for defining monitors programmatically.

from datadog_monitor_deployer.core.monitor import Monitor

monitor = Monitor(
    name="CPU Alert",
    type="metric alert",
    query="avg(last_5m):avg:system.cpu.user{*} > 80",
    message="CPU usage is high",
    tags=["env:production"],
    options={"notify_no_data": True}
)

Properties

Property Type Description
name str Monitor name
type str Monitor type
query str Monitor query
message str Alert message
tags List[str] Monitor tags
options Dict[str, Any] Monitor options
priority Optional[int] Alert priority
restricted_roles Optional[List[str]] Access roles

Methods

def to_dict(self) -> Dict[str, Any]:
    """Convert monitor to dictionary format."""

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "Monitor":
    """Create monitor from dictionary."""

def validate(self) -> bool:
    """Validate monitor configuration."""

MonitorDeployer Class

Main class for deploying and managing monitors.

from datadog_monitor_deployer.core.deployer import MonitorDeployer

deployer = MonitorDeployer()

Methods

def deploy(self, config: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Deploy monitors from configuration."""

def validate_config(self, config: Dict[str, Any]) -> bool:
    """Validate monitor configuration."""

def list_monitors(
    self,
    monitor_id: Optional[str] = None,
    name: Optional[str] = None,
    tags: Optional[List[str]] = None
) -> List[Dict[str, Any]]:
    """List existing monitors with optional filtering."""

def delete_monitor(self, monitor_id: str) -> None:
    """Delete a monitor by ID."""

Configuration Management

ConfigLoader

Utility class for loading and validating configurations.

from datadog_monitor_deployer.utils.config import load_config

config = load_config("monitors/cpu.yaml")

Functions

def load_config(config_path: str) -> Dict[str, Any]:
    """Load and validate configuration from file."""

Template Management

TemplateManager

Class for handling monitor templates and variables.

from datadog_monitor_deployer.utils.template import TemplateManager

template_manager = TemplateManager()

Methods

def render_template(
    self,
    template: str,
    variables: Dict[str, Any]
) -> str:
    """Render template with variables."""

def load_template(self, template_path: str) -> Dict[str, Any]:
    """Load template from file."""

Utility Functions

Logger Setup

from datadog_monitor_deployer.utils.logger import setup_logger

logger = setup_logger(name="custom_logger")

Environment Variables

from datadog_monitor_deployer.utils.env import load_env_vars

load_env_vars()  # Load variables from .env file

Examples

Creating and Deploying a Monitor

from datadog_monitor_deployer.core.monitor import Monitor
from datadog_monitor_deployer.core.deployer import MonitorDeployer

# Create monitor
monitor = Monitor(
    name="High CPU Usage",
    type="metric alert",
    query="avg(last_5m):avg:system.cpu.user{*} > 80",
    message="CPU usage is above 80%",
    tags=["env:production", "service:web"],
    options={
        "notify_no_data": True,
        "thresholds": {
            "critical": 80,
            "warning": 70
        }
    }
)

# Deploy monitor
deployer = MonitorDeployer()
result = deployer.deploy({"monitors": [monitor.to_dict()]})

Working with Templates

from datadog_monitor_deployer.utils.template import TemplateManager

# Load and render template
template_manager = TemplateManager()
template = template_manager.load_template("templates/base.yaml")

variables = {
    "service": "web",
    "threshold": 80
}

rendered = template_manager.render_template(template, variables)

Listing and Managing Monitors

from datadog_monitor_deployer.core.deployer import MonitorDeployer

deployer = MonitorDeployer()

# List monitors
all_monitors = deployer.list_monitors()
filtered_monitors = deployer.list_monitors(
    name="CPU",
    tags=["env:production"]
)

# Delete monitor
deployer.delete_monitor("monitor-id")

Error Handling

The API uses custom exceptions for different error cases:

from datadog_monitor_deployer.exceptions import (
    ConfigurationError,
    ValidationError,
    DeploymentError,
    AuthenticationError
)

try:
    deployer.deploy(config)
except ConfigurationError as e:
    print(f"Configuration error: {e}")
except ValidationError as e:
    print(f"Validation error: {e}")
except DeploymentError as e:
    print(f"Deployment error: {e}")
except AuthenticationError as e:
    print(f"Authentication error: {e}")

Best Practices

  1. Error Handling

    • Always wrap API calls in try-except blocks
    • Handle specific exceptions appropriately
    • Log errors with context
  2. Resource Management

    • Use context managers when appropriate
    • Clean up resources properly
    • Handle rate limits
  3. Configuration

    • Validate configurations before deployment
    • Use type hints and docstrings
    • Follow Python best practices

Additional Resources