Files
CyberPanel/plogical/backupSchedule.py

376 lines
15 KiB
Python
Raw Normal View History

2019-12-10 23:04:24 +05:00
#!/usr/local/CyberCP/bin/python
2019-03-31 02:47:35 +05:00
import os.path
import sys
import django
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
2019-12-17 21:34:55 +05:00
from plogical import CyberCPLogFileWriter as logging
2017-10-24 19:16:36 +05:00
import subprocess
import shlex
import os
import time
2019-12-15 13:30:40 +05:00
from plogical.backupUtilities import backupUtilities
from re import match,I,M
2020-05-21 23:21:36 +05:00
from websiteFunctions.models import Backups, BackupJob, BackupJobLogs
2019-03-31 02:47:35 +05:00
from plogical.processUtilities import ProcessUtilities
2019-07-18 14:08:00 +05:00
from random import randint
import json, requests
2019-12-13 17:43:00 +05:00
from datetime import datetime
2019-12-14 16:23:47 +05:00
import signal
2017-10-24 19:16:36 +05:00
2019-12-14 16:23:47 +05:00
class backupSchedule:
now = datetime.now()
2020-05-21 23:21:36 +05:00
LOCAL = 0
REMOTE = 1
INFO = 0
ERROR = 1
backupLog = ''
runningPath = '/home/cyberpanel/remoteBackupPID'
2018-04-23 19:23:03 +05:00
@staticmethod
2020-05-21 23:21:36 +05:00
def remoteBackupLogging(fileName, message, status = 0):
2018-04-23 19:23:03 +05:00
try:
file = open(fileName,'a')
file.writelines("[" + time.strftime("%m.%d.%Y_%H-%M-%S") + "] "+ message + "\n")
2019-12-10 15:09:10 +05:00
print(("[" + time.strftime("%m.%d.%Y_%H-%M-%S") + "] "+ message + "\n"))
2018-04-23 19:23:03 +05:00
file.close()
2020-05-21 23:21:36 +05:00
BackupJobLogs(owner=backupSchedule.backupLog, status=status, message="[" + time.strftime("%m.%d.%Y_%H-%M-%S") + "] "+ message).save()
2019-12-10 15:09:10 +05:00
except IOError as msg:
2018-04-23 19:23:03 +05:00
return "Can not write to error file."
2017-10-24 19:16:36 +05:00
@staticmethod
2018-08-18 03:56:25 +05:00
def createLocalBackup(virtualHost, backupLogPath):
2017-10-24 19:16:36 +05:00
try:
2019-12-13 17:43:00 +05:00
startingTime = datetime.now()
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Starting local backup for: " + virtualHost)
2017-10-24 19:16:36 +05:00
2019-07-18 14:08:00 +05:00
###
2018-08-18 03:56:25 +05:00
2019-07-18 14:08:00 +05:00
pathToFile = "/home/cyberpanel/" + str(randint(1000, 9999))
file = open(pathToFile, "w+")
file.close()
2019-03-31 02:47:35 +05:00
2019-07-18 14:08:00 +05:00
finalData = json.dumps({'randomFile': pathToFile, 'websiteToBeBacked': virtualHost})
r = requests.post("https://localhost:8090/backup/localInitiate", data=finalData, verify=False)
2019-03-31 02:47:35 +05:00
2020-01-29 11:05:47 +05:00
if os.path.exists(ProcessUtilities.debugPath):
logging.CyberCPLogFileWriter.writeToFile(r.text)
2019-07-18 14:08:00 +05:00
data = json.loads(r.text)
tempStoragePath = data['tempStorage']
2017-10-24 19:16:36 +05:00
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Waiting for backup to complete.. ")
time.sleep(5)
schedulerPath = '/home/cyberpanel/%s-backup.txt' % (virtualHost)
2018-08-18 03:56:25 +05:00
2017-10-24 19:16:36 +05:00
while (1):
diff = datetime.now() - startingTime
2019-03-31 02:47:35 +05:00
backupDomain = virtualHost
status = os.path.join("/home", backupDomain, "backup/status")
backupFileNamePath = os.path.join("/home", backupDomain, "backup/backupFileName")
pid = os.path.join("/home", backupDomain, "backup/pid")
## read file name
try:
fileName = open(backupFileNamePath, 'r').read()
except:
fileName = "Fetching.."
2020-05-24 23:35:08 +05:00
ifRunning = ProcessUtilities.outputExecutioner('ps aux')
if (ifRunning.find('startBackup') > -1 or ifRunning.find('BackupRoot') > -1) and ifRunning.find('/%s/' % (backupDomain)):
pass
else:
2020-05-25 00:08:05 +05:00
if os.path.exists(status):
status = open(status, 'r').read()
time.sleep(2)
if status.find("Completed") > -1:
### Removing Files
command = 'sudo rm -f ' + status
ProcessUtilities.normalExecutioner(command)
command = 'sudo rm -f ' + backupFileNamePath
ProcessUtilities.normalExecutioner(command)
command = 'sudo rm -f ' + pid
ProcessUtilities.normalExecutioner(command)
backupSchedule.remoteBackupLogging(backupLogPath, "Backup Completed for: " + virtualHost)
try:
os.remove(pathToFile)
except:
pass
return 1, tempStoragePath
else:
return 0, 'Backup process killed without reporting any error.'
else:
return 0, 'Backup process killed without reporting any error.'
2020-05-24 23:35:08 +05:00
2019-03-31 02:47:35 +05:00
## file name read ends
if os.path.exists(status):
status = open(status, 'r').read()
2019-07-18 14:08:00 +05:00
time.sleep(2)
2019-03-31 02:47:35 +05:00
if status.find("Completed") > -1:
### Removing Files
command = 'sudo rm -f ' + status
ProcessUtilities.normalExecutioner(command)
command = 'sudo rm -f ' + backupFileNamePath
ProcessUtilities.normalExecutioner(command)
command = 'sudo rm -f ' + pid
ProcessUtilities.normalExecutioner(command)
backupSchedule.remoteBackupLogging(backupLogPath, "Backup Completed for: " + virtualHost)
2019-07-18 14:08:00 +05:00
try:
os.remove(pathToFile)
except:
pass
2019-03-31 02:47:35 +05:00
return 1, tempStoragePath
elif status.find("[5009]") > -1:
## removing status file, so that backup can re-run
try:
command = 'sudo rm -f ' + status
ProcessUtilities.normalExecutioner(command)
command = 'sudo rm -f ' + backupFileNamePath
ProcessUtilities.normalExecutioner(command)
command = 'sudo rm -f ' + pid
ProcessUtilities.normalExecutioner(command)
backupObs = Backups.objects.filter(fileName=fileName)
for items in backupObs:
items.delete()
except:
pass
2020-05-21 23:21:36 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Local backup creating failed for %s, Error message: %s" % (virtualHost, status), backupSchedule.ERROR)
2019-07-18 14:08:00 +05:00
try:
os.remove(pathToFile)
except:
pass
2019-03-31 02:47:35 +05:00
return 0, tempStoragePath
2020-05-21 23:21:36 +05:00
elif os.path.exists(schedulerPath):
2020-05-21 23:21:36 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, 'Backup process killed without reporting any error.',
backupSchedule.ERROR)
os.remove(schedulerPath)
return 0, 'Backup process killed without reporting any error.'
2019-12-10 15:09:10 +05:00
except BaseException as msg:
2019-07-18 14:08:00 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [119:startBackup]")
2020-05-21 23:21:36 +05:00
backupSchedule.remoteBackupLogging(backupLogPath,
"Local backup creating failed for %s, Error message: %s" % (
virtualHost, str(msg)), backupSchedule.ERROR)
return 0, str(msg)
2018-04-23 19:23:03 +05:00
2018-08-18 03:56:25 +05:00
@staticmethod
def createBackup(virtualHost, ipAddress, backupLogPath , port='22', user='root'):
2018-08-18 03:56:25 +05:00
try:
2018-04-23 19:23:03 +05:00
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Preparing to create backup for: " + virtualHost)
backupSchedule.remoteBackupLogging(backupLogPath, "Backup started for: " + virtualHost)
2018-04-23 19:23:03 +05:00
2018-08-18 03:56:25 +05:00
retValues = backupSchedule.createLocalBackup(virtualHost, backupLogPath)
2017-10-24 19:16:36 +05:00
2018-08-18 03:56:25 +05:00
if retValues[0] == 1:
backupPath = retValues[1]
2017-10-24 19:16:36 +05:00
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Backup created for: " + virtualHost)
2017-10-24 19:16:36 +05:00
2018-08-18 03:56:25 +05:00
## Prepping to send backup.
2017-10-24 19:16:36 +05:00
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Preparing to send backup for: " + virtualHost +" to " + ipAddress)
2017-10-24 19:16:36 +05:00
backupSchedule.sendBackup(backupPath+".tar.gz", ipAddress, backupLogPath, port, user)
2017-10-24 19:16:36 +05:00
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Backup for: " + virtualHost + " is sent to " + ipAddress)
## Backup sent.
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "#################################################")
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "")
2020-05-29 23:39:41 +05:00
return 1
2018-08-18 03:56:25 +05:00
else:
backupSchedule.remoteBackupLogging(backupLogPath, 'Remote backup creation failed for %s.' % (virtualHost) )
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "#################################################")
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "")
2020-05-29 23:39:41 +05:00
return 0
2017-10-24 19:16:36 +05:00
2019-12-10 15:09:10 +05:00
except BaseException as msg:
2019-03-13 18:22:12 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [backupSchedule.createBackup]")
2017-10-24 19:16:36 +05:00
@staticmethod
def sendBackup(backupPath, IPAddress, backupLogPath , port='22', user='root'):
2017-10-24 19:16:36 +05:00
try:
2018-04-23 19:23:03 +05:00
## IPAddress of local server
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddressLocal = ipData.split('\n', 1)[0]
##
writeToFile = open(backupLogPath, "a")
command = "sudo scp -o StrictHostKeyChecking=no -P "+port+" -i /root/.ssh/cyberpanel " + backupPath + " " + user + "@" + IPAddress+":~/backup/" + ipAddressLocal + "/" + time.strftime("%a-%b") + "/"
2019-03-26 16:19:03 +05:00
subprocess.call(shlex.split(command), stdout=writeToFile)
2018-07-29 01:20:46 +05:00
2020-04-29 04:46:01 +05:00
if os.path.exists(ProcessUtilities.debugPath):
logging.CyberCPLogFileWriter.writeToFile(command)
2018-07-29 01:20:46 +05:00
## Remove backups already sent to remote destinations
os.remove(backupPath)
2019-12-10 15:09:10 +05:00
except BaseException as msg:
2019-07-18 14:08:00 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [189:startBackup]")
2017-10-24 19:16:36 +05:00
@staticmethod
def prepare():
try:
if os.path.exists(backupSchedule.runningPath):
pid = open(backupSchedule.runningPath, 'r').read()
output = ProcessUtilities.outputExecutioner('ps aux')
if output.find('/usr/local/CyberCP/plogical/backupSchedule.py') > -1 and output.find(pid) > -1:
print(
'\n\nRemote backup is already running with PID: %s. If you want to run again kindly kill the backup process: \n\n kill -9 %s.\n\n' % (
pid, pid))
return 0
else:
os.remove(backupSchedule.runningPath)
writeToFile = open(backupSchedule.runningPath, 'w')
writeToFile.write(str(os.getpid()))
writeToFile.close()
2018-04-23 19:23:03 +05:00
## IP of Remote server.
2017-10-24 19:16:36 +05:00
2020-04-27 21:01:28 +05:00
destinations = backupUtilities.destinationsPath
data = json.loads(open(destinations, 'r').read())
port = data['port']
try:
user = data['user']
except:
user = 'root'
2020-04-27 21:01:28 +05:00
ipAddress = data['ipAddress']
2017-10-24 19:16:36 +05:00
jobSuccessSites = 0
jobFailedSites = 0
2020-05-22 16:57:44 +05:00
backupLogPath = "/usr/local/lscp/logs/backup_log." + time.strftime("%m.%d.%Y_%H-%M-%S")
backupSchedule.backupLog = BackupJob(logFile=backupLogPath, location=backupSchedule.REMOTE,
2020-05-22 16:57:44 +05:00
jobSuccessSites=jobSuccessSites, jobFailedSites=jobFailedSites,
ipAddress=ipAddress, port=port)
backupSchedule.backupLog.save()
2020-05-22 16:57:44 +05:00
destinations = backupUtilities.destinationsPath
backupSchedule.remoteBackupLogging(backupLogPath,"#################################################")
backupSchedule.remoteBackupLogging(backupLogPath," Backup log for: " +time.strftime("%m.%d.%Y_%H-%M-%S"))
backupSchedule.remoteBackupLogging(backupLogPath,"#################################################\n")
backupSchedule.remoteBackupLogging(backupLogPath, "")
backupSchedule.remoteBackupLogging(backupLogPath, "")
2018-04-23 19:23:03 +05:00
## IPAddress of local server
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddressLocal = ipData.split('\n', 1)[0]
2017-10-24 19:16:36 +05:00
2019-03-13 23:20:15 +05:00
if backupUtilities.checkIfHostIsUp(ipAddress) != 1:
backupSchedule.remoteBackupLogging(backupLogPath, "Ping for : " + ipAddress + " does not seems to work, however we will continue.")
2018-02-19 23:42:57 +05:00
2019-03-13 23:20:15 +05:00
checkConn = backupUtilities.checkConnection(ipAddress)
if checkConn[0] == 0:
backupSchedule.remoteBackupLogging(backupLogPath,
"Connection to: " + ipAddress + " Failed, please resetup this destination from CyberPanel, aborting.")
2017-10-24 19:16:36 +05:00
return 0
2019-03-13 23:20:15 +05:00
else:
## Create backup dir on remote server in ~/backup
2019-03-13 23:20:15 +05:00
command = "sudo ssh -o StrictHostKeyChecking=no -p " + port + " -i /root/.ssh/cyberpanel " + user + "@" + ipAddress + " mkdir -p ~/backup/" + ipAddressLocal + "/" + time.strftime(
2019-03-13 23:20:15 +05:00
"%a-%b")
2019-03-26 16:19:03 +05:00
subprocess.call(shlex.split(command))
2019-03-13 23:20:15 +05:00
pass
2017-10-24 19:16:36 +05:00
for virtualHost in os.listdir("/home"):
2020-02-27 16:51:17 +05:00
if match(r'^[a-zA-Z0-9-]*[a-zA-Z0-9-]{0,61}[a-zA-Z0-9-](?:\.[a-zA-Z0-9-]{2,})+$', virtualHost, M | I):
2020-05-29 23:39:41 +05:00
if backupSchedule.createBackup(virtualHost, ipAddress, backupLogPath, port, user):
jobSuccessSites = jobSuccessSites + 1
else:
jobFailedSites = jobFailedSites + 1
2017-10-24 19:16:36 +05:00
2020-05-29 23:39:41 +05:00
backupSchedule.backupLog.jobFailedSites = jobFailedSites
backupSchedule.backupLog.jobSuccessSites = jobSuccessSites
backupSchedule.backupLog.save()
2018-08-18 03:56:25 +05:00
backupSchedule.remoteBackupLogging(backupLogPath, "Remote backup job completed.\n")
if os.path.exists(backupSchedule.runningPath):
os.remove(backupSchedule.runningPath)
2018-08-18 03:56:25 +05:00
2019-12-10 15:09:10 +05:00
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [prepare]")
2017-10-24 19:16:36 +05:00
2018-08-18 15:16:15 +05:00
def main():
backupSchedule.prepare()
2017-10-24 19:16:36 +05:00
2019-12-14 16:23:47 +05:00
def handler(signum, frame):
diff = datetime.now() - backupSchedule.now
logging.CyberCPLogFileWriter.writeToFile('Signal: %s, time spent: %s' % (str(signum), str(diff.total_seconds())))
2018-08-18 15:16:15 +05:00
if __name__ == "__main__":
2019-12-14 16:23:47 +05:00
for i in range(1,32):
if i == 9 or i == 19 or i == 32:
continue
signal.signal(i, handler)
2018-08-18 15:16:15 +05:00
main()