Skip to content

Commit

Permalink
add new database columns + emit two new django signals
Browse files Browse the repository at this point in the history
- add new columns `gcom_org_contract_type` and `gcom_org_has_irm_sku` to
`user_management_organization` table + `is_restricted` column to
`alerts_alertgroup` table
- emit two new Django signals
  - `org_sync_signal` at the end of the organization sync task
  - `alert_group_created_signal` when a new Alert Group is created
  • Loading branch information
joeyorlando committed Mar 22, 2023
1 parent bfe06ac commit 5d0d2d2
Show file tree
Hide file tree
Showing 15 changed files with 136 additions and 29 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Modified `check_escalation_finished_task` celery task to use read-only databases for its query, if one is defined +
make the validation logic stricter + ping a configurable heartbeat on successful completion of this task ([1266](https://github.com/grafana/oncall/pull/1266))
- add new columns `gcom_org_contract_type` and `gcom_org_has_irm_sku` to `user_management_organization` table +
`is_restricted` column to `alerts_alertgroup` table ([1522](https://github.com/grafana/oncall/pull/1522))
- emit two new Django signals ([1522](https://github.com/grafana/oncall/pull/1522))
- `org_sync_signal` at the end of the `engine/apps/user_management/sync.py::sync_organization` method
- `alert_group_created_signal` when a new Alert Group is created

### Changed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ def templater_class(self):

def render(self):
templated_alert = self.templated_alert
rendered_alert = {
"title": str_or_backup(templated_alert.title, "Alert"),
"message": str_or_backup(templated_alert.message, ""),
"image_url": str_or_backup(templated_alert.image_url, None),
"source_link": str_or_backup(templated_alert.source_link, None),
is_restricted = self.alert.group.is_restricted

# TODO: update these..
is_restricted_msg = "RESTRICTED TODO TODO"
return {
"title": is_restricted_msg if is_restricted else str_or_backup(templated_alert.title, "Alert"),
"message": is_restricted_msg if is_restricted else str_or_backup(templated_alert.message, ""),
"image_url": None if is_restricted else str_or_backup(templated_alert.image_url, None),
"source_link": None if is_restricted else str_or_backup(templated_alert.source_link, None),
}
return rendered_alert


class AlertGroupClassicMarkdownRenderer(AlertGroupBaseRenderer):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ def render(self):
templated_alert = self.alert_renderer.templated_alert
title = str_or_backup(templated_alert.title, DEFAULT_BACKUP_TITLE)

text = self.TEMPLATE.format(
if self.alert_group.is_restricted:
# TODO: update this text
return "RESTRICTED TODO TODO"

return self.TEMPLATE.format(
integration_name=self.alert_group.channel.short_name,
title=title,
alert_count=self.alert_group.alerts.count(),
)

return text
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def render_alert_attachments(self):
return attachments


# TODO:
class AlertGroupSlackRenderer(AlertGroupBaseRenderer):
def __init__(self, alert_group):
super().__init__(alert_group)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ def alert_renderer_class(self):
def render(self):
templated_alert = self.alert_renderer.templated_alert
title = str_or_backup(templated_alert.title, DEFAULT_BACKUP_TITLE)

if self.alert_group.is_restricted:
# TODO: update this text
return "RESTRICTED TODO TODO"

if self.alert_group.channel.organization.slack_team_identity and (
permalink := self.alert_group.slack_permalink
):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,20 @@ def render(self):
# First line in the invisible link with id of organization.
# It is needed to add info about organization to the telegram message for the oncall-gateway.
text = f"<a href='{self.alert_group.channel.organization.web_link_with_uuid}'>&#8205;</a>"
text += f"{status_emoji} #{self.alert_group.inside_organization_number}, {title}\n"
text += f"{status_verbose}, alerts: {alerts_count_str}\n"
text += f"Source: {self.alert_group.channel.short_name}\n"
text += f"{self.alert_group.web_link}"

if message:
text += f"\n\n{message}"
if self.alert_group.is_restricted:
# TODO: update this text
text += "RESTRICTED TODO TODO"
else:
text += f"{status_emoji} #{self.alert_group.inside_organization_number}, {title}\n"
text += f"{status_verbose}, alerts: {alerts_count_str}\n"
text += f"Source: {self.alert_group.channel.short_name}\n"
text += f"{self.alert_group.web_link}"

if message:
text += f"\n\n{message}"

if image_url is not None:
text = f"<a href='{image_url}'>&#8205;</a>" + text
if image_url is not None:
text = f"<a href='{image_url}'>&#8205;</a>" + text

return emojize(text, use_aliases=True)
15 changes: 9 additions & 6 deletions engine/apps/alerts/incident_appearance/renderers/web_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ def templater_class(self):

def render(self):
templated_alert = self.templated_alert
rendered_alert = {
"title": str_or_backup(templated_alert.title, "Alert"),
"message": str_or_backup(templated_alert.message, ""),
"image_url": str_or_backup(templated_alert.image_url, None),
"source_link": str_or_backup(templated_alert.source_link, None),
is_restricted = self.alert.group.is_restricted

# TODO: update these..
is_restricted_msg = "RESTRICTED TODO TODO"
return {
"title": is_restricted_msg if is_restricted else str_or_backup(templated_alert.title, "Alert"),
"message": is_restricted_msg if is_restricted else str_or_backup(templated_alert.message, ""),
"image_url": None if is_restricted else str_or_backup(templated_alert.image_url, None),
"source_link": None if is_restricted else str_or_backup(templated_alert.source_link, None),
}
return rendered_alert


class AlertGroupWebRenderer(AlertGroupBaseRenderer):
Expand Down
29 changes: 29 additions & 0 deletions engine/apps/alerts/migrations/0011_auto_20230322_0951.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 3.2.18 on 2023-03-22 09:51

import datetime
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('alerts', '0010_channelfilter_filtering_term_type'),
]

operations = [
migrations.AddField(
model_name='alertgroup',
name='is_restricted',
field=models.BooleanField(default=False, null=True),
),
migrations.AddField(
model_name='alertgroupcounter',
name='current_month',
field=models.DateField(default=datetime.date.today),
),
migrations.AddField(
model_name='alertgroupcounter',
name='value_this_month',
field=models.PositiveBigIntegerField(default=0),
),
]
11 changes: 6 additions & 5 deletions engine/apps/alerts/models/alert_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from apps.alerts.incident_appearance.renderers.constants import DEFAULT_BACKUP_TITLE
from apps.alerts.incident_appearance.renderers.slack_renderer import AlertGroupSlackRenderer
from apps.alerts.incident_log_builder import IncidentLogBuilder
from apps.alerts.signals import alert_group_action_triggered_signal
from apps.alerts.signals import alert_group_action_triggered_signal, alert_group_created_signal
from apps.alerts.tasks import acknowledge_reminder_task, call_ack_url, send_alert_group_signal, unsilence_task
from apps.slack.slack_formatter import SlackFormatter
from apps.user_management.models import User
Expand Down Expand Up @@ -88,10 +88,9 @@ def get_or_create_grouping(self, channel, channel_filter, group_data):

# Create a new group if we couldn't group it to any existing ones
try:
return (
self.create(**search_params, is_open_for_grouping=True, web_title_cache=group_data.web_title_cache),
True,
)
ag = self.create(**search_params, is_open_for_grouping=True, web_title_cache=group_data.web_title_cache)
alert_group_created_signal.send(sender=self.__class__, alert_group=ag)
return (ag, True)
except IntegrityError:
try:
return self.get(**search_params, is_open_for_grouping__isnull=False), False
Expand Down Expand Up @@ -351,6 +350,8 @@ def status(self):
# https://code.djangoproject.com/ticket/28545
is_open_for_grouping = models.BooleanField(default=None, null=True, blank=True)

is_restricted = models.BooleanField(default=False, null=True)

@staticmethod
def get_silenced_state_filter():
"""
Expand Down
18 changes: 17 additions & 1 deletion engine/apps/alerts/models/alert_group_counter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import date

from django.db import models


Expand All @@ -9,7 +11,18 @@ class AlertGroupCounterQuerySet(models.QuerySet):
def get_value(self, organization):
counter, _ = self.get_or_create(organization=organization)

num_updated_rows = self.filter(organization=organization, value=counter.value).update(value=counter.value + 1)
today = date.today()
update_kwargs = {}
if counter.current_month.month != today.month or counter.current_month.year != today.year:
# if the previous alert group was created not in the current month, reset the monthly counter values
update_kwargs["current_month"] = today
update_kwargs["value_this_month"] = 1
else:
update_kwargs["value_this_month"] = counter.value_this_month + 1

num_updated_rows = self.filter(organization=organization, value=counter.value).update(
value=counter.value + 1, **update_kwargs
)
if num_updated_rows == 0:
raise ConcurrentUpdateError()

Expand All @@ -28,3 +41,6 @@ class AlertGroupCounter(models.Model):

organization = models.OneToOneField("user_management.Organization", on_delete=models.CASCADE)
value = models.PositiveBigIntegerField(default=0)

current_month = models.DateField(default=date.today)
value_this_month = models.PositiveBigIntegerField(default=0)
6 changes: 6 additions & 0 deletions engine/apps/alerts/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
]
)

alert_group_created_signal = django.dispatch.Signal(
providing_args=[
"alert_group",
]
)

# Signal to rerender alert group in all connected integrations (Slack, Telegram) when its state is changed
alert_group_action_triggered_signal = django.dispatch.Signal(
providing_args=[
Expand Down
23 changes: 23 additions & 0 deletions engine/apps/user_management/migrations/0010_auto_20230321_1054.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 3.2.18 on 2023-03-21 10:54

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('user_management', '0009_organization_cluster_slug'),
]

operations = [
migrations.AddField(
model_name='organization',
name='gcom_org_contract_type',
field=models.CharField(default=None, max_length=300, null=True),
),
migrations.AddField(
model_name='organization',
name='gcom_org_has_irm_sku',
field=models.BooleanField(default=False, null=True),
),
]
2 changes: 2 additions & 0 deletions engine/apps/user_management/models/organization.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ def _get_subscription_strategy(self):

gcom_token = mirage_fields.EncryptedCharField(max_length=300, null=True, default=None)
gcom_token_org_last_time_synced = models.DateTimeField(null=True, default=None)
gcom_org_contract_type = models.CharField(max_length=300, null=True, default=None)
gcom_org_has_irm_sku = models.BooleanField(default=False, null=True)

last_time_synced = models.DateTimeField(null=True, default=None)

Expand Down
3 changes: 3 additions & 0 deletions engine/apps/user_management/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import django.dispatch

org_sync_signal = django.dispatch.Signal()
3 changes: 3 additions & 0 deletions engine/apps/user_management/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from apps.grafana_plugin.helpers.client import GcomAPIClient, GrafanaAPIClient
from apps.user_management.models import Organization, Team, User
from apps.user_management.signals import org_sync_signal

logger = get_task_logger(__name__)
logger.setLevel(logging.DEBUG)
Expand Down Expand Up @@ -55,6 +56,8 @@ def sync_organization(organization):
]
)

org_sync_signal.send(sender=None, org_id=organization.id)


def _sync_instance_info(organization):
if organization.gcom_token:
Expand Down

0 comments on commit 5d0d2d2

Please sign in to comment.