lbry-sdk/lbry/blob/disk_space_manager.py

59 lines
1.9 KiB
Python
Raw Normal View History

2021-08-16 14:15:12 -04:00
import asyncio
import logging
log = logging.getLogger(__name__)
2021-08-06 10:44:57 -04:00
class DiskSpaceManager:
2021-09-30 21:38:02 -04:00
def __init__(self, config, db, blob_manager, cleaning_interval=30 * 60, analytics=None):
2021-08-06 10:44:57 -04:00
self.config = config
self.db = db
self.blob_manager = blob_manager
2021-08-16 14:15:12 -04:00
self.cleaning_interval = cleaning_interval
self.running = False
self.task = None
2021-09-30 21:38:02 -04:00
self.analytics = analytics
2021-08-06 10:44:57 -04:00
async def get_space_used_bytes(self):
return await self.db.get_stored_blob_disk_usage()
2021-08-06 10:44:57 -04:00
async def get_space_used_mb(self):
return int(await self.get_space_used_bytes()/1024.0/1024.0)
2021-08-16 14:15:12 -04:00
async def clean(self):
2021-09-30 21:38:02 -04:00
space_used_bytes = await self.get_space_used_bytes()
storage_limit = self.config.blob_storage_limit*1024*1024 if self.config.blob_storage_limit else None
if self.analytics:
asyncio.create_task(self.analytics.send_disk_space_used(space_used_bytes, storage_limit))
if not storage_limit:
2021-08-16 17:03:40 -04:00
return 0
delete = []
2021-09-30 21:38:02 -04:00
available = storage_limit - space_used_bytes
2021-09-10 10:53:52 -04:00
if available > 0:
return 0
2021-09-15 10:49:03 -04:00
for blob_hash, file_size, _ in await self.db.get_stored_blobs(is_mine=False):
2021-09-10 10:53:52 -04:00
delete.append(blob_hash)
2021-08-16 14:15:12 -04:00
available += file_size
if available > 0:
break
if delete:
await self.db.stop_all_files()
await self.blob_manager.delete_blobs(delete, delete_from_db=True)
return len(delete)
2021-08-16 14:15:12 -04:00
async def cleaning_loop(self):
while self.running:
await asyncio.sleep(self.cleaning_interval)
await self.clean()
2021-08-16 14:15:12 -04:00
async def start(self):
self.running = True
self.task = asyncio.create_task(self.cleaning_loop())
self.task.add_done_callback(lambda _: log.info("Stopping blob cleanup service."))
async def stop(self):
if self.running:
self.running = False
self.task.cancel()