Skip to content

Commit 9b81679

Browse files
committed
initiate cloudbackup
1 parent 3fa1049 commit 9b81679

File tree

3 files changed

+212
-7
lines changed

3 files changed

+212
-7
lines changed

cloudAPI/cloudManager.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1638,3 +1638,59 @@ def ResetDNSConfigurations(self):
16381638

16391639
except BaseException as msg:
16401640
return self.ajaxPre(0, str(msg))
1641+
1642+
def SubmitCloudBackup(self):
1643+
try:
1644+
1645+
tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999))
1646+
1647+
writeToFile = open(tempStatusPath, 'w')
1648+
writeToFile.write('Starting..,0')
1649+
writeToFile.close()
1650+
1651+
execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/backupUtilities.py"
1652+
execPath = execPath + " CloudBackup --backupDomain %s --data 1 --emails 1 --databases 1 --tempStoragePath %s" % (self.data['domain'], tempStatusPath)
1653+
ProcessUtilities.popenExecutioner(execPath)
1654+
1655+
final_dic = {'status': 1, 'tempStatusPath': tempStatusPath}
1656+
final_json = json.dumps(final_dic)
1657+
return HttpResponse(final_json)
1658+
1659+
except BaseException as msg:
1660+
return self.ajaxPre(0, str(msg))
1661+
1662+
def getCurrentCloudBackups(self):
1663+
try:
1664+
1665+
backupDomain = self.data['domainName']
1666+
backupsPath = '/home/cyberpanel/backups/%s/' % (backupDomain)
1667+
backups = os.listdir(backupsPath)
1668+
backups.reverse()
1669+
1670+
json_data = "["
1671+
checker = 0
1672+
1673+
counter = 1
1674+
for items in backups:
1675+
1676+
size = str(int(int(os.path.getsize('%s/%s' % (backupsPath, items)))/int(1048576)))
1677+
1678+
dic = {'id': counter,
1679+
'file': items,
1680+
'size': '%s MBs' % (size),
1681+
}
1682+
counter = counter + 1
1683+
1684+
if checker == 0:
1685+
json_data = json_data + json.dumps(dic)
1686+
checker = 1
1687+
else:
1688+
json_data = json_data + ',' + json.dumps(dic)
1689+
1690+
json_data = json_data + ']'
1691+
final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': "None", "data": json_data})
1692+
return HttpResponse(final_json)
1693+
except BaseException as msg:
1694+
final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)}
1695+
final_json = json.dumps(final_dic)
1696+
return HttpResponse(final_json)

cloudAPI/views.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ def router(request):
5151
return cm.ReadReportDNS()
5252
elif controller == 'ResetDNSConfigurations':
5353
return cm.ResetDNSConfigurations()
54+
elif controller == 'SubmitCloudBackup':
55+
return cm.SubmitCloudBackup()
56+
elif controller == 'getCurrentCloudBackups':
57+
return cm.getCurrentCloudBackups()
5458
elif controller == 'fetchWebsites':
5559
return cm.fetchWebsites()
5660
elif controller == 'fetchWebsiteDataJSON':

plogical/backupUtilities.py

Lines changed: 152 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,15 @@
5454

5555
class backupUtilities:
5656
Server_root = "/usr/local/lsws"
57-
5857
completeKeyPath = "/home/cyberpanel/.ssh"
5958
destinationsPath = "/home/cyberpanel/destinations"
6059
licenseKey = '/usr/local/lsws/conf/license.key'
60+
NiceDefault = '10'
61+
CPUDefault = '40'
62+
CloudBackupConfigPath = '/home/cyberpanel/CloudBackup.json'
63+
64+
def __init__(self, extraArgs):
65+
self.extraArgs = extraArgs
6166

6267
@staticmethod
6368
def prepareBackupMeta(backupDomain, backupName, tempStoragePath, backupPath):
@@ -1246,6 +1251,134 @@ def getAliases(masterDomain):
12461251
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [getAliases]")
12471252
print(0)
12481253

