oncall-engine/engine/apps/api_for_grafana_incident/serializers.py
Aron Bordin d583727c05
add labels in grafana-incident alertgroup endpoint (#4448)
# What this PR does

## Which issue(s) this PR closes

this PR updates the grafana incident API to include information about
the alert group labels.

## Checklist

- [x] Unit, integration, and e2e (if applicable) tests updated
- [x] Documentation added (or `pr:no public docs` PR label added if not
required)
- [x] Added the relevant release notes label (see labels prefixed w/
`release:`). These labels dictate how your PR will
    show up in the autogenerated release notes.

---------

Co-authored-by: Joey Orlando <joey.orlando@grafana.com>
2024-06-25 14:50:55 +00:00

71 lines
2.3 KiB
Python

import logging
from rest_framework import serializers
from apps.alerts.incident_appearance.renderers.web_renderer import AlertGroupWebRenderer
from apps.alerts.models import Alert, AlertGroup
from apps.api.serializers.alert_group import AlertGroupFieldsCacheSerializerMixin
from apps.labels.models import AlertGroupAssociatedLabel
logger = logging.getLogger(__name__)
class AlertSerializer(serializers.ModelSerializer):
id_oncall = serializers.CharField(read_only=True, source="public_primary_key")
payload = serializers.JSONField(read_only=True, source="raw_request_data")
class Meta:
model = Alert
fields = [
"id_oncall",
"payload",
]
class LabelsSerializer(serializers.ModelSerializer):
key = serializers.CharField(read_only=True, source="key_name")
value = serializers.CharField(read_only=True, source="value_name")
class Meta:
model = AlertGroupAssociatedLabel
fields = [
"key",
"value",
]
class AlertGroupSerializer(serializers.ModelSerializer):
id = serializers.CharField(read_only=True, source="public_primary_key")
status = serializers.SerializerMethodField(source="get_status")
link = serializers.CharField(read_only=True, source="web_link")
title = serializers.CharField(read_only=True, source="long_verbose_name_without_formatting")
alerts = AlertSerializer(many=True, read_only=True)
labels = LabelsSerializer(many=True, read_only=True)
render_for_web = serializers.SerializerMethodField()
def get_status(self, obj):
return next(filter(lambda status: status[0] == obj.status, AlertGroup.STATUS_CHOICES))[1].lower()
def get_render_for_web(self, obj):
last_alert = obj.alerts.last()
if last_alert is None:
return {}
return AlertGroupFieldsCacheSerializerMixin.get_or_set_web_template_field(
obj,
last_alert,
AlertGroupFieldsCacheSerializerMixin.RENDER_FOR_WEB_FIELD_NAME,
AlertGroupWebRenderer,
)
class Meta:
model = AlertGroup
fields = [
"id",
"link",
"status",
"alerts",
"title",
"render_for_web",
"labels",
]