Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from datetime import datetime, timezone, timedelta

from django.core.management.base import BaseCommand
from django_q.tasks import schedule, Schedule


import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class Command(BaseCommand):
"""
Registers a django-q schedule that updates allocations based on set criterias. The schedule runs everyday
"""

def handle(self, *args, **options):
date = datetime.now(timezone.utc) + timedelta(days=1)
date = date.replace(
hour=0, minute=0, second=0, microsecond=0
) # TODO: What time of day to run this job?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

schedule(
"coldfront_plugin_cloud.tasks.remind_allocations_revoked",
schedule_type=Schedule.DAILY,
next_run=date,
)
48 changes: 45 additions & 3 deletions src/coldfront_plugin_cloud/tasks.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import datetime
from datetime import datetime, timezone, timedelta
import logging
import time
from string import Template
Expand All @@ -8,6 +8,9 @@
AllocationUser,
AllocationAttribute,
)
from coldfront.core.utils import mail
from coldfront.core.utils.common import import_from_settings


from coldfront_plugin_cloud import (
attributes,
Expand All @@ -22,6 +25,12 @@

logger = logging.getLogger(__name__)

CENTER_BASE_URL = import_from_settings("CENTER_BASE_URL")
EMAIL_SENDER = import_from_settings("EMAIL_SENDER")

REMINDER_SCHEDULE_DAYS = [30, 14, 7, 2]
EXPIRATION_REMINDER_TEMPLATE = """""" # TODO (Quan): To be filled by https://github.com/nerc-project/coldfront-plugin-cloud/issues/316


def get_kc_client():
return kc_client.KeyCloakAPIClient()
Expand Down Expand Up @@ -106,13 +115,13 @@ def add_user_to_allocation(allocation_user_pk):
# Note(knikolla): This task may be executed at the same time as
# activating an allocation, therefore it has to wait for the project
# to finish creating. Maximum wait is 2 minutes.
time_start = datetime.datetime.utcnow()
time_start = datetime.utcnow()
max_wait_seconds = 120

while not (
project_id := allocation.get_attribute(attributes.ALLOCATION_PROJECT_ID)
):
delta = datetime.datetime.utcnow() - time_start
delta = datetime.utcnow() - time_start
if delta.seconds >= max_wait_seconds:
raise Exception(
f"Project not yet created after {delta.seconds} seconds."
Expand Down Expand Up @@ -220,3 +229,36 @@ def remove_user_from_keycloak(allocation_user_pk):
)
return
kc_admin_client.remove_user_from_group(user_id, group_id)


def remind_allocations_revoked():
today = datetime.now(timezone.utc)
reminder_dates = [today + timedelta(days=d) for d in REMINDER_SCHEDULE_DAYS]
status_to_remind = [ # TODO: Confirm these are the statuses we want alerted?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@joachimweyl @knikolla @naved001 What about current existing allocations that are in the soon-to-be-removed Active (Needs Renewal) status?

"Expired"
]

allocations_to_alert = Allocation.objects.filter(
status__name__in=status_to_remind, end_date__in=reminder_dates
)

for allocation in allocations_to_alert:
pi_email = allocation.project.pi.email
managers_query = allocation.project.projectuser_set.filter(
role__name="Manager", status__name="Active", enable_notifications=True
)
manager_emails = [
manager.user.email
for manager in managers_query
if manager.user.email != pi_email
]

mail.send_email(
subject="Allocation Expiration Reminder",
body=EXPIRATION_REMINDER_TEMPLATE.format(
allocation=allocation,
),
sender=EMAIL_SENDER,
receiver_list=[pi_email],
cc=manager_emails,
)
47 changes: 47 additions & 0 deletions src/coldfront_plugin_cloud/tests/unit/test_allocation_alerts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from unittest.mock import patch
from datetime import datetime, timezone, timedelta

from coldfront_plugin_cloud.tasks import remind_allocations_revoked
from coldfront_plugin_cloud.tests import base


class TestAllocationAlerts(base.TestBase):
@patch("coldfront_plugin_cloud.tasks.EMAIL_SENDER", "test@example.com")
def test_remind_allocations_expired(self):
"""Test that remind_allocations_expired sends emails for allocations expiring soon."""
# Setup mock datetime to control what "now" returns
# fake_now = datetime(2025, 11, 1, tzinfo=timezone.utc)
# mock_datetime.now.return_value = fake_now

# Create test data
resource = self.new_openstack_resource(
name="TestResource", internal_name="TestResource"
)
project = self.new_project()

# Create allocation expiring in 30 days (should trigger reminder)
allocation = self.new_allocation(
project=project,
resource=resource,
quantity=1,
status="Expired",
)

manager = self.new_user()
self.new_project_user(manager, project, role="Manager")

expiration_date = datetime.now(timezone.utc) + timedelta(days=30)
allocation.end_date = expiration_date
allocation.save()

with patch("coldfront.core.utils.mail.send_email") as mock_send_email:
remind_allocations_revoked()

# Assert mail.send_email was called once
mock_send_email.assert_called_once_with(
subject="Allocation Expiration Reminder",
sender="test@example.com",
receiver_list=[allocation.project.pi.email],
cc=[manager.email],
body="",
)
Loading