generated from NHSDigital/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 4
Azure monitor infrastructure metrics on storage queues more testing #617
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
Merged
mrlockstar
merged 13 commits into
main
from
feat/DTOSS-11379-Azure-monitor-infrastructure-metrics-on-storage-queues-more-testing
Nov 26, 2025
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6177404
DTOSS-11379: Create a custom metric in the app
mrlockstar 5aeb688
DTOSS-11379: Unit test for metric service class
mrlockstar c9e9a59
DTOSS-11379: Azure monitor metrics on storage queues
mrlockstar 779d76b
DTOSS-11379: Update unit test for queue service
mrlockstar ed935ca
Pass a key to add method
steventux a0a7d74
Simplify message_count method
steventux dc97c57
Add Django admin command to collect metrics
steventux 9c60251
Remove metrics calculation from save message status job
steventux 2be9706
Add terraform config for collect_metrics container app job
steventux c397452
Metric service class now a singleton with an array of gauges per inst…
mrlockstar f23728f
update the unit tests
mrlockstar 69ff47d
Remove try/catch on service class so we can see the exception type
mrlockstar 3abef93
Make Metrics a singleton class
steventux 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
Some comments aren't visible on the classic Files Changed page.
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
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
25 changes: 25 additions & 0 deletions
25
manage_breast_screening/notifications/management/commands/collect_metrics.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,25 @@ | ||
| import logging | ||
|
|
||
| from django.core.management.base import BaseCommand, CommandError | ||
|
|
||
| from manage_breast_screening.notifications.services.metrics import Metrics | ||
| from manage_breast_screening.notifications.services.queue import Queue | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| def handle(self, *args, **options): | ||
| try: | ||
| # Set queue_size metrics | ||
| for queue in [Queue.RetryMessageBatches(), Queue.MessageStatusUpdates()]: | ||
| Metrics().set_gauge_value( | ||
| f"queue_size_{queue.queue_name}", | ||
| "messages", | ||
| "Queue length", | ||
| queue.get_message_count(), | ||
| ) | ||
|
|
||
| except Exception as e: | ||
| logger.error(e, exc_info=True) | ||
| raise CommandError(e) |
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,50 @@ | ||
| import logging | ||
| import os | ||
|
|
||
| from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter | ||
| from opentelemetry import metrics | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class Metrics: | ||
| _instance = None | ||
|
|
||
| def __new__(cls, *args, **kwargs): | ||
| if cls._instance is None: | ||
| cls._instance = super().__new__(cls) | ||
| return cls._instance | ||
|
|
||
| def __init__(self): | ||
| environment = os.getenv("ENVIRONMENT") | ||
| logger.debug((f"Initialising Metrics(environment: {environment})")) | ||
|
|
||
| exporter = AzureMonitorMetricExporter( | ||
| connection_string=os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING") | ||
| ) | ||
| metrics.set_meter_provider( | ||
| MeterProvider(metric_readers=[PeriodicExportingMetricReader(exporter)]) | ||
| ) | ||
| self.meter = metrics.get_meter(__name__) | ||
| self.environment = environment | ||
|
|
||
| def set_gauge_value(self, metric_name, units, description, value): | ||
| logger.debug( | ||
| ( | ||
| f"Metrics: set_gauge_value(metric_name: {metric_name} " | ||
| f"units: {units}, description: {description}, value: {value})" | ||
| ) | ||
| ) | ||
|
|
||
| # Create gauge metric | ||
| gauge = self.meter.create_gauge( | ||
| metric_name, unit=units, description=description | ||
| ) | ||
|
|
||
| # Set metric value | ||
| gauge.set( | ||
| value, | ||
| {"environment": self.environment}, | ||
| ) |
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
46 changes: 46 additions & 0 deletions
46
manage_breast_screening/notifications/tests/management/commands/test_collect_metrics.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,46 @@ | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| import pytest | ||
|
|
||
| from manage_breast_screening.notifications.management.commands.collect_metrics import ( | ||
| Command, | ||
| ) | ||
|
|
||
|
|
||
| class TestCollectMetrics: | ||
| @pytest.fixture(autouse=True) | ||
| def setup(self, monkeypatch): | ||
| monkeypatch.setenv("ENVIRONMENT", "test") | ||
|
|
||
| @patch(f"{Command.__module__}.Queue") | ||
| @patch(f"{Command.__module__}.Metrics") | ||
| def test_handle_sends_queue_lengths(self, mock_metrics_class, mock_queue): | ||
| mock_retry = MagicMock() | ||
| mock_retry.queue_name = "retry_queue" | ||
| mock_retry.get_message_count.return_value = 8 | ||
|
|
||
| mock_status = MagicMock() | ||
| mock_status.queue_name = "status_queue" | ||
| mock_status.get_message_count.return_value = 2 | ||
|
|
||
| mock_queue.RetryMessageBatches.return_value = mock_retry | ||
| mock_queue.MessageStatusUpdates.return_value = mock_status | ||
|
|
||
| Command().handle() | ||
|
|
||
| metrics_instance = mock_metrics_class.return_value | ||
|
|
||
| metrics_instance.set_gauge_value.assert_any_call( | ||
| "queue_size_retry_queue", | ||
| "messages", | ||
| "Queue length", | ||
| 8, | ||
| ) | ||
| metrics_instance.set_gauge_value.assert_any_call( | ||
| "queue_size_status_queue", | ||
| "messages", | ||
| "Queue length", | ||
| 2, | ||
| ) | ||
|
|
||
| assert metrics_instance.set_gauge_value.call_count == 2 |
92 changes: 92 additions & 0 deletions
92
manage_breast_screening/notifications/tests/services/test_metrics.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,92 @@ | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| import pytest | ||
|
|
||
| from manage_breast_screening.notifications.services.metrics import Metrics | ||
|
|
||
|
|
||
| @patch(f"{Metrics.__module__}.AzureMonitorMetricExporter") | ||
| @patch(f"{Metrics.__module__}.PeriodicExportingMetricReader") | ||
| @patch(f"{Metrics.__module__}.metrics") | ||
| @patch(f"{Metrics.__module__}.MeterProvider") | ||
| class TestMetrics: | ||
| @pytest.fixture | ||
| def conn_string(self): | ||
| return "InstrumentationKey=00000000-0000-0000-0000-000000000000" | ||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def setup(self, monkeypatch, conn_string): | ||
| monkeypatch.setenv("APPLICATIONINSIGHTS_CONNECTION_STRING", conn_string) | ||
| monkeypatch.setenv("ENVIRONMENT", "dev") | ||
|
|
||
| def test_metrics_initialisation( | ||
| self, | ||
| mock_meter_provider, | ||
| mock_metrics, | ||
| mock_metric_reader, | ||
| mock_metric_exporter, | ||
| conn_string, | ||
| ): | ||
| mock_meter = MagicMock() | ||
| mock_metrics.get_meter.return_value = mock_meter | ||
|
|
||
| subject = Metrics() | ||
|
|
||
| mock_metric_exporter.assert_called_once_with(connection_string=str(conn_string)) | ||
| mock_metric_reader.assert_called_once_with(mock_metric_exporter.return_value) | ||
| mock_meter_provider.assert_called_once_with( | ||
| metric_readers=[mock_metric_reader.return_value] | ||
| ) | ||
| mock_metrics.set_meter_provider.assert_called_once_with( | ||
| mock_meter_provider.return_value | ||
| ) | ||
| mock_metrics.get_meter.assert_called_once_with( | ||
| "manage_breast_screening.notifications.services.metrics" | ||
| ) | ||
|
|
||
| assert subject.meter == mock_meter | ||
| assert subject.environment == "dev" | ||
|
|
||
| def test_metrics_is_a_singleton( | ||
| self, | ||
| mock_meter_provider, | ||
| mock_metrics, | ||
| mock_reader, | ||
| mock_exporter, | ||
| ): | ||
| subject = Metrics() | ||
| the_same_instance = Metrics() | ||
| assert subject == the_same_instance | ||
|
|
||
| def test_set_gauge_value( | ||
| self, | ||
| mock_meter_provider, | ||
| mock_metrics, | ||
| mock_reader, | ||
| mock_exporter, | ||
| ): | ||
| mock_meter = MagicMock() | ||
| mock_gauge = MagicMock() | ||
|
|
||
| mock_metrics.get_meter.return_value = mock_meter | ||
| mock_meter.create_gauge.return_value = mock_gauge | ||
|
|
||
| subject = Metrics() | ||
|
|
||
| subject.set_gauge_value( | ||
| metric_name="queue_depth", | ||
| units="messages", | ||
| description="Number of messages", | ||
| value=999, | ||
| ) | ||
|
|
||
| mock_meter.create_gauge.assert_called_once_with( | ||
| "queue_depth", | ||
| unit="messages", | ||
| description="Number of messages", | ||
| ) | ||
|
|
||
| mock_gauge.set.assert_called_once_with( | ||
| 999, | ||
| {"environment": "dev"}, | ||
| ) |
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
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.