diff --git a/backup/backupManager.py b/backup/backupManager.py new file mode 100644 index 000000000..33ae9b06d --- /dev/null +++ b/backup/backupManager.py @@ -0,0 +1,1326 @@ +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import json +from plogical.acl import ACLManager +import plogical.CyberCPLogFileWriter as logging +from websiteFunctions.models import Websites, Backups, dest, backupSchedules +from plogical.virtualHostUtilities import virtualHostUtilities +import subprocess +import shlex +from django.shortcuts import HttpResponse, render +from loginSystem.models import Administrator +from plogical.mailUtilities import mailUtilities +from random import randint +import time +import plogical.backupUtilities as backupUtil +import requests + +class BackupManager: + def __init__(self, domain = None, childDomain = None): + self.domain = domain + self.childDomain = childDomain + + def loadBackupHome(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + return render(request, 'backup/index.html', currentACL) + except BaseException, msg: + return HttpResponse(str(msg)) + + def backupSite(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + return render(request, 'backup/backup.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def restoreSite(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'restoreBackup') == 0: + return ACLManager.loadError() + + path = os.path.join("/home", "backup") + + if not os.path.exists(path): + return render(request, 'backup/restore.html') + else: + all_files = [] + ext = ".tar.gz" + + command = 'sudo chown -R cyberpanel:cyberpanel ' + path + ACLManager.executeCall(command) + + files = os.listdir(path) + for filename in files: + if filename.endswith(ext): + all_files.append(filename) + + return render(request, 'backup/restore.html', {'backups': all_files}) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def getCurrentBackups(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + backupDomain = data['websiteToBeBacked'] + + if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + website = Websites.objects.get(domain=backupDomain) + + backups = website.backups_set.all() + + json_data = "[" + checker = 0 + + for items in backups: + if items.status == 0: + status = "Pending" + else: + status = "Completed" + dic = {'id': items.id, + 'file': items.fileName, + 'date': items.date, + 'size': items.size, + 'status': status + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + except BaseException, msg: + final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def submitBackupCreation(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + backupDomain = data['websiteToBeBacked'] + website = Websites.objects.get(domain=backupDomain) + + if ACLManager.checkOwnership(backupDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('metaStatus', 0) + + ## defining paths + + ## /home/example.com/backup + backupPath = os.path.join("/home", backupDomain, "backup/") + domainUser = website.externalApp + backupName = 'backup-' + domainUser + "-" + time.strftime("%I-%M-%S-%a-%b-%Y") + + ## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018 + tempStoragePath = os.path.join(backupPath, backupName) + + execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " submitBackupCreation --tempStoragePath " + tempStoragePath + " --backupName " \ + + backupName + " --backupPath " + backupPath + ' --backupDomain ' + backupDomain + + subprocess.Popen(shlex.split(execPath)) + + time.sleep(2) + + final_json = json.dumps({'status': 1, 'metaStatus': 1, 'error_message': "None", 'tempStorage': tempStoragePath}) + return HttpResponse(final_json) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + final_dic = {'status': 0, 'metaStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def backupStatus(self, userID = None, data = None): + try: + + backupDomain = data['websiteToBeBacked'] + 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: + command = "sudo cat " + backupFileNamePath + fileName = subprocess.check_output(shlex.split(command)) + except: + fileName = "Fetching.." + + ## file name read ends + + if os.path.exists(status): + command = "sudo cat " + status + status = subprocess.check_output(shlex.split(command)) + + if status.find("Completed") > -1: + + backupOb = Backups.objects.get(fileName=fileName) + backupOb.status = 1 + + ## adding backup data to database. + try: + backupOb.size = str(int(float( + os.path.getsize("/home/" + backupDomain + "/backup/" + fileName + ".tar.gz")) / ( + 1024.0 * 1024.0))) + "MB" + backupOb.save() + except: + backupOb.size = str( + int(os.path.getsize("/home/" + backupDomain + "/backup/" + fileName + ".tar.gz"))) + backupOb.save() + + ### Removing Files + + command = 'sudo rm -f ' + status + subprocess.call(shlex.split(command)) + + command = 'sudo rm -f ' + backupFileNamePath + subprocess.call(shlex.split(command)) + + command = 'sudo rm -f ' + pid + subprocess.call(shlex.split(command)) + + final_json = json.dumps( + {'backupStatus': 1, 'error_message': "None", "status": status, "abort": 1, + 'fileName': fileName, }) + return HttpResponse(final_json) + + elif status.find("[5009]") > -1: + ## removing status file, so that backup can re-run + try: + command = 'sudo rm -f ' + status + subprocess.call(shlex.split(command)) + + command = 'sudo rm -f ' + backupFileNamePath + subprocess.call(shlex.split(command)) + + command = 'sudo rm -f ' + pid + subprocess.call(shlex.split(command)) + + backupObs = Backups.objects.filter(fileName=fileName) + for items in backupObs: + items.delete() + + except: + pass + + final_json = json.dumps( + {'backupStatus': 1, 'fileName': fileName, 'error_message': "None", "status": status, + "abort": 1}) + return HttpResponse(final_json) + else: + final_json = json.dumps( + {'backupStatus': 1, 'error_message': "None", 'fileName': fileName, "status": status, + "abort": 0}) + return HttpResponse(final_json) + else: + final_json = json.dumps({'backupStatus': 0, 'error_message': "None", "status": 0, "abort": 0}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'backupStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [backupStatus]") + return HttpResponse(final_json) + + def cancelBackupCreation(self, userID = None, data = None): + try: + + backupCancellationDomain = data['backupCancellationDomain'] + fileName = data['fileName'] + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + + execPath = execPath + " cancelBackupCreation --backupCancellationDomain " + backupCancellationDomain + " --fileName " + fileName + + subprocess.call(shlex.split(execPath)) + + try: + backupOb = Backups.objects.get(fileName=fileName) + backupOb.delete() + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [cancelBackupCreation]") + + final_json = json.dumps({'abortStatus': 1, 'error_message': "None", "status": 0}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'abortStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def deleteBackup(self, userID = None, data = None): + try: + backupID = data['backupID'] + backup = Backups.objects.get(id=backupID) + + domainName = backup.website.domain + + path = "/home/" + domainName + "/backup/" + backup.fileName + ".tar.gz" + command = 'sudo rm -f ' + path + ACLManager.executeCall(command) + + backup.delete() + + final_json = json.dumps({'status': 1, 'deleteStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + except BaseException, msg: + final_dic = {'status': 0, 'deleteStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + + return HttpResponse(final_json) + + def submitRestore(self, data = None): + try: + backupFile = data['backupFile'] + originalFile = "/home/backup/" + backupFile + + if not os.path.exists(originalFile): + dir = data['dir'] + else: + dir = "CyberPanelRestore" + + execPath = "sudo nice -n 10 python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " submitRestore --backupFile " + backupFile + " --dir " + dir + subprocess.Popen(shlex.split(execPath)) + time.sleep(4) + + final_dic = {'restoreStatus': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException, msg: + final_dic = {'restoreStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def restoreStatus(self, data = None): + try: + backupFile = data['backupFile'].strip(".tar.gz") + + path = os.path.join("/home", "backup", data['backupFile']) + + if os.path.exists(path): + path = os.path.join("/home", "backup", backupFile) + elif os.path.exists(data['backupFile']): + path = data['backupFile'].strip(".tar.gz") + else: + dir = data['dir'] + path = "/home/backup/transfer-" + str(dir) + "/" + backupFile + + if os.path.exists(path): + try: + execPath = "sudo cat " + path + "/status" + status = subprocess.check_output(shlex.split(execPath)) + + if status.find("Done") > -1: + + command = "sudo rm -rf " + path + subprocess.call(shlex.split(command)) + + final_json = json.dumps( + {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 1, + 'running': 'Completed'}) + return HttpResponse(final_json) + elif status.find("[5009]") > -1: + ## removing temporarily generated files while restoring + command = "sudo rm -rf " + path + subprocess.call(shlex.split(command)) + final_json = json.dumps({'restoreStatus': 1, 'error_message': "None", + "status": status, 'abort': 1, 'alreadyRunning': 0, + 'running': 'Error'}) + return HttpResponse(final_json) + else: + final_json = json.dumps( + {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 0, + 'running': 'Running..'}) + return HttpResponse(final_json) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + status = "Just Started" + final_json = json.dumps( + {'restoreStatus': 1, 'error_message': "None", "status": status, 'abort': 0, + 'running': 'Running..'}) + return HttpResponse(final_json) + else: + final_json = json.dumps( + {'restoreStatus': 1, 'error_message': "None", "status": "OK To Run", 'running': 'Halted', + 'abort': 1}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'restoreStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def backupDestinations(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: + return ACLManager.loadError() + + return render(request, 'backup/backupDestinations.html', {}) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def submitDestinationCreation(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: + return ACLManager.loadErrorJson('destStatus', 0) + + destinations = backupUtil.backupUtilities.destinationsPath + + ipAddress = data['IPAddress'] + password = data['password'] + + if dest.objects.all().count() == 2: + final_dic = {'destStatus': 0, + 'error_message': "Currently only one remote destination is allowed."} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + try: + d = dest.objects.get(destLoc=ipAddress) + final_dic = {'destStatus': 0, 'error_message': "This destination already exists."} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except: + + try: + port = data['backupSSHPort'] + except: + port = "22" + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " submitDestinationCreation --ipAddress " + ipAddress + " --password " \ + + password + " --port " + port + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find('1,') > -1: + try: + writeToFile = open(destinations, "w") + writeToFile.writelines(ipAddress + "\n") + writeToFile.writelines(data['backupSSHPort'] + "\n") + writeToFile.close() + newDest = dest(destLoc=ipAddress) + newDest.save() + except: + writeToFile = open(destinations, "w") + writeToFile.writelines(ipAddress + "\n") + writeToFile.writelines("22" + "\n") + writeToFile.close() + newDest = dest(destLoc=ipAddress) + newDest.save() + + final_dic = {'destStatus': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'destStatus': 0, 'error_message': output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'destStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def getCurrentBackupDestinations(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: + return ACLManager.loadErrorJson('fetchStatus', 0) + + records = dest.objects.all() + + json_data = "[" + checker = 0 + + for items in records: + if items.destLoc == "Home": + continue + dic = {'id': items.id, + 'ip': items.destLoc, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def getConnectionStatus(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: + return ACLManager.loadErrorJson('connStatus', 0) + + ipAddress = data['IPAddress'] + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py" + execPath = execPath + " getConnectionStatus --ipAddress " + ipAddress + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find('1,') > -1: + final_dic = {'connStatus': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'connStatus': 0, 'error_message': output} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'connStatus': 1, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def deleteDestination(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0: + return ACLManager.loadErrorJson('delStatus', 0) + + ipAddress = data['IPAddress'] + + delDest = dest.objects.get(destLoc=ipAddress) + delDest.delete() + + path = "/usr/local/CyberCP/backup/" + destinations = path + "destinations" + + data = open(destinations, 'r').readlines() + + writeToFile = open(destinations, 'r') + + for items in data: + if items.find(ipAddress) > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + ## Deleting Cron Tab Entries for this destination + + path = "/etc/crontab" + + data = open(path, 'r').readlines() + + writeToFile = open(path, 'w') + + for items in data: + if items.find("backupSchedule.py") > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + final_dic = {'delStatus': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'delStatus': 1, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def scheduleBackup(self, request, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: + return ACLManager.loadError() + + if dest.objects.all().count() <= 1: + try: + homeDest = dest(destLoc="Home") + homeDest.save() + except: + pass + backups = dest.objects.all() + + destinations = [] + + for items in backups: + destinations.append(items.destLoc) + + return render(request, 'backup/backupSchedule.html', {'destinations': destinations}) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def getCurrentBackupSchedules(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: + return ACLManager.loadErrorJson('fetchStatus', 0) + + records = backupSchedules.objects.all() + + json_data = "[" + checker = 0 + + for items in records: + dic = {'id': items.id, + 'destLoc': items.dest.destLoc, + 'frequency': items.frequency, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def submitBackupSchedule(self, userID = None, data = None): + try: + backupDest = data['backupDest'] + backupFreq = data['backupFreq'] + + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: + return ACLManager.loadErrorJson('scheduleStatus', 0) + + path = "/etc/crontab" + + ## check if already exists + try: + schedule = backupSchedules.objects.get(frequency=backupFreq) + if schedule.dest.destLoc == backupDest: + final_json = json.dumps( + {'scheduleStatus': 0, 'error_message': "This schedule already exists"}) + return HttpResponse(final_json) + else: + if backupDest == "Home" and backupFreq == "Daily": + cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest == "Home" and backupFreq == "Weekly": + cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest != "Home" and backupFreq == "Daily": + cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest != "Home" and backupFreq == "Weekly": + cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py " + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + except: + if backupDest == "Home" and backupFreq == "Daily": + cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py" + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest == "Home" and backupFreq == "Weekly": + cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupScheduleLocal.py " + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest != "Home" and backupFreq == "Daily": + cronJob = "0 3 * * 0-6 root python /usr/local/CyberCP/plogical/backupSchedule.py" + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest != "Home" and backupFreq == "Weekly": + cronJob = "0 3 * * 3 root python /usr/local/CyberCP/plogical/backupSchedule.py " + + virtualHostUtilities.permissionControl(path) + + writeToFile = open(path, 'a') + writeToFile.writelines(cronJob + "\n") + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules(dest=destination, frequency=backupFreq) + newSchedule.save() + + final_json = json.dumps({'scheduleStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + except BaseException, msg: + final_json = json.dumps({'scheduleStatus': 0, 'error_message': str(msg)}) + return HttpResponse(final_json) + + def scheduleDelete(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0: + return ACLManager.loadErrorJson('scheduleStatus', 0) + + backupDest = data['destLoc'] + backupFreq = data['frequency'] + + path = "/etc/crontab" + + if backupDest == "Home" and backupFreq == "Daily": + + virtualHostUtilities.permissionControl(path) + + data = open(path, "r").readlines() + writeToFile = open(path, 'w') + + for items in data: + if items.find("0-6") > -1 and items.find("backupScheduleLocal.py") > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) + newSchedule.delete() + + final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest == "Home" and backupFreq == "Weekly": + + virtualHostUtilities.permissionControl(path) + + data = open(path, "r").readlines() + writeToFile = open(path, 'w') + + for items in data: + if items.find("* 3") > -1 and items.find("backupScheduleLocal.py") > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) + newSchedule.delete() + + final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest != "Home" and backupFreq == "Daily": + + virtualHostUtilities.permissionControl(path) + + data = open(path, "r").readlines() + writeToFile = open(path, 'w') + + for items in data: + if items.find("0-6") > -1 and items.find("backupSchedule.py") > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) + newSchedule.delete() + + final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + elif backupDest != "Home" and backupFreq == "Weekly": + + virtualHostUtilities.permissionControl(path) + + data = open(path, "r").readlines() + writeToFile = open(path, 'w') + + for items in data: + if items.find("* 3") > -1 and items.find("backupSchedule.py") > -1: + continue + else: + writeToFile.writelines(items) + + writeToFile.close() + + virtualHostUtilities.leaveControl(path) + + command = "sudo systemctl restart crond" + + subprocess.call(shlex.split(command)) + + destination = dest.objects.get(destLoc=backupDest) + newSchedule = backupSchedules.objects.get(dest=destination, frequency=backupFreq) + newSchedule.delete() + + final_json = json.dumps({'delStatus': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + except BaseException, msg: + final_json = json.dumps({'delStatus': 0, 'error_message': str(msg)}) + return HttpResponse(final_json) + + def remoteBackups(self, request, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadError() + + return render(request, 'backup/remoteBackups.html') + + except BaseException, msg: + return HttpResponse(str(msg)) + + def submitRemoteBackups(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadErrorJson() + + ipAddress = data['ipAddress'] + password = data['password'] + + ## Ask for Remote version of CyberPanel + + try: + finalData = json.dumps({'username': "admin", "password": password}) + + url = "https://" + ipAddress + ":8090/api/cyberPanelVersion" + + r = requests.post(url, data=finalData, verify=False) + + data = json.loads(r.text) + + if data['getVersion'] == 1: + + if float(data['currentVersion']) >= 1.6 and data['build'] >= 0: + pass + else: + data_ret = {'status': 0, + 'error_message': "Your version does not match with version of remote server.", + "dir": "Null"} + data_ret = json.dumps(data_ret) + return HttpResponse(data_ret) + else: + data_ret = {'status': 0, + 'error_message': "Not able to fetch version of remote server. Error Message: " + + data[ + 'error_message'], "dir": "Null"} + data_ret = json.dumps(data_ret) + return HttpResponse(data_ret) + + + except BaseException, msg: + data_ret = {'status': 0, + 'error_message': "Not able to fetch version of remote server. Error Message: " + str( + msg), + "dir": "Null"} + data_ret = json.dumps(data_ret) + return HttpResponse(data_ret) + + ## Fetch public key of remote server! + + finalData = json.dumps({'username': "admin", "password": password}) + + url = "https://" + ipAddress + ":8090/api/fetchSSHkey" + r = requests.post(url, data=finalData, verify=False) + data = json.loads(r.text) + + if data['pubKeyStatus'] == 1: + pubKey = data["pubKey"].strip("\n") + else: + final_json = json.dumps({'status': 0, + 'error_message': "I am sorry, I could not fetch key from remote server. Error Message: " + + data['error_message'] + }) + return HttpResponse(final_json) + + ## write key + + ## Writing key to a temporary location, to be read later by backup process. + + mailUtilities.checkHome() + + pathToKey = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(pathToKey, "w") + vhost.write(pubKey) + vhost.close() + + ## + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" + execPath = execPath + " writeAuthKey --pathToKey " + pathToKey + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + pass + else: + final_json = json.dumps({'status': 0, 'error_message': output}) + return HttpResponse(final_json) + + ## + + try: + finalData = json.dumps({'username': "admin", "password": password}) + + url = "https://" + ipAddress + ":8090/api/fetchAccountsFromRemoteServer" + + r = requests.post(url, data=finalData, verify=False) + + data = json.loads(r.text) + + if data['fetchStatus'] == 1: + json_data = data['data'] + data_ret = {'status': 1, 'error_message': "None", + "dir": "Null", 'data': json_data} + data_ret = json.dumps(data_ret) + return HttpResponse(data_ret) + else: + data_ret = {'status': 0, + 'error_message': "Not able to fetch accounts from remote server. Error Message: " + + data['error_message'], "dir": "Null"} + data_ret = json.dumps(data_ret) + return HttpResponse(data_ret) + except BaseException, msg: + data_ret = {'status': 0, + 'error_message': "Not able to fetch accounts from remote server. Error Message: " + str( + msg), "dir": "Null"} + data_ret = json.dumps(data_ret) + return HttpResponse(data_ret) + + except BaseException, msg: + final_json = json.dumps({'status': 0, 'error_message': str(msg)}) + return HttpResponse(final_json) + + def starRemoteTransfer(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadErrorJson('remoteTransferStatus', 0) + + ipAddress = data['ipAddress'] + password = data['password'] + accountsToTransfer = data['accountsToTransfer'] + + try: + + ipFile = os.path.join("/etc", "cyberpanel", "machineIP") + f = open(ipFile) + ownIP = f.read() + + finalData = json.dumps({'username': "admin", "password": password, "ipAddress": ownIP, + "accountsToTransfer": accountsToTransfer}) + + url = "https://" + ipAddress + ":8090/api/remoteTransfer" + + r = requests.post(url, data=finalData, verify=False) + + data = json.loads(r.text) + + if data['transferStatus'] == 1: + + ## Create local backup dir + + localBackupDir = os.path.join("/home", "backup") + + if not os.path.exists(localBackupDir): + command = "sudo mkdir " + localBackupDir + subprocess.call(shlex.split(command)) + + ## create local directory that will host backups + + localStoragePath = "/home/backup/transfer-" + str(data['dir']) + + ## making local storage directory for backups + + command = "sudo mkdir " + localStoragePath + subprocess.call(shlex.split(command)) + + final_json = json.dumps( + {'remoteTransferStatus': 1, 'error_message': "None", "dir": data['dir']}) + return HttpResponse(final_json) + else: + final_json = json.dumps({'remoteTransferStatus': 0, + 'error_message': "Can not initiate remote transfer. Error message: " + + data['error_message']}) + return HttpResponse(final_json) + + except BaseException, msg: + final_json = json.dumps({'remoteTransferStatus': 0, + 'error_message': "Can not initiate remote transfer. Error message: " + + str(msg)}) + return HttpResponse(final_json) + + except BaseException, msg: + final_json = json.dumps({'remoteTransferStatus': 0, 'error_message': str(msg)}) + return HttpResponse(final_json) + + def getRemoteTransferStatus(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadErrorJson('remoteTransferStatus', 0) + + ipAddress = data['ipAddress'] + password = data['password'] + dir = data['dir'] + username = "admin" + + finalData = json.dumps({'dir': dir, "username": username, "password": password}) + r = requests.post("https://" + ipAddress + ":8090/api/FetchRemoteTransferStatus", data=finalData, + verify=False) + + data = json.loads(r.text) + + if data['fetchStatus'] == 1: + if data['status'].find("Backups are successfully generated and received on") > -1: + + data = {'remoteTransferStatus': 1, 'error_message': "None", "status": data['status'], + 'backupsSent': 1} + json_data = json.dumps(data) + return HttpResponse(json_data) + elif data['status'].find("[5010]") > -1: + data = {'remoteTransferStatus': 0, 'error_message': data['status'], + 'backupsSent': 0} + json_data = json.dumps(data) + return HttpResponse(json_data) + else: + data = {'remoteTransferStatus': 1, 'error_message': "None", "status": data['status'], + 'backupsSent': 0} + json_data = json.dumps(data) + return HttpResponse(json_data) + else: + data = {'remoteTransferStatus': 0, 'error_message': data['error_message'], + 'backupsSent': 0} + json_data = json.dumps(data) + return HttpResponse(json_data) + except BaseException, msg: + data = {'remoteTransferStatus': 0, 'error_message': str(msg), 'backupsSent': 0} + json_data = json.dumps(data) + return HttpResponse(json_data) + + def remoteBackupRestore(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadErrorJson('remoteTransferStatus', 0) + + backupDir = data['backupDir'] + + backupDirComplete = "/home/backup/transfer-" + str(backupDir) + # adminEmail = admin.email + + ## + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/remoteTransferUtilities.py" + + execPath = execPath + " remoteBackupRestore --backupDirComplete " + backupDirComplete + " --backupDir " + str( + backupDir) + + subprocess.Popen(shlex.split(execPath)) + + time.sleep(3) + + data = {'remoteRestoreStatus': 1, 'error_message': 'None'} + json_data = json.dumps(data) + return HttpResponse(json_data) + + except BaseException, msg: + data = {'remoteRestoreStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data) + return HttpResponse(json_data) + + def localRestoreStatus(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadErrorJson('remoteTransferStatus', 0) + + backupDir = data['backupDir'] + + # admin = Administrator.objects.get(userName=username) + backupLogPath = "/home/backup/transfer-" + backupDir + "/" + "backup_log" + + removalPath = "/home/backup/transfer-" + str(backupDir) + + time.sleep(3) + + if os.path.isfile(backupLogPath): + command = "sudo cat " + backupLogPath + status = subprocess.check_output(shlex.split(command)) + + if status.find("completed[success]") > -1: + command = "sudo rm -rf " + removalPath + # subprocess.call(shlex.split(command)) + data_ret = {'remoteTransferStatus': 1, 'error_message': "None", "status": status, "complete": 1} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif status.find("[5010]") > -1: + command = "sudo rm -rf " + removalPath + # subprocess.call(shlex.split(command)) + data = {'remoteTransferStatus': 0, 'error_message': status, + "status": "None", "complete": 0} + json_data = json.dumps(data) + return HttpResponse(json_data) + else: + data_ret = {'remoteTransferStatus': 1, 'error_message': "None", "status": status, "complete": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'remoteTransferStatus': 0, 'error_message': "No such log found", "status": "None", + "complete": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + except BaseException, msg: + data = {'remoteTransferStatus': 0, 'error_message': str(msg), "status": "None", "complete": 0} + json_data = json.dumps(data) + return HttpResponse(json_data) + + def cancelRemoteBackup(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0: + return ACLManager.loadErrorJson('cancelStatus', 0) + + ipAddress = data['ipAddress'] + password = data['password'] + dir = data['dir'] + username = "admin" + + finalData = json.dumps({'dir': dir, "username": username, "password": password}) + r = requests.post("https://" + ipAddress + ":8090/api/cancelRemoteTransfer", data=finalData, + verify=False) + + data = json.loads(r.text) + + if data['cancelStatus'] == 1: + pass + else: + logging.CyberCPLogFileWriter.writeToFile( + "Some error cancelling at remote server, see the log file for remote server.") + + path = "/home/backup/transfer-" + str(dir) + pathpid = path + "/pid" + + command = "sudo cat " + pathpid + pid = subprocess.check_output(shlex.split(command)) + + command = "sudo kill -KILL " + pid + subprocess.call(shlex.split(command)) + + command = "sudo rm -rf " + path + subprocess.call(shlex.split(command)) + + data = {'cancelStatus': 1, 'error_message': "None"} + json_data = json.dumps(data) + return HttpResponse(json_data) + + except BaseException, msg: + data = {'cancelStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data) + return HttpResponse(json_data) diff --git a/backup/static/backup/backup.js b/backup/static/backup/backup.js index eb2bcfa22..3648f61bd 100644 --- a/backup/static/backup/backup.js +++ b/backup/static/backup/backup.js @@ -4,235 +4,233 @@ //*** Backup site ****// -app.controller('backupWebsiteControl', function($scope,$http,$timeout) { +app.controller('backupWebsiteControl', function ($scope, $http, $timeout) { - $scope.destination = true; - $scope.backupButton = true; + $scope.destination = true; + $scope.backupButton = true; + $scope.backupLoading = true; + $scope.runningBackup = true; + $scope.cancelButton = true; + + populateCurrentRecords(); + + $scope.cancelBackup = function () { + + var backupCancellationDomain = $scope.websiteToBeBacked; + + url = "/backup/cancelBackupCreation"; + + var data = { + backupCancellationDomain: backupCancellationDomain, + fileName: $scope.fileName, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + }; + + $scope.fetchDetails = function () { + getBackupStatus(); + populateCurrentRecords(); + $scope.destination = false; + $scope.runningBackup = true; + + }; + + + function getBackupStatus() { + + $scope.backupLoadingBottom = false; + + var websiteToBeBacked = $scope.websiteToBeBacked; + + url = "/backup/backupStatus"; + + var data = { + websiteToBeBacked: websiteToBeBacked, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.backupStatus === 1) { + + if (response.data.abort === 1) { + $timeout.cancel(); + $scope.backupLoadingBottom = true; + $scope.destination = false; + $scope.runningBackup = false; + $scope.cancelButton = true; + $scope.backupButton = false; + $scope.backupLoading = true; + $scope.fileName = response.data.fileName; + $scope.status = response.data.status; + populateCurrentRecords(); + return; + } + else { + $scope.destination = true; + $scope.backupButton = true; + $scope.runningBackup = false; + $scope.cancelButton = false; + + $scope.fileName = response.data.fileName; + $scope.status = response.data.status; + $timeout(getBackupStatus, 2000); + + } + } + else { + $timeout.cancel(); + $scope.backupLoadingBottom = true; $scope.backupLoading = true; - $scope.runningBackup = true; $scope.cancelButton = true; + $scope.backupButton = false; + } + + } + + function cantLoadInitialDatas(response) { + } + + }; + + + $scope.destinationSelection = function () { + $scope.backupButton = false; + }; + + + function populateCurrentRecords() { + + var websiteToBeBacked = $scope.websiteToBeBacked; + + url = "/backup/getCurrentBackups"; + + var data = { + websiteToBeBacked: websiteToBeBacked, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.fetchStatus == 1) { + $scope.records = JSON.parse(response.data.data); + } + + + } + + function cantLoadInitialDatas(response) { + } + + }; + + + $scope.createBackup = function () { + + var websiteToBeBacked = $scope.websiteToBeBacked; + $scope.backupLoading = false; + + + url = "/backup/submitBackupCreation"; + + var data = { + websiteToBeBacked: websiteToBeBacked, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.metaStatus === 1) { + getBackupStatus(); + } + + } + + function cantLoadInitialDatas(response) { + } + + }; + + + $scope.deleteBackup = function (id) { + + + url = "/backup/deleteBackup"; + + var data = { + backupID: id, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + + if (response.data.deleteStatus == 1) { populateCurrentRecords(); - $scope.cancelBackup = function () { - var backupCancellationDomain = $scope.websiteToBeBacked; + } + else { - url = "/backup/cancelBackupCreation"; + } - var data = { - backupCancellationDomain:backupCancellationDomain, - fileName:$scope.fileName, - }; + } - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + function cantLoadInitialDatas(response) { - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - }; - - $scope.fetchDetails = function () { - getBackupStatus(); - populateCurrentRecords(); - $scope.destination = false; - $scope.runningBackup = true; - - }; - - - function getBackupStatus(){ - - $scope.backupLoadingBottom = false; - - var websiteToBeBacked = $scope.websiteToBeBacked; - - url = "/backup/backupStatus"; - - var data = { - websiteToBeBacked:websiteToBeBacked, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.backupStatus === 1){ - - if(response.data.abort === 1){ - $timeout.cancel(); - $scope.backupLoadingBottom = true; - $scope.destination = false; - $scope.runningBackup = false; - $scope.cancelButton = true; - $scope.backupButton = false; - $scope.backupLoading = true; - $scope.fileName = response.data.fileName; - $scope.status = response.data.status; - populateCurrentRecords(); - return; - } - else{ - $scope.destination = true; - $scope.backupButton = true; - $scope.runningBackup = false; - $scope.cancelButton = false; - - $scope.fileName = response.data.fileName; - $scope.status = response.data.status; - $timeout(getBackupStatus, 2000); - - } - } - else{ - $timeout.cancel(); - $scope.backupLoadingBottom = true; - $scope.backupLoading = true; - $scope.cancelButton = true; - $scope.backupButton = false; - } - - } - function cantLoadInitialDatas(response) {} - - }; - - - $scope.destinationSelection = function () { - $scope.backupButton = false; - }; - - - function populateCurrentRecords(){ - - var websiteToBeBacked = $scope.websiteToBeBacked; - - url = "/backup/getCurrentBackups"; - - var data = { - websiteToBeBacked:websiteToBeBacked, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.fetchStatus == 1){ - $scope.records = JSON.parse(response.data.data); - } - - - } - function cantLoadInitialDatas(response) {} - - }; - - - - $scope.createBackup = function(){ - - var websiteToBeBacked = $scope.websiteToBeBacked; - $scope.backupLoading = false; - - - - url = "/backup/submitBackupCreation"; - - var data = { - websiteToBeBacked:websiteToBeBacked, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.metaStatus === 1){ - getBackupStatus(); - } - - } - function cantLoadInitialDatas(response) {} - - }; - - - $scope.deleteBackup = function (id) { - - - url = "/backup/deleteBackup"; - - var data = { - backupID:id, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.deleteStatus == 1){ - - populateCurrentRecords(); - - - } - else{ - - } - - } - function cantLoadInitialDatas(response) { - - - } - - - - }; + } + }; }); @@ -240,15 +238,14 @@ app.controller('backupWebsiteControl', function($scope,$http,$timeout) { ///** Backup site ends **/// - ///** Restore site ***// -app.controller('restoreWebsiteControl', function($scope,$http,$timeout) { +app.controller('restoreWebsiteControl', function ($scope, $http, $timeout) { $scope.restoreLoading = true; $scope.runningRestore = true; - $scope.restoreButton=true; + $scope.restoreButton = true; $scope.restoreFinished = false; $scope.couldNotConnect = true; $scope.backupError = true; @@ -260,164 +257,161 @@ app.controller('restoreWebsiteControl', function($scope,$http,$timeout) { $scope.fetchDetails = function () { - $scope.restoreLoading = false; - getRestoreStatus(); - }; + $scope.restoreLoading = false; + getRestoreStatus(); + }; - function getRestoreStatus(){ + function getRestoreStatus() { - var backupFile = $scope.backupFile; - - url = "/backup/restoreStatus"; - - var data = { - backupFile:backupFile, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - - if(response.data.restoreStatus === 1){ - - if(response.data.abort === 1){ - $scope.running = response.data.running; - $scope.fileName = $scope.backupFile; - $scope.restoreLoading = true; - $scope.status = response.data.status; - $scope.runningRestore = false; - $scope.restoreButton=false; - $scope.restoreFinished = true; - $timeout.cancel(); - return; - } - else{ - $scope.running = response.data.running; - $scope.fileName = $scope.backupFile; - $scope.restoreLoading = false; - $scope.status = response.data.status; - $scope.runningRestore = false; - $scope.restoreButton = true; - $timeout(getRestoreStatus, 2000); - } - } - - } - function cantLoadInitialDatas(response) { - $scope.couldNotConnect = false; - - - } - - }; - - - $scope.restoreBackup = function(){ var backupFile = $scope.backupFile; - $scope.running = "Lets start.." - url = "/backup/submitRestore"; + url = "/backup/restoreStatus"; - var data = { - backupFile:backupFile, - }; + var data = { + backupFile: backupFile, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { + + if (response.data.restoreStatus === 1) { + + if (response.data.abort === 1) { + $scope.running = response.data.running; + $scope.fileName = $scope.backupFile; $scope.restoreLoading = true; - if(response.data.restoreStatus == 1){ - $scope.runningRestore = false; - $scope.running = "Running"; - $scope.fileName = $scope.backupFile; - $scope.status = "Just Started.."; - - getRestoreStatus(); - } - else{ - $scope.backupError = false; - $scope.errorMessage = response.data.error_message; - } - + $scope.status = response.data.status; + $scope.runningRestore = false; + $scope.restoreButton = false; + $scope.restoreFinished = true; + $timeout.cancel(); + return; } - function cantLoadInitialDatas(response) { - $scope.couldNotConnect = false; - + else { + $scope.running = response.data.running; + $scope.fileName = $scope.backupFile; + $scope.restoreLoading = false; + $scope.status = response.data.status; + $scope.runningRestore = false; + $scope.restoreButton = true; + $timeout(getRestoreStatus, 2000); } + } - }; - - - function createWebsite(){ - - var backupFile = $scope.backupFile; - - url = "/websites/CreateWebsiteFromBackup"; - - var data = { - backupFile:backupFile, - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); - - - function ListInitialDatas(response) { - - if(response.data.createWebSiteStatus == 1){ - getRestoreStatus(); - } - else if(response.data.existsStatus == 1){ - $scope.backupError = false; - $scope.errorMessage = response.data.error_message; - $scope.restoreButton = true; - $scope.runningRestore = true; - } - else{ - $scope.websiteDomain = domainName; - $scope.backupError = false; - $scope.errorMessage = response.data.error_message; - } - - - } - function cantLoadInitialDatas(response) { - $scope.couldNotConnect = false; - } - - + } + + function cantLoadInitialDatas(response) { + $scope.couldNotConnect = false; + } }; + $scope.restoreBackup = function () { + var backupFile = $scope.backupFile; + $scope.running = "Lets start.." + + url = "/backup/submitRestore"; + + var data = { + backupFile: backupFile, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + $scope.restoreLoading = true; + if (response.data.restoreStatus == 1) { + $scope.runningRestore = false; + $scope.running = "Running"; + $scope.fileName = $scope.backupFile; + $scope.status = "Just Started.."; + + getRestoreStatus(); + } + else { + $scope.backupError = false; + $scope.errorMessage = response.data.error_message; + } + + } + + function cantLoadInitialDatas(response) { + $scope.couldNotConnect = false; + + } + + }; + + + function createWebsite() { + + var backupFile = $scope.backupFile; + + url = "/websites/CreateWebsiteFromBackup"; + + var data = { + backupFile: backupFile, + }; + + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; + + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); + + + function ListInitialDatas(response) { + + if (response.data.createWebSiteStatus == 1) { + getRestoreStatus(); + } + else if (response.data.existsStatus == 1) { + $scope.backupError = false; + $scope.errorMessage = response.data.error_message; + $scope.restoreButton = true; + $scope.runningRestore = true; + } + else { + $scope.websiteDomain = domainName; + $scope.backupError = false; + $scope.errorMessage = response.data.error_message; + } + + + } + + function cantLoadInitialDatas(response) { + $scope.couldNotConnect = false; + } + + + }; + }); @@ -425,11 +419,10 @@ app.controller('restoreWebsiteControl', function($scope,$http,$timeout) { //*** Resotre site ends here ***/// - ///** Backup Destination ***// -app.controller('backupDestinations', function($scope,$http,$timeout) { +app.controller('backupDestinations', function ($scope, $http, $timeout) { $scope.destinationLoading = true; $scope.connectionFailed = true; @@ -452,59 +445,59 @@ app.controller('backupDestinations', function($scope,$http,$timeout) { url = "/backup/submitDestinationCreation"; - var data = { - IPAddress : $scope.IPAddress, - password : $scope.password, - backupSSHPort:$scope.backupSSHPort, - }; + var data = { + IPAddress: $scope.IPAddress, + password: $scope.password, + backupSSHPort: $scope.backupSSHPort, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.destStatus == 1){ + if (response.data.destStatus == 1) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = false; - $scope.couldNotConnect = true; + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = false; + $scope.couldNotConnect = true; - populateCurrentRecords(); + populateCurrentRecords(); - } - else { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = false; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; + } + else { + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = false; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; - } - } - function cantLoadInitialDatas(response) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = false; - } + $scope.errorMessage = response.data.error_message; + } + } - }; + function cantLoadInitialDatas(response) { + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = false; + } + + }; $scope.checkConn = function (ip) { @@ -518,58 +511,58 @@ app.controller('backupDestinations', function($scope,$http,$timeout) { url = "/backup/getConnectionStatus"; - var data = { - IPAddress : ip, - }; + var data = { + IPAddress: ip, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.connStatus == 1){ + if (response.data.connStatus == 1) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = false; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = false; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; - $scope.IPAddress = ip; + $scope.IPAddress = ip; - } - else { - $scope.destinationLoading = true; - $scope.connectionFailed = false; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; + } + else { + $scope.destinationLoading = true; + $scope.connectionFailed = false; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; - $scope.IPAddress = ip; - } - } - function cantLoadInitialDatas(response) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = false; - } + $scope.errorMessage = response.data.error_message; + $scope.IPAddress = ip; + } + } - }; + function cantLoadInitialDatas(response) { + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = false; + } + + }; $scope.delDest = function (ip) { @@ -583,94 +576,92 @@ app.controller('backupDestinations', function($scope,$http,$timeout) { url = "/backup/deleteDestination"; - var data = { - IPAddress : ip, - }; + var data = { + IPAddress: ip, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.delStatus == 1){ + if (response.data.delStatus == 1) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; - populateCurrentRecords(); + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; + populateCurrentRecords(); - $scope.IPAddress = ip; + $scope.IPAddress = ip; - } - else { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; + } + else { + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; - $scope.IPAddress = ip; - } - } - function cantLoadInitialDatas(response) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = false; - } + $scope.errorMessage = response.data.error_message; + $scope.IPAddress = ip; + } + } - }; + function cantLoadInitialDatas(response) { + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = false; + } + + }; + function populateCurrentRecords() { - function populateCurrentRecords(){ + url = "/backup/getCurrentBackupDestinations"; - url = "/backup/getCurrentBackupDestinations"; + var data = {}; - var data = { - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - } - } - function cantLoadInitialDatas(response) { - $scope.couldNotConnect = false; - } + } + } - }; + function cantLoadInitialDatas(response) { + $scope.couldNotConnect = false; + } + + }; }); @@ -681,7 +672,7 @@ app.controller('backupDestinations', function($scope,$http,$timeout) { ///** Schedule Backup ***// -app.controller('scheduleBackup', function($scope,$http,$timeout) { +app.controller('scheduleBackup', function ($scope, $http, $timeout) { $scope.scheduleBackupLoading = true; $scope.canNotAddSchedule = true; @@ -722,67 +713,65 @@ app.controller('scheduleBackup', function($scope,$http,$timeout) { $scope.scheduleBtn = false; - url = "/backup/submitBackupSchedule"; - var data = { - backupDest : $scope.backupDest, - backupFreq : $scope.backupFreq, - }; + var data = { + backupDest: $scope.backupDest, + backupFreq: $scope.backupFreq, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.scheduleStatus == 1){ + if (response.data.scheduleStatus == 1) { - $scope.scheduleBackupLoading = true; - $scope.canNotAddSchedule = true; - $scope.scheduleAdded = false; - $scope.couldNotConnect = true; - $scope.scheduleFreq = true; - $scope.scheduleBtn = true; + $scope.scheduleBackupLoading = true; + $scope.canNotAddSchedule = true; + $scope.scheduleAdded = false; + $scope.couldNotConnect = true; + $scope.scheduleFreq = true; + $scope.scheduleBtn = true; + populateCurrentRecords(); - populateCurrentRecords(); + } + else { - } - else { + $scope.scheduleBackupLoading = true; + $scope.canNotAddSchedule = false; + $scope.scheduleAdded = true; + $scope.couldNotConnect = true; + $scope.scheduleFreq = false; + $scope.scheduleBtn = false; - $scope.scheduleBackupLoading = true; - $scope.canNotAddSchedule = false; - $scope.scheduleAdded = true; - $scope.couldNotConnect = true; - $scope.scheduleFreq = false; - $scope.scheduleBtn = false; + $scope.errorMessage = response.data.error_message; + } + } - $scope.errorMessage = response.data.error_message; - } - } - function cantLoadInitialDatas(response) { + function cantLoadInitialDatas(response) { - $scope.scheduleBackupLoading = true; - $scope.canNotAddSchedule = true; - $scope.scheduleAdded = true; - $scope.couldNotConnect = false; - $scope.scheduleFreq = false; - $scope.scheduleBtn = false; + $scope.scheduleBackupLoading = true; + $scope.canNotAddSchedule = true; + $scope.scheduleAdded = true; + $scope.couldNotConnect = false; + $scope.scheduleFreq = false; + $scope.scheduleBtn = false; - } + } - }; + }; $scope.checkConn = function (ip) { @@ -796,60 +785,60 @@ app.controller('scheduleBackup', function($scope,$http,$timeout) { url = "/backup/getConnectionStatus"; - var data = { - IPAddress : ip, - }; + var data = { + IPAddress: ip, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.connStatus == 1){ + if (response.data.connStatus == 1) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = false; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = false; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; - $scope.IPAddress = ip; + $scope.IPAddress = ip; - } - else { - $scope.destinationLoading = true; - $scope.connectionFailed = false; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = true; + } + else { + $scope.destinationLoading = true; + $scope.connectionFailed = false; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = true; - $scope.errorMessage = response.data.error_message; - $scope.IPAddress = ip; - } - } - function cantLoadInitialDatas(response) { - $scope.destinationLoading = true; - $scope.connectionFailed = true; - $scope.connectionSuccess = true; - $scope.canNotAddDestination = true; - $scope.destinationAdded = true; - $scope.couldNotConnect = false; - } + $scope.errorMessage = response.data.error_message; + $scope.IPAddress = ip; + } + } - }; + function cantLoadInitialDatas(response) { + $scope.destinationLoading = true; + $scope.connectionFailed = true; + $scope.connectionSuccess = true; + $scope.canNotAddDestination = true; + $scope.destinationAdded = true; + $scope.couldNotConnect = false; + } - $scope.delSchedule = function (destLoc,frequency) { + }; + + $scope.delSchedule = function (destLoc, frequency) { $scope.scheduleBackupLoading = false; $scope.canNotAddSchedule = true; @@ -862,96 +851,94 @@ app.controller('scheduleBackup', function($scope,$http,$timeout) { url = "/backup/scheduleDelete"; - var data = { - destLoc : destLoc, - frequency: frequency, - }; + var data = { + destLoc: destLoc, + frequency: frequency, + }; - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.delStatus == 1){ + if (response.data.delStatus == 1) { - $scope.scheduleBackupLoading = true; - $scope.canNotAddSchedule = true; - $scope.scheduleAdded = true; - $scope.couldNotConnect = true; - $scope.scheduleFreq = true; - $scope.scheduleBtn = true; + $scope.scheduleBackupLoading = true; + $scope.canNotAddSchedule = true; + $scope.scheduleAdded = true; + $scope.couldNotConnect = true; + $scope.scheduleFreq = true; + $scope.scheduleBtn = true; - populateCurrentRecords(); + populateCurrentRecords(); - } - else { + } + else { - $scope.scheduleBackupLoading = true; - $scope.canNotAddSchedule = true; - $scope.scheduleAdded = true; - $scope.couldNotConnect = true; - $scope.scheduleFreq = true; - $scope.scheduleBtn = true; - $scope.errorMessage = response.data.error_message; - } - } - function cantLoadInitialDatas(response) { + $scope.scheduleBackupLoading = true; + $scope.canNotAddSchedule = true; + $scope.scheduleAdded = true; + $scope.couldNotConnect = true; + $scope.scheduleFreq = true; + $scope.scheduleBtn = true; + $scope.errorMessage = response.data.error_message; + } + } - $scope.scheduleBackupLoading = true; - $scope.canNotAddSchedule = true; - $scope.scheduleAdded = true; - $scope.couldNotConnect = false; - $scope.scheduleFreq = true; - $scope.scheduleBtn = true; - } + function cantLoadInitialDatas(response) { - }; + $scope.scheduleBackupLoading = true; + $scope.canNotAddSchedule = true; + $scope.scheduleAdded = true; + $scope.couldNotConnect = false; + $scope.scheduleFreq = true; + $scope.scheduleBtn = true; + } + + }; + function populateCurrentRecords() { - function populateCurrentRecords(){ + url = "/backup/getCurrentBackupSchedules"; - url = "/backup/getCurrentBackupSchedules"; + var data = {}; - var data = { - }; - - var config = { - headers : { - 'X-CSRFToken': getCookie('csrftoken') - } - }; + var config = { + headers: { + 'X-CSRFToken': getCookie('csrftoken') + } + }; - - $http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas); + $http.post(url, data, config).then(ListInitialDatas, cantLoadInitialDatas); - function ListInitialDatas(response) { + function ListInitialDatas(response) { - if(response.data.fetchStatus == 1){ + if (response.data.fetchStatus == 1) { - $scope.records = JSON.parse(response.data.data); + $scope.records = JSON.parse(response.data.data); - } - } - function cantLoadInitialDatas(response) { - $scope.couldNotConnect = false; - } + } + } - }; + function cantLoadInitialDatas(response) { + $scope.couldNotConnect = false; + } + + }; }); @@ -960,7 +947,7 @@ app.controller('scheduleBackup', function($scope,$http,$timeout) { //*** Remote Backup site ****// -app.controller('remoteBackupControl', function($scope, $http, $timeout) { +app.controller('remoteBackupControl', function ($scope, $http, $timeout) { $scope.backupButton = true; $scope.backupLoading = true; @@ -993,47 +980,46 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { var index = 0; var tempTransferDir = ""; - $scope.passwordEnter = function() { + $scope.passwordEnter = function () { $scope.backupButton = false; }; - $scope.addRemoveWebsite = function (website,websiteStatus) { + $scope.addRemoveWebsite = function (website, websiteStatus) { - if(websiteStatus === true) - { + if (websiteStatus === true) { var check = 1; - for(var j = 0; j < websitesToBeBacked.length; j++){ - if (websitesToBeBacked[j] == website){ - check = 0; - break; - } + for (var j = 0; j < websitesToBeBacked.length; j++) { + if (websitesToBeBacked[j] == website) { + check = 0; + break; } - if(check == 1) { + } + if (check == 1) { websitesToBeBacked.push(website); } } - else{ + else { var tempArray = []; - for(var j = 0; j < websitesToBeBacked.length; j++){ - if (websitesToBeBacked[j] != website){ - tempArray.push(websitesToBeBacked[j]); - } + for (var j = 0; j < websitesToBeBacked.length; j++) { + if (websitesToBeBacked[j] != website) { + tempArray.push(websitesToBeBacked[j]); } + } websitesToBeBacked = tempArray; } }; $scope.allChecked = function (webSiteStatus) { - if(webSiteStatus === true) { + if (webSiteStatus === true) { websitesToBeBacked = websitesToBeBackedTemp; $scope.webSiteStatus = true; } - else{ + else { websitesToBeBacked = []; $scope.webSiteStatus = false; } @@ -1076,7 +1062,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { $scope.records = JSON.parse(response.data.data); var parsed = JSON.parse(response.data.data); - for(var j = 0; j < parsed.length; j++){ + for (var j = 0; j < parsed.length; j++) { websitesToBeBackedTemp.push(parsed[j].website); } @@ -1138,8 +1124,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { $scope.backupCancelled = true; - - if(websitesToBeBacked.length === 0){ + if (websitesToBeBacked.length === 0) { alert("No websites selected for transfer."); return; } @@ -1157,7 +1142,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { var data = { ipAddress: IPAddress, password: password, - accountsToTransfer:websitesToBeBacked, + accountsToTransfer: websitesToBeBacked, }; var config = { @@ -1172,28 +1157,28 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { function ListInitialDatas(response) { if (response.data.remoteTransferStatus === 1) { - tempTransferDir = response.data.dir; - $scope.accountsInRemoteServerTable = true; + tempTransferDir = response.data.dir; + $scope.accountsInRemoteServerTable = true; - // notifications boxes - $scope.notificationsBox = false; - $scope.errorMessage = true; - $scope.couldNotConnect = true; - $scope.accountsFetched = true; - $scope.backupProcessStarted = false; - $scope.backupCancelled = true; + // notifications boxes + $scope.notificationsBox = false; + $scope.errorMessage = true; + $scope.couldNotConnect = true; + $scope.accountsFetched = true; + $scope.backupProcessStarted = false; + $scope.backupCancelled = true; - // disable transfer button + // disable transfer button - $scope.startTransferbtn = true; + $scope.startTransferbtn = true; - // enable cancel button + // enable cancel button - $scope.stopTransferbtn = false; + $scope.stopTransferbtn = false; - getBackupStatus(); + getBackupStatus(); } @@ -1218,15 +1203,15 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { function cantLoadInitialDatas(response) { - // Notifications box settings + // Notifications box settings - // notifications boxes - $scope.notificationsBox = false; - $scope.errorMessage = true; - $scope.couldNotConnect = false; - $scope.accountsFetched = true; - $scope.backupProcessStarted = true; - $scope.backupCancelled = true; + // notifications boxes + $scope.notificationsBox = false; + $scope.errorMessage = true; + $scope.couldNotConnect = false; + $scope.accountsFetched = true; + $scope.backupProcessStarted = true; + $scope.backupCancelled = true; } @@ -1237,7 +1222,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { url = "/backup/getRemoteTransferStatus"; var data = { - password : $scope.password, + password: $scope.password, ipAddress: $scope.IPAddress, dir: tempTransferDir }; @@ -1255,12 +1240,12 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { if (response.data.remoteTransferStatus === 1) { - if(response.data.backupsSent === 0){ + if (response.data.backupsSent === 0) { $scope.backupStatus = false; $scope.requestData = response.data.status; $timeout(getBackupStatus, 2000); } - else{ + else { $scope.requestData = response.data.status; $timeout.cancel(); @@ -1269,7 +1254,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { remoteBackupRestore(); } } - else{ + else { $scope.error_message = response.data.error_message; $scope.backupLoading = true; @@ -1288,16 +1273,16 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { } function cantLoadInitialDatas(response) { - // Notifications box settings + // Notifications box settings - $scope.couldNotConnect = false; - $scope.errorMessage = true; - $scope.accountsFetched = true; - $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.errorMessage = true; + $scope.accountsFetched = true; + $scope.notificationsBox = false; } }; - function remoteBackupRestore(){ + function remoteBackupRestore() { url = "/backup/remoteBackupRestore"; var data = { @@ -1316,18 +1301,18 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { function ListInitialDatas(response) { if (response.data.remoteRestoreStatus === 1) { - localRestoreStatus(); + localRestoreStatus(); } } function cantLoadInitialDatas(response) { - // Notifications box settings + // Notifications box settings - $scope.couldNotConnect = false; - $scope.errorMessage = true; - $scope.accountsFetched = true; - $scope.notificationsBox = false; - $scope.backupLoading = true; + $scope.couldNotConnect = false; + $scope.errorMessage = true; + $scope.accountsFetched = true; + $scope.notificationsBox = false; + $scope.backupLoading = true; } /////////////// @@ -1337,7 +1322,6 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { function localRestoreStatus(password) { - url = "/backup/localRestoreStatus"; var data = { @@ -1357,19 +1341,19 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { if (response.data.remoteTransferStatus === 1) { - if(response.data.complete === 0){ + if (response.data.complete === 0) { $scope.backupStatus = false; $scope.restoreData = response.data.status; $timeout(localRestoreStatus, 2000); } - else{ + else { $scope.restoreData = response.data.status; $timeout.cancel(); $scope.backupLoading = true; $scope.startTransferbtn = false; } } - else{ + else { $scope.error_message = response.data.error_message; $scope.backupLoading = true; @@ -1387,12 +1371,12 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { } function cantLoadInitialDatas(response) { - // Notifications box settings + // Notifications box settings - $scope.couldNotConnect = false; - $scope.errorMessage = true; - $scope.accountsFetched = true; - $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.errorMessage = true; + $scope.accountsFetched = true; + $scope.notificationsBox = false; } }; @@ -1402,7 +1386,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { url = "/backup/getRemoteTransferStatus"; var data = { - password : $scope.password, + password: $scope.password, ipAddress: $scope.IPAddress, dir: tempTransferDir, }; @@ -1420,12 +1404,12 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { if (response.data.remoteTransferStatus == 1) { - if(response.data.backupsSent == 0){ + if (response.data.backupsSent == 0) { $scope.backupStatus = false; $scope.requestData = response.data.status; $timeout(getBackupStatus, 2000); } - else{ + else { $timeout.cancel(); } } @@ -1433,12 +1417,12 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { } function cantLoadInitialDatas(response) { - // Notifications box settings + // Notifications box settings - $scope.couldNotConnect = false; - $scope.errorMessage = true; - $scope.accountsFetched = true; - $scope.notificationsBox = false; + $scope.couldNotConnect = false; + $scope.errorMessage = true; + $scope.accountsFetched = true; + $scope.notificationsBox = false; } }; @@ -1463,7 +1447,7 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { var data = { ipAddress: IPAddress, password: password, - dir:tempTransferDir, + dir: tempTransferDir, }; var config = { @@ -1478,35 +1462,35 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { function ListInitialDatas(response) { if (response.data.cancelStatus == 1) { - $scope.backupLoading = true; + $scope.backupLoading = true; - // notifications boxes - $scope.notificationsBox = false; - $scope.errorMessage = true; - $scope.couldNotConnect = true; - $scope.accountsFetched = true; - $scope.backupProcessStarted = true; - $scope.backupCancelled = false; + // notifications boxes + $scope.notificationsBox = false; + $scope.errorMessage = true; + $scope.couldNotConnect = true; + $scope.accountsFetched = true; + $scope.backupProcessStarted = true; + $scope.backupCancelled = false; - // enable transfer button + // enable transfer button - $scope.startTransferbtn = false; + $scope.startTransferbtn = false; - //disable cancel button + //disable cancel button - $scope.stopTransferbtn = true; + $scope.stopTransferbtn = true; - // hide status box + // hide status box - $scope.backupStatus = true; + $scope.backupStatus = true; - // bring back websites table + // bring back websites table - $scope.accountsInRemoteServerTable = false; + $scope.accountsInRemoteServerTable = false; - // enable fetch button + // enable fetch button - $scope.fetchAccountsBtn = false; + $scope.fetchAccountsBtn = false; } @@ -1525,21 +1509,20 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) { $scope.backupCancelled = true; - } } function cantLoadInitialDatas(response) { - // notifications boxes + // notifications boxes - $scope.notificationsBox = false; - $scope.errorMessage = true; - $scope.couldNotConnect = false; - $scope.accountsFetched = true; - $scope.backupProcessStarted = true; - $scope.backupCancelled = true; + $scope.notificationsBox = false; + $scope.errorMessage = true; + $scope.couldNotConnect = false; + $scope.accountsFetched = true; + $scope.backupProcessStarted = true; + $scope.backupCancelled = true; } diff --git a/backup/views.py b/backup/views.py index 3dc6bea67..b4796c76a 100644 --- a/backup/views.py +++ b/backup/views.py @@ -1,12 +1,14 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.shortcuts import redirect # Create your views here. import json -from loginSystem.views import loadLoginPage -from plogical.backupManager import BackupManager + +from django.shortcuts import redirect + +from backup.backupManager import BackupManager from backup.pluginManager import pluginManager +from loginSystem.views import loadLoginPage def loadBackupHome(request): diff --git a/cloudAPI/cloudManager.py b/cloudAPI/cloudManager.py index 9c86c5f09..48606cbb0 100644 --- a/cloudAPI/cloudManager.py +++ b/cloudAPI/cloudManager.py @@ -1,30 +1,33 @@ -from loginSystem.models import Administrator -from django.shortcuts import HttpResponse import json -from plogical.website import WebsiteManager -from plogical.acl import ACLManager -from plogical.virtualHostUtilities import virtualHostUtilities -from websiteFunctions.models import Websites -import subprocess, shlex +import os +import shlex +import subprocess +from random import randint + +from django.shortcuts import HttpResponse + +import userManagment.views as um +from backup.backupManager import BackupManager from databases.databaseManager import DatabaseManager from dns.dnsManager import DNSManager -from mailServer.mailserverManager import MailServerManager -from ftp.ftpManager import FTPManager -from manageSSL.views import issueSSL, obtainHostNameSSL, obtainMailServerSSL -from plogical.backupManager import BackupManager -import userManagment.views as um -from packages.packagesManager import PackagesManager -from plogical.processUtilities import ProcessUtilities from firewall.firewallManager import FirewallManager -from serverLogs.views import getLogsFromFile -from random import randint +from ftp.ftpManager import FTPManager from highAvailability.haManager import HAManager +from loginSystem.models import Administrator +from mailServer.mailserverManager import MailServerManager +from manageSSL.views import issueSSL, obtainHostNameSSL, obtainMailServerSSL +from packages.packagesManager import PackagesManager +from plogical.acl import ACLManager from plogical.httpProc import httpProc -from s3Backups.s3Backups import S3Backups -import os -from serverStatus.views import topProcessesStatus, killProcess from plogical.mysqlUtilities import mysqlUtilities -from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging +from plogical.processUtilities import ProcessUtilities +from plogical.virtualHostUtilities import virtualHostUtilities +from plogical.website import WebsiteManager +from s3Backups.s3Backups import S3Backups +from serverLogs.views import getLogsFromFile +from serverStatus.views import topProcessesStatus, killProcess +from websiteFunctions.models import Websites + class CloudManager: def __init__(self, data=None, admin = None): diff --git a/plogical/backupUtilities.py b/plogical/backupUtilities.py index f51559115..d37f3a5d3 100644 --- a/plogical/backupUtilities.py +++ b/plogical/backupUtilities.py @@ -230,6 +230,7 @@ class backupUtilities: ## Saving original vhost conf file completPathToConf = virtualHostUtilities.Server_root + '/conf/vhosts/' + domainName + '/vhost.conf' + if os.path.exists(backupUtilities.licenseKey): copy(completPathToConf, tempStoragePath + '/vhost.conf') @@ -243,7 +244,12 @@ class backupUtilities: sslStoragePath = '/etc/letsencrypt/live/' + domainName if os.path.exists(sslStoragePath): - make_archive(os.path.join(tempStoragePath, "sslData-" + domainName), 'gztar', sslStoragePath) + try: + copy(os.path.join(sslStoragePath, "cert.pem"), os.path.join(tempStoragePath, domainName + ".cert.pem")) + copy(os.path.join(sslStoragePath, "fullchain.pem"), os.path.join(tempStoragePath, domainName + ".fullchain.pem")) + copy(os.path.join(sslStoragePath, "privkey.pem"), os.path.join(tempStoragePath, domainName + ".privkey.pem")) + except: + pass ## backup email accounts @@ -281,10 +287,23 @@ class backupUtilities: completPathToConf = virtualHostUtilities.Server_root + '/conf/vhosts/' + actualChildDomain + '/vhost.conf' copy(completPathToConf, tempStoragePath + '/' + actualChildDomain + '.vhost.conf') + ### Storing SSL for child domainsa + sslStoragePath = '/etc/letsencrypt/live/' + actualChildDomain if os.path.exists(sslStoragePath): - make_archive(os.path.join(tempStoragePath, "sslData-" + actualChildDomain), 'gztar', sslStoragePath) + try: + copy(os.path.join(sslStoragePath, "cert.pem"), + os.path.join(tempStoragePath, actualChildDomain + ".cert.pem")) + copy(os.path.join(sslStoragePath, "fullchain.pem"), + os.path.join(tempStoragePath, actualChildDomain + ".fullchain.pem")) + copy(os.path.join(sslStoragePath, "privkey.pem"), + os.path.join(tempStoragePath, actualChildDomain + ".privkey.pem")) + make_archive(os.path.join(tempStoragePath, "sslData-" + domainName), 'gztar', + sslStoragePath) + except: + pass + except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]") @@ -295,10 +314,8 @@ class backupUtilities: make_archive(os.path.join(backupPath,backupName), 'gztar', tempStoragePath) rmtree(tempStoragePath) - logging.CyberCPLogFileWriter.statusWriter(status, "Completed\n") - except BaseException,msg: try: os.remove(os.path.join(backupPath,backupName+".tar.gz")) @@ -464,14 +481,22 @@ class backupUtilities: if result[0] == 1: ## Let us try to restore SSL. - sslStoragePath = completPath + "/sslData-" + masterDomain + '.tar.gz' + sslStoragePath = completPath + "/" + masterDomain + ".cert.pem" if os.path.exists(sslStoragePath): sslHome = '/etc/letsencrypt/live/' + masterDomain - tar = tarfile.open(sslStoragePath) - tar.extractall(sslHome) - tar.close() - sslUtilities.installSSLForDomain(masterDomain) + + try: + if not os.path.exists(sslHome): + os.mkdir(sslHome) + + copy(completPath + "/" + masterDomain + ".cert.pem", sslHome + "/cert.pem") + copy(completPath + "/" + masterDomain + ".privkey.pem", sslHome + "/privkey.pem") + copy(completPath + "/" + masterDomain + ".fullchain.pem", sslHome + "/fullchain.pem") + + sslUtilities.installSSLForDomain(masterDomain) + except: + pass else: logging.CyberCPLogFileWriter.statusWriter(status, "Error Message: " + result[1] + ". Not able to create Account, Databases and DNS Records, aborting. [5009]") @@ -512,14 +537,23 @@ class backupUtilities: completPathToConf = virtualHostUtilities.Server_root + '/conf/vhosts/' + domain + '/vhost.conf' copy(completPath + '/' + domain + '.vhost.conf', completPathToConf) - sslStoragePath = completPath + "/sslData-" + domain + '.tar.gz' + sslStoragePath = completPath + "/" + domain + ".cert.pem" if os.path.exists(sslStoragePath): sslHome = '/etc/letsencrypt/live/' + domain - tar = tarfile.open(sslStoragePath) - tar.extractall(sslHome) - tar.close() - sslUtilities.installSSLForDomain(domain) + + try: + if not os.path.exists(sslHome): + os.mkdir(sslHome) + + copy(completPath + "/" + domain + ".cert.pem", sslHome + "/cert.pem") + copy(completPath + "/" + domain + ".privkey.pem", sslHome + "/privkey.pem") + copy(completPath + "/" + domain + ".fullchain.pem", + sslHome + "/fullchain.pem") + + sslUtilities.installSSLForDomain(domain) + except: + pass except: logging.CyberCPLogFileWriter.writeToFile('While restoring backup we had minor issues for rebuilding vhost conf for: ' + domain + '. However this will be auto healed.')