nova-api/api/backup_manager/main.py

58 lines
1.8 KiB
Python
Raw Permalink Normal View History

2023-09-21 19:55:14 +02:00
import os
import json
import asyncio
2023-09-21 22:38:12 +02:00
from sys import argv
from bson import json_util
from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient
2023-09-21 19:55:14 +02:00
load_dotenv()
2023-09-21 22:38:12 +02:00
MONGO_URI = os.environ['MONGO_URI']
2023-09-21 19:55:14 +02:00
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
2023-10-12 00:03:15 +02:00
async def main(output_dir: str) -> None:
2023-09-21 19:55:14 +02:00
await make_backup(output_dir)
2023-10-12 00:03:15 +02:00
async def make_backup(output_dir: str) -> None:
"""Makes a backup of all collections in the database."""
2023-09-21 22:38:12 +02:00
output_dir = os.path.join(FILE_DIR, '..', 'backups', output_dir)
2023-09-21 19:55:14 +02:00
2023-10-12 00:03:15 +02:00
os.makedirs(output_dir, exist_ok=True)
2023-09-21 19:55:14 +02:00
client = AsyncIOMotorClient(MONGO_URI)
databases = await client.list_database_names()
databases = {db: await client[db].list_collection_names() for db in databases}
for database in databases:
2023-09-21 22:38:12 +02:00
if database == 'local':
continue
2023-10-12 00:03:15 +02:00
os.makedirs(os.path.join(output_dir, database), exist_ok=True)
2023-09-21 19:55:14 +02:00
for collection in databases[database]:
2023-10-12 00:03:15 +02:00
print(f'Initiated backup for {database}/{collection}')
2023-09-21 19:55:14 +02:00
await make_backup_for_collection(database, collection, output_dir)
2023-10-12 00:03:15 +02:00
print(f'Finished backup for {database}/{collection}')
2023-09-21 19:55:14 +02:00
2023-10-12 00:03:15 +02:00
async def make_backup_for_collection(database, collection, output_dir) -> None:
"""Makes a backup of a collection in the database."""
2023-10-06 09:37:16 +02:00
path = os.path.join(output_dir, database, f'{collection}.json')
2023-09-21 19:55:14 +02:00
client = AsyncIOMotorClient(MONGO_URI)
collection = client[database][collection]
documents = await collection.find({}).to_list(length=None)
2023-10-12 00:03:15 +02:00
with open(path, 'w') as f:
2023-10-06 09:37:16 +02:00
for chunk in json.JSONEncoder(default=json_util.default).iterencode(documents):
2023-10-12 00:03:15 +02:00
f.write(chunk)
2023-09-21 19:55:14 +02:00
2023-09-21 22:38:12 +02:00
if __name__ == '__main__':
2023-09-21 19:55:14 +02:00
if len(argv) < 2 or len(argv) > 2:
2023-09-21 22:38:12 +02:00
print('Usage: python3 main.py <output_dir>')
2023-09-21 19:55:14 +02:00
exit(1)
output_dir = argv[1]
asyncio.run(main(output_dir))