|
| 1 | +import datetime |
| 2 | +from typing import List |
| 3 | + |
| 4 | +from sqlalchemy import select |
| 5 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 6 | +from sqlalchemy.orm import joinedload |
| 7 | + |
| 8 | +from dstack._internal.core.models.profiles import parse_duration |
| 9 | +from dstack._internal.core.models.volumes import VolumeStatus |
| 10 | +from dstack._internal.server.db import get_session_ctx |
| 11 | +from dstack._internal.server.models import VolumeModel |
| 12 | +from dstack._internal.server.services.locking import get_locker |
| 13 | +from dstack._internal.server.services.volumes import delete_volumes, get_volume_configuration |
| 14 | +from dstack._internal.utils.common import get_current_datetime |
| 15 | +from dstack._internal.utils.logging import get_logger |
| 16 | + |
| 17 | +logger = get_logger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +async def process_idle_volumes(batch_size: int = 10): |
| 21 | + """ |
| 22 | + Process volumes to check if they have exceeded their idle_duration and delete them. |
| 23 | + """ |
| 24 | + lock, lockset = get_locker().get_lockset(VolumeModel.__tablename__) |
| 25 | + async with get_session_ctx() as session: |
| 26 | + async with lock: |
| 27 | + res = await session.execute( |
| 28 | + select(VolumeModel) |
| 29 | + .where( |
| 30 | + VolumeModel.status == VolumeStatus.ACTIVE, |
| 31 | + VolumeModel.deleted == False, |
| 32 | + VolumeModel.id.not_in(lockset), |
| 33 | + ) |
| 34 | + .options(joinedload(VolumeModel.project)) |
| 35 | + .options(joinedload(VolumeModel.attachments)) |
| 36 | + .order_by(VolumeModel.last_processed_at.asc()) |
| 37 | + .limit(batch_size) |
| 38 | + .with_for_update(skip_locked=True) |
| 39 | + ) |
| 40 | + volume_models = list(res.unique().scalars().all()) |
| 41 | + if not volume_models: |
| 42 | + return |
| 43 | + |
| 44 | + # Add to lockset |
| 45 | + for volume_model in volume_models: |
| 46 | + lockset.add(volume_model.id) |
| 47 | + |
| 48 | + try: |
| 49 | + volumes_to_delete = [] |
| 50 | + for volume_model in volume_models: |
| 51 | + if await _should_delete_idle_volume(volume_model): |
| 52 | + volumes_to_delete.append(volume_model) |
| 53 | + |
| 54 | + if volumes_to_delete: |
| 55 | + await _delete_idle_volumes(session, volumes_to_delete) |
| 56 | + |
| 57 | + finally: |
| 58 | + # Remove from lockset |
| 59 | + for volume_model in volume_models: |
| 60 | + lockset.difference_update([volume_model.id]) |
| 61 | + |
| 62 | + |
| 63 | +async def _should_delete_idle_volume(volume_model: VolumeModel) -> bool: |
| 64 | + """ |
| 65 | + Check if a volume should be deleted based on its idle duration. |
| 66 | + """ |
| 67 | + # Get volume configuration |
| 68 | + configuration = get_volume_configuration(volume_model) |
| 69 | + |
| 70 | + # If no idle_duration is configured, don't delete |
| 71 | + if configuration.idle_duration is None: |
| 72 | + return False |
| 73 | + |
| 74 | + # If idle_duration is disabled (negative value), don't delete |
| 75 | + if isinstance(configuration.idle_duration, int) and configuration.idle_duration < 0: |
| 76 | + return False |
| 77 | + |
| 78 | + # Parse idle duration |
| 79 | + idle_duration_seconds = parse_duration(configuration.idle_duration) |
| 80 | + if idle_duration_seconds is None or idle_duration_seconds <= 0: |
| 81 | + return False |
| 82 | + |
| 83 | + # Check if volume is currently attached to any instance |
| 84 | + if len(volume_model.attachments) > 0: |
| 85 | + logger.debug("Volume %s is still attached to instances, not deleting", volume_model.name) |
| 86 | + return False |
| 87 | + |
| 88 | + # Calculate how long the volume has been idle |
| 89 | + idle_duration = _get_volume_idle_duration(volume_model) |
| 90 | + idle_threshold = datetime.timedelta(seconds=idle_duration_seconds) |
| 91 | + |
| 92 | + if idle_duration > idle_threshold: |
| 93 | + logger.info( |
| 94 | + "Volume %s idle duration expired: idle time %s seconds, threshold %s seconds. Marking for deletion", |
| 95 | + volume_model.name, |
| 96 | + idle_duration.total_seconds(), |
| 97 | + idle_threshold.total_seconds(), |
| 98 | + ) |
| 99 | + return True |
| 100 | + |
| 101 | + return False |
| 102 | + |
| 103 | + |
| 104 | +def _get_volume_idle_duration(volume_model: VolumeModel) -> datetime.timedelta: |
| 105 | + """ |
| 106 | + Calculate how long a volume has been idle. |
| 107 | + A volume is considered idle from the time it was last processed by a job. |
| 108 | + If it was never used by a job, use the created_at time. |
| 109 | + """ |
| 110 | + last_time = volume_model.created_at.replace(tzinfo=datetime.timezone.utc) |
| 111 | + if volume_model.last_job_processed_at is not None: |
| 112 | + last_time = volume_model.last_job_processed_at.replace(tzinfo=datetime.timezone.utc) |
| 113 | + return get_current_datetime() - last_time |
| 114 | + |
| 115 | + |
| 116 | +async def _delete_idle_volumes(session: AsyncSession, volume_models: List[VolumeModel]): |
| 117 | + """ |
| 118 | + Delete volumes that have exceeded their idle duration. |
| 119 | + """ |
| 120 | + # Group volumes by project |
| 121 | + volumes_by_project = {} |
| 122 | + for volume_model in volume_models: |
| 123 | + project = volume_model.project |
| 124 | + if project not in volumes_by_project: |
| 125 | + volumes_by_project[project] = [] |
| 126 | + volumes_by_project[project].append(volume_model.name) |
| 127 | + |
| 128 | + # Delete volumes by project |
| 129 | + for project, volume_names in volumes_by_project.items(): |
| 130 | + logger.info("Deleting idle volumes for project %s: %s", project.name, volume_names) |
| 131 | + try: |
| 132 | + await delete_volumes(session, project, volume_names) |
| 133 | + except Exception as e: |
| 134 | + logger.error("Failed to delete idle volumes for project %s: %s", project.name, str(e)) |
0 commit comments