-
Notifications
You must be signed in to change notification settings - Fork 569
feat: clica command for a full backup/restore #3042
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
tchoumi313
wants to merge
10
commits into
main
Choose a base branch
from
CA-1432-add-clica-command-to-create-a-full-backup-with-attachments
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.
+1,431
−52
Open
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4d42fb4
feat: clica command for a full backup/restore
tchoumi313 346b00a
update complete backup of your cisoassistant instance
tchoumi313 23d41a5
update
tchoumi313 b64efb2
update
tchoumi313 63c2bed
update
tchoumi313 0a40a6c
Update .gitignore
eric-intuitem b55a92d
Merge branch 'main' into CA-1432-add-clica-command-to-create-a-full-b…
eric-intuitem e4c8d7b
fix migration
eric-intuitem 4e28ee7
ruff
eric-intuitem 71e45f9
remove dead code
eric-intuitem 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
73 changes: 73 additions & 0 deletions
73
backend/core/migrations/0119_add_attachment_hash_to_evidencerevision.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,73 @@ | ||
| # Generated by Django 5.2.8 on 2025-12-15 14:07 | ||
|
|
||
| import hashlib | ||
| from django.db import migrations, models | ||
| from django.core.files.storage import default_storage | ||
|
|
||
|
|
||
| def backfill_attachment_hashes(apps, schema_editor): | ||
| """ | ||
| Compute and store SHA256 hashes for all existing attachments. | ||
| Uses chunked reading to avoid loading large files into memory. | ||
| """ | ||
| EvidenceRevision = apps.get_model("core", "EvidenceRevision") | ||
|
|
||
| revisions_with_attachments = EvidenceRevision.objects.filter( | ||
| attachment__isnull=False | ||
| ).exclude(attachment="") | ||
|
|
||
| total = revisions_with_attachments.count() | ||
| processed = 0 | ||
| errors = 0 | ||
|
|
||
| print(f"Backfilling attachment hashes for {total} evidence revisions...") | ||
|
|
||
| for revision in revisions_with_attachments.iterator(chunk_size=100): | ||
| try: | ||
| if revision.attachment and default_storage.exists(revision.attachment.name): | ||
| hash_obj = hashlib.sha256() | ||
| with default_storage.open(revision.attachment.name, "rb") as f: | ||
| for chunk in iter(lambda: f.read(1024 * 1024), b""): # 1MB chunks | ||
| hash_obj.update(chunk) | ||
|
|
||
| revision.attachment_hash = hash_obj.hexdigest() | ||
| revision.save(update_fields=["attachment_hash"]) | ||
| processed += 1 | ||
|
|
||
| if processed % 100 == 0: | ||
| print(f" Processed {processed}/{total} revisions...") | ||
| except Exception as e: | ||
| errors += 1 | ||
| print(f" Error processing revision {revision.id}: {e}") | ||
|
|
||
| print(f"Completed: {processed} hashes computed, {errors} errors") | ||
|
|
||
|
|
||
| def reverse_backfill(apps, schema_editor): | ||
| """ | ||
| Clear all attachment hashes (reverse operation). | ||
| """ | ||
| EvidenceRevision = apps.get_model("core", "EvidenceRevision") | ||
| EvidenceRevision.objects.update(attachment_hash=None) | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
| dependencies = [ | ||
| ("core", "0118_riskscenario_antecedent_scenarios_and_more"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.AddField( | ||
| model_name="evidencerevision", | ||
| name="attachment_hash", | ||
| field=models.CharField( | ||
| blank=True, | ||
| db_index=True, | ||
| help_text="SHA256 hash of the attachment file for integrity verification", | ||
| max_length=64, | ||
| null=True, | ||
| verbose_name="Attachment SHA256 Hash", | ||
| ), | ||
| ), | ||
| migrations.RunPython(backfill_attachment_hashes, reverse_backfill), | ||
| ] |
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,194 @@ | ||
| import io | ||
| import os | ||
| import zipfile | ||
| from typing import Optional, BinaryIO | ||
|
|
||
| import structlog | ||
| from django.core.files.storage import default_storage | ||
| from django.db.models import QuerySet | ||
|
|
||
| from core.models import Evidence, EvidenceRevision | ||
|
|
||
| logger = structlog.get_logger(__name__) | ||
|
|
||
|
|
||
| class AttachmentExporter: | ||
| def collect_all_attachments(self, scope: Optional[QuerySet] = None) -> QuerySet: | ||
| if scope is None: | ||
| revisions = EvidenceRevision.objects.all() | ||
| else: | ||
| revisions = scope | ||
|
|
||
| return revisions.filter(attachment__isnull=False).select_related( | ||
| "evidence", "folder" | ||
| ) | ||
|
|
||
| def package_attachments_to_zip( | ||
| self, revisions: QuerySet, zipf: zipfile.ZipFile | ||
| ) -> int: | ||
| count = 0 | ||
|
|
||
| for revision in revisions: | ||
| if revision.attachment and default_storage.exists(revision.attachment.name): | ||
| try: | ||
| with default_storage.open(revision.attachment.name, "rb") as file: | ||
| file_content = file.read() | ||
|
|
||
| filename = ( | ||
| f"{revision.evidence_id}_v{revision.version}_" | ||
| f"{os.path.basename(revision.attachment.name)}" | ||
| ) | ||
|
|
||
| zip_path = os.path.join( | ||
| "attachments", "evidence-revisions", filename | ||
| ) | ||
|
|
||
| zipf.writestr(zip_path, file_content) | ||
| count += 1 | ||
|
|
||
|
||
| except Exception as e: | ||
| logger.error( | ||
| "Failed to add attachment to ZIP", | ||
| revision_id=revision.id, | ||
| evidence_id=revision.evidence_id, | ||
| attachment_name=revision.attachment.name, | ||
| error=str(e), | ||
| ) | ||
| continue | ||
|
|
||
| return count | ||
|
|
||
| def create_attachments_zip( | ||
| self, revisions: Optional[QuerySet] = None | ||
| ) -> tuple[io.BytesIO, int]: | ||
| if revisions is None: | ||
| revisions = self.collect_all_attachments() | ||
|
|
||
| logger.info("Creating attachments ZIP", total_revisions=revisions.count()) | ||
|
|
||
| zip_buffer = io.BytesIO() | ||
|
|
||
| with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf: | ||
| count = self.package_attachments_to_zip(revisions, zipf) | ||
|
|
||
| zip_buffer.seek(0) | ||
|
|
||
| logger.info( | ||
| "Attachments ZIP created successfully", | ||
| attachments_count=count, | ||
| zip_size=len(zip_buffer.getvalue()), | ||
| ) | ||
|
|
||
| return zip_buffer, count | ||
|
|
||
|
|
||
| class AttachmentImporter: | ||
| def extract_attachments_from_zip( | ||
| self, zip_file: BinaryIO, dry_run: bool = False | ||
| ) -> dict: | ||
| stats = {"processed": 0, "restored": 0, "errors": []} | ||
|
|
||
| try: | ||
| with zipfile.ZipFile(zip_file, "r") as zipf: | ||
| attachment_files = [ | ||
| f | ||
| for f in zipf.namelist() | ||
| if f.startswith("attachments/evidence-revisions/") | ||
| and not f.endswith("/") | ||
| ] | ||
|
|
||
| stats["processed"] = len(attachment_files) | ||
|
|
||
| logger.info( | ||
| "Starting attachment import", | ||
| total_files=stats["processed"], | ||
| dry_run=dry_run, | ||
| ) | ||
|
|
||
| for file_path in attachment_files: | ||
| try: | ||
| filename = os.path.basename(file_path) | ||
| parts = filename.split("_", 2) | ||
|
|
||
| if len(parts) < 3: | ||
| stats["errors"].append( | ||
| f"Invalid filename format: {filename}" | ||
| ) | ||
| continue | ||
|
|
||
| evidence_id = parts[0] | ||
| version_str = parts[1] | ||
| original_filename = parts[2] | ||
|
|
||
| if not version_str.startswith("v"): | ||
| stats["errors"].append( | ||
| f"Invalid version format in: {filename}" | ||
| ) | ||
| continue | ||
|
|
||
| version = int(version_str[1:]) | ||
|
|
||
| if not dry_run: | ||
| # Find the corresponding EvidenceRevision | ||
| try: | ||
| revision = EvidenceRevision.objects.get( | ||
| evidence_id=evidence_id, version=version | ||
| ) | ||
|
|
||
| file_content = zipf.read(file_path) | ||
|
|
||
| storage_path = ( | ||
| f"evidence-revisions/{evidence_id}/" | ||
| f"v{version}/{original_filename}" | ||
| ) | ||
|
|
||
| saved_path = default_storage.save( | ||
| storage_path, io.BytesIO(file_content) | ||
| ) | ||
|
|
||
| revision.attachment = saved_path | ||
| revision.save(update_fields=["attachment"]) | ||
|
|
||
| stats["restored"] += 1 | ||
|
|
||
| except EvidenceRevision.DoesNotExist: | ||
| stats["errors"].append( | ||
| f"EvidenceRevision not found: " | ||
| f"evidence_id={evidence_id}, version={version}" | ||
| ) | ||
| except Exception as e: | ||
| stats["errors"].append(f"Failed to restore {filename}") | ||
| else: | ||
| stats["restored"] += 1 | ||
|
|
||
| except Exception as e: | ||
| logger.error( | ||
| "Error processing file path", | ||
| file_path=file_path, | ||
| error=str(e), | ||
| exc_info=True, | ||
| ) | ||
| stats["errors"].append( | ||
| f"Error processing {os.path.basename(file_path)}" | ||
| ) | ||
| continue | ||
|
|
||
| except zipfile.BadZipFile: | ||
| stats["errors"].append("Invalid ZIP file") | ||
| except Exception as e: | ||
| logger.error( | ||
| "Unexpected error during attachment import", | ||
| error=str(e), | ||
| exc_info=True, | ||
| ) | ||
| stats["errors"].append("Unexpected error occurred during import") | ||
|
|
||
| logger.info( | ||
| "Attachment import completed", | ||
| processed=stats["processed"], | ||
| restored=stats["restored"], | ||
| errors_count=len(stats["errors"]), | ||
| dry_run=dry_run, | ||
| ) | ||
|
|
||
| return stats | ||
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.
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.
Prefer
self.attachment.storageoverdefault_storagefor hashing readsIf
EvidenceRevision.attachmentever uses a non-default storage backend,default_storagemay read a different file than the one referenced by the field. Consider using the field’s storage (fallback todefault_storageonly if needed).Proposed fix (also removes the need for
exists())🤖 Prompt for AI Agents