-
-
Notifications
You must be signed in to change notification settings - Fork 230
[fix] Record monitoring metrics for sessions closed via bulk updates #735
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
+719
−29
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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
Empty file.
Empty file.
122 changes: 122 additions & 0 deletions
122
...p_radius/integrations/monitoring/management/commands/rebuild_radius_accounting_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,122 @@ | ||
| from django.core.management.base import BaseCommand, CommandError | ||
| from django.utils import timezone | ||
| from django.utils.dateparse import parse_datetime | ||
| from openwisp_monitoring.db import timeseries_db | ||
| from swapper import load_model | ||
|
|
||
| from openwisp_radius.integrations.monitoring import tasks | ||
| from openwisp_radius.integrations.monitoring.utils import sha1_hash | ||
|
|
||
| RadiusAccounting = load_model("openwisp_radius", "RadiusAccounting") | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| """ | ||
| Rebuild RADIUS accounting metrics missed by the NAS-Reboot bulk update path. | ||
|
|
||
| See https://github.com/openwisp/openwisp-radius/issues/734. | ||
| TODO: remove in version 1.4. | ||
| """ | ||
|
|
||
| help = "Private command to rebuild monitoring metrics for closed RADIUS sessions." | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument( | ||
| "--commit", | ||
| action="store_true", | ||
| help="Write metrics. Without this flag the command only reports the count.", | ||
| ) | ||
| parser.add_argument( | ||
| "--start", | ||
| help=( | ||
| "Only process sessions with stop_time greater than or equal " | ||
| "to this date." | ||
| ), | ||
| ) | ||
| parser.add_argument( | ||
| "--end", | ||
| help=( | ||
| "Only process sessions with stop_time lower than or equal " | ||
| "to this date." | ||
| ), | ||
| ) | ||
| parser.add_argument( | ||
| "--chunk-size", | ||
| type=int, | ||
| default=1000, | ||
| help="Number of sessions fetched per database batch.", | ||
| ) | ||
|
|
||
| def handle(self, *args, **options): | ||
| queryset = RadiusAccounting.objects.filter( | ||
| stop_time__isnull=False, | ||
| terminate_cause="NAS-Reboot", | ||
| ) | ||
| if options["start"]: | ||
| queryset = queryset.filter( | ||
| stop_time__gte=self._parse_datetime(options["start"], "start") | ||
| ) | ||
| if options["end"]: | ||
| queryset = queryset.filter( | ||
| stop_time__lte=self._parse_datetime(options["end"], "end") | ||
| ) | ||
| queryset = queryset.order_by("stop_time", "unique_id").only( | ||
| "unique_id", | ||
| "username", | ||
| "organization_id", | ||
| "input_octets", | ||
| "output_octets", | ||
| "calling_station_id", | ||
| "called_station_id", | ||
| "stop_time", | ||
| "terminate_cause", | ||
| ) | ||
| count = queryset.count() | ||
| if not options["commit"]: | ||
| self.stdout.write(f"Dry run: {count} closed sessions would be processed.") | ||
| return | ||
| processed = 0 | ||
| chunk_size = options["chunk_size"] | ||
| self.stdout.write(f"Starting to rebuild {count} accounting metrics.") | ||
| for session in queryset.iterator(chunk_size=chunk_size): | ||
| self._delete_radius_accounting_metric(session) | ||
| tasks.post_save_radiusaccounting( | ||
| username=session.username, | ||
| organization_id=str(session.organization_id), | ||
| input_octets=session.input_octets, | ||
| output_octets=session.output_octets, | ||
| calling_station_id=session.calling_station_id, | ||
| called_station_id=session.called_station_id, | ||
| time=session.stop_time, | ||
| ) | ||
| processed += 1 | ||
| if processed % chunk_size == 0 or processed == count: | ||
| self.stdout.write( | ||
| f"Processed {processed} of {count} accounting metrics." | ||
| ) | ||
|
|
||
| def _parse_datetime(self, value, option): | ||
| parsed = parse_datetime(value) | ||
| if parsed is None: | ||
| raise CommandError(f"Invalid --{option} datetime: {value}") | ||
| if timezone.is_naive(parsed): | ||
| parsed = timezone.make_aware(parsed) | ||
| return parsed | ||
|
|
||
| def _delete_radius_accounting_metric(self, session): | ||
| tags = { | ||
| "organization_id": str(session.organization_id), | ||
| "calling_station_id": sha1_hash(session.calling_station_id), | ||
| "called_station_id": session.called_station_id, | ||
| } | ||
| where = " AND ".join( | ||
| f"\"{key}\" = '{self._escape_tag_value(value)}'" | ||
| for key, value in tags.items() | ||
| ) | ||
| timeseries_db.query( | ||
| "DELETE FROM radius_acc " | ||
| f"WHERE time = '{session.stop_time.isoformat()}' AND {where}" | ||
| ) | ||
|
|
||
| def _escape_tag_value(self, value): | ||
| return str(value).replace("'", r"\'") |
Oops, something went wrong.
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.
Will it make more sense to always send this signal when the RadiusAccounting session is closed? It will help in cleaner implementation downstream (openwisp-monitoring integration).
Right now, we will have to listen to two different signals, which is fine. but requires developers to be aware of the context.