-
Notifications
You must be signed in to change notification settings - Fork 14
Added scheduler to alert users on allocation revocation #322
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
Open
QuanMPhm
wants to merge
1
commit into
nerc-project:main
Choose a base branch
from
QuanMPhm:309/expiration_reminder
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+119
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
src/coldfront_plugin_cloud/management/commands/register_allocation_alerts.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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? | ||
| schedule( | ||
| "coldfront_plugin_cloud.tasks.remind_allocations_revoked", | ||
| schedule_type=Schedule.DAILY, | ||
| next_run=date, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
@@ -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, | ||
|
|
@@ -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() | ||
|
|
@@ -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." | ||
|
|
@@ -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? | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| "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
47
src/coldfront_plugin_cloud/tests/unit/test_allocation_alerts.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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="", | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@joachimweyl @knikolla @naved001