šŸ Python Extensions — Module 9

Python Extension Basics

Hands-on

Python Extension Architecture

When SNMP can't reach the data you need — REST APIs, CLI commands, databases, custom protocols — Python extensions are the answer. They run on the Extension Execution Controller (EEC) or ActiveGate and execute your Python code on a schedule.

How Python Extensions Work

A Python extension is a standard extension package with Python code inside a .whl (wheel) file:

extension-package.zip
ā”œā”€ā”€ extension.zip
│   ā”œā”€ā”€ extension.yaml      # Same YAML you already know
│   └── lib/
│       └── your_extension-0.0.1-py3-none-any.whl
│           └── your_extension/
│               ā”œā”€ā”€ __init__.py
│               └── __main__.py   # Entry point (REQUIRED)
└── extension.zip.sig

The Extension SDK

Every Python extension inherits from Extension and uses the @extension.schedule decorator:

from dynatrace_extension import Extension, Status, StatusValue

class MyExtension(Extension):
    def initialize(self):
        """Called once when extension starts."""
        self.logger.info("Extension initialized")

    @Extension.schedule(period=60)  # Run every 60 seconds
    def collect_data(self):
        """Main data collection loop."""
        # Get config from monitoring configuration
        url = self.config.get("url", "")
        token = self.config.get("api_token", "")

        # Collect and report metrics
        response = self.http_client.get(url, headers={"Authorization": f"Bearer {token}"})
        data = response.json()

        self.report_metric(
            key="com.dynatrace.extension.my-ext.cpu",
            value=data["cpu_percent"],
            dimensions={"device.address": url, "device.name": data["hostname"]},
        )

    def fastcheck(self) -> Status:
        """Health check — called before first schedule run."""
        return Status(StatusValue.OK)

def main():
    MyExtension().run()

if __name__ == "__main__":
    main()

Key SDK Methods

MethodPurpose
self.report_metric(key, value, dimensions)Send a metric datapoint to Dynatrace
self.configAccess monitoring configuration values
self.loggerWrite to extension log
self.http_clientPre-configured HTTP client with proxy support
self.activation_configAccess activation context (environment URL, etc.)

extension.yaml for Python

The YAML structure is identical to SNMP — you still define metrics:, topology:, and screens:. The only difference is the data source section:

python:
  runtime:
    module: your_extension
    version:
      min: "3.10"
  activation:
    remote:
      path: activationSchema.json
    local:
      path: activationSchema.json

The activationSchema.json defines what fields appear in the monitoring configuration UI — URLs, credentials, polling intervals, etc.

SNMP vs Python: When to Use Which

Use SNMP when...Use Python when...
Device supports SNMPData comes from REST API
Standard MIBs cover your needsCustom protocol or CLI commands
No code maintenance desiredComplex data transformation needed
Simple metric collectionMulti-step authentication (OAuth, etc.)

Real Example: FortiSwitch

Our FortiSwitch extension (v1.0.2, 19 alerts, 7 entity types) uses Python to hit the FortiSwitch REST API + ICMP ping. It collects PSU status, fan speeds, PCB temperatures, port statistics, trunk status, and NTP sync — none of which were available via SNMP on this device.

Real Example: Waze Police

The Waze Police extension polls the Waze Live Map GeoRSS API every 60 seconds for 5 configured cities, reports police sighting locations as metrics with lat/lon dimensions, and creates entity types for regions and individual alerts. Pure API integration — SNMP would be impossible here.

šŸ›  Hands-On Exercise

Edit the YAML in the editor, then click "Check My Work" to validate.

Python Extension YAML

Complete this extension.yaml for a Python extension that monitors a REST API device.

  • Add the python: runtime section with module name my_api_monitor
  • Define two metrics: cpu (gauge, Percent) and requests.count (count, Count)
  • Remember: count metrics need the .count suffix in the key
extension.yamlYAML
Loading...