Power Outage Data in PagerDuty

To get power outage alerts into PagerDuty, run a Python poller every 15 minutes that sends your sites' coordinates to the PowerOutage.us v2 REST API and turns the answer into PagerDuty Events API v2 events: a trigger when an outage covers one of your sites, and a resolve when it no longer covers any. Each alert's dedup_key is built from the outage's utilityId and outageId, so PagerDuty keeps one alert per outage however many runs see it, and your service's escalation policy, urgency rules and alert grouping take it from there.

What you'll have

  • A PagerDuty alert as soon as a utility reports an outage covering one of your sites, with the utility, customers out, cause and estimated restoration in its custom details.
  • One alert per outage, with the dedup_key poweroutage:<utilityId>:<outageId>, listing every watched site it covers.
  • Automatic resolution when the outage no longer covers any watched site, and never a resolution from a failed check.
  • No PagerDuty REST API key: the service integration key only sends events.

What you need

An API key (request one with the form below) and these endpoints. Full details are in the API reference.

EndpointMethodUsed forPackage
/geojson/at-pointPOSTChecks up to 100 site coordinates per request and returns, in request order, the active outages covering each one and the utilities serving it.Standard + Locations

Step 1: Check what you need

/geojson/at-point is in the Standard + Locations package, and this guide depends on it. In PagerDuty you need a service with an escalation policy, and a role that can add integrations to it: Manager, Admin, Global Admin or Account Owner. The poller runs on any host with Python 3.8 or later and outbound HTTPS to poweroutage.us and events.pagerduty.com. If your PagerDuty account is in the EU service region (you sign in at app.eu.pagerduty.com), change the URL in the script to https://events.eu.pagerduty.com/v2/enqueue.

Step 2: Add an Events API V2 integration

Go to Services > Service Directory and open the service that should receive outage alerts. On the Integrations tab, select Add another integration, choose Events API V2, and select Add. Open the new integration and copy its Integration Key: that is the routing_key the poller sends with every event. It can only send events to this service, but anyone who has it can open alerts there, so keep it with the API key and out of the script.

Step 3: List your sites

Save your sites as JSON, one object per site with a unique id, the name responders will see, and coordinates in decimal degrees. The poller sends them in batches of 100, the endpoint maximum.

json
[
  {"id": "store-101", "name": "Store 101, Atlanta", "lat": 33.749, "lon": -84.388},
  {"id": "store-214", "name": "Store 214, Savannah", "lat": 32.0809, "lon": -81.0912}
]

Step 4: Write the poller

Save this as /opt/poweroutage/poweroutage_pagerduty.py. It uses only the Python standard library. It checks every site first, so a failed or rate-limited request (it waits the Retry-After seconds after a 429, three tries at most) stops the run before anything is triggered or resolved. Outages are keyed poweroutage:<utilityId>:<outageId>; when one covers several sites, they share one alert. A trigger goes out when an outage is new or its list of sites changed, and PagerDuty folds a repeat trigger into the open alert with the same dedup_key. A resolve goes out for each open alert whose outage no longer covers any site. The state file remembers which alerts are open; the poller updates it only after PagerDuty answers 202, and on a 429 or 5xx it leaves the event for the next run.

python
import json
import os
import time
import urllib.error
import urllib.request
from pathlib import Path

API_KEY = os.environ['POWEROUTAGE_API_KEY']
ROUTING_KEY = os.environ['PAGERDUTY_ROUTING_KEY']
# [{"id": "store-101", "name": "Store 101, Atlanta", "lat": 33.749, "lon": -84.388}, ...]
SITES = json.loads(Path(os.environ['SITES_FILE']).read_text())
STATE_FILE = Path(os.environ['STATE_FILE'])  # alerts this script has open, kept between runs
SEVERITY = 'warning'  # critical, error, warning or info


def call(url, body):
    """POST a JSON body to PowerOutage.us, waiting out a 429 for as long as Retry-After says."""
    request = urllib.request.Request(
        url,
        data=json.dumps(body).encode(),
        headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'},
    )
    for attempt in range(3):
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as err:
            if err.code != 429 or attempt == 2:
                raise
            time.sleep(int(err.headers.get('Retry-After', '10')))


