-
Notifications
You must be signed in to change notification settings - Fork 174
Implement service bus monitoring with heartbeat detection and automatic recovery #4601
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
Copilot
wants to merge
23
commits into
main
Choose a base branch
from
copilot/fix-4464
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.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
4da5850
Initial plan
Copilot 6cd0b5f
Add restart mechanism to deployment status updater to fix stuck opera…
Copilot c20078a
Merge branch 'main' into copilot/fix-4464
marrobi c7072b9
Add heartbeat monitoring to supervisor function for stuck process det…
Copilot 202e726
Move heartbeat monitoring from resource processor to deployment statu…
Copilot 381bd9c
Fix linting issues and increment API version
Copilot 7c5ff5d
Refactor service bus components to implement heartbeat monitoring and…
marrobi 9329c94
update tests and fix issue.
marrobi 96e39b2
Fix lint.
marrobi f81e9eb
Merge branch 'main' into copilot/fix-4464
marrobi 75d77dd
remove duplicate tests.
marrobi b190ab3
Merge branch 'main' of https://github.com/microsoft/AzureTRE into cop…
marrobi 7b78e99
Enhance Service Bus consumer with error handling and heartbeat manage…
marrobi 32d8c75
Enhance Service Bus consumer with error handling and heartbeat manage…
marrobi 681d5ad
Merge branch 'copilot/fix-4464' of https://github.com/microsoft/Azure…
marrobi b6f7e29
Update tests
marrobi ba8d1e9
update tests
marrobi 49245fe
Update api_app/service_bus/deployment_status_updater.py
marrobi 37291c3
Define format once for two instrumentors.
marrobi 3840d8c
Merge branch 'copilot/fix-4464' of https://github.com/microsoft/Azure…
marrobi 975ed29
Update api_app/service_bus/deployment_status_updater.py
marrobi 7eac68b
Update api_app/tests_ma/test_service_bus/test_service_bus_edge_cases.py
marrobi ff963ac
Move tempfile import to top and add explanatory comment to except clause
Copilot 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
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 +1 @@ | ||
| __version__ = "0.25.1" | ||
| __version__ = "0.26.0" |
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
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
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
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,110 @@ | ||
| import asyncio | ||
| import os | ||
| import tempfile | ||
| import time | ||
|
|
||
| from services.logging import logger | ||
|
|
||
| # Configuration constants for monitoring intervals | ||
| HEARTBEAT_CHECK_INTERVAL_SECONDS = 60 | ||
| HEARTBEAT_STALENESS_THRESHOLD_SECONDS = 300 | ||
| RESTART_DELAY_SECONDS = 5 | ||
| SUPERVISOR_ERROR_DELAY_SECONDS = 30 | ||
|
|
||
|
|
||
| class ServiceBusConsumer: | ||
|
|
||
| def __init__(self, heartbeat_file_prefix: str): | ||
| # Create a unique identifier for this worker process | ||
| self.worker_id = os.getpid() | ||
| temp_dir = tempfile.gettempdir() | ||
| self.heartbeat_file = os.path.join(temp_dir, f"{heartbeat_file_prefix}_heartbeat_{self.worker_id}.txt") | ||
| self.service_name = heartbeat_file_prefix.replace('_', ' ').title() | ||
| logger.info(f"Initializing {self.service_name}") | ||
|
|
||
| def update_heartbeat(self): | ||
| try: | ||
| # Ensure directory exists | ||
| os.makedirs(os.path.dirname(self.heartbeat_file), exist_ok=True) | ||
| with open(self.heartbeat_file, 'w') as f: | ||
| f.write(str(time.time())) | ||
| except PermissionError: | ||
| logger.error(f"Permission denied writing heartbeat to {self.heartbeat_file}") | ||
| except OSError as e: | ||
| logger.error(f"OS error updating heartbeat: {e}") | ||
| except Exception as e: | ||
| logger.warning(f"Unexpected error updating heartbeat: {e}") | ||
|
|
||
| def check_heartbeat(self, max_age_seconds: int = 300) -> bool: | ||
| try: | ||
| if not os.path.exists(self.heartbeat_file): | ||
| logger.warning("Heartbeat file does not exist") | ||
| return False | ||
|
|
||
| with open(self.heartbeat_file, 'r') as f: | ||
| heartbeat_time = float(f.read().strip()) | ||
|
|
||
| current_time = time.time() | ||
| age = current_time - heartbeat_time | ||
|
|
||
| if age > max_age_seconds: | ||
| logger.warning(f"Heartbeat is {age:.1f} seconds old, exceeding the limit of {max_age_seconds} seconds") | ||
|
|
||
| return age <= max_age_seconds | ||
| except (ValueError, IOError) as e: | ||
| logger.warning(f"Failed to read heartbeat: {e}") | ||
| return False | ||
|
|
||
| async def receive_messages_with_restart_check(self): | ||
| while True: | ||
| try: | ||
| logger.info("Starting the receive_messages loop...") | ||
| await self.receive_messages() | ||
| except Exception as e: | ||
| logger.exception(f"receive_messages stopped unexpectedly. Restarting... - {e}") | ||
| await asyncio.sleep(RESTART_DELAY_SECONDS) | ||
|
|
||
| async def supervisor_with_heartbeat_check(self): | ||
| task = None | ||
| try: | ||
| while True: | ||
| try: | ||
| # Start the receive_messages task if not running | ||
| if task is None or task.done(): | ||
| if task and task.done(): | ||
| try: | ||
| await task # Check for any exception | ||
| except Exception as e: | ||
| logger.exception(f"receive_messages task failed: {e}") | ||
|
|
||
| logger.info("Starting receive_messages task...") | ||
| task = asyncio.create_task(self.receive_messages_with_restart_check()) | ||
|
|
||
| # Wait before checking heartbeat | ||
| await asyncio.sleep(HEARTBEAT_CHECK_INTERVAL_SECONDS) # Check every minute | ||
|
|
||
| # Check if heartbeat is stale | ||
| if not self.check_heartbeat(max_age_seconds=HEARTBEAT_STALENESS_THRESHOLD_SECONDS): # 5 minutes max age | ||
| logger.warning("Heartbeat is stale, restarting receive_messages task...") | ||
| task.cancel() | ||
| try: | ||
| await task | ||
| except asyncio.CancelledError: | ||
| # Expected when cancelling a task - ignore and proceed with restart | ||
| pass | ||
| task = None | ||
| except Exception as e: | ||
| logger.exception(f"Supervisor error: {e}") | ||
| await asyncio.sleep(SUPERVISOR_ERROR_DELAY_SECONDS) | ||
| finally: | ||
| # Ensure proper cleanup on shutdown | ||
| if task and not task.done(): | ||
| logger.info("Cleaning up supervisor task...") | ||
| task.cancel() | ||
| try: | ||
| await task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| async def receive_messages(self): | ||
| raise NotImplementedError("Subclasses must implement receive_messages()") | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.