Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
delete_old_unclaimed_attachments: Add flag to clean up storage.
Alex Vandiver3bf3f47b49c6
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.pyindex 65ddae14d63..bb613939d54 100644--- a/zerver/lib/upload/__init__.py+++ b/zerver/lib/upload/__init__.py@@ -1,8 +1,9 @@import ioimport loggingimport urllib+from datetime import datetimefrom mimetypes import guess_type-from typing import IO, Any, Callable, List, Optional, Tuple+from typing import IO, Any, Callable, Iterator, List, Optional, Tuplefrom urllib.parse import urljoinfrom django.conf import settings@@ -114,6 +115,10 @@ def delete_message_attachments(path_ids: List[str]) -> None:return upload_backend.delete_message_attachments(path_ids)+def all_message_attachments() -> Iterator[Tuple[str, datetime]]:+ return upload_backend.all_message_attachments()++# Avatar image uploadsdiff --git a/zerver/lib/upload/base.py b/zerver/lib/upload/base.pyindex 244bc875491..eced4976093 100644--- a/zerver/lib/upload/base.py+++ b/zerver/lib/upload/base.py@@ -2,7 +2,8 @@ import ioimport osimport reimport unicodedata-from typing import IO, Any, Callable, List, Optional, Tuple+from datetime import datetime+from typing import IO, Any, Callable, Iterator, List, Optional, Tuplefrom django.utils.translation import gettext as _from markupsafe import Markup@@ -210,6 +211,9 @@ class ZulipUploadBackend:for path_id in path_ids:self.delete_message_attachment(path_id)+ def all_message_attachments(self) -> Iterator[Tuple[str, datetime]]:+ raise NotImplementedError+# Avatar image uploadsdef get_avatar_url(self, hash_key: str, medium: bool = False) -> str:raise NotImplementedErrordiff --git a/zerver/lib/upload/local.py b/zerver/lib/upload/local.pyindex 24fff92ddb8..2d2e638ae92 100644--- a/zerver/lib/upload/local.py+++ b/zerver/lib/upload/local.py@@ -3,11 +3,13 @@ import osimport randomimport secretsimport shutil-from typing import IO, Any, Callable, Literal, Optional+from datetime import datetime+from typing import IO, Any, Callable, Iterator, Literal, Optional, Tuplefrom django.conf import settingsfrom zerver.lib.avatar_hash import user_avatar_path+from zerver.lib.timestamp import timestamp_to_datetimefrom zerver.lib.upload.base import (MEDIUM_AVATAR_SIZE,ZulipUploadBackend,@@ -99,6 +101,16 @@ class LocalUploadBackend(ZulipUploadBackend):def delete_message_attachment(self, path_id: str) -> bool:return delete_local_file("files", path_id)+ def all_message_attachments(self) -> Iterator[Tuple[str, datetime]]:+ assert settings.LOCAL_UPLOADS_DIR is not None+ for dirname, _, files in os.walk(settings.LOCAL_UPLOADS_DIR + "/files"):+ for f in files:+ fullpath = os.path.join(dirname, f)+ yield (+ os.path.relpath(fullpath, settings.LOCAL_UPLOADS_DIR + "/files"),+ timestamp_to_datetime(os.path.getmtime(fullpath)),+ )+def get_avatar_url(self, hash_key: str, medium: bool = False) -> str:medium_suffix = "-medium" if medium else ""return f"/user_avatars/{hash_key}{medium_suffix}.png"diff --git a/zerver/lib/upload/s3.py b/zerver/lib/upload/s3.pyindex cccbf87c251..7fc0c686fd8 100644--- a/zerver/lib/upload/s3.py+++ b/zerver/lib/upload/s3.py@@ -2,8 +2,9 @@ import loggingimport osimport secretsimport urllib+from datetime import datetimefrom mimetypes import guess_type-from typing import IO, Any, Callable, List, Optional+from typing import IO, Any, Callable, Iterator, List, Optional, Tupleimport boto3import botocore@@ -238,6 +239,21 @@ class S3UploadBackend(ZulipUploadBackend):Delete={"Objects": [{"Key": path_id} for path_id in path_ids]})+ def all_message_attachments(self) -> Iterator[Tuple[str, datetime]]:+ client = self.session.client(+ "s3", region_name=settings.S3_REGION, endpoint_url=settings.S3_ENDPOINT_URL+ )+ paginator = client.get_paginator("list_objects_v2")+ page_iterator = paginator.paginate(Bucket=self.uploads_bucket.name)++ for page in page_iterator:+ if page["KeyCount"] > 0:+ for item in page["Contents"]:+ yield (+ item["Key"],+ item["LastModified"],+ )+def write_avatar_images(self,s3_file_name: str,diff --git a/zerver/management/commands/delete_old_unclaimed_attachments.py b/zerver/management/commands/delete_old_unclaimed_attachments.pyindex 51e36542395..764f4702ce3 100644--- a/zerver/management/commands/delete_old_unclaimed_attachments.py+++ b/zerver/management/commands/delete_old_unclaimed_attachments.py@@ -1,10 +1,13 @@+import datetimefrom argparse import ArgumentParserfrom typing import Anyfrom django.core.management.base import BaseCommand, CommandError+from django.utils.timezone import now as timezone_nowfrom zerver.actions.uploads import do_delete_old_unclaimed_attachments-from zerver.models import get_old_unclaimed_attachments+from zerver.lib.upload import all_message_attachments, delete_message_attachments+from zerver.models import ArchivedAttachment, Attachment, get_old_unclaimed_attachmentsclass Command(BaseCommand):@@ -29,6 +32,14 @@ class Command(BaseCommand):help="Actually remove the files from the storage.",)+ parser.add_argument(+ "-C",+ "--clean-up-storage",+ action="store_true",+ help="Examine all attachments in storage (local disk or S3) and remove "+ "any files which are not in the database. This may take a very long time!",+ )+def handle(self, *args: Any, **options: Any) -> None:delta_weeks = options["delta_weeks"]print(f"Deleting unclaimed attached files older than {delta_weeks} weeks")@@ -42,10 +53,39 @@ class Command(BaseCommand):f"* {old_archived_attachment.file_name} created at {old_archived_attachment.create_time}")- print("")+ if options["for_real"]:+ do_delete_old_unclaimed_attachments(delta_weeks)+ print("")+ print("Unclaimed files deleted.")++ if options["clean_up_storage"]:+ print("")+ self.clean_attachment_upload_backend(dry_run=not options["for_real"])+if not options["for_real"]:+ print("")raise CommandError("This was a dry run. Pass -f to actually delete.")- do_delete_old_unclaimed_attachments(delta_weeks)- print("")- print("Unclaimed files deleted.")+ def clean_attachment_upload_backend(self, dry_run: bool = True) -> None:+ cutoff = timezone_now() - datetime.timedelta(minutes=5)+ print(f"Removing extra files in storage black-end older than {cutoff.isoformat()}")+ to_delete = []+ for path_id, modified_at in all_message_attachments():+ if Attachment.objects.filter(path_id=path_id).exists():+ continue+ if ArchivedAttachment.objects.filter(path_id=path_id).exists():+ continue+ if modified_at > cutoff:+ # We upload files to the backend storage and _then_+ # make the database entry, so must give some leeway to+ # recently-added files which do not have DB rows.+ continue+ print(f"* {path_id} modified at {modified_at}")+ if dry_run:+ continue+ to_delete.append(path_id)+ if len(to_delete) > 1000:+ delete_message_attachments(to_delete)+ to_delete = []+ if not dry_run and len(to_delete) > 0:+ delete_message_attachments(to_delete)diff --git a/zerver/tests/test_upload_local.py b/zerver/tests/test_upload_local.pyindex f79eebe228a..83794454967 100644--- a/zerver/tests/test_upload_local.py+++ b/zerver/tests/test_upload_local.py@@ -17,6 +17,7 @@ from zerver.lib.test_helpers import (read_test_image_file,)from zerver.lib.upload import (+ all_message_attachments,delete_export_tarball,delete_message_attachment,delete_message_attachments,@@ -117,6 +118,14 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)self.assertFalse(os.path.isfile(file_path))+ def test_all_message_attachments(self) -> None:+ write_local_file("files", "foo", b"content")+ write_local_file("files", "bar/baz", b"content")+ write_local_file("files", "bar/troz", b"content")+ write_local_file("files", "test/other/file", b"content")+ found_files = [r[0] for r in all_message_attachments()]+ self.assertEqual(sorted(found_files), ["bar/baz", "bar/troz", "foo", "test/other/file"])+def test_avatar_url(self) -> None:self.login("hamlet")with get_test_image_file("img.png") as image_file:diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.pyindex ea63a982039..4b46aefd57e 100644--- a/zerver/tests/test_upload_s3.py+++ b/zerver/tests/test_upload_s3.py@@ -21,6 +21,7 @@ from zerver.lib.test_helpers import (use_s3_backend,)from zerver.lib.upload import (+ all_message_attachments,delete_export_tarball,delete_message_attachment,delete_message_attachments,@@ -147,6 +148,20 @@ class S3Test(ZulipTestCase):],)+ @use_s3_backend+ def test_all_message_attachments(self) -> None:+ create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)++ user_profile = self.example_user("hamlet")+ path_ids = []+ for n in range(1, 5):+ uri = upload_message_attachment(+ "dummy.txt", len(b"zulip!"), "text/plain", b"zulip!", user_profile+ )+ path_ids.append(re.sub("/user_uploads/", "", uri))+ found_paths = [r[0] for r in all_message_attachments()]+ self.assertEqual(sorted(found_paths), sorted(path_ids))+@use_s3_backenddef test_user_uploads_authed(self) -> None:"""