Last active
February 28, 2025 15:03
-
-
Save erickdsama/6eed3207296198751e4abbcc68f3b798 to your computer and use it in GitHub Desktop.
Restore database with the last backup in develop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import os | |
import subprocess | |
import sys | |
import time | |
import boto3 | |
BUCKET = 'erpnext-backups-zeb' | |
def convert_size(size_bytes): | |
if size_bytes == 0: | |
return "0B" | |
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") | |
i = int(math.floor(math.log(size_bytes, 1024))) | |
p = math.pow(1024, i) | |
s = round(size_bytes / p, 2) | |
return "%s %s" % (s, size_name[i]) | |
def get_last_backup_s3(s3_client=None): | |
if not s3_client: | |
s3_client = boto3.client('s3') | |
response = s3_client.list_objects_v2(Bucket=BUCKET, Prefix='development/erp-development.zebrands.mx/minimal_backup/') | |
# get last file from the list | |
files = response.get("Contents", []) | |
files.sort(key=lambda x: x.get("LastModified")) | |
last_file = files[-1].get("Key") | |
print(f"Last file found in s3 {last_file}") | |
return last_file | |
def download_backup_from_s3(): | |
print("Trying to download backup from s3") | |
s3_client = boto3.client('s3') | |
last_file = get_last_backup_s3(s3_client=s3_client) | |
file_name = last_file.split("/")[-1] | |
meta_data = s3_client.head_object(Bucket=BUCKET, Key=last_file) | |
total_length = int(meta_data.get('ContentLength', 0)) | |
downloaded = 0 | |
def progress(chunk): | |
nonlocal downloaded | |
downloaded += chunk | |
done = int(50 * downloaded / total_length) | |
sys.stdout.write("%s[%s%s] %s/%s\r" % ('', "#" * done, "." * (50 - done), convert_size(downloaded), convert_size(total_length))) | |
sys.stdout.flush() | |
print(f'Downloading {file_name}') | |
with open(file_name, 'wb') as f: | |
s3_client.download_fileobj(BUCKET, last_file, f, | |
Callback=progress) | |
print("Downloaded backup from s3") | |
return file_name | |
def verify_pv_installed(): | |
try: | |
subprocess.run(["pv", "--version"]) | |
except FileNotFoundError: | |
subprocess.run(["sudo", "apt-get", "install", "pv", "-y", "-qq"]) | |
if __name__ == "__main__": | |
start_time = time.time() | |
verify_pv_installed() | |
backup_name = 'min_20241231_230023-erp-development_zebrands_mx-database.sql.gz' | |
backup_path = os.path.abspath(backup_name) | |
subprocess.run(f"bench restore {backup_path} --mariadb-root-username root --mariadb-root-password 123 --admin-password 123", shell=True) | |
print("--- %s seconds ---" % (time.time() - start_time)) |
Author
erickdsama
commented
Apr 3, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment