2023-09-21 19:55:14 +02:00
|
|
|
import os
|
|
|
|
import json
|
|
|
|
import asyncio
|
2023-10-06 09:37:16 +02:00
|
|
|
import aiofiles
|
|
|
|
import aiofiles.os
|
2023-09-21 19:55:14 +02:00
|
|
|
|
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
|
|
|
|
2023-10-06 09:37:16 +02:00
|
|
|
await aiofiles.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-06 09:37:16 +02:00
|
|
|
await aiofiles.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-09-23 21:41:48 +02:00
|
|
|
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-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-06 09:37:16 +02:00
|
|
|
async with aiofiles.open(path, 'w') as f:
|
|
|
|
for chunk in json.JSONEncoder(default=json_util.default).iterencode(documents):
|
|
|
|
await 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]
|
2023-09-23 21:41:48 +02:00
|
|
|
asyncio.run(main(output_dir))
|