# Buggy code
def parse_prometheus(alert, external_url):
    status = alert.get("status", "firing")

    labels = copy(alert["labels"])
    annotations = copy(alert["annotations"])

    starts_at = parse_date(alert["startsAt"])
    if alert["endsAt"] == "0001-01-01T00:00:00Z":
        ends_at = None
    else:
        ends_at = parse_date(alert["endsAt"])

    if status == "firing":
        severity = labels.pop("severity", "warning")
        create_time = starts_at
    elif status == "resolved":
        severity = "normal"
        create_time = ends_at
    else:
        severity = "unknown"
        create_time = ends_at or starts_at

    # get labels
    resource = labels.pop("exported_instance", None) or labels.pop("instance", "n/a")
    event = labels.pop("alertname")
    environment = labels.pop("environment", "Production")

    # get annotations
    correlate = (
        annotations.pop("correlate").split(",") if "correlate" in annotations else None
    )
    service = annotations.pop("service", "").split(",")
    group = annotations.pop("job", "Prometheus")
    value = annotations.pop("value", None)

    # build alert text
    summary = annotations.pop("summary", None)
    description = annotations.pop("description", None)
    text = (
        description
        or summary
        or "%s: %s on %s" % (labels["job"], labels["alertname"], labels["instance"])
    )

    try:
        timeout = int(labels.pop("timeout", 0)) or None
    except ValueError:
        timeout = None

    if external_url:
        annotations["externalUrl"] = external_url
    if "generatorURL" in alert:
        annotations["moreInfo"] = (
            '<a href="%s" target="_blank">Prometheus Graph</a>' % alert["generatorURL"]
        )

    return Alert(
        resource=resource,
        event=event,
        environment=environment,
        severity=severity,
        correlate=correlate,
        service=service,
        group=group,
        value=value,
        text=text,
        attributes=annotations,
        origin="prometheus/" + labels.pop("monitor", "-"),
        event_type="prometheusAlert",
        create_time=create_time.astimezone(tz=pytz.UTC).replace(tzinfo=None),
        timeout=timeout,
        raw_data=alert,
        tags=["%s=%s" % t for t in labels.items()],  # any labels left are used for tags
    )


# Traceback (KeyError)
alerta_1        | 2018-08-05 21:56:22,585 DEBG 'uwsgi' stdout output:
alerta_1        | [pid: 71|app: 0|req: 218/1482] 172.30.0.2 () {38 vars in 518 bytes} [Sun Aug  5 21:56:22 2018] POST /api/webhooks/prometheus => generated 1088 bytes in 329 msecs (HTTP/1.1 500) 4 headers in 153 bytes (1 switches on core 0)
alerta_1        |
alerta_1        | 2018-08-05 21:56:22,585 DEBG 'nginx' stdout output:
alerta_1        | ip=\- [\05/Aug/2018:21:56:22 +0000] "\POST /api/webhooks/prometheus HTTP/1.1" \500 \1088 "\-" "\Alertmanager/0.15.1"
alerta_1        | 2018/08/05 21:56:22 [info] 66#66: *2730 client 172.30.0.2 closed keepalive connection
alerta_1        |
alerta_1        | 2018-08-05 21:56:22,699 DEBG 'uwsgi' stdout output:
alerta_1        | 2018-08-05 21:56:22,698 - flask.app[73]: ERROR - 'alertname' [in /venv/lib/python3.7/site-packages/alerta/exceptions.py:95]
alerta_1        | Traceback (most recent call last):
alerta_1        |   File "/venv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
alerta_1        |     rv = self.dispatch_request()
alerta_1        |   File "/venv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
alerta_1        |     return self.view_functions[rule.endpoint](**req.view_args)
alerta_1        |   File "/venv/lib/python3.7/site-packages/flask_cors/decorator.py", line 128, in wrapped_function
alerta_1        |     resp = make_response(f(*args, **kwargs))
alerta_1        |   File "/venv/lib/python3.7/site-packages/alerta/auth/decorators.py", line 88, in wrapped
alerta_1        |     return f(*args, **kwargs)
alerta_1        |   File "/venv/lib/python3.7/site-packages/alerta/webhooks/prometheus.py", line 94, in prometheus
alerta_1        |     incomingAlert = parse_prometheus(alert, external_url)
alerta_1        |   File "/venv/lib/python3.7/site-packages/alerta/webhooks/prometheus.py", line 52, in parse_prometheus
alerta_1        |     text = description or summary or '%s: %s on %s' % (labels['job'], labels['alertname'], labels['instance'])
alerta_1        | KeyError: 'alertname'
alerta_1        | 2018-08-05 21:56:22,700 DEBG 'uwsgi' stdout output:
alerta_1        |
alerta_1        |
db_1            | 2018-08-05T21:56:22.703+0000 I NETWORK  [conn2971] end connection 172.31.0.3:52282 (1 connection now open)
db_1            | 2018-08-05T21:56:22.704+0000 I NETWORK  [conn2972] end connection 172.31.0.3:52284 (0 connections now open)
alerta_1        | 2018-08-05 21:56:22,707 DEBG 'nginx' stdout output:
alerta_1        | ip=\- [\05/Aug/2018:21:56:22 +0000] "\POST /api/webhooks/prometheus HTTP/1.1" \500 \1088 "\-" "\Alertmanager/0.15.1"

# Fixed code
def parse_prometheus(alert, external_url):
    status = alert.get("status", "firing")

    labels = copy(alert["labels"])
    annotations = copy(alert["annotations"])

    starts_at = parse_date(alert["startsAt"])
    if alert["endsAt"] == "0001-01-01T00:00:00Z":
        ends_at = None
    else:
        ends_at = parse_date(alert["endsAt"])

    if status == "firing":
        severity = labels.pop("severity", "warning")
        create_time = starts_at
    elif status == "resolved":
        severity = "normal"
        create_time = ends_at
    else:
        severity = "unknown"
        create_time = ends_at or starts_at

    # get labels
    resource = labels.pop("exported_instance", None) or labels.pop("instance", "n/a")
    event = labels.pop("alertname")
    environment = labels.pop("environment", "Production")

    # get annotations
    correlate = (
        annotations.pop("correlate").split(",") if "correlate" in annotations else None
    )
    service = annotations.pop("service", "").split(",")
    group = annotations.pop("job", "Prometheus")
    value = annotations.pop("value", None)

    # build alert text
    summary = annotations.pop("summary", None)
    description = annotations.pop("description", None)
    text = (
        description
        or summary
        or "{}: {} is {}".format(severity.upper(), resource, event)
    )

    try:
        timeout = int(labels.pop("timeout", 0)) or None
    except ValueError:
        timeout = None

    if external_url:
        annotations["externalUrl"] = external_url
    if "generatorURL" in alert:
        annotations["moreInfo"] = (
            '<a href="%s" target="_blank">Prometheus Graph</a>' % alert["generatorURL"]
        )

    return Alert(
        resource=resource,
        event=event,
        environment=environment,
        severity=severity,
        correlate=correlate,
        service=service,
        group=group,
        value=value,
        text=text,
        attributes=annotations,
        origin="prometheus/" + labels.pop("monitor", "-"),
        event_type="prometheusAlert",
        create_time=create_time.astimezone(tz=pytz.UTC).replace(tzinfo=None),
        timeout=timeout,
        raw_data=alert,
        tags=["%s=%s" % t for t in labels.items()],  # any labels left are used for tags
    )