from django.core.management.base import BaseCommand from django.db import transaction from apps.herd.models import ( HerdRancherTemporary, ) from apps.herd.services.herd_rancher_sync import HerdRancherSyncService class Command(BaseCommand): help = "Bulk Sync Rancher & Herd from HerdRancherTemporary" def add_arguments(self, parser): parser.add_argument( '--limit', type=int, help='limit number of records' ) parser.add_argument( '--dry-run', action='store_true', help='run without saving data' ) parser.add_argument( '--batch-size', type=int, default=1000, help='batch size' ) def handle(self, *args, **options): limit = options['limit'] dry_run = options['dry_run'] batch_size = options['batch_size'] qs = HerdRancherTemporary.objects.all() if limit: qs = qs[:limit] total = qs.count() self.stdout.write( self.style.NOTICE(f"Start bulk syncing {total} records") ) if dry_run: self.stdout.write( self.style.WARNING("Running in DRY-RUN mode (no DB writes)") ) return try: with transaction.atomic(): HerdRancherSyncService.bulk_sync( queryset=qs, batch_size=batch_size ) qs.update(sync_status='S') except Exception as e: qs.update(sync_status='F') raise e self.stdout.write( self.style.SUCCESS( f"Done. synced={total}" ) )