1254+
### Cloud Backup functions
1255+
1256+
def CheckIfSleepNeeded(self):
1257+
import psutil
1258+
while (1):
1259+
if int(psutil.cpu_percent()) > int(self.cpu):
1260+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1261+
'Current CPU usage exceeds %s percent. Backup process will sleep for 10 seconds..,0' % (self.cpu))
1262+
import time
1263+
time.sleep(10)
1264+
else:
1265+
break
1266+
1267+
def BackupData(self):
1268+
1269+
### Creating the dir to store backups
1270+
self.BackupDataPath = '%s/data' % (self.BackupPath)
1271+
command = 'mkdir -p %s' % (self.BackupDataPath)
1272+
ProcessUtilities.executioner(command)
1273+
self.DataPath = '/home/%s' % (self.extraArgs['domain'])
1274+
1275+
## Backing up data
1276+
1277+
self.CheckIfSleepNeeded()
1278+
1279+
command = 'nice -n %s cp -R %s %s' % (self.nice, self.DataPath, self.BackupDataPath)
1280+
ProcessUtilities.executioner(command)
1281+
1282+
## Store child domains if any in json format
1283+
1284+
DataJson = {}
1285+
childs = []
1286+
import json
1287+
1288+
for child in self.website.childdomains_set.all():
1289+
childs.append(child.domain)
1290+
1291+
DataJson['ChildDomains'] = childs
1292+
1293+
DataJsonPath = '%s/%s' % (self.BackupPath, 'data.json')
1294+
1295+
writeToFile = open(DataJsonPath, 'w')
1296+
writeToFile.write(json.dumps(DataJson))
1297+
writeToFile.close()
1298+
1299+
return 1
1300+
1301+
def BackupEmails(self):
1302+
1303+
### Creating the dir to store backups
1304+
self.BackupDataPath = '%s/emails' % (self.BackupPath)
1305+
command = 'mkdir -p %s' % (self.BackupDataPath)
1306+
ProcessUtilities.executioner(command)
1307+
self.DataPath = '/home/vmail/%s' % (self.extraArgs['domain'])
1308+
1309+
## Backing up data
1310+
1311+
self.CheckIfSleepNeeded()
1312+
1313+
command = 'nice -n %s cp -R %s %s' % (self.nice, self.DataPath, self.BackupDataPath)
1314+
ProcessUtilities.executioner(command)
1315+
1316+
## Store child domains if any in json format
1317+
1318+
DataJson = {}
1319+
emailsList = []
1320+
import json
1321+
1322+
from mailServer.models import Domains, EUsers
1323+
emailDomain = Domains.objects.get(domainOwner=self.website)
1324+
1325+
for emails in emailDomain.eusers_set.all():
1326+
emailsList.append({'email': emails.email, 'password': emails.password})
1327+
1328+
DataJson['emails'] = emailsList
1329+
DataJsonPath = '%s/%s' % (self.BackupPath, 'emails.json')
1330+
writeToFile = open(DataJsonPath, 'w')
1331+
writeToFile.write(json.dumps(DataJson))
1332+
writeToFile.close()
1333+
1334+
return 1
1335+
1336+
def CloudBackups(self):
1337+
import json
1338+
if os.path.exists(backupUtilities.CloudBackupConfigPath):
1339+
result = json.loads(open(backupUtilities.CloudBackupConfigPath, 'r').read())
1340+
self.nice = result['nice']
1341+
self.cpu = result['cpu']
1342+
else:
1343+
self.nice = backupUtilities.NiceDefault
1344+
self.cpu = backupUtilities.CPUDefault
1345+
1346+
self.BackupPath = '/home/cyberpanel/backups/%s/backup-' % (self.extraArgs['domain']) + self.extraArgs['domain'] + "-" + time.strftime("%m.%d.%Y_%H-%M-%S")
1347+
self.website = Websites.objects.get(domain=self.extraArgs['domain'])
1348+
1349+
command = 'mkdir -p %s' % (self.BackupPath)
1350+
ProcessUtilities.executioner(command)
1351+
1352+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1353+
'Starting backup generation..,0')
1354+
if self.extraArgs['data']:
1355+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1356+
'Generating backup for your data,5')
1357+
if self.BackupData() == 0:
1358+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1359+
'Failed to generate backups for data. [404], 0')
1360+
return 0
1361+
1362+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1363+
'Data backup successfully generated,30')
1364+
1365+
if self.extraArgs['emails']:
1366+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1367+
'Generating backup for your emails,5')
1368+
if self.BackupEmails() == 0:
1369+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1370+
'Failed to generate backups for emails. [404], 0')
1371+
return 0
1372+
1373+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'],
1374+
'Emails backup successfully generated,30')
1375+
1376+
logging.CyberCPLogFileWriter.statusWriter(self.extraArgs['tempStatusPath'], 'Completed [200].')
1377+
1378+
1379+
1380+
### Cloud Backup functions ends
1381+
12491382

