nova-api/api/backup_manager/main.py

56 lines
1.6 KiB
Python
Raw 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-09-21 22:38:12 +02:00
async def main(output_dir: str):
2023-09-21 19:55:14 +02:00
await make_backup(output_dir)
2023-09-21 22:38:12 +02:00
async def make_backup(output_dir: str):
output_dir = os.path.join(FILE_DIR, '..', 'backups', output_dir)
2023-09-21 19:55:14 +02:00
if not os.path.exists(output_dir):
os.makedirs(output_dir)
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
if not os.path.exists(f'{output_dir}/{database}'):
os.mkdir(f'{output_dir}/{database}')
2023-09-21 19:55:14 +02:00
for collection in databases[database]:
print(f'Initiated database backup for {database}/{collection}')
2023-09-21 19:55:14 +02:00
await make_backup_for_collection(database, collection, output_dir)
async def make_backup_for_collection(database, collection, output_dir):
2023-09-21 22:38:12 +02:00
path = f'{output_dir}/{database}/{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-09-21 22:38:12 +02:00
with open(path, 'w') as f:
2023-09-21 19:55:14 +02:00
json.dump(documents, f, default=json_util.default)
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))