Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat(Escalation policies): A Hackweek project #76386

Draft
wants to merge 39 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
c50c1f9
CRUDL APIs for escalation policies and rotation schedules
mikejihbe Aug 14, 2024
3aed160
CRUDL for rotation schedules and escalation policies
mikejihbe Aug 14, 2024
b1e24ba
Add schedule layer coalescing logic and tests
mikejihbe Aug 19, 2024
a4f3c51
Fix up tests
mikejihbe Aug 19, 2024
569ab55
Fix up tests
mikejihbe Aug 19, 2024
382d490
Add coalesced schedules to schedule serializers. use UTC everywhere e…
mikejihbe Aug 19, 2024
b6cf20d
Add endpoints and tests for querying escalation policy states
mikejihbe Aug 19, 2024
118458e
update datastore
mikejihbe Aug 19, 2024
a14dd5c
Seed WIP
corps Aug 20, 2024
dae20f6
Let migration be unsafe for now
corps Aug 20, 2024
cac957c
Typo fix
corps Aug 20, 2024
8d911e0
Add rotation periods to each layer serialization
mikejihbe Aug 20, 2024
69ecc4c
feat(escalation_policies): Add FE hooks for Rotation Schedule and Esc…
MichaelSun48 Aug 20, 2024
54772f2
Add page routes for schedule and escalation policies (#76408)
MichaelSun48 Aug 20, 2024
8e1b516
Add occurrence list page
mikejihbe Aug 20, 2024
f6c41af
Camelcase serialized responses
mikejihbe Aug 20, 2024
7dfc1cc
Fix data formatting issue
corps Aug 20, 2024
d3fa496
Fix team serialization in APIs
mikejihbe Aug 20, 2024
27e3bce
Add a REALLY FUGLY occurrences list that allows for updating state of…
mikejihbe Aug 20, 2024
f1b06f4
feat(escalation_policies): Add preliminary design for escalation poli…
MichaelSun48 Aug 20, 2024
6375c1a
Wire up escalation policies
mikejihbe Aug 20, 2024
5b7d709
feat(escalation_policies): Add basic, unfinished designs for schedule…
MichaelSun48 Aug 20, 2024
c55a66c
Feat(Escalation policies): Escalation event action
RyanSkonnord Aug 21, 2024
abcc3d6
hook up rotation schedule list
mikejihbe Aug 21, 2024
48b6281
Unify schedule timelines and make timeWindowConfig work properly
mikejihbe Aug 21, 2024
45a339e
Get basic schedule timeline view working
mikejihbe Aug 21, 2024
2fe434e
remove schedule name to clean up the rotation timeline
mikejihbe Aug 21, 2024
c0d7570
Add description to rotation schedules
mikejihbe Aug 21, 2024
5399bfc
Adding escalation job
corps Aug 21, 2024
a366d41
Merge branch 'hackweek/escalation_policies_alert_rule_action' into ha…
RyanSkonnord Aug 21, 2024
4bd515a
feat(escalation_policies): Various improvements to the occurrences ta…
MichaelSun48 Aug 21, 2024
4ffed7f
Fix serializer
mikejihbe Aug 21, 2024
8fd4d5b
add tooltip for schedule periods (#76477)
MichaelSun48 Aug 22, 2024
8ee4222
WIP
corps Aug 22, 2024
4c0f542
WIP
corps Aug 22, 2024
0623757
WIP
corps Aug 22, 2024
a889ecd
Add requisite copy-paste to NotifyEscalationAction
RyanSkonnord Aug 22, 2024
9e0a3a1
Works!
corps Aug 22, 2024
1743ed6
chore(escalation_policies): Minor UI Improvements across the board (#…
MichaelSun48 Aug 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
391 changes: 391 additions & 0 deletions bin/escalation-policy-seed-data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,391 @@
#!/usr/bin/env python
import dataclasses
import datetime
import random
from functools import cached_property
from typing import Protocol

from sentry.runner import configure

configure()

import click


@click.command()
def seed_policy_data():
from sentry.escalation_policies.models.escalation_policy import (
EscalationPolicy,
EscalationPolicyStep,
EscalationPolicyStepRecipient,
)
from sentry.escalation_policies.models.rotation_schedule import (
RotationSchedule,
RotationScheduleLayer,
RotationScheduleLayerRotationType,
RotationScheduleOverride,
RotationScheduleUserOrder,
ScheduleLayerRestriction,
)
from sentry.models.organization import Organization
from sentry.models.team import Team, TeamStatus
from sentry.testutils.factories import Factories # noqa: S007

def make_restrictions() -> list[tuple[str, str]]:
start = 0
result = []
for i in range(random.randint(0, 4)):
start += random.randint(1, 60 * 5)
end = start + random.randint(1, 60 * 5)
if end >= 60 * 24:
break
result.append(
(f"{int(start / 60):02d}:{start % 60:02d}", f"{int(end / 60):02d}:{end % 60:02d}")
)
return result

class TeamAndUserId(Protocol):
team: Team
user_id: int

@dataclasses.dataclass
class OrgContext:
org_id: int = 1
team_count: int = 5
user_count: int = 5
schedule_count: int = 8
policy_count: int = 5

def ensure_team_and_user_pool(self):
for i in range(self.team_count - len(self.teams)):
self.teams.append(
Factories.create_team(
organization=self.organization,
name=f"Demo Team {i}",
)
)
for i in range(self.user_count - len(self.user_ids)):
u = Factories.create_user()
Factories.create_member(teams=self.teams, user=u, organization=self.organization)
self.user_ids.append(u.id)
for i in range(self.schedule_count - len(self.schedules)):
self.schedules.append(RotationScheduleFactory(org_context=self).build())

# Fix restrictions by recomputing
for schedule in self.schedules:
for layer in RotationScheduleLayer.objects.filter(schedule=schedule):
restriction: ScheduleLayerRestriction = {
"Sun": make_restrictions(),
"Mon": make_restrictions(),
"Tue": make_restrictions(),
"Wed": make_restrictions(),
"Thu": make_restrictions(),
"Fri": make_restrictions(),
"Sat": make_restrictions(),
}

layer.schedule_layer_restrictions = restriction
layer.save()

def ensure_policies(self):
for i in range(self.policy_count - len(self.policies)):
pf = PolicyFactory(self)
self.policies.append(pf.build())

def contextualize_slug_or_user_id(
self, model: TeamAndUserId, slug_or_user_id: str | int | None
):
if isinstance(slug_or_user_id, str):
model.team = next(t for t in self.teams if t.slug == slug_or_user_id)
elif isinstance(slug_or_user_id, int):
model.user_id = slug_or_user_id
else:
if random.random() < 0.5:
slug_or_user_id = random.choice(self.teams).slug
else:
slug_or_user_id = random.choice(self.user_ids)
self.contextualize_slug_or_user_id(model, slug_or_user_id)

@cached_property
def organization(self) -> Organization:
return Organization.objects.get(pk=self.org_id)

@cached_property
def policies(self) -> list[EscalationPolicy]:
return list(EscalationPolicy.objects.filter(organization=self.organization))

@cached_property
def user_ids(self) -> list[int]:
return list(self.organization.member_set.values_list("user_id", flat=True))

@cached_property
def schedules(self) -> list[RotationSchedule]:
return list(RotationSchedule.objects.filter(organization=self.organization))

@cached_property
def teams(self) -> list[Team]:
return list(
Team.objects.filter(
status=TeamStatus.ACTIVE,
organization=self.organization,
)
)

@dataclasses.dataclass
class RotationScheduleFactory:
org_context: OrgContext
name: str = ""
owner_user_id_or_team_slug: str | int | None = None

@cached_property
def organization(self) -> Organization:
return self.org_context.organization

@cached_property
def rotation_schedule(self) -> RotationSchedule:
schedule = RotationSchedule(
organization=self.organization,
name=self.final_name,
description=self.final_desc,
)

self.org_context.contextualize_slug_or_user_id(
schedule, self.owner_user_id_or_team_slug
)

schedule.save()
return schedule

@cached_property
def final_name(self) -> str:
c = 1
name = self.name or "Rotation Schedule"
while True:
if not RotationSchedule.objects.filter(
organization=self.organization, name=name
).exists():
break
name = name.removesuffix(" " + str(c))
c += 1
name += " " + str(c)
return name

@cached_property
def final_desc(self) -> str:
words = [
"liberty",
"kettle",
"courage",
"stand",
"satisfaction",
"compliance",
"work",
"voyage",
"district",
"dialogue",
"quit",
"management",
"standard",
"remain",
"graze",
"carpet",
"master",
"relevance",
"machinery",
"rubbish",
"singer",
"presidency",
"horn",
"activate",
"carry",
"sphere",
"shape",
"waiter",
"peasant",
"string",
"result",
"rhetoric",
"occasion",
"thanks",
"auction",
"dawn",
"head",
"wind",
"cater",
"brilliance",
"packet",
"unfair",
"wolf",
"loan",
"thick",
"strikebreaker",
"sunrise",
"minimum",
"resource",
"digital",
]
return "This is a schedule for " + " ".join(random.choices(words, k=5))

@cached_property
def overrides(self) -> list[RotationScheduleOverride]:
start = datetime.datetime.utcnow() - datetime.timedelta(hours=12)
results = []
for i in range(random.randint(0, 6)):
end = start + datetime.timedelta(hours=random.randint(3, 9))
user_id = random.choice(self.org_context.user_ids)
override = RotationScheduleOverride(
rotation_schedule=self.rotation_schedule,
user_id=user_id,
start_time=start,
end_time=end,
)
override.save()
start = end + datetime.timedelta(hours=random.randint(3, 9))
results.append(override)
return results

@cached_property
def schedule_layers(self) -> list[RotationScheduleLayer]:
results = []
for i in range(random.randint(1, 5)):
layer = RotationScheduleLayer(
schedule=self.rotation_schedule,
precedence=i,
rotation_type=random.choice(list(RotationScheduleLayerRotationType)),
handoff_time=f"{random.randint(0, 23):02d}:{random.randint(0, 59):02d}",
start_date=(
datetime.datetime.utcnow() - datetime.timedelta(days=random.randint(1, 30))
).date(),
)

restriction: ScheduleLayerRestriction = {
"Sun": make_restrictions(),
"Mon": make_restrictions(),
"Tue": make_restrictions(),
"Wed": make_restrictions(),
"Thu": make_restrictions(),
"Fri": make_restrictions(),
"Sat": make_restrictions(),
}

layer.schedule_layer_restrictions = restriction
layer.save()
results.append(layer)
return results

@cached_property
def user_orders(self) -> list[RotationScheduleUserOrder]:
result = []
for layer in self.schedule_layers:
user_ids = random.sample(self.org_context.user_ids, random.randint(1, 5))
for i, user_id in enumerate(user_ids):
uo = RotationScheduleUserOrder(
schedule_layer=layer,
user_id=user_id,
order=i,
)
uo.save()
result.append(uo)
return result

def build(self):
return (
self.rotation_schedule,
self.schedule_layers,
self.user_orders,
)[0]

@dataclasses.dataclass
class PolicyFactory:
org_context: OrgContext
owner_user_id_or_team_slug: str | int | None = None
name: str = ""
repeat_n_times: int = dataclasses.field(default_factory=lambda: random.randint(1, 5))

@cached_property
def organization(self) -> Organization:
return self.org_context.organization

@cached_property
def final_name(self) -> str:
c = 1
name = self.name or "Escalation Policy"
while True:
if not EscalationPolicy.objects.filter(
organization=self.organization, name=name
).exists():
break
name = name.removesuffix(" " + str(c))
c += 1
name += " " + str(c)
return name

@cached_property
def policy(self) -> EscalationPolicy:
policy = EscalationPolicy(
organization=self.organization,
name=self.final_name,
description="",
repeat_n_times=self.repeat_n_times,
)

self.org_context.contextualize_slug_or_user_id(policy, self.owner_user_id_or_team_slug)

policy.save()
return policy

@cached_property
def steps(self):
result = []
for i in range(5):
step = EscalationPolicyStep(
policy=self.policy,
step_number=i + 1,
escalate_after_sec=random.randint(1, 5) * 15,
)
step.save()
result.append(step)
return result

@cached_property
def recipients(self):
result = []
for step in self.steps:
result.append(
EscalationPolicyStepRecipient(
escalation_policy_step=step,
schedule=random.choice(self.org_context.schedules),
)
)
result.append(
EscalationPolicyStepRecipient(
escalation_policy_step=step,
team=random.choice(self.org_context.teams),
)
)
result.append(
EscalationPolicyStepRecipient(
escalation_policy_step=step,
user_id=random.choice(self.org_context.user_ids),
)
)

for recipient in result:
recipient.save()

return result

def build(self):
return (
self.policy,
self.steps,
self.recipients,
)[0]

context = OrgContext()
context.ensure_team_and_user_pool()
context.ensure_policies()


if __name__ == "__main__":
seed_policy_data()
2 changes: 1 addition & 1 deletion migrations_lockfile.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ hybridcloud: 0016_add_control_cacheversion
nodestore: 0002_nodestore_no_dictfield
remote_subscriptions: 0003_drop_remote_subscription
replays: 0004_index_together
sentry: 0747_create_datasecrecywaiver_table
sentry: 0751_escalation_policies3
social_auth: 0002_default_auto_field
uptime: 0006_projectuptimesubscription_name_owner
Loading
Loading