12501383
def submitBackupCreation(tempStoragePath, backupName, backupPath, backupDomain):
12511384
try:
@@ -1386,7 +1519,6 @@ def submitBackupCreation(tempStoragePath, backupName, backupPath, backupDomain):
13861519
logging.CyberCPLogFileWriter.writeToFile(
13871520
str(msg) + " [submitBackupCreation]")
13881521

1389-
13901522
def cancelBackupCreation(backupCancellationDomain, fileName):
13911523
try:
13921524

@@ -1421,7 +1553,6 @@ def cancelBackupCreation(backupCancellationDomain, fileName):
14211553
str(msg) + " [cancelBackupCreation]")
14221554
print("0," + str(msg))
14231555

1424-
14251556
def submitRestore(backupFile, dir):
14261557
try:
14271558

@@ -1435,7 +1566,6 @@ def submitRestore(backupFile, dir):
14351566
str(msg) + " [cancelBackupCreation]")
14361567
print("0," + str(msg))
14371568

1438-
14391569
def submitDestinationCreation(ipAddress, password, port='22', user='root'):
14401570
setupKeys = backupUtilities.setupSSHKeys(ipAddress, password, port, user)
14411571

@@ -1445,7 +1575,6 @@ def submitDestinationCreation(ipAddress, password, port='22', user='root'):
14451575
else:
14461576
print(setupKeys[1])
14471577

1448-
14491578
def getConnectionStatus(ipAddress):
14501579
try:
14511580
checkCon = backupUtilities.checkConnection(ipAddress)
@@ -1460,8 +1589,8 @@ def getConnectionStatus(ipAddress):
14601589

14611590

14621591
def main():
1463-
parser = argparse.ArgumentParser(description='CyberPanel Installer')
1464-
parser.add_argument('function', help='Specific a function to call!')
1592+
parser = argparse.ArgumentParser(description='CyberPanel Backup Generator')
1593+
parser.add_argument('function', help='Specify a function to call!')
14651594
parser.add_argument('--tempStoragePath', help='')
14661595
parser.add_argument('--backupName', help='!')
14671596
parser.add_argument('--backupPath', help='')
@@ -1485,6 +1614,13 @@ def main():
14851614
parser.add_argument('--backupFile', help='')
14861615
parser.add_argument('--dir', help='')
14871616

1617+
### For Cloud Backups
1618+
1619+
parser.add_argument('--data', help='')
1620+
parser.add_argument('--emails', help='')
1621+
parser.add_argument('--databases', help='')
1622+
1623+
14881624
args = parser.parse_args()
14891625

14901626
if args.function == "submitBackupCreation":
@@ -1501,6 +1637,15 @@ def main():
15011637
backupUtilities.startBackup(args.tempStoragePath, args.backupName, args.backupPath, args.metaPath)
15021638
elif args.function == "BackupRoot":
15031639
backupUtilities.BackupRoot(args.tempStoragePath, args.backupName, args.backupPath, args.metaPath)
1640+
elif args.function == 'CloudBackup':
1641+
extraArgs = {}
1642+
extraArgs['domain'] = args.backupDomain
1643+
extraArgs['tempStatusPath'] = args.tempStoragePath
1644+
extraArgs['data'] = int(args.data)
1645+
extraArgs['emails'] = int(args.emails)
1646+
extraArgs['databases'] = int(args.databases)
1647+
bu = backupUtilities(extraArgs)
1648+
bu.CloudBackups()
15041649

15051650

15061651
if __name__ == "__main__":

0 commit comments

Comments
 (0)