Open source video conferencing app powered by LiveKit. Built with Django and React.
♻️(backend) add command to purge inactive rooms
briquetb4b9fe54fb6b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee0b403d..2e530291 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ and this project adheres to### Added- ✨(backend) make the LiveKit default video codec configurable+- ✨(backend) purge rooms inactive for a configurable period- 🔧(dev) add support for Bureautix workstations- ✨(frontend) add screen share zoom controls #1498- 🔨(makefile) add targets to list and download files stored in Garagediff --git a/src/backend/core/management/commands/purge_inactive_rooms.py b/src/backend/core/management/commands/purge_inactive_rooms.pynew file mode 100644index 00000000..10bfe3f8--- /dev/null+++ b/src/backend/core/management/commands/purge_inactive_rooms.py@@ -0,0 +1,94 @@+"""Purge inactive rooms."""++from datetime import timedelta+from itertools import batched+from logging import getLogger++from django.conf import settings+from django.core.management.base import BaseCommand+from django.db.models import Exists, OuterRef, Q+from django.utils import timezone++from core.models import Recording, RecordingStatusChoices, Room++logger = getLogger(__name__)++CHUNK_SIZE = 500+++class Command(BaseCommand):+ """+ Delete rooms that have not been started for ROOM_INACTIVITY_DELETION_DAYS days:+ - rooms which were last started before that period+ - rooms never started and created before that period++ Rooms holding a saved recording that has not expired are kept.+ """++ help = "Purge inactive rooms"++ def add_arguments(self, parser):+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="List the rooms that would be purged without deleting them",+ )++ def handle(self, *args, **options):+ """Browse inactive rooms and delete them chunk by chunk."""++ if not settings.ROOM_INACTIVITY_DELETION_DAYS:+ self.stdout.write(+ "Purging inactive rooms is disabled "+ "(ROOM_INACTIVITY_DELETION_DAYS is not set)."+ )+ return++ now = timezone.now()+ inactive_rooms = self.get_inactive_rooms(now)++ inactive_count = inactive_rooms.count()+ if not inactive_count:+ self.stdout.write("No inactive room to purge.")+ return++ if options["dry_run"]:+ self.stdout.write(+ f"[dry-run] {inactive_count} inactive room(s) would be purged:"+ )+ names = inactive_rooms.values_list("name", flat=True)+ for name in names.iterator(chunk_size=CHUNK_SIZE):+ self.stdout.write(f"- {name}")+ return++ purged_count = 0+ rooms = inactive_rooms.values_list("pk", "slug").iterator(chunk_size=CHUNK_SIZE)+ for chunk in batched(rooms, CHUNK_SIZE, strict=False):+ for room_id, slug in chunk:+ logger.info("Purging inactive room %s (%s)", room_id, slug)++ _, deleted_by_model = inactive_rooms.filter(+ pk__in=[room_id for room_id, _ in chunk]+ ).delete()+ purged_count += deleted_by_model.get("core.Room", 0)++ self.stdout.write(f"Purged {purged_count} inactive room(s).")++ @staticmethod+ def get_inactive_rooms(now):+ """Return the rooms inactive for too long that no recording protects."""++ threshold = now - timedelta(days=settings.ROOM_INACTIVITY_DELETION_DAYS)+ is_inactive = Q(last_started_at__lt=threshold) | Q(+ last_started_at__isnull=True, created_at__lt=threshold+ )++ protected_recordings = Recording.objects.filter(+ room=OuterRef("pk"), status__in=RecordingStatusChoices.saved_statuses()+ )+ if settings.RECORDING_EXPIRATION_DAYS:+ protected_recordings = protected_recordings.filter(+ created_at__gte=now - timedelta(days=settings.RECORDING_EXPIRATION_DAYS)+ )++ return Room.objects.filter(is_inactive, ~Exists(protected_recordings))diff --git a/src/backend/core/models.py b/src/backend/core/models.pyindex 720e615f..8fe51940 100644--- a/src/backend/core/models.py+++ b/src/backend/core/models.py@@ -87,6 +87,17 @@ class RecordingStatusChoices(models.TextChoices):cls.FAILED_TO_STOP,}+ @classmethod+ def saved_statuses(cls):+ """Return the statuses of a recording whose file users can access."""++ return {+ cls.NOTIFICATION_SUCCEEDED,+ cls.SAVED,+ cls.EXTERNAL_PROCESS_SUCCESSFUL,+ cls.EXTERNAL_PROCESS_FAILED,+ }+class RecordingModeChoices(models.TextChoices):"""Recording mode choices."""@@ -689,12 +700,7 @@ class Recording(BaseModel):@propertydef is_saved(self) -> bool:"""Check if the recording is in a saved state."""- return self.status in {- RecordingStatusChoices.NOTIFICATION_SUCCEEDED,- RecordingStatusChoices.SAVED,- RecordingStatusChoices.EXTERNAL_PROCESS_SUCCESSFUL,- RecordingStatusChoices.EXTERNAL_PROCESS_FAILED,- }+ return self.status in RecordingStatusChoices.saved_statuses()@propertydef extension(self):diff --git a/src/backend/core/tests/commands/test_purge_inactive_rooms.py b/src/backend/core/tests/commands/test_purge_inactive_rooms.pynew file mode 100644index 00000000..7c7704a1--- /dev/null+++ b/src/backend/core/tests/commands/test_purge_inactive_rooms.py@@ -0,0 +1,239 @@+"""Tests for the purge_inactive_rooms management command."""++import logging+from datetime import timedelta+from io import StringIO+from unittest import mock++from django.core.management import call_command+from django.utils import timezone++import pytest++from core import factories, models++pytestmark = pytest.mark.django_db++COMMAND_MODULE = "core.management.commands.purge_inactive_rooms"++BEFORE_PERIOD = timedelta(days=366)+WITHIN_PERIOD = timedelta(days=364)++[email protected](name="purge_enabled", autouse=True)+def fixture_purge_enabled(settings):+ """Enable the purge of the rooms inactive for a year."""+ settings.ROOM_INACTIVITY_DELETION_DAYS = 365+ settings.RECORDING_EXPIRATION_DAYS = 30+++def create_at(date, factory, **kwargs):+ """Build an object with the factory as if it was created at the given date."""+ with mock.patch("django.utils.timezone.now", return_value=date):+ return factory(**kwargs)+++def call_purge(*args):+ """Run the purge command and return what it wrote on stdout."""+ out = StringIO()+ call_command("purge_inactive_rooms", *args, stdout=out)+ return out.getvalue()+++def room_exists(room):+ """Tell whether the room is still in database."""+ return models.Room.objects.filter(pk=room.pk).exists()+++def test_purge_inactive_rooms_disabled(settings):+ """Should delete nothing when no inactivity period is configured."""+ settings.ROOM_INACTIVITY_DELETION_DAYS = None+ room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)++ assert "disabled" in call_purge()++ assert room_exists(room)+++def test_purge_inactive_rooms_without_recording_expiration(settings):+ """Should purge when recordings never expire, keeping rooms with a saved one."""+ settings.RECORDING_EXPIRATION_DAYS = None+ long_ago = timezone.now() - BEFORE_PERIOD+ room = create_at(long_ago, factories.RoomFactory)+ room_with_recording = create_at(long_ago, factories.RoomFactory)+ create_at(+ long_ago,+ factories.RecordingFactory,+ room=room_with_recording,+ status=models.RecordingStatusChoices.SAVED,+ )++ assert call_purge() == "Purged 1 inactive room(s).\n"++ assert not room_exists(room)+ assert room_exists(room_with_recording)+++def test_purge_inactive_rooms_without_recording_expiration_not_saved(settings):+ """Should delete a room whose recordings were never saved when none expire."""+ settings.RECORDING_EXPIRATION_DAYS = None+ room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)+ factories.RecordingFactory(room=room, status=models.RecordingStatusChoices.FAILED)++ call_purge()++ assert not room_exists(room)+++def test_purge_inactive_rooms_started_before_period(caplog):+ """Should delete a room that was last started before the inactivity period."""+ now = timezone.now()+ room = create_at(+ now - timedelta(days=800),+ factories.RoomFactory,+ last_started_at=now - BEFORE_PERIOD,+ )++ with caplog.at_level(logging.INFO, logger=COMMAND_MODULE):+ output = call_purge()++ assert output == "Purged 1 inactive room(s).\n"+ assert not room_exists(room)+ assert f"Purging inactive room {room.pk} ({room.slug})" in caplog.text+++def test_purge_inactive_rooms_never_started_created_before_period():+ """Should delete a room that was never started and created before the period."""+ room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)++ call_purge()++ assert not room_exists(room)+++def test_purge_inactive_rooms_started_within_period():+ """Should keep a room created long ago that was started within the period."""+ now = timezone.now()+ room = create_at(+ now - timedelta(days=800),+ factories.RoomFactory,+ last_started_at=now - WITHIN_PERIOD,+ )++ assert call_purge() == "No inactive room to purge.\n"++ assert room_exists(room)+++def test_purge_inactive_rooms_never_started_created_within_period():+ """Should keep a room that was never started but created within the period."""+ room = create_at(timezone.now() - WITHIN_PERIOD, factories.RoomFactory)++ assert call_purge() == "No inactive room to purge.\n"++ assert room_exists(room)+++ "status", sorted(models.RecordingStatusChoices.saved_statuses())+)+def test_purge_inactive_rooms_recording_not_expired(settings, status):+ """Should keep a room holding a saved recording that has not expired yet."""+ settings.RECORDING_EXPIRATION_DAYS = 400+ long_ago = timezone.now() - BEFORE_PERIOD+ room = create_at(long_ago, factories.RoomFactory)+ create_at(long_ago, factories.RecordingFactory, room=room, status=status)++ call_purge()++ assert room_exists(room)+++def test_purge_inactive_rooms_recording_expired(settings):+ """Should delete a room along with its recordings when they all have expired."""+ settings.RECORDING_EXPIRATION_DAYS = 30+ long_ago = timezone.now() - BEFORE_PERIOD+ room = create_at(long_ago, factories.RoomFactory)+ recording = create_at(+ long_ago,+ factories.RecordingFactory,+ room=room,+ status=models.RecordingStatusChoices.SAVED,+ )++ call_purge()++ assert not room_exists(room)+ assert not models.Recording.objects.filter(pk=recording.pk).exists()+++ "status",+ [+ status+ for status in models.RecordingStatusChoices+ if status not in models.RecordingStatusChoices.saved_statuses()+ ],+)+def test_purge_inactive_rooms_recording_not_saved(status):+ """Should delete a room whose recordings were never saved, even unexpired."""+ room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)+ factories.RecordingFactory(room=room, status=status)++ call_purge()++ assert not room_exists(room)+++def test_purge_inactive_rooms_recording_saved_among_others():+ """Should keep a room holding a saved recording next to a failed one."""+ room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)+ factories.RecordingFactory(room=room, status=models.RecordingStatusChoices.FAILED)+ factories.RecordingFactory(room=room, status=models.RecordingStatusChoices.SAVED)++ call_purge()++ assert room_exists(room)+++def test_purge_inactive_rooms_deletes_accesses_and_resource():+ """Should delete the last owner access and the resource of a purged room."""+ room = create_at(timezone.now() - BEFORE_PERIOD, factories.RoomFactory)+ access = factories.UserResourceAccessFactory(+ resource=room, role=models.RoleChoices.OWNER+ )++ call_purge()++ assert not room_exists(room)+ assert not models.Resource.objects.filter(pk=room.pk).exists()+ assert not models.ResourceAccess.objects.filter(pk=access.pk).exists()+ assert models.User.objects.filter(pk=access.user.pk).exists()+++def test_purge_inactive_rooms_dry_run():+ """Should list the inactive rooms by name without deleting them on a dry run."""+ long_ago = timezone.now() - BEFORE_PERIOD+ rooms = [+ create_at(long_ago, factories.RoomFactory, name=name)+ for name in ("Alpha room", "Beta room")+ ]+ factories.RoomFactory(name="Recent room")++ assert call_purge("--dry-run") == (+ "[dry-run] 2 inactive room(s) would be purged:\n- Alpha room\n- Beta room\n"+ )++ assert all(room_exists(room) for room in rooms)+++def test_purge_inactive_rooms_several_chunks():+ """Should delete every inactive room when they span several chunks."""+ long_ago = timezone.now() - BEFORE_PERIOD+ rooms = [create_at(long_ago, factories.RoomFactory) for _ in range(5)]++ with mock.patch(f"{COMMAND_MODULE}.CHUNK_SIZE", 2):+ output = call_purge()++ assert output == "Purged 5 inactive room(s).\n"+ assert not any(room_exists(room) for room in rooms)diff --git a/src/backend/meet/settings.py b/src/backend/meet/settings.pyindex a0606d00..48cb8c76 100755--- a/src/backend/meet/settings.py+++ b/src/backend/meet/settings.py@@ -730,6 +730,9 @@ class Base(Configuration):ALLOW_UNREGISTERED_ROOMS = values.BooleanValue(True, environ_name="ALLOW_UNREGISTERED_ROOMS", environ_prefix=None)+ ROOM_INACTIVITY_DELETION_DAYS = values.PositiveIntegerValue(+ None, environ_name="ROOM_INACTIVITY_DELETION_DAYS", environ_prefix=None+ )# if provided, treat as suspicious (possible privilege escalation attempt).PARTICIPANT_FORBIDDEN_PERMISSION_FIELDS = values.ListValue(["hidden", "recorder", "agent"],@@ -1249,6 +1252,25 @@ class Base(Configuration):stacklevel=2,)+ if cls.ROOM_INACTIVITY_DELETION_DAYS:+ if not cls.RECORDING_EXPIRATION_DAYS:+ warnings.warn(+ "ROOM_INACTIVITY_DELETION_DAYS is set but "+ "RECORDING_EXPIRATION_DAYS is not. Recordings never expire, so "+ "inactive rooms holding a saved recording will never be purged.",+ UserWarning,+ stacklevel=2,+ )+ elif cls.RECORDING_EXPIRATION_DAYS >= cls.ROOM_INACTIVITY_DELETION_DAYS:+ warnings.warn(+ "RECORDING_EXPIRATION_DAYS is greater than or equal to "+ "ROOM_INACTIVITY_DELETION_DAYS. Inactive rooms holding a saved "+ "recording will be kept past the inactivity period, until their "+ "recordings expire.",+ UserWarning,+ stacklevel=2,+ )+# The SENTRY_DSN setting should be available to activate sentry for an environmentif cls.SENTRY_DSN is not None:sentry_sdk.init(