mirror of
https://gitlab.sectorq.eu/jaydee/omv_backup.git
synced 2025-09-13 12:10:12 +02:00
Compare commits
59 Commits
1714817673
...
main
Author | SHA1 | Date | |
---|---|---|---|
122ef64ad7 | |||
99f673996e | |||
68e23da03b | |||
1c30fb9995 | |||
b94b61ba5d | |||
26c3245cf3 | |||
1510dc2e8d | |||
d949188a34 | |||
298c9aee23 | |||
808f92c4d1 | |||
43f6d2abcb | |||
81c7ead7b2 | |||
cd818da774 | |||
a1dfbd664c | |||
571219881d | |||
0c07fde85a | |||
f46eacf627 | |||
92226734ef | |||
d3359e9a68 | |||
fdbe4eebe1 | |||
3a3faad97e | |||
8be3e20523 | |||
126ab1813b | |||
28efc95b4d | |||
f6a106fd91 | |||
bbe4d72666 | |||
b536c8ecb1 | |||
7a8130c3f0 | |||
5756798269 | |||
d6af0c24b5 | |||
6f9a2bba67 | |||
11bc56ecb3 | |||
b4032eca7e | |||
f75ac2eb79 | |||
a555567c4b | |||
de63a1e9aa | |||
d3eab9f50e | |||
72a2fa5710 | |||
b3be50bfdd | |||
f32ada9ad5 | |||
d6492ebf80 | |||
7cee7570b4 | |||
ce7c855808 | |||
d3e15e973a | |||
cee1cf353c | |||
f9e7654c47 | |||
1816bd516c | |||
dad1c49409 | |||
66644b6bb9 | |||
781a74ba20 | |||
29cb028c5c | |||
1667ce0079 | |||
984b3e09a0 | |||
64bea0a833 | |||
dd51f14699 | |||
35aa35a3b5 | |||
4f868047be | |||
ba09aeb502 | |||
8e9e915cdc |
@@ -25,6 +25,6 @@ build-job: # This job runs in the build stage, which runs first.
|
|||||||
script:
|
script:
|
||||||
- column=":"
|
- column=":"
|
||||||
- echo "${flow_id}"
|
- echo "${flow_id}"
|
||||||
- curl -X POST https://kestra.sectorq.eu/api/v1/executions/webhook/jaydee/ansible-all/${flow_id} -d '{"tag":["setup","omv_backup"],"target":["servers"]}' -H "Content-Type${column} application/json"
|
- curl -X POST https://kestra.sectorq.eu/api/v1/executions/webhook/jaydee/ansible-all/${flow_id} -d '{"tag":["omv_backup"],"target":["servers"]}' -H "Content-Type${column} application/json"
|
||||||
rules:
|
rules:
|
||||||
- if: '$CI_COMMIT_MESSAGE =~ /build/'
|
- if: '$CI_COMMIT_MESSAGE =~ /build/'
|
||||||
|
@@ -11,3 +11,5 @@ var_lib_motioneye/*
|
|||||||
*/.esphome/build/*
|
*/.esphome/build/*
|
||||||
nextcloud/mariadb/*
|
nextcloud/mariadb/*
|
||||||
zabbix-server/postgres-data/*
|
zabbix-server/postgres-data/*
|
||||||
|
gitea-runner/*
|
||||||
|
immich/library/*
|
274
omv_backup.py
274
omv_backup.py
@@ -17,14 +17,21 @@ import fnmatch
|
|||||||
import yaml
|
import yaml
|
||||||
import paramiko
|
import paramiko
|
||||||
import shutil
|
import shutil
|
||||||
|
import signal
|
||||||
import paho.mqtt.client as mqtt
|
import paho.mqtt.client as mqtt
|
||||||
#import numpy as np
|
#import numpy as np
|
||||||
|
|
||||||
|
def signal_handler(sig, frame):
|
||||||
|
print('You pressed Ctrl+C!')
|
||||||
|
conn.close()
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
file_path = os.path.realpath(__file__)
|
file_path = os.path.realpath(__file__)
|
||||||
dir_path = os.path.dirname(file_path)
|
dir_path = os.path.dirname(file_path)
|
||||||
VERSION="1.0.9"
|
VERSION="1.0.10"
|
||||||
# print(file_path)
|
# print(file_path)
|
||||||
# print(dir_path)
|
# print(dir_path)
|
||||||
os.chdir(dir_path)
|
os.chdir(dir_path)
|
||||||
@@ -45,6 +52,7 @@ status, output = subprocess.getstatusoutput(cmnd)
|
|||||||
if int(output) > 0:
|
if int(output) > 0:
|
||||||
print("Running already!")
|
print("Running already!")
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
def is_port_open(host, port):
|
def is_port_open(host, port):
|
||||||
try:
|
try:
|
||||||
sock = socket.create_connection((host, port))
|
sock = socket.create_connection((host, port))
|
||||||
@@ -102,9 +110,6 @@ for o, a in opts:
|
|||||||
elif o in ("-r", "--restore"):
|
elif o in ("-r", "--restore"):
|
||||||
_RESTORE = True
|
_RESTORE = True
|
||||||
_APP = a
|
_APP = a
|
||||||
print("RESTORE")
|
|
||||||
elif o in ("-b", "--backup"):
|
|
||||||
_BACKUP = True
|
|
||||||
elif o in ("-D", "--dry"):
|
elif o in ("-D", "--dry"):
|
||||||
_EXECUTE = False
|
_EXECUTE = False
|
||||||
elif o in ("-T", "--dry"):
|
elif o in ("-T", "--dry"):
|
||||||
@@ -198,14 +203,14 @@ logging.info("Test connection")
|
|||||||
hm = socket.gethostbyaddr(BACKUP_HOST)
|
hm = socket.gethostbyaddr(BACKUP_HOST)
|
||||||
|
|
||||||
logging.info(_RESTORE)
|
logging.info(_RESTORE)
|
||||||
def send_mqtt_message(topic,msg):
|
def send_mqtt_message(topic,msg,qos=0,retain=False):
|
||||||
client2 = mqtt.Client()
|
client2 = mqtt.Client()
|
||||||
client2.username_pw_set(USERNAME, PASSWORD)
|
client2.username_pw_set("jaydee", "jaydee1")
|
||||||
try:
|
try:
|
||||||
client2.connect(broker,1883,60)
|
client2.connect("mqtt.home.lan",1883,60)
|
||||||
client2.publish(topic, json.dumps(msg))
|
client2.publish(topic, json.dumps(msg), qos=qos, retain=retain)
|
||||||
client2.disconnect()
|
client2.disconnect()
|
||||||
logging.info(f"Message sent {topic}, {msg}")
|
logging.info(f"Message1 sent {topic}, {msg}")
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
logging.error("Failed to send")
|
logging.error("Failed to send")
|
||||||
print("Failed to send")
|
print("Failed to send")
|
||||||
@@ -234,13 +239,13 @@ if _STOP:
|
|||||||
continue
|
continue
|
||||||
cmnd = f"docker stop {c.split()[-1]}"
|
cmnd = f"docker stop {c.split()[-1]}"
|
||||||
status, running_containers = subprocess.getstatusoutput(cmnd)
|
status, running_containers = subprocess.getstatusoutput(cmnd)
|
||||||
def restore_job():
|
def restore_job(_APP):
|
||||||
logging.info(f'starting restore job')
|
#global VERSION
|
||||||
return 0
|
|
||||||
logging.info("Starting Restore")
|
logging.info("Starting Restore")
|
||||||
print("Starting Restore")
|
print(f"Starting restore : {VERSION}")
|
||||||
now = datetime.datetime.now()
|
now = datetime.datetime.now()
|
||||||
STARTTIME = now.strftime("%Y-%m-%d_%H:%M:%S")
|
STARTTIME = now.strftime("%Y-%m-%d_%H:%M:%S")
|
||||||
|
_DATE = "pick"
|
||||||
if _APP == "all":
|
if _APP == "all":
|
||||||
_DATE = "latest"
|
_DATE = "latest"
|
||||||
if host == "rpi5.home.lan" or host == "rpi5":
|
if host == "rpi5.home.lan" or host == "rpi5":
|
||||||
@@ -253,6 +258,7 @@ def restore_job():
|
|||||||
#input("????")
|
#input("????")
|
||||||
else:
|
else:
|
||||||
_APP = _APP.split(",")
|
_APP = _APP.split(",")
|
||||||
|
|
||||||
PROGRESS = 0
|
PROGRESS = 0
|
||||||
topic = "sectorq/amd/restore"
|
topic = "sectorq/amd/restore"
|
||||||
step = 100 / len(_APP)
|
step = 100 / len(_APP)
|
||||||
@@ -274,7 +280,7 @@ def restore_job():
|
|||||||
if _DATE == "pick":
|
if _DATE == "pick":
|
||||||
cmnd = f"ssh root@amd.home.lan 'ls {BACKUP_DEVICE}/backup/m-server/docker_data'"
|
cmnd = f"ssh root@amd.home.lan 'ls {BACKUP_DEVICE}/backup/m-server/docker_data'"
|
||||||
status, output = subprocess.getstatusoutput(cmnd)
|
status, output = subprocess.getstatusoutput(cmnd)
|
||||||
print(output)
|
# print(output)
|
||||||
dates = output.splitlines()
|
dates = output.splitlines()
|
||||||
n = 1
|
n = 1
|
||||||
for i in dates:
|
for i in dates:
|
||||||
@@ -301,7 +307,7 @@ def restore_job():
|
|||||||
LATEST_LINK = f"/{host}/{app}/{_DATE}"
|
LATEST_LINK = f"/{host}/{app}/{_DATE}"
|
||||||
|
|
||||||
logging.info("Create backup dir")
|
logging.info("Create backup dir")
|
||||||
logging.info(cmnd)
|
#logging.info(cmnd)
|
||||||
|
|
||||||
|
|
||||||
#cmnd = "rsync -av --delete {}/ --link-dest {} --exclude=\".cache\" {}".format(SOURCE_DIR, LATEST_LINK, BACKUP_PATH)
|
#cmnd = "rsync -av --delete {}/ --link-dest {} --exclude=\".cache\" {}".format(SOURCE_DIR, LATEST_LINK, BACKUP_PATH)
|
||||||
@@ -470,26 +476,45 @@ def restore_job():
|
|||||||
|
|
||||||
msg = {"mode":_MODE, "status":"restore","bak_name":"Restore","host":host,"cur_job":app,"start_time":STARTTIME,"end_time":"","progress":100,"finished":ENDJOB,"used_space":1}
|
msg = {"mode":_MODE, "status":"restore","bak_name":"Restore","host":host,"cur_job":app,"start_time":STARTTIME,"end_time":"","progress":100,"finished":ENDJOB,"used_space":1}
|
||||||
logging.info(msg)
|
logging.info(msg)
|
||||||
|
|
||||||
send_mqtt_message(topic,msg)
|
send_mqtt_message(topic,msg)
|
||||||
if _MODE == "auto":
|
if _MODE == "auto":
|
||||||
cmnd = "ssh root@amd.home.lan 'systemctl suspend &'"
|
cmnd = "ssh root@amd.home.lan 'systemctl suspend &'"
|
||||||
status, output = subprocess.getstatusoutput(cmnd)
|
status, output = subprocess.getstatusoutput(cmnd)
|
||||||
|
|
||||||
def backup_job(server):
|
def backup_job(pl):
|
||||||
|
client2 = mqtt.Client()
|
||||||
|
client2.username_pw_set("jaydee", "jaydee1")
|
||||||
|
client2.connect("mqtt.home.lan",1883,60)
|
||||||
|
if "log" in pl:
|
||||||
|
if pl["log"] == "debug":
|
||||||
|
logging.info(f'Debug enabled')
|
||||||
|
LOG_FILE = "omv_backup.log"
|
||||||
|
logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG, format='%(asctime)s : %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
|
||||||
logging.info(f'starting backup job')
|
logging.info(f'starting backup job')
|
||||||
message = "start"
|
|
||||||
topic = "sectorq/backups/start"
|
|
||||||
|
|
||||||
|
|
||||||
|
server = pl["host"]
|
||||||
|
if pl["mode"] == "dry":
|
||||||
|
_DRYRUN = True
|
||||||
|
logging.info("Dry run active")
|
||||||
|
else:
|
||||||
|
_DRYRUN = False
|
||||||
|
logging.info("Full mode active")
|
||||||
|
|
||||||
finished = []
|
finished = []
|
||||||
|
sub_finished = []
|
||||||
now = datetime.datetime.now()
|
now = datetime.datetime.now()
|
||||||
STARTTIME = now.strftime("%Y-%m-%d_%H:%M:%S")
|
STARTTIME = now.strftime("%Y-%m-%d_%H:%M:%S")
|
||||||
topic = "sectorq/amd/restore"
|
topic = "sectorq/amd/restore"
|
||||||
msg = {"mode":"restore", "status":"restore","bak_name":"s","host":0,"cur_job":"aaa","start_time":1,"end_time":1,"progress":0,"finished":0,"used_space":0}
|
msg = {"mode":"restore", "status":"restore","bak_name":"s","host":0,"cur_job":"aaa","start_time":1,"end_time":1,"progress":0,"finished":0,"used_space":0}
|
||||||
send_mqtt_message(topic,msg)
|
|
||||||
#client.publish(topic, msg)
|
client2.publish(topic, json.dumps(msg),qos=0, retain=True)
|
||||||
|
#client2.publish(topic, msg)
|
||||||
topic = "sectorq/amd/backups"
|
topic = "sectorq/amd/backups"
|
||||||
msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":"","cur_job":"","start_time":STARTTIME,"end_time":"in progress","progress":0,"finished":",".join(finished)}
|
msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":"","cur_job":"","start_time":STARTTIME,"end_time":"in progress","progress":0,"finished":",".join(finished)}
|
||||||
send_mqtt_message(topic,msg)
|
client2.publish(topic, json.dumps(msg),qos=0, retain=True)
|
||||||
|
|
||||||
# iterate over files in
|
# iterate over files in
|
||||||
# that directory
|
# that directory
|
||||||
@@ -502,7 +527,7 @@ def backup_job(server):
|
|||||||
if not backups[host]["jobs"][b]["active"]:
|
if not backups[host]["jobs"][b]["active"]:
|
||||||
logging.info("Backup {} is not active!".format(b))
|
logging.info("Backup {} is not active!".format(b))
|
||||||
msg = {"status":"inactive","bak_name":b,"start_time":"inactive","end_time":"inactive","progress":0}
|
msg = {"status":"inactive","bak_name":b,"start_time":"inactive","end_time":"inactive","progress":0}
|
||||||
send_mqtt_message(topic,msg)
|
client2.publish(topic, json.dumps(msg),qos=0, retain=True)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
SOURCE_DIR = backups[host]["jobs"][b]["source"]
|
SOURCE_DIR = backups[host]["jobs"][b]["source"]
|
||||||
@@ -522,9 +547,9 @@ def backup_job(server):
|
|||||||
|
|
||||||
# msg = {"status":"started","bak_name":b,"start_time":DATETIME,"end_time":"in progress", "progress":0}
|
# msg = {"status":"started","bak_name":b,"start_time":DATETIME,"end_time":"in progress", "progress":0}
|
||||||
msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":host,"cur_job":b,"start_time":STARTTIME,"end_time":"in progress","progress":0,"finished":",".join(finished)}
|
msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":host,"cur_job":b,"start_time":STARTTIME,"end_time":"in progress","progress":0,"finished":",".join(finished)}
|
||||||
client.connect(broker,1883,60)
|
|
||||||
client.publish(topic, json.dumps(msg),qos=0, retain=True)
|
client2.publish(topic, json.dumps(msg),qos=0, retain=True)
|
||||||
client.disconnect()
|
|
||||||
|
|
||||||
|
|
||||||
cmnd = "mkdir -p " + NEW_BACKUP_DIR
|
cmnd = "mkdir -p " + NEW_BACKUP_DIR
|
||||||
@@ -547,18 +572,16 @@ def backup_job(server):
|
|||||||
|
|
||||||
step = round(100 / c,1)
|
step = round(100 / c,1)
|
||||||
progress = 0
|
progress = 0
|
||||||
#cmd = f"rsync -avz --delete {BACKUP_DIR} --link-dest {FULL_BACKUP_LATEST}/ --exclude=\"jellyfin/cache/transcodes\" --exclude=\"gitlab/logs/prometheus\" --exclude=\"home-assistant.log\" --exclude=\"gitlab/logs/*\" --exclude=\"esphome/config/.esphome\" --exclude=\".cache\" --exclude=\".git\" --exclude=\"var_lib_motioneye\" {NEW_BACKUP_DIR}"
|
|
||||||
#cmd = [ 'rsync', '-avz','--info=progress2', BACKUP_DIR , NEW_BACKUP_DIR]
|
|
||||||
|
|
||||||
#cmd = ['rsync', '-avz', '--delete', BACKUP_DIR, '--link-dest', FULL_BACKUP_LATEST, '--exclude="home-assistant_v2.db"', '--exclude="jellyfin/cache/transcodes"', '--exclude=".@__thumb/"', '--exclude="gitlab/logs/prometheus"', '--exclude="home-assistant.log"', '--exclude="gitlab/logs/*"', '--exclude="esphome/config/.esphome"', '--exclude=".cache"', '--exclude=".git"', '--exclude="var_lib_motioneye"', '--exclude="/.esphome/build"', '--exclude="nextcloud\mariadb\*"', NEW_BACKUP_DIR]
|
|
||||||
|
|
||||||
cmd = ['rsync', '-avz', '--delete', BACKUP_DIR, '--link-dest', FULL_BACKUP_LATEST, '--exclude-from=/myapps/exclude.txt', NEW_BACKUP_DIR]
|
cmd = ['rsync', '-avz', '--delete', BACKUP_DIR, '--link-dest', FULL_BACKUP_LATEST, '--exclude-from=/myapps/exclude.txt', NEW_BACKUP_DIR]
|
||||||
logging.info(" ".join(cmd))
|
logging.info(" ".join(cmd))
|
||||||
|
topic = "sectorq/amd/backups"
|
||||||
|
|
||||||
|
if not _DRYRUN:
|
||||||
process = subprocess.Popen(cmd,
|
process = subprocess.Popen(cmd,
|
||||||
stdout=subprocess.PIPE)
|
stdout=subprocess.PIPE)
|
||||||
while process.poll() is None:
|
while process.poll() is None:
|
||||||
line = process.stdout.readline().decode("utf-8").split("/")
|
line = process.stdout.readline().decode("utf-8").split("/")
|
||||||
print(line[0])
|
#print(line[0])
|
||||||
if line[0] in apps:
|
if line[0] in apps:
|
||||||
logging.info(f"Working on app {line[0]}")
|
logging.info(f"Working on app {line[0]}")
|
||||||
while True:
|
while True:
|
||||||
@@ -568,45 +591,19 @@ def backup_job(server):
|
|||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
apps.remove(line[0])
|
apps.remove(line[0])
|
||||||
#print(len(apps))
|
sub_finished.append(line[0])
|
||||||
topic = "sectorq/amd/backups"
|
msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":host,"cur_job":b,"sub":line[0],"start_time":STARTTIME,"end_time":"in progress","progress":str(round(progress)) + "%","finished":",".join(finished),"sub_finished":",".join(sub_finished)}
|
||||||
msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":host,"cur_job":b,"sub":line[0],"start_time":STARTTIME,"end_time":"in progress","progress":str(round(progress)) + "%","finished":",".join(finished)}
|
logging.info(f"Sending message with topic {topic} {json.dumps(msg)}")
|
||||||
send_mqtt_message(topic,msg)
|
if not "gitea-runner" == line[0]:
|
||||||
|
client2.publish(topic, json.dumps(msg),qos=0, retain=False)
|
||||||
progress = progress + step
|
progress = progress + step
|
||||||
# input(apps)
|
|
||||||
|
|
||||||
# for a in apps:
|
|
||||||
# logging.info(f"App {a}")
|
|
||||||
# topic = "sectorq/amd/backups"
|
|
||||||
# msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":host,"cur_job":b,"sub":a,"start_time":STARTTIME,"end_time":"in progress","progress":round(progress),"finished":",".join(finished)}
|
|
||||||
# send_mqtt_message(topic,msg)
|
|
||||||
# logger.debug(cmnd)
|
|
||||||
# if _FIRST:
|
|
||||||
# cmnd = f"rsync -avz --delete {SOURCE_DIR} --exclude=\"jellyfin/cache/transcodes\" --exclude=\"gitlab/logs/prometheus\" --exclude=\"home-assistant.log\" --exclude=\"gitlab/logs/*\" --exclude=\"esphome/config/.esphome\" --exclude=\".cache\" --exclude=\".git\" --exclude=\"var_lib_motioneye\" rsync://{BACKUP_HOST}{BACKUP_PATH}"
|
|
||||||
# else:
|
|
||||||
# cmnd = f"rsync -avz --delete {BACKUP_DIR}{a} --link-dest {FULL_BACKUP_LATEST}/{a} --exclude=\"jellyfin/cache/transcodes\" --exclude=\"gitlab/logs/prometheus\" --exclude=\"home-assistant.log\" --exclude=\"gitlab/logs/*\" --exclude=\"esphome/config/.esphome\" --exclude=\".cache\" --exclude=\".git\" --exclude=\"var_lib_motioneye\" {NEW_BACKUP_DIR}"
|
|
||||||
|
|
||||||
# ans = "y"
|
|
||||||
# logging.info(cmnd)
|
|
||||||
# logging.info("Sync files1")
|
|
||||||
# #input("??????")
|
|
||||||
# if _TEST:
|
|
||||||
# ans = input("continue?") or "n"
|
|
||||||
# if ans == "y" and _EXECUTE:
|
|
||||||
# status, output = subprocess.getstatusoutput(cmnd)
|
|
||||||
# #proc = subprocess.Popen(cmnd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd = "/myapps/",shell=True)
|
|
||||||
# progress = progress + step
|
|
||||||
# topic = "sectorq/amd/backups"
|
|
||||||
# msg = {"mode":_MODE, "status":"started","bak_name":"complete","host":host,"cur_job":b,"sub":a,"start_time":STARTTIME,"end_time":"in progress","progress":round(progress),"finished":",".join(finished)}
|
|
||||||
# send_mqtt_message(topic,msg)
|
|
||||||
|
|
||||||
|
|
||||||
cmnd = f"rm -rf {FULL_BACKUP_LATEST}"
|
cmnd = f"rm -rf {FULL_BACKUP_LATEST}"
|
||||||
|
|
||||||
logging.info(cmnd)
|
#logging.info(cmnd)
|
||||||
logging.info("Removing latest link")
|
logging.info("Removing latest link")
|
||||||
# input("????")
|
# input("????")
|
||||||
if _EXECUTE:
|
if not _DRYRUN:
|
||||||
status, output = subprocess.getstatusoutput(cmnd)
|
status, output = subprocess.getstatusoutput(cmnd)
|
||||||
if _FIRST:
|
if _FIRST:
|
||||||
cmnd = f"cd {BACKUP_ROOT}; ln -s initial latest"
|
cmnd = f"cd {BACKUP_ROOT}; ln -s initial latest"
|
||||||
@@ -615,28 +612,21 @@ def backup_job(server):
|
|||||||
logging.info("Creating new latest link")
|
logging.info("Creating new latest link")
|
||||||
#print(cmnd)
|
#print(cmnd)
|
||||||
# input("????")
|
# input("????")
|
||||||
if _EXECUTE:
|
if not _DRYRUN:
|
||||||
status, output = subprocess.getstatusoutput(cmnd)
|
status, output = subprocess.getstatusoutput(cmnd)
|
||||||
|
|
||||||
|
|
||||||
#Remove old
|
#Remove old
|
||||||
logging.info("Removing old dirs")
|
logging.info("Removing old dirs")
|
||||||
# input("????")
|
|
||||||
#cmnd = "find {} -maxdepth 1 -type d -mtime +30 -exec rm -rf {{}} \;".format(BACKUP_DIR)
|
|
||||||
#cmnd = f"cd {BACKUP_ROOT} find ./ -maxdepth 1 -type d -mmin +30 -exec rm -rf {{}} \\;"
|
|
||||||
|
|
||||||
cmnd = f"ls {BACKUP_ROOT}"
|
cmnd = f"ls {BACKUP_ROOT}"
|
||||||
|
|
||||||
|
if not _DRYRUN:
|
||||||
#print(cmnd)
|
|
||||||
# input("????")
|
|
||||||
if _EXECUTE:
|
|
||||||
status, output = subprocess.getstatusoutput(cmnd)
|
status, output = subprocess.getstatusoutput(cmnd)
|
||||||
for f in output.splitlines():
|
for f in output.splitlines():
|
||||||
pattern = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}$" # regex pattern: string starts with 'abc'
|
pattern = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}$" # regex pattern: string starts with 'abc'
|
||||||
logging.info(f"Checking {f}")
|
# logging.info(f"Checking {f}")
|
||||||
if re.match(pattern, f):
|
if re.match(pattern, f):
|
||||||
logging.info("Match!")
|
# logging.info("Match!")
|
||||||
dt = datetime.datetime.strptime(f, "%Y-%m-%d_%H-%M-%S")
|
dt = datetime.datetime.strptime(f, "%Y-%m-%d_%H-%M-%S")
|
||||||
epoch_time = int(dt.timestamp())
|
epoch_time = int(dt.timestamp())
|
||||||
|
|
||||||
@@ -649,12 +639,54 @@ def backup_job(server):
|
|||||||
shutil.rmtree(dir_path)
|
shutil.rmtree(dir_path)
|
||||||
else:
|
else:
|
||||||
print("No match.")
|
print("No match.")
|
||||||
|
if not _DRYRUN:
|
||||||
|
logging.info(f"Clearing multiple days")
|
||||||
|
multiple_per_day = {}
|
||||||
|
to_remove = []
|
||||||
|
for f in output.splitlines():
|
||||||
|
pattern = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}$" # regex pattern: string starts with 'abc'
|
||||||
|
|
||||||
|
if re.match(pattern, f):
|
||||||
|
cday = f.split("_")[0]
|
||||||
|
if cday in multiple_per_day:
|
||||||
|
multiple_per_day[cday].append(f)
|
||||||
|
else:
|
||||||
|
multiple_per_day[cday] = [f]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# # logging.info("Match!")
|
||||||
|
# dt = datetime.datetime.strptime(f, "%Y-%m-%d_%H-%M-%S")
|
||||||
|
# epoch_time = int(dt.timestamp())
|
||||||
|
# now_epoch = int(datetime.datetime.now().timestamp())
|
||||||
|
|
||||||
|
|
||||||
|
# x = now_epoch - epoch_time
|
||||||
|
# # logging.info(epoch_time) # Output: 45
|
||||||
|
# if x > 2592000:
|
||||||
|
# dir_path = f"{BACKUP_ROOT}/{f}"
|
||||||
|
# logging.info(f"removing {dir_path}")
|
||||||
|
# shutil.rmtree(dir_path)
|
||||||
|
else:
|
||||||
|
print("No match.")
|
||||||
|
logging.info(f"Clearing multiple days: {multiple_per_day}")
|
||||||
|
for f in multiple_per_day:
|
||||||
|
logging.info(f"Looping multiple_per_day : {f}")
|
||||||
|
if len(multiple_per_day[f]) > 1:
|
||||||
|
last = multiple_per_day[f][-1]
|
||||||
|
multiple_per_day[f].pop()
|
||||||
|
logging.info(f"Last from day: {last}")
|
||||||
|
for d in multiple_per_day[f]:
|
||||||
|
logging.info(f"Looping multiple_per_day : {f} : {d}")
|
||||||
|
dir_path = f"{BACKUP_ROOT}/{d}"
|
||||||
|
logging.info(f"removing {dir_path}")
|
||||||
|
shutil.rmtree(dir_path)
|
||||||
|
|
||||||
|
|
||||||
cmnd = f"ls {BACKUP_ROOT}|grep _running"
|
cmnd = f"ls {BACKUP_ROOT}|grep _running"
|
||||||
#print(cmnd)
|
|
||||||
# input("????")
|
|
||||||
logging.info(f"removing obsolete dirs")
|
logging.info(f"removing obsolete dirs")
|
||||||
if _EXECUTE:
|
if not _DRYRUN:
|
||||||
status, output = subprocess.getstatusoutput(cmnd)
|
status, output = subprocess.getstatusoutput(cmnd)
|
||||||
for f in output.splitlines():
|
for f in output.splitlines():
|
||||||
dir_path = f"{BACKUP_ROOT}/{f}"
|
dir_path = f"{BACKUP_ROOT}/{f}"
|
||||||
@@ -666,7 +698,7 @@ def backup_job(server):
|
|||||||
#msg = {"status":"finished","bak_name":b,"start_time":DATETIME,"end_time":ENDTIME,"progress":0}
|
#msg = {"status":"finished","bak_name":b,"start_time":DATETIME,"end_time":ENDTIME,"progress":0}
|
||||||
finished.append(b)
|
finished.append(b)
|
||||||
msg = {"mode":_MODE, "status":"finished","bak_name":"complete","host":host,"cur_job":b,"start_time":ENDTIME,"end_time":"in progress","progress":0,"finished":",".join(finished)}
|
msg = {"mode":_MODE, "status":"finished","bak_name":"complete","host":host,"cur_job":b,"start_time":ENDTIME,"end_time":"in progress","progress":0,"finished":",".join(finished)}
|
||||||
send_mqtt_message(topic,msg)
|
client2.publish(topic, json.dumps(msg),qos=0, retain=True)
|
||||||
|
|
||||||
logging.info("Getting size of FS")
|
logging.info("Getting size of FS")
|
||||||
cmnd = "df -h /mnt/raid|awk '{ print $3 }'|tail -1"
|
cmnd = "df -h /mnt/raid|awk '{ print $3 }'|tail -1"
|
||||||
@@ -681,11 +713,20 @@ def backup_job(server):
|
|||||||
msg = {"mode":_MODE, "status":"finished","bak_name":"complete","host":host,"cur_job":b,"start_time":STARTTIME,"end_time":ENDTIME,"progress":0,"finished":",".join(finished),"used_space":used_space}
|
msg = {"mode":_MODE, "status":"finished","bak_name":"complete","host":host,"cur_job":b,"start_time":STARTTIME,"end_time":ENDTIME,"progress":0,"finished":",".join(finished),"used_space":used_space}
|
||||||
logging.info(msg)
|
logging.info(msg)
|
||||||
|
|
||||||
send_mqtt_message(topic,msg)
|
client2.publish(topic, json.dumps(msg),qos=0, retain=True)
|
||||||
|
topic = "sectorq/backups/start"
|
||||||
|
logging.info(f"LALA : {topic}")
|
||||||
|
client2.publish(topic, "finished",qos=0, retain=True)
|
||||||
|
time.sleep(1)
|
||||||
|
client2.publish(topic, "finished2",qos=0, retain=True)
|
||||||
|
client2.disconnect()
|
||||||
|
#return "finished"
|
||||||
|
|
||||||
|
if _DRYRUN:
|
||||||
|
return
|
||||||
topic = "sectorq/amd/restore"
|
topic = "sectorq/amd/restore"
|
||||||
for s in servers:
|
for s in servers:
|
||||||
|
logging.info(f"Restoring {s}")
|
||||||
#if s != "rack.home.lan":
|
#if s != "rack.home.lan":
|
||||||
if s == "m-server.home.lan":
|
if s == "m-server.home.lan":
|
||||||
continue
|
continue
|
||||||
@@ -696,9 +737,10 @@ def backup_job(server):
|
|||||||
user = "jd"
|
user = "jd"
|
||||||
cmnd = "sudo /myapps/omv_backup.py -r all"
|
cmnd = "sudo /myapps/omv_backup.py -r all"
|
||||||
msg = {"mode":_MODE, "status":"restore","bak_name":"s","host":s,"cur_job":"aaa","start_time":1,"end_time":1,"progress":0,"finished":1,"used_space":1}
|
msg = {"mode":_MODE, "status":"restore","bak_name":"s","host":s,"cur_job":"aaa","start_time":1,"end_time":1,"progress":0,"finished":1,"used_space":1}
|
||||||
logging.info(msg)
|
#logging.info(msg)
|
||||||
|
|
||||||
send_mqtt_message(topic,msg)
|
send_mqtt_message(topic,msg)
|
||||||
|
#continue
|
||||||
if is_port_open(s,22):
|
if is_port_open(s,22):
|
||||||
ssh = paramiko.SSHClient()
|
ssh = paramiko.SSHClient()
|
||||||
ssh.load_system_host_keys()
|
ssh.load_system_host_keys()
|
||||||
@@ -726,40 +768,13 @@ def backup_job(server):
|
|||||||
os.remove("/backups/restore")
|
os.remove("/backups/restore")
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
# if _MODE == "auto":
|
|
||||||
# hostup = True
|
return "finished1"
|
||||||
# cmnd = "ssh root@omv.home.lan 'systemctl suspend &'"
|
|
||||||
# status, output = subprocess.getstatusoutput(cmnd)
|
|
||||||
# while hostup:
|
|
||||||
# #HOST_UP = os.system(f"ping -c 1 -w 2 omv.home.lan") == 0
|
|
||||||
# cmnd = f"ping -c 1 -w 2 {BACKUP_HOST}"
|
|
||||||
# status, output = subprocess.getstatusoutput(cmnd)
|
|
||||||
# # print(status)
|
|
||||||
# # print(output)
|
|
||||||
|
|
||||||
|
|
||||||
# if status == 0:
|
if _RESTORE:
|
||||||
# print(f"Backup host up, waiting - {n}\r", end="")
|
restore_job(_APP)
|
||||||
# time.sleep(5)
|
sys.exit()
|
||||||
# n += 1
|
|
||||||
# else:
|
|
||||||
# print("Backup host down " )
|
|
||||||
# hostup = False
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# try:
|
|
||||||
# url = "http://m-server.home.lan:8123/api/webhook/-0eWYFhSTzdusAO8jwQS9t1AT?mode=off"
|
|
||||||
|
|
||||||
# x = requests.post(url)
|
|
||||||
|
|
||||||
# print(x.text)
|
|
||||||
# except:
|
|
||||||
# pass
|
|
||||||
message= "finished1"
|
|
||||||
client.publish(topic, message,qos=2,retain=True)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if _SSH_TEST:
|
if _SSH_TEST:
|
||||||
user = "root"
|
user = "root"
|
||||||
cmnd = "ls -la"
|
cmnd = "ls -la"
|
||||||
@@ -771,7 +786,7 @@ if _SSH_TEST:
|
|||||||
# user = "admin"
|
# user = "admin"
|
||||||
# cmnd = "/share/Data/__GITLAB/omv_backup/venv/bin/python3 /share/Data/__GITLAB/omv_backup/omv_backup.py -r all"
|
# cmnd = "/share/Data/__GITLAB/omv_backup/venv/bin/python3 /share/Data/__GITLAB/omv_backup/omv_backup.py -r all"
|
||||||
msg = {"mode":_MODE, "status":"restore","bak_name":"s","host":s,"cur_job":"aaa","start_time":1,"end_time":1,"progress":0,"finished":1,"used_space":1}
|
msg = {"mode":_MODE, "status":"restore","bak_name":"s","host":s,"cur_job":"aaa","start_time":1,"end_time":1,"progress":0,"finished":1,"used_space":1}
|
||||||
logging.info(msg)
|
#logging.info(msg)
|
||||||
|
|
||||||
send_mqtt_message(topic,msg)
|
send_mqtt_message(topic,msg)
|
||||||
if s != "rack.home.lan":
|
if s != "rack.home.lan":
|
||||||
@@ -802,13 +817,25 @@ if _SSH_TEST:
|
|||||||
|
|
||||||
# Define actions based on payload
|
# Define actions based on payload
|
||||||
def handle_payload(payload):
|
def handle_payload(payload):
|
||||||
payload = payload.lower()
|
try:
|
||||||
if payload == 'm-server':
|
pl = json.loads(payload)
|
||||||
logging.info("💡 Starting backup job")
|
except:
|
||||||
backup_job(payload)
|
pl = payload
|
||||||
else:
|
logging.debug(pl)
|
||||||
logging.error(f"⚠️ Unknown command: {payload}")
|
|
||||||
|
|
||||||
|
if "host" in pl:
|
||||||
|
if pl["host"] == 'm-server':
|
||||||
|
logging.info("💡 Starting backup job")
|
||||||
|
backup_job(pl)
|
||||||
|
logging.info(f"💡 Finished backup job")
|
||||||
|
elif pl["host"] == 'nas':
|
||||||
|
logging.info("💡 Starting backup job")
|
||||||
|
backup_job(pl)
|
||||||
|
logging.info(f"💡 Finished backup job")
|
||||||
|
else:
|
||||||
|
logging.error(f"⚠️ Unknown command: {pl}")
|
||||||
|
else:
|
||||||
|
logging.error(f"⚠️ Wrong payload: {pl}")
|
||||||
# Callback when connected
|
# Callback when connected
|
||||||
def on_connect(client, userdata, flags, rc):
|
def on_connect(client, userdata, flags, rc):
|
||||||
if rc == 0:
|
if rc == 0:
|
||||||
@@ -836,4 +863,7 @@ if USE_TLS:
|
|||||||
|
|
||||||
# Connect and loop forever
|
# Connect and loop forever
|
||||||
client.connect(BROKER, PORT, keepalive=60)
|
client.connect(BROKER, PORT, keepalive=60)
|
||||||
|
|
||||||
|
|
||||||
|
client.publish("sectorq/backups/start", "finished", qos=0, retain=True)
|
||||||
client.loop_forever()
|
client.loop_forever()
|
Reference in New Issue
Block a user