Files
CyberPanel/plogical/remoteTransferUtilities.py

378 lines
16 KiB
Python
Raw Normal View History

2017-12-09 22:30:10 +05:00
import argparse
import os
import CyberCPLogFileWriter as logging
import remoteBackup as rBackup
import backupUtilities as backupUtil
import time
from multiprocessing import Process
2018-02-20 22:39:07 +05:00
import json
import requests
import subprocess
import shlex
from shutil import move
2017-12-09 22:30:10 +05:00
class remoteTransferUtilities:
@staticmethod
def writeAuthKey(pathToKey):
try:
2018-02-22 12:17:38 +05:00
authorized_keys = os.path.join("/root",".ssh","authorized_keys")
2017-12-09 22:30:10 +05:00
presenseCheck = 0
try:
data = open(authorized_keys, "r").readlines()
for items in data:
if items.find(open(pathToKey,"r").read()) > -1:
try:
os.remove(pathToKey)
except:
pass
print "1,None"
return
except:
pass
if presenseCheck == 0:
writeToFile = open(authorized_keys, 'a')
writeToFile.writelines("#Added by CyberPanel\n")
writeToFile.writelines(open(pathToKey,"r").read())
writeToFile.writelines("\n")
writeToFile.close()
try:
os.remove(pathToKey)
except:
pass
print "1,None"
return
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile("For remote transfer, I am not able to write key to auth file, Error Message: "+str(msg))
2018-05-11 00:03:26 +05:00
print "0,"+"For remote transfer, I am not able to write key to auth file, Error Message: " + str(msg)
2017-12-09 22:30:10 +05:00
2018-05-11 00:03:26 +05:00
## House keeping function to run remote backups
2017-12-09 22:30:10 +05:00
@staticmethod
2018-05-11 00:03:26 +05:00
def remoteTransfer(ipAddress, dir, accountsToTransfer):
2017-12-09 22:30:10 +05:00
try:
2018-02-20 22:39:07 +05:00
destination = "/home/backup/transfer-" + dir
backupLogPath = destination + "/backup_log"
2017-12-09 22:30:10 +05:00
2018-05-11 00:03:26 +05:00
data = open(accountsToTransfer, 'r').readlines()
accountsToTransfer = []
for items in data:
accountsToTransfer.append(items.strip('\n'))
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
if not os.path.exists(destination):
os.makedirs(destination)
writeToFile = open(backupLogPath, "w+")
2017-12-09 22:30:10 +05:00
writeToFile.writelines("############################\n")
2018-02-20 22:39:07 +05:00
writeToFile.writelines(" Starting remote Backup\n")
2017-12-09 22:30:10 +05:00
writeToFile.writelines(" Start date: " + time.strftime("%I-%M-%S-%a-%b-%Y") + "\n")
writeToFile.writelines("############################\n")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
2018-02-20 22:39:07 +05:00
if backupUtil.backupUtilities.checkIfHostIsUp(ipAddress) == 1:
checkConn = backupUtil.backupUtilities.checkConnection(ipAddress)
if checkConn[0] == 0:
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Connection to:" + ipAddress + " Failed, please resetup this destination from CyberPanel, aborting. [5010]" + "\n")
writeToFile.close()
return
else:
pass
2017-12-09 22:30:10 +05:00
else:
2018-02-20 22:39:07 +05:00
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Host:" + ipAddress + " is down, aborting. [5010]" + "\n")
2017-12-09 22:30:10 +05:00
writeToFile.close()
return
2018-02-20 22:39:07 +05:00
writeToFile.close()
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
## destination = /home/backup/transfer-2558
## backupLogPath = /home/backup/transfer-2558/backup_log
## dir = 2558
## Array of domains to be transferred
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
p = Process(target=remoteTransferUtilities.backupProcess,
args=(ipAddress, destination, backupLogPath, dir, accountsToTransfer))
p.start()
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
pid = open(destination + '/pid', "w")
2017-12-09 22:30:10 +05:00
pid.write(str(p.pid))
pid.close()
return
except BaseException, msg:
writeToFile = open(backupLogPath, "w+")
writeToFile.writelines(str(msg) + " [5010]" + "\n")
writeToFile.close()
2018-02-20 22:39:07 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [remoteTransfer]")
2018-05-11 00:03:26 +05:00
return [0, str(msg)]
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
## destination = /home/backup/transfer-2558
## backupLogPath = /home/backup/transfer-2558/backup_log
## dir = 2558
## Array of domains to be transferred
2017-12-09 22:30:10 +05:00
@staticmethod
2018-02-20 22:39:07 +05:00
def backupProcess(ipAddress, dir, backupLogPath, folderNumber, accountsToTransfer):
try:
## dir is without forward slash
for virtualHost in accountsToTransfer:
try:
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Currently generating local backups for: " + virtualHost + "\n")
writeToFile.close()
finalData = json.dumps({'websiteToBeBacked': virtualHost})
r = requests.post("http://localhost:5003/backup/submitBackupCreation", data=finalData,
verify=False)
data = json.loads(r.text)
fileName = data['tempStorage'] + ".tar.gz"
completePathToBackupFile = fileName
while (1):
time.sleep(2)
r = requests.post("http://localhost:5003/backup/backupStatus", data=finalData, verify=False)
data = json.loads(r.text)
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Waiting for backup to complete.. " + "\n")
writeToFile.close()
if data['backupStatus'] == 0:
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + "Failed to generate local backup for: " + virtualHost + ". Error message: " +
data['error_message'] + "\n")
break
elif data['abort'] == 1:
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Local Backup Completed for: " + virtualHost + " with status: " +
data['status'] + "\n")
## move the generated backup file to specified destination
if os.path.exists(completePathToBackupFile):
move(completePathToBackupFile, dir)
completedPathToSend = dir + "/" + completePathToBackupFile.split("/")[-1]
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Sending " + completedPathToSend + " to " + ipAddress + ".\n")
remoteTransferUtilities.sendBackup(completedPathToSend, ipAddress, str(folderNumber), writeToFile)
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Sent " + completedPathToSend + " to " + ipAddress + ".\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " #############################################" + "\n")
writeToFile.close()
break
2018-09-24 18:56:48 +05:00
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
2018-02-20 22:39:07 +05:00
pass
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Backups are successfully generated and received on: " + ipAddress + "\n")
writeToFile.close()
## removing local directory where backups were generated
#time.sleep(5)
# rmtree(dir)
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [backupProcess]")
@staticmethod
def sendBackup(completedPathToSend, IPAddress, folderNumber,writeToFile):
2017-12-09 22:30:10 +05:00
try:
2018-02-20 22:39:07 +05:00
## complete path is a path to the file need to send
2017-12-09 22:30:10 +05:00
2018-02-22 12:17:38 +05:00
command = "sudo scp -o StrictHostKeyChecking=no -i /root/.ssh/cyberpanel " + completedPathToSend + " root@" + IPAddress + ":/home/backup/transfer-" + folderNumber + "/"
2019-03-21 23:26:42 +05:00
ProcessUtilities.executioner(shlex.split(command), stdout=writeToFile)
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
except BaseException, msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [startBackup]")
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
@staticmethod
def remoteBackupRestore(backupDir, dir):
try:
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
## dir is transfer-###
# backupDir is /home/backup/transfer-###
backupLogPath = backupDir + "/backup_log"
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
writeToFile = open(backupLogPath, "a+")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
2017-12-09 22:30:10 +05:00
writeToFile.writelines("############################\n")
2018-02-20 22:39:07 +05:00
writeToFile.writelines(" Starting Backup Restore\n")
2017-12-09 22:30:10 +05:00
writeToFile.writelines(" Start date: " + time.strftime("%I-%M-%S-%a-%b-%Y") + "\n")
writeToFile.writelines("############################\n")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
2018-02-20 22:39:07 +05:00
writeToFile.close()
2017-12-09 22:30:10 +05:00
2018-02-20 22:39:07 +05:00
if os.path.exists(backupDir):
pass
2017-12-09 22:30:10 +05:00
else:
2018-02-20 22:39:07 +05:00
writeToFile = open(backupLogPath, "w+")
writeToFile.writelines(
"No such directory found (Local directory where backups are placed does not exists)' [5010]" + "\n")
2017-12-09 22:30:10 +05:00
writeToFile.close()
return
2018-02-20 22:39:07 +05:00
p = Process(target=remoteTransferUtilities.startRestore, args=(backupDir, backupLogPath, dir,))
2017-12-09 22:30:10 +05:00
p.start()
2018-02-20 22:39:07 +05:00
pid = open(backupDir + '/pid', "w")
2017-12-09 22:30:10 +05:00
pid.write(str(p.pid))
pid.close()
return
except BaseException, msg:
2018-02-20 22:39:07 +05:00
backupLogPath = backupDir + "/backup_log"
2017-12-09 22:30:10 +05:00
writeToFile = open(backupLogPath, "w+")
writeToFile.writelines(str(msg) + " [5010]" + "\n")
writeToFile.close()
2018-02-20 22:39:07 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [remoteRestore]")
2017-12-09 22:30:10 +05:00
return [0, msg]
2018-02-20 22:39:07 +05:00
@staticmethod
def startRestore(backupDir, backupLogPath, dir):
try:
ext = ".tar.gz"
for backup in os.listdir(backupDir):
if backup.endswith(ext):
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Starting restore for: " + backup + ".\n")
writeToFile.close()
finalData = json.dumps({'backupFile': backup, "dir": dir})
r = requests.post("http://localhost:5003/backup/submitRestore", data=finalData, verify=False)
data = json.loads(r.text)
if data['restoreStatus'] == 1:
while (1):
time.sleep(1)
finalData = json.dumps({'backupFile': backup, "dir": dir})
r = requests.post("http://localhost:5003/backup/restoreStatus", data=finalData,
verify=False)
data = json.loads(r.text)
if data['abort'] == 1 and data['running'] == "Error":
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Restore aborted for: " + backup + ". Error message: " +
data['status'] + "\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " #########################################\n")
writeToFile.close()
break
elif data['abort'] == 1 and data['running'] == "Completed":
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Restore Completed for: " + backup + ".\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " #########################################\n")
writeToFile.close()
break
else:
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Waiting for restore to complete.\n")
writeToFile.close()
time.sleep(3)
pass
else:
logging.CyberCPLogFileWriter.writeToFile("Could not start restore process for: " + backup)
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + "Could not start restore process for: " + backup + "\n")
writeToFile.close()
writeToFile = open(backupLogPath, "a")
writeToFile.writelines("\n")
writeToFile.writelines("\n")
writeToFile.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "]" + " Backup Restore complete\n")
writeToFile.writelines("completed[success]")
except BaseException, msg:
2018-09-05 19:06:06 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [remoteTransferUtilities.startRestore]")
2018-02-20 22:39:07 +05:00
2017-12-09 22:30:10 +05:00
def main():
parser = argparse.ArgumentParser(description='CyberPanel Installer')
2018-02-20 22:39:07 +05:00
parser.add_argument('function', help='Specific function to call!')
2017-12-09 22:30:10 +05:00
parser.add_argument('--pathToKey', help='')
## remote transfer arguments
parser.add_argument('--ipAddress', help='')
parser.add_argument('--dir', help='')
parser.add_argument('--accountsToTransfer', help='')
## remote backup restore arguments
parser.add_argument('--backupDirComplete', help='')
parser.add_argument('--backupDir', help='')
args = parser.parse_args()
if args.function == "writeAuthKey":
remoteTransferUtilities.writeAuthKey(args.pathToKey)
elif args.function == "remoteTransfer":
remoteTransferUtilities.remoteTransfer(args.ipAddress,args.dir,args.accountsToTransfer)
elif args.function == "remoteBackupRestore":
remoteTransferUtilities.remoteBackupRestore(args.backupDirComplete,args.backupDir)
if __name__ == "__main__":
main()