def send(event):
    """Send one Events API v2 event. False means PagerDuty asked us to try again later."""
    request = urllib.request.Request(
        'https://events.pagerduty.com/v2/enqueue',
        data=json.dumps({'routing_key': ROUTING_KEY, **event}).encode(),
        headers={'Content-Type': 'application/json'},
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return response.status == 202
    except urllib.error.HTTPError as err:
        if err.code == 429 or err.code >= 500:
            print(f"PagerDuty answered {err.code} for {event['dedup_key']}; the next run retries")
            return False
        raise


# Every outage covering a watched site, keyed the same way as the PagerDuty alert.
# Any failed request stops the script here, before anything is triggered or resolved.
current = {}
for i in range(0, len(SITES), 100):  # up to 100 points per request
    batch = SITES[i : i + 100]
    result = call(
        'https://poweroutage.us/api/v2/geojson/at-point',
        {'points': [{'lat': s['lat'], 'lon': s['lon']} for s in batch]},
    )
    for site, point in zip(batch, result['data']['points']):  # same order as the request
        names = {u['utilityId']: u['name'] for u in point['utilities']}
        for outage in point['outages']:
            key = f"poweroutage:{outage['utilityId']}:{outage['outageId']}"
            utility = names.get(outage['utilityId']) or f"Utility {outage['utilityId']}"
            entry = current.setdefault(key, {'outage': outage, 'utility': utility, 'sites': []})
            entry['sites'].append(site['name'])

open_alerts = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
try:
    for key, entry in current.items():
        if open_alerts.get(key) == entry['sites']:
            continue  # already open for the same sites
        outage = entry['outage']
        sent = send({
            'event_action': 'trigger',
            'dedup_key': key,
            'payload': {
                'summary': f"Power outage at {', '.join(entry['sites'])} ({entry['utility']})"[:1024],
                'source': entry['sites'][0],
                'severity': SEVERITY,
                'class': 'power outage',
                'custom_details': {
                    'utility': entry['utility'],
                    'customersOut': outage['customersOut'],
                    'cause': outage['cause'],
                    'estimatedRestorationAt': outage['estimatedRestorationAt'],
                    'firstSeenAt': outage['firstSeenAt'],
                    'sites': entry['sites'],
                },
            },
        })
        if sent:
            open_alerts[key] = entry['sites']
    for key in [k for k in open_alerts if k not in current]:
        if send({'event_action': 'resolve', 'dedup_key': key}):
            del open_alerts[key]
finally:
    STATE_FILE.write_text(json.dumps(open_alerts))
print(f'{len(current)} outage(s) cover watched sites; {len(open_alerts)} alert(s) open')

Step 5: Know what each event carries

This is every field the poller sends. customersOut, cause and estimatedRestorationAt can be null when the utility does not report them. To route outage alerts differently from your other alerts, or to set urgency by site, add Event Orchestration rules that match on class or on fields in custom_details.

text
Events API v2 field          value
routing_key                  the Integration Key, from PAGERDUTY_ROUTING_KEY
event_action                 trigger, then resolve once no watched site is in the outage
dedup_key                    poweroutage:<utilityId>:<outageId>
payload.summary              Power outage at <site names> (<utility name>)
payload.source               the first site name
payload.severity             SEVERITY from the script (warning)
payload.class                power outage
payload.custom_details       utility, customersOut, cause, estimatedRestorationAt (UTC),
                             firstSeenAt (UTC), sites

Step 6: Run it every 15 minutes

Put the API key and the routing key in an environment file that only the job's account can read, and run the poller from that account's crontab. The shell reads the file, so keep every value in single quotes, as shown. flock -n skips a run while the previous one still holds the lock, so two runs never edit the state file at once. Every 15 minutes is enough for most sites. The data updates every minute, so for the latest answers run it every 1 or 2 minutes (* * * * * or */2 * * * *). The first run triggers alerts for any site already inside an outage.

text
# /opt/poweroutage/pagerduty.env: owned by the account that runs the job, chmod 600.
# Put every value in single quotes, as below; write a single quote inside a value as '\''.
POWEROUTAGE_API_KEY='...'
PAGERDUTY_ROUTING_KEY='...'
SITES_FILE='/opt/poweroutage/sites.json'
STATE_FILE='/opt/poweroutage/pagerduty-open-alerts.json'

# crontab -e, as that account. flock skips a run if the previous one is still going.
*/15 * * * * set -a && . /opt/poweroutage/pagerduty.env && flock -n /opt/poweroutage/pagerduty.lock /usr/bin/python3 /opt/poweroutage/poweroutage_pagerduty.py >> /opt/poweroutage/poweroutage_pagerduty.log 2>&1

Tips for PagerDuty

  • Keep the state file. If it is lost, the poller forgets which alerts it opened and will not resolve them, so resolve those by hand. On a serverless scheduler, store the state in S3, DynamoDB or similar instead of a local file.
  • PagerDuty throttles busy integration keys and answers 429. The poller sends at most one event per outage per run, and anything throttled is retried on the next run.
  • A site whose utilities all report providesGeospatialData: false never gets an alert, because those utilities publish counts by area only. Check the utilities list in the response to see which sites are affected.
  • Utilities sometimes report overlapping outages, so one site can sit in two open alerts with different dedup_key values.
  • Set SEVERITY to critical for sites that should page someone at night, or run a second copy of the poller with its own sites file and routing key for those sites.

Used by

Related integrations

FAQ

Here are some commonly asked questions

Request API access

Tell us what you're building and we'll set you up with a trial key.