Virtual machine manager

This commit is contained in:
usmannasir
2018-09-10 01:45:43 +05:00
parent a1fc607f38
commit 88b95d511f
152 changed files with 13102 additions and 89 deletions

View File

@@ -24,7 +24,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xr%j*p!*$0d%(-(e%@-*hyoz4$f%y77coq0u)6pwmjg4)q&19f'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG = True
ALLOWED_HOSTS = ['*']
@@ -58,8 +58,12 @@ INSTALLED_APPS = [
'manageSSL',
'api',
'filemanager',
'manageServices',
'emailPremium',
'manageServices',
'ipManagement',
'vpsManagement',
'hypervisor'
]
MIDDLEWARE = [

View File

@@ -37,4 +37,7 @@ urlpatterns = [
url(r'^filemanager/',include('filemanager.urls')),
url(r'^emailPremium/',include('emailPremium.urls')),
url(r'^manageservices/',include('manageServices.urls')),
url(r'^ip/', include('ipManagement.urls')),
url(r'^vps/',include('vpsManagement.urls')),
url(r'^hv/',include('hypervisor.urls')),
]

35
CyberTronAPI/CyberTronLogger.py Executable file
View File

@@ -0,0 +1,35 @@
import subprocess
import time
class CyberTronLogger:
fileName = "/home/cyberpanel/error-logs.txt"
operationsLogFile = "/home/cyberpanel/error-logs.txt"
@staticmethod
def writeToFile(message,level,method):
try:
file = open(CyberTronLogger.fileName,'a')
file.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "] [" + level + ":" + method + "] " + message + "\n")
file.close()
file.close()
except IOError:
return "Can not write to error file!"
@staticmethod
def operationsLog(message,level,method):
try:
file = open(CyberTronLogger.operationsLogFile, 'a')
file.writelines("[" + time.strftime(
"%I-%M-%S-%a-%b-%Y") + "] [" + level + ":"+ method + "] " + message + "\n")
file.close()
except IOError:
return "Can not write to error file!"
@staticmethod
def readLastNFiles(numberOfLines,fileName):
try:
lastFewLines = subprocess.check_output(["tail", "-n",str(numberOfLines),fileName])
return lastFewLines
except subprocess.CalledProcessError:
return "File was empty!"

0
CyberTronAPI/__init__.py Executable file
View File

489
CyberTronAPI/cybertron.py Executable file
View File

@@ -0,0 +1,489 @@
#!/usr/local/CyberCP/bin/python2
import os,sys
sys.path.append('/usr/local/CyberCP')
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
import threading as multi
from CyberTronLogger import CyberTronLogger as logger
from inspect import stack
from shlex import split
from subprocess import call,CalledProcessError
from os.path import join
from random import randint
from logLevel import logLevel
from ipManagement.models import IPAddresses
from packages.models import VMPackage as Package
from django.db.models import Max
import CyberTronAPI.randomPassword as randomPassword
from vpsManagement.models import VPS, SSHKeys
from loginSystem.models import Administrator
from CyberTronAPI.virtualMachineAPIKVM import virtualMachineAPI
import plogical.CyberCPLogFileWriter as logging
from os import remove
class CyberTron(multi.Thread):
imagesPath = join('/var', 'lib', 'libvirt', 'images')
templatesPath = join('/var', 'lib', 'libvirt', 'templates')
def __init__(self, data):
multi.Thread.__init__(self)
self.data = data
def run(self):
try:
self.createVirtualMachine(self.data)
except BaseException, msg:
logger.writeToFile(str(msg), "Error", stack()[0][3])
def setupNetworkingFiles(self, ipAddress, osName, ipPool, hostName, tempStatusPath):
try:
if logLevel.debug == True:
logger.operationsLog('Setting up network for: ' + ipAddress + '.', 'Debug', stack()[0][3])
uploadSource = []
## Set Device name
deviceName = ''
if osName == 'centos-6':
deviceName = 'eth0'
elif osName == 'centos-7.2':
deviceName = 'ens3'
elif osName == 'debian-9' or osName == 'ubuntu-16.04':
deviceName = 'ens3'
if osName.find("centos") > -1:
###### /etc/sysconfig/network-scripts/ifcfg-eth0
eth0 = "/home/cyberpanel/ifcfg-ens3" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('DEVICE="' + deviceName + '"\n')
eth0File.writelines('NM_CONTROLLED="yes"\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('BOOTPROTO=static\n')
eth0File.writelines('NAME="System ' + deviceName + '"\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + ipPool.netmask + '\n')
eth0File.close()
uploadSource.append(eth0)
###### /etc/sysconfig/network
network = "/home/cyberpanel/network_" + str(randint(10000, 99999) + 1)
networkFile = open(network, 'w')
networkFile.writelines('NETWORKING=yes\n')
networkFile.writelines('HOSTNAME=' + hostName + '\n')
networkFile.writelines('GATEWAY=' + ipPool.gateway + '\n')
networkFile.close()
uploadSource.append(network)
###### /etc/resolv.conf
resolv = "/home/cyberpanel/resolv_" + str(randint(10000, 99999) + 2)
resolvFile = open(resolv, 'w')
resolvFile.writelines("nameserver 8.8.8.8\n")
resolvFile.close()
uploadSource.append(resolv)
elif osName == 'ubuntu-18.04':
eth0 = "/home/cyberpanel/interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('# This file describes the network interfaces available on your system\n')
eth0File.writelines('# For more information, see netplan(5).\n')
eth0File.writelines('\n')
eth0File.writelines('network:\n')
eth0File.writelines(' version: 2\n')
eth0File.writelines(' renderer: networkd\n')
eth0File.writelines(' ethernets:\n')
eth0File.writelines(' ens2:\n')
eth0File.writelines(' dhcp4: yes\n')
eth0File.writelines(' ens3:\n')
eth0File.writelines(' dhcp4: no\n')
eth0File.writelines(' addresses: [' + ipAddress + '/24]\n')
eth0File.writelines(' gateway4: ' + ipPool.gateway + '\n')
eth0File.writelines(' nameservers:\n')
eth0File.writelines(' addresses: [8.8.8.8,8.8.4.4]\n')
eth0File.writelines('\n')
eth0File.close()
uploadSource.append(eth0)
elif osName.find("debian") > -1 or osName.find("ubuntu") > -1:
###### ip
eth0 = "/home/cyberpanel/interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('# This file describes the network interfaces available on your system\n')
eth0File.writelines('# and how to activate them. For more information, see interfaces(5).\n')
eth0File.writelines('\n')
eth0File.writelines('# The loopback network interface\n')
eth0File.writelines('auto lo\n')
eth0File.writelines('iface lo inet loopback\n')
eth0File.writelines('\n')
## To deal with Debian 9.3 and ubuntu 16.04 issue.
eth0File.writelines('# The primary network interface\n')
eth0File.writelines('allow-hotplug ' + deviceName + '\n')
eth0File.writelines('iface ' + deviceName + ' inet static\n')
eth0File.writelines(' address ' + ipAddress + '\n')
eth0File.writelines(' netmask ' + ipPool.netmask + '\n')
eth0File.writelines(' gateway ' + ipPool.gateway + '\n')
eth0File.writelines('# dns-* options are implemented by the resolvconf package, if installed\n')
eth0File.writelines('dns-nameservers 8.8.8.8\n')
eth0File.writelines('dns-search com\n')
eth0File.close()
uploadSource.append(eth0)
elif osName.find("fedora") > -1:
###### /etc/sysconfig/network-scripts/ifcfg-ens3
eth0 = "/home/cyberpanel/interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('PROXY_METHOD=none\n')
eth0File.writelines('BROWSER_ONLY=no\n')
eth0File.writelines('BOOTPROTO=none\n')
eth0File.writelines('DEFROUTE=yes\n')
eth0File.writelines('IPV4_FAILURE_FATAL=no\n')
eth0File.writelines('IPV6INIT=yes\n')
eth0File.writelines('IPV6_AUTOCONF=yes\n')
eth0File.writelines('IPV6_DEFROUTE=yes\n')
eth0File.writelines('IPV6_FAILURE_FATAL=no\n')
eth0File.writelines('IPV6_ADDR_GEN_MODE=stable-privacy\n')
eth0File.writelines('NAME=ens3\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('AUTOCONNECT_PRIORITY=-999\n')
eth0File.writelines('DEVICE=ens3\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + ipPool.netmask + '\n')
eth0File.writelines('GATEWAY=' + ipPool.gateway + '\n')
eth0File.writelines('DNS1=8.8.8.8\n')
eth0File.writelines('IPV6_PRIVACY=no\n')
eth0File.close()
uploadSource.append(eth0)
elif osName.find("freebsd") > -1:
###### /etc/rc.conf
eth0 = "/home/cyberpanel/ifcfg-eth0_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('DEVICE="eth0"\n')
eth0File.writelines('NM_CONTROLLED="yes"\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('BOOTPROTO=static\n')
eth0File.writelines('NAME="System eth0"\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + ipPool.gateway + '\n')
eth0File.close()
uploadSource.append(eth0)
if logLevel.debug == True:
logger.operationsLog('Network settings installed for: ' + ipAddress + '.', 'Debug', stack()[0][3])
return uploadSource
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
def buildCustomDisk(self, vmName, osName, size, rootPassword, uploadCommand, tempStatusPath):
try:
sourcePath = join(virtualMachineAPI.templatesPath, osName + ".img")
tempPath = join(virtualMachineAPI.imagesPath, vmName + "-temp.qcow2")
finalPath = join(virtualMachineAPI.imagesPath, vmName + ".qcow2")
## Creating temporary disk image.
command = "sudo cp " + sourcePath + " " + tempPath
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Temporary image created for: " + vmName + ".", "Debug", stack()[0][3])
command = "sudo qemu-img create -f qcow2 " + finalPath + " " + size
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Created resized final image for: " + vmName + ".", "Debug", stack()[0][3])
command = "sudo virt-resize --expand /dev/sda1 " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
command = "sudo virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand
call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Root password and network configured for: " + vmName + ".", "Debug",
stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
def setupVMDisk(self, vmName, osName, uploadSource, rootPassword, package, tempStatusPath, sshKey = None):
try:
size = package.diskSpace + 'G'
if osName.find('centos') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/sysconfig/network-scripts/ifcfg-eth0"
uploadCommand = uploadCommand + " --upload " + uploadSource[1] + ":" + "/etc/sysconfig/network"
uploadCommand = uploadCommand + " --upload " + uploadSource[2] + ":" + "/etc/resolv.conf"
elif osName == 'ubuntu-18.04':
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/netplan/01-netcfg.yaml --firstboot-command 'dpkg-reconfigure openssh-server'"
elif osName.find('debian') > -1 or osName.find('ubuntu') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/network/interfaces --firstboot-command 'ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key && ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key && ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key'"
elif osName.find('fedora') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/sysconfig/network-scripts/ifcfg-ens3"
finalImageLocation = join(CyberTron.imagesPath, vmName + '.qcow2')
## "virt-builder centos-7.1 -o /var/lib/libvirt/images192.168.100.1.qcow2 --size 50G --format qcow2 --upload ifcfg-eth0:/etc/sysconfig/network-scripts/ --upload network:/etc/sysconfig
if osName == 'debian-9' or osName == 'fedora-28' or osName == 'ubuntu-16.04':
self.buildCustomDisk(vmName, osName, size, rootPassword, uploadCommand, tempStatusPath)
else:
if sshKey != None:
command = "sudo virt-builder " + osName + " -o " + finalImageLocation + " --size " + size + \
" --format qcow2 --root-password password:" + rootPassword + uploadCommand + " --ssh-inject 'root:string:" + sshKey + "'"
else:
command = "sudo virt-builder " + osName + " -o " + finalImageLocation + " --size " + size + \
" --format qcow2 --root-password password:" + rootPassword + uploadCommand
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Disk image created for: " + vmName + ".", "Debug", stack()[0][3])
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
def bootVirtualMachine(self, package, vmName, vncHost, vncPort, vncPassword, webSocketPort, hostname, bridgeName, tempStatusPath):
try:
if logLevel.debug == True:
logger.operationsLog('Booting: ' + vmName + '.', 'Debug', stack()[0][3])
finalImageLocation = join(CyberTron.imagesPath, vmName + ".qcow2")
# virt-install --name 109.238.12.214 --ram 2048 --vcpus=1 --disk 109.238.12.214.qcow2 --graphics vnc,listen=localhost,port=5500 --noautoconsole --hvm --import --os-type=linux --os-variant=rhel7 --network bridge=virbr0
command = "sudo virt-install --name " + hostname + " --ram " + str(package.guaranteedRam) + " --vcpu " + str(package.cpuCores) + " --disk " + \
finalImageLocation + " --graphics vnc,listen=" + vncHost + ",port=" + vncPort + ",password=" + vncPassword + \
" --noautoconsole --hvm --import --autostart --os-type=linux " \
+ "--network bridge=" + bridgeName
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Successfully booted: " + vmName + ".", "Debug", stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
def createVirtualMachine(self, data):
try:
osName = data['osName']
vpsPackage = data['vpsPackage']
vpsOwner = data['vpsOwner']
vpsIP = data['vpsIP']
hostname = data['hostname']
rootPassword = data['rootPassword']
networkSpeed = data['networkSpeed']
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Running some checks..,0')
try:
sshKey = data['sshKey']
key = SSHKeys.objects.get(keyName=sshKey)
sshKey = key.key
except:
sshKey = None
owner = Administrator.objects.get(userName=vpsOwner)
package = Package.objects.get(packageName=vpsPackage)
ip = IPAddresses.objects.get(ipAddr=vpsIP)
## Some checks
if ip.used == 1:
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'This IP is already in use. [404]')
return 0, 'This IP is already in use.'
if VPS.objects.filter(hostName=hostname).count() > 0:
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Hostname is already taken. [404]')
return 0, 'Hostname is already taken.'
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Starting to create virtual machine..,10')
logger.operationsLog('Starting to create virtual machine: ' + vpsIP, 'Info', stack()[0][3])
##
uploadSource = self.setupNetworkingFiles(vpsIP, osName, ip.pool, hostname, data['tempStatusPath'])
##
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'],
'Creating virtual machine disk..,20')
if self.setupVMDisk(hostname, osName, uploadSource, rootPassword, package, data['tempStatusPath'], sshKey) == 0:
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Failed to setup virtual machine disk. [404]')
return 0
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'],
'Booting virtual machine..,80')
## Server IP
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
vncHost = ipData.split('\n', 1)[0]
## Finding VNC Port
if VPS.objects.count() == 0:
vncPort = 5900
webSocketPort = 0
else:
vncPort = VPS.objects.all().aggregate(Max('vncPort'))['vncPort__max'] + 1
webSocketPort = VPS.objects.count()
vncPassword = randomPassword.generate_pass(50)
if self.bootVirtualMachine(package, hostname, vncHost, str(vncPort), vncPassword, str(webSocketPort), hostname, 'virbr0', data['tempStatusPath']) == 0:
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Failed to boot virtual machine. [404]')
return 0
## Saving VM To database
newVPS = VPS(owner=owner, ipAddr=ip, package=package, hostName=hostname, networkSpeed=networkSpeed,
vncPort=vncPort, vncPassword=vncPassword, websocketPort=webSocketPort)
newVPS.save()
ip.used = 1
ip.save()
## Installing network limitations
## Reading interface name
interfaceFile = "/etc/cyberpanel/interfaceName"
f = open(interfaceFile)
interfaceData = f.read()
interfaceName = interfaceData.split('\n', 1)[0]
virtualMachineAPI.limitVMSpeed(str(newVPS.id), vpsIP, 'virbr0', networkSpeed)
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Virtual Machine successfully created.. [200]')
logger.operationsLog('Virtual machine ' + vpsIP + ' successfully created.', 'Success', stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], str(msg) + ' [404]')
return 0

13
CyberTronAPI/hashPassword.py Executable file
View File

@@ -0,0 +1,13 @@
import uuid
import hashlib
def hash_password(password):
# uuid is used to generate a random number
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

2
CyberTronAPI/logLevel.py Executable file
View File

@@ -0,0 +1,2 @@
class logLevel:
debug = False

38
CyberTronAPI/randomPassword.py Executable file
View File

@@ -0,0 +1,38 @@
from os import urandom
from random import choice
char_set = {'small': 'abcdefghijklmnopqrstuvwxyz',
'nums': '0123456789',
'big': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
}
def generate_pass(length=14):
"""Function to generate a password"""
password = []
while len(password) < length:
key = choice(char_set.keys())
a_char = urandom(1)
if a_char in char_set[key]:
if check_prev_char(password, char_set[key]):
continue
else:
password.append(a_char)
return ''.join(password)
def check_prev_char(password, current_char_set):
"""Function to ensure that there are no consecutive
UPPERCASE/lowercase/numbers/special-characters."""
index = len(password)
if index == 0:
return False
else:
prev_char = password[index - 1]
if prev_char in current_char_set:
return True
else:
return False

341
CyberTronAPI/sslUtilities.py Executable file
View File

@@ -0,0 +1,341 @@
import CyberCPLogFileWriter as logging
import shutil
import os
import shlex
import subprocess
import socket
class sslUtilities:
Server_root = "/usr/local/lsws"
@staticmethod
def checkIfSSLMap(virtualHostName):
try:
data = open("/usr/local/lsws/conf/httpd_config.conf").readlines()
sslCheck = 0
for items in data:
if items.find("listener") >-1 and items.find("SSL") > -1:
sslCheck = 1
continue
if sslCheck == 1:
if items.find("}") > -1:
return 0
if items.find(virtualHostName) > -1 and sslCheck == 1:
data = filter(None, items.split(" "))
if data[1] == virtualHostName:
return 1
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [IO Error with main config file [checkIfSSLMap]]")
return 0
@staticmethod
def installSSLForDomain(virtualHostName):
pathToStoreSSL = sslUtilities.Server_root + "/conf/vhosts/" + "SSL-" + virtualHostName
confPath = sslUtilities.Server_root + "/conf/vhosts/" + virtualHostName
completePathToConfigFile = confPath + "/vhost.conf"
try:
map = " map " + virtualHostName + " " + virtualHostName + "\n"
if sslUtilities.checkSSLListener()!=1:
writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'a')
listener = "listener SSL {" + "\n"
address = " address *:443" + "\n"
secure = " secure 1" + "\n"
keyFile = " keyFile " + pathToStoreSSL + "/privkey.pem" + "\n"
certFile = " certFile " + pathToStoreSSL + "/fullchain.pem" + "\n"
certChain = " certChain 1" + "\n"
sslProtocol = " sslProtocol 30" + "\n"
map = " map " + virtualHostName + " " + virtualHostName + "\n"
final = "}" + "\n" + "\n"
writeDataToFile.writelines("\n")
writeDataToFile.writelines(listener)
writeDataToFile.writelines(address)
writeDataToFile.writelines(secure)
writeDataToFile.writelines(keyFile)
writeDataToFile.writelines(certFile)
writeDataToFile.writelines(certChain)
writeDataToFile.writelines(sslProtocol)
writeDataToFile.writelines(map)
writeDataToFile.writelines(final)
writeDataToFile.writelines("\n")
writeDataToFile.close()
else:
if sslUtilities.checkIfSSLMap(virtualHostName) == 0:
data = open("/usr/local/lsws/conf/httpd_config.conf").readlines()
writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'w')
sslCheck = 0
for items in data:
if items.find("listener")>-1 and items.find("SSL") > -1:
sslCheck = 1
if (sslCheck == 1):
writeDataToFile.writelines(items)
writeDataToFile.writelines(map)
sslCheck = 0
else:
writeDataToFile.writelines(items)
writeDataToFile.close()
###################### Write per host Configs for SSL ###################
data = open(completePathToConfigFile,"r").readlines()
## check if vhssl is already in vhconf file
vhsslPresense = 0
for items in data:
if items.find("vhssl")>-1:
vhsslPresense = 1
if vhsslPresense == 0:
writeSSLConfig = open(completePathToConfigFile,"a")
vhssl = "vhssl {" + "\n"
keyFile = " keyFile " + pathToStoreSSL + "/privkey.pem" + "\n"
certFile = " certFile " + pathToStoreSSL + "/fullchain.pem" + "\n"
certChain = " certChain 1" + "\n"
sslProtocol = " sslProtocol 30" + "\n"
final = "}"
writeSSLConfig.writelines("\n")
writeSSLConfig.writelines(vhssl)
writeSSLConfig.writelines(keyFile)
writeSSLConfig.writelines(certFile)
writeSSLConfig.writelines(certChain)
writeSSLConfig.writelines(sslProtocol)
writeSSLConfig.writelines(final)
writeSSLConfig.writelines("\n")
writeSSLConfig.close()
return 1
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [installSSLForDomain]]")
return 0
@staticmethod
def checkSSLListener():
try:
data = open("/usr/local/lsws/conf/httpd_config.conf").readlines()
for items in data:
if items.find("listener SSL") > -1:
return 1
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [IO Error with main config file [checkSSLListener]]")
return str(msg)
return 0
@staticmethod
def getDNSRecords(virtualHostName):
try:
withoutWWW = socket.gethostbyname(virtualHostName)
withWWW = socket.gethostbyname('www.' + virtualHostName)
return [1, withWWW, withoutWWW]
except BaseException, msg:
return [0, "347 " + str(msg) + " [issueSSLForDomain]"]
@staticmethod
def obtainSSLForADomain(virtualHostName,adminEmail,sslpath, aliasDomain = None):
try:
## Obtaining Server IP
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
serverIPAddress = ipData.split('\n', 1)[0]
## Obtaining Domain IPs
if aliasDomain == None:
ipRecords = sslUtilities.getDNSRecords(virtualHostName)
if ipRecords[0] == 1:
if serverIPAddress == ipRecords[1] and serverIPAddress == ipRecords[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d www." + virtualHostName
logging.CyberCPLogFileWriter.writeToFile(
"SSL successfully issued for domain : " + virtualHostName + " and www." + virtualHostName)
else:
if serverIPAddress == ipRecords[2]:
command = "certbot certonly -n --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName
logging.CyberCPLogFileWriter.writeToFile(
"SSL is issued without 'www' due to DNS error for domain : " + virtualHostName)
else:
logging.CyberCPLogFileWriter.writeToFile(
"DNS Records for " + virtualHostName + " does not point to this server, issuing self signed certificate.")
return 0
else:
logging.CyberCPLogFileWriter.writeToFile(
"Failed to obtain DNS records for " + virtualHostName + ", issuing self signed certificate.")
return 0
else:
ipRecords = sslUtilities.getDNSRecords(virtualHostName)
if ipRecords[0] == 1:
if serverIPAddress == ipRecords[1] and serverIPAddress == ipRecords[2]:
ipRecordsAlias = sslUtilities.getDNSRecords(aliasDomain)
if serverIPAddress == ipRecordsAlias[1] and serverIPAddress == ipRecordsAlias[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d www." + virtualHostName + " -d " + aliasDomain + " -d www." + aliasDomain
else:
if serverIPAddress == ipRecordsAlias[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d www." + virtualHostName + " -d " + aliasDomain
else:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d www." + virtualHostName
else:
if serverIPAddress == ipRecords[2]:
ipRecordsAlias = sslUtilities.getDNSRecords(aliasDomain)
if serverIPAddress == ipRecordsAlias[1] and serverIPAddress == ipRecordsAlias[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d " + aliasDomain + " -d www." + aliasDomain
else:
if serverIPAddress == ipRecordsAlias[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName + " -d " + aliasDomain
else:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + virtualHostName
logging.CyberCPLogFileWriter.writeToFile(
"SSL is issued without 'www' due to DNS error for domain : " + virtualHostName)
else:
ipRecordsAlias = sslUtilities.getDNSRecords(aliasDomain)
if serverIPAddress == ipRecordsAlias[1] and serverIPAddress == ipRecordsAlias[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + aliasDomain + " -d www." + aliasDomain
else:
if serverIPAddress == ipRecordsAlias[2]:
command = "certbot certonly -n --expand --agree-tos --email " + adminEmail + " --webroot -w " + sslpath + " -d " + aliasDomain
else:
return 0
else:
logging.CyberCPLogFileWriter.writeToFile(
"Failed to obtain DNS records for " + virtualHostName + ", issuing self signed certificate.")
return 0
## SSL Paths
pathToStoreSSL = sslUtilities.Server_root + "/conf/vhosts/" + "SSL-" + virtualHostName
if not os.path.exists(pathToStoreSSL):
os.mkdir(pathToStoreSSL)
pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
##
output = subprocess.check_output(shlex.split(command))
data = output.split('\n')
if output.find('Congratulations!') > -1:
###### Copy SSL To config location ######
for items in data:
if items.find(virtualHostName) > -1 and items.find('fullchain.pem') > -1:
srcFullChain = items.strip(' ')
elif items.find(virtualHostName) > -1 and items.find('privkey.pem') > -1:
srcPrivKey = items.strip(' ')
if os.path.exists(pathToStoreSSLPrivKey):
os.remove(pathToStoreSSLPrivKey)
if os.path.exists(pathToStoreSSLFullChain):
os.remove(pathToStoreSSLFullChain)
shutil.copy(srcPrivKey, pathToStoreSSLPrivKey)
shutil.copy(srcFullChain, pathToStoreSSLFullChain)
return 1
elif output.find('no action taken.') > -1:
return 1
elif output.find('Failed authorization procedure') > -1:
logging.CyberCPLogFileWriter.writeToFile('Failed authorization procedure for ' + virtualHostName + " while issuing Let's Encrypt SSL.")
return 0
elif output.find('Too many SSL requests for this domain, please try to get SSL at later time.') > -1:
logging.CyberCPLogFileWriter.writeToFile(
'Too many SSL requests for ' + virtualHostName + " please try to get SSL at later time.")
return 0
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Failed to obtain SSL. [obtainSSLForADomain]]")
return 0
def issueSSLForDomain(domain,adminEmail,sslpath, aliasDomain = None):
try:
if sslUtilities.obtainSSLForADomain(domain, adminEmail, sslpath, aliasDomain) == 1:
if sslUtilities.installSSLForDomain(domain) == 1:
return [1, "None"]
else:
return [0, "210 Failed to install SSL for domain. [issueSSLForDomain]"]
else:
pathToStoreSSL = sslUtilities.Server_root + "/conf/vhosts/" + "SSL-" + domain
if not os.path.exists(pathToStoreSSL):
os.mkdir(pathToStoreSSL)
pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem"
pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem"
command = 'openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout ' + pathToStoreSSLPrivKey + ' -out ' + pathToStoreSSLFullChain
cmd = shlex.split(command)
subprocess.call(cmd)
if sslUtilities.installSSLForDomain(domain) == 1:
logging.CyberCPLogFileWriter.writeToFile("Self signed SSL issued for " + domain + ".")
return [1, "None"]
else:
return [0, "220 Failed to install SSL for domain. [issueSSLForDomain]"]
except BaseException,msg:
return [0, "347 "+ str(msg)+ " [issueSSLForDomain]"]

29
CyberTronAPI/test.py Executable file
View File

@@ -0,0 +1,29 @@
#!/usr/local/CyberCP/bin/python2
import os,sys
sys.path.append('/usr/local/CyberCP')
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
import threading as multi
from CyberTronLogger import CyberTronLogger as logger
from inspect import stack
from shlex import split
from subprocess import call,CalledProcessError
from os.path import join
from random import randint
from logLevel import logLevel
from ipManagement.models import IPAddresses
from packages.models import VMPackage as Package
from django.db.models import Max
import CyberTronAPI.randomPassword as randomPassword
from vpsManagement.models import VPS
from loginSystem.models import Administrator
from CyberTronAPI.virtualMachineAPIKVM import virtualMachineAPI
def setupVMDisk():
command = 'sudo virt-builder centos-7.2 -o /var/lib/libvirt/images/199.241.188.139.qcow2 --size 100G --root-password password:9xvps --upload /home/cyberpanel/ifcfg-ens384536:/etc/sysconfig/network-scripts/ifcfg-eth0 --upload /home/cyberpanel/network_62835:/etc/sysconfig/network --upload /home/cyberpanel/resolv_80440:/etc/resolv.conf'
result = call(split(command))
setupVMDisk()

638
CyberTronAPI/virtualMachineAPI.py Executable file
View File

@@ -0,0 +1,638 @@
from CyberTronLogger import CyberTronLogger as logger
from inspect import stack
from shlex import split
from subprocess import call,CalledProcessError
from os.path import join
from os import remove
from random import randint
from shutil import move
import libvirt
from logLevel import logLevel
class virtualMachineAPI:
## os.path.join
templatesPath = join('/var','lib','libvirt','templates')
imagesPath = join('/var','lib','libvirt','images')
@staticmethod
def setupNetworkingFiles(vmName, osName, ipAddress, netmask, gateway, hostName):
try:
if logLevel.debug == True:
logger.operationsLog('Setting up network for: ' + vmName + '.', 'Debug', stack()[0][3])
uploadSource = []
if osName.find("centos") > -1:
###### /etc/sysconfig/network-scripts/ifcfg-eth0
eth0 = "ifcfg-eth0_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('DEVICE="eth0"\n')
eth0File.writelines('NM_CONTROLLED="yes"\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('BOOTPROTO=static\n')
eth0File.writelines('NAME="System eth0"\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + netmask + '\n')
eth0File.close()
uploadSource.append(eth0)
###### /etc/sysconfig/network
network = "network_" + str(randint(10000, 99999) + 1)
networkFile = open(network, 'w')
networkFile.writelines('NETWORKING=yes\n')
networkFile.writelines('HOSTNAME=' + hostName + '\n')
networkFile.writelines('GATEWAY=' + gateway + '\n')
networkFile.close()
uploadSource.append(network)
###### /etc/resolv.conf
resolv = "resolv_" + str(randint(10000, 99999) + 2)
resolvFile = open(resolv, 'w')
resolvFile.writelines("nameserver 8.8.8.8\n")
resolvFile.close()
uploadSource.append(resolv)
elif osName.find("debian") > -1 or osName.find("ubuntu") > -1:
###### /etc/network/interfaces
eth0 = "interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('# This file describes the network interfaces available on your system\n')
eth0File.writelines('# and how to activate them. For more information, see interfaces(5).\n')
eth0File.writelines('\n')
eth0File.writelines('# The loopback network interface\n')
eth0File.writelines('auto lo\n')
eth0File.writelines('iface lo inet loopback\n')
eth0File.writelines('\n')
## To deal with Debian 9.3 and ubuntu 16.04 issue.
eth0File.writelines('# The primary network interface\n')
if osName == "debian-9.3.x64" or osName == "ubuntu-16.04.x32" or osName == "ubuntu-16.04.x64" or osName == "ubuntu-17.10.x64":
eth0File.writelines('allow-hotplug ens3\n')
eth0File.writelines('iface ens3 inet static\n')
else:
eth0File.writelines('allow-hotplug eth0\n')
eth0File.writelines('iface eth0 inet static\n')
eth0File.writelines(' address '+ipAddress+'\n')
eth0File.writelines(' netmask ' + netmask +'\n')
eth0File.writelines(' gateway ' + gateway + '\n')
eth0File.writelines('# dns-* options are implemented by the resolvconf package, if installed\n')
eth0File.writelines('dns-nameservers 8.8.8.8\n')
eth0File.writelines('dns-search com\n')
eth0File.close()
uploadSource.append(eth0)
elif osName.find("fedora") > -1:
###### /etc/sysconfig/network-scripts/ifcfg-ens3
eth0 = "interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('PROXY_METHOD=none\n')
eth0File.writelines('BROWSER_ONLY=no\n')
eth0File.writelines('BOOTPROTO=none\n')
eth0File.writelines('DEFROUTE=yes\n')
eth0File.writelines('IPV4_FAILURE_FATAL=no\n')
eth0File.writelines('IPV6INIT=yes\n')
eth0File.writelines('IPV6_AUTOCONF=yes\n')
eth0File.writelines('IPV6_DEFROUTE=yes\n')
eth0File.writelines('IPV6_FAILURE_FATAL=no\n')
eth0File.writelines('IPV6_ADDR_GEN_MODE=stable-privacy\n')
eth0File.writelines('NAME=ens3\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('AUTOCONNECT_PRIORITY=-999\n')
eth0File.writelines('DEVICE=ens3\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + netmask + '\n')
eth0File.writelines('GATEWAY=' + gateway + '\n')
eth0File.writelines('DNS1=8.8.8.8\n')
eth0File.writelines('IPV6_PRIVACY=no\n')
eth0File.close()
uploadSource.append(eth0)
elif osName.find("freebsd") > -1:
###### /etc/rc.conf
eth0 = "ifcfg-eth0_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('DEVICE="eth0"\n')
eth0File.writelines('NM_CONTROLLED="yes"\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('BOOTPROTO=static\n')
eth0File.writelines('NAME="System eth0"\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + netmask + '\n')
eth0File.close()
uploadSource.append(eth0)
if logLevel.debug == True:
logger.operationsLog('Network settings installed for: ' + vmName + '.', 'Debug', stack()[0][3])
return uploadSource
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
'''
vmName = Usually IP Address.
osName = Examples operatingSystem-X.xx.x86
uploadSource = An array containing complete path of files to be uploaded to the image after creation.
rootPassword = Virtual Machine root password.
'''
@staticmethod
def setupVMDisk(vmName, osName, size, uploadSource, rootPassword):
try:
if logLevel.debug == True:
logger.operationsLog('Creating disk image for: ' + vmName + '.', 'Debug', stack()[0][3])
sourcePath = join(virtualMachineAPI.templatesPath,osName+".qcow2")
tempPath = join(virtualMachineAPI.imagesPath,vmName+"-temp.qcow2")
finalPath = join(virtualMachineAPI.imagesPath,vmName+".qcow2")
## Build upload command
uploadCommand = ""
if osName.find('centos') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/sysconfig/network-scripts/ifcfg-eth0"
uploadCommand = uploadCommand + " --upload " + uploadSource[1] + ":" + "/etc/sysconfig/network"
uploadCommand = uploadCommand + " --upload " + uploadSource[2] + ":" + "/etc/resolv.conf"
elif osName.find('debian') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/network/interfaces" + " --firstboot-command 'apt-get purge openssh-server -y' --firstboot-command 'apt-get install openssh-server -y'"
elif osName.find('ubuntu') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/network/interfaces" + " --firstboot-command 'apt-get remove openssh-server -y' --firstboot-command 'apt-get install openssh-server -y'"
elif osName.find('fedora') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/sysconfig/network-scripts/ifcfg-ens3" + " --firstboot-command 'yum erase openssh-server -y' --firstboot-command 'yum install openssh-server -y'"
## Creating temporary disk image.
command = "qemu-img create -b " + sourcePath + " -f qcow2 " + tempPath
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Temporary image created for: " + vmName + ".", "Debug", stack()[0][3])
## Checking size, if less or = 3GB, no need to resize.
if int(size) <= 3:
move(tempPath, finalPath)
if logLevel.debug == True:
logger.operationsLog("Image successfully prepared for: " + vmName + ".", "Debug", stack()[0][3])
else:
command = "qemu-img create -f qcow2 " + finalPath + " " + size + "G"
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Created resized final image for: " + vmName + ".", "Debug", stack()[0][3])
if osName == "centos-7.4.x64":
command = "virt-resize --expand /dev/sda2 --lv-expand /dev/centos/root " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
elif osName == "centos-6.9.x64" or osName == "centos-6.9.x32":
command = "virt-resize --expand /dev/sda2 --lv-expand /dev/VolGroup/lv_root " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
elif osName == "debian-7.11.x32" or osName == "debian-7.11.x64":
command = "virt-resize --expand /dev/sda1 --lv-expand /dev/debian/root " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
elif osName == "debian-8.10.x32" or osName == "debian-8.10.x64" or osName == "debian-9.3.x64":
command = "virt-resize --expand /dev/sda2 --lv-expand /dev/debian/root " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
elif osName == "fedora-27.x64" or osName == "fedora-26.x64":
command = "virt-resize --expand /dev/sda2 --lv-expand /dev/fedora/root " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
elif osName == "ubuntu-14.04.x32" or osName == "ubuntu-14.04.x64" or osName == "ubuntu-16.04.x32" or osName == "ubuntu-16.04.x64" or osName == "ubuntu-17.10.x64":
command = "virt-resize --expand /dev/sda2 --lv-expand /dev/ubuntu/root " + tempPath + " " + finalPath
result = call(split(command))
if result == 1:
remove(tempPath)
raise CalledProcessError
else:
remove(tempPath)
if logLevel.debug == True:
logger.operationsLog("Disk resized and ready to use for: " + vmName + ".", "Debug",
stack()[0][3])
## Setup network and customize root password
command = "virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand
call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Root password and network configured for: " + vmName + ".", "Debug",
stack()[0][3])
return 1
return 1
except BaseException,msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError,msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
"""
Function to create Virtual Machine Disk, which can than be used to create virtual machine.
vmName = Name of vps, this will be combined with imgDestination and format.
osName = Name of OS, with which this image should be created.
vmDestination = Destination on disk where this image should be placed.
size = Size in GBs.
format = Examples, qcow2, img, qcow, recommend is qcow2.
uploadSource = An array containing complete path of files to be uploaded to the image after creation.
debug = Enable or disable extended debug logging. Defaults to false.
"""
@staticmethod
def createVirtualMachineDisk(vmName, osName , vmDestination, size, format, uploadSource):
try:
if logLevel.debug == True:
logger.operationsLog('Creating disk image for: ' + vmName + '.', 'Debug', stack()[0][3])
## Build upload command
uploadCommand = ""
if osName.find('centos') > -1:
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/sysconfig/network-scripts/ifcfg-eth0"
uploadCommand = uploadCommand + " --upload " + uploadSource[1] + ":" + "/etc/sysconfig/network"
uploadCommand = uploadCommand + " --upload " + uploadSource[2] + ":" + "/etc/resolv.conf"
## Final Image Location -- finalImageLocation = /var/lib/libvirt/192.168.100.1.qcow2
finalImageLocation = join(vmDestination, vmName + "." + format)
## "virt-builder centos-7.1 -o /var/lib/libvirt/images192.168.100.1.qcow2 --size 50G --format qcow2 --upload ifcfg-eth0:/etc/sysconfig/network-scripts/ --upload network:/etc/sysconfig
command = "virt-builder " + osName + " -o " + finalImageLocation + " --size " + size + " --format " + format + uploadCommand
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Disk image created for: " + vmName + ".", "Debug", stack()[0][3])
## Remove temporary generated files
#for tempFiles in uploadSource:
#remove(tempFiles)
return 1
except BaseException,msg:
if logLevel.debug == True:
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError,msg:
if logLevel.debug == True:
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
"""
vmName = Name of the virtual machine, usually the IP Address.
vmRam = Ram to be assigned to this virtual machine.
vmVCPUs = Virtual CPUs to be assigned to this virtual machine.
vmDestination = Path where VM image will be housed.
format = Examples, qcow2, img, qcow, recommend is qcow2.
vncPort = VNC Port for this virtual machine.
osType = OS Type e.g. linux,windows.
osVariant = OS Variant e.g. centos 6, centos 7.
bridgeName = Bridge name to which the interface of this VM will be attached.
debug = Enable or disable extended debug logging. Defaults to false.
"""
@staticmethod
def bootVirtualMachine(vmName, vmRam, vmVCPUs, vncHost, vncPort, osType, osVariant, bridgeName):
try:
if logLevel.debug == True:
logger.operationsLog('Booting: ' + vmName + '.','Debug',stack()[0][3])
finalImageLocation = join(virtualMachineAPI.imagesPath,vmName+".qcow2")
# virt-install --name 109.238.12.214 --ram 2048 --vcpus=1 --disk 109.238.12.214.qcow2 --graphics vnc,listen=localhost,port=5500 --noautoconsole --hvm --import --os-type=linux --os-variant=rhel7 --network bridge=virbr0
command = "virt-install --name " + vmName + " --ram " + vmRam + " --vcpu " + vmVCPUs + " --disk " + \
finalImageLocation + " --graphics vnc,listen=" +vncHost + ",port=" + vncPort + \
" --noautoconsole --hvm --import --autostart --os-type=" + osType + " --os-variant=" + \
osVariant + " --network bridge=" + bridgeName
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Successfully booted: " + vmName + ".", "Debug", stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
"""
osName = Name of OS, with which this image should be created.
imgDestination = Destination on disk where this image should be placed.
imgName = Name of vps, this will be combined with imgDestination.
size = Size in GBs.
format = Examples, qcow2, img, qcow, recommend is qcow2.
uploadSource = An array containing complete path of files to be uploaded to the image after creation.
UploadDestination = Corressponding array of upload source, defining upload destination of files.
--
vmName = Name of the virtual machine, usually the IP Address.
vmRam = Ram to be assigned to this virtual machine.
vmVCPUs = Virtual CPUs to be assigned to this virtual machine.
diskImage = A complete path to disk image for this virtual machine.
vncPort = VNC Port for this virtual machine.
osType = OS Type e.g. linux,windows.
osVariant = OS Variant e.g. centos 6, centos 7.
bridgeName = Bridge name to which the interface of this VM will be attached.
"""
@staticmethod
def createVirtualMachine(vmName, osName, rootPassword, size, vncHost, vmRam, vmVCPUs, vncPort, osType, osVariant, bridgeName, ipAddress, netmask, gateway, hostName):
try:
logger.operationsLog('Starting to create virtual machine: ' + vmName, 'Info', stack()[0][3])
##
uploadSource = virtualMachineAPI.setupNetworkingFiles(vmName, osName, ipAddress, netmask, gateway, hostName)
##
if virtualMachineAPI.setupVMDisk(vmName, osName, size, uploadSource, rootPassword) == 0:
return 0
##
if virtualMachineAPI.bootVirtualMachine(vmName, vmRam, vmVCPUs, vncHost, vncPort, osType, osVariant, bridgeName) == 0:
return 0
##
logger.operationsLog('Virtual machine ' + vmName + ' successfully created.', 'Success', stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def deleteVirtualMachine(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.hasCurrentSnapshot():
snapShots = virtualMachine.listAllSnapshots()
for snapShot in snapShots:
snapShot.delete()
if virtualMachine.isActive():
virtualMachine.destroy()
virtualMachine.undefine()
## Removing virtual machine file.
try:
pathToImg = join(virtualMachineAPI.imagesPath, virtualMachineName + '.qcow2')
remove(pathToImg)
except BaseException,msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
##
return 1,'No error.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def obtainVirtualMachineObject(virtualMachineName):
try:
connection = libvirt.open('qemu:///system')
if connection == None:
return 0, 'Failed to establish connection.'
virtualMachine = connection.lookupByName(virtualMachineName)
if virtualMachine == None:
return 0, 'Can not find virtual machine.'
return 1,virtualMachine
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def revertToSnapshot(virtualMachineName, snapshotName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
snapshot = virtualMachine.snapshotLookupByName(snapshotName)
virtualMachine.revertToSnapshot(snapshot)
return 1, 'No error.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def softReboot(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.reboot():
return 1, 'No error.'
else:
return 0,'Failed to reboot.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def hardShutdown(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.destroy():
return 1, 'No error.'
else:
return 0,'Failed to shutdown.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
virtualMachineAPI.createVirtualMachine('192.111.145.235','centos-7.4.x64',"litespeedtech","50",'192.111.145.234','2048','2','5900','linux','rhel7','virbr0','192.111.145.235','255.255.255.248','192.111.145.233','usman.cybertronproject.com')
#print virtualMachineAPI.deleteVirtualMachine('109.238.12.214')
#print virtualMachineAPI.revertToSnapshot('109.238.12.214','CyberPanel')
#virtualMachineAPI.softReboot('109.238.12.214')

View File

@@ -0,0 +1,613 @@
from CyberTronLogger import CyberTronLogger as logger
from inspect import stack
from shlex import split
from subprocess import call,CalledProcessError
from os.path import join
from os import remove, path
from random import randint
import libvirt
from logLevel import logLevel
from xml.etree import ElementTree
class virtualMachineAPI:
## os.path.join
templatesPath = join('/var','lib','libvirt','templates')
imagesPath = join('/var','lib','libvirt','images')
@staticmethod
def obtainVirtualMachineObject(virtualMachineName):
try:
connection = libvirt.open('qemu:///system')
if connection == None:
return 0, 'Failed to establish connection.'
virtualMachine = connection.lookupByName(virtualMachineName)
if virtualMachine == None:
return 0, 'Can not find virtual machine.'
return 1, virtualMachine
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def limitVMSpeed(vpsID, vpsIP, interface, interfaceLimit):
try:
## Creating class
command = 'tc class add dev ' + interface + ' parent 2:1 classid ' + '2:' + vpsID + ' htb rate ' + interfaceLimit
logger.writeToFile(command,'Info',stack()[0][3])
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
## Create IP Filter.
command = 'tc filter add dev ' + interface + ' parent 2:0 protocol ip prio 1 u32 match ip src ' + vpsIP + ' flowid 2:' + vpsID
logger.writeToFile(command,'Info',stack()[0][3])
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def removeVMSpeedLimit(vpsID, interface):
try:
## Removing filter.
command = 'tc filter del dev ' + interface + ' parent 2:0 protocol ip prio 1 u32 flowid 2:' + vpsID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
## Removing class.
command = 'tc class del dev ' + interface + ' classid 2:' + vpsID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def deleteVirtualMachine(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.hasCurrentSnapshot():
snapShots = virtualMachine.listAllSnapshots()
for snapShot in snapShots:
snapShot.delete()
if virtualMachine.isActive():
virtualMachine.destroy()
virtualMachine.undefine()
## Removing virtual machine file.
try:
pathToImg = join(virtualMachineAPI.imagesPath, virtualMachineName + '.qcow2')
remove(pathToImg)
except BaseException,msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
##
return 1,'No error.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def revertToSnapshot(virtualMachineName, snapshotName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
snapshot = virtualMachine.snapshotLookupByName(snapshotName)
virtualMachine.revertToSnapshot(snapshot)
return 1, 'No error.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def softReboot(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.isActive():
virtualMachine.reboot()
return 1, 'No error.'
else:
command = 'virsh start ' + virtualMachineName
call(split(command))
return 1, 'No error.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def hardShutdown(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.isActive():
virtualMachine.destroy()
return 1, 'No error.'
else:
return 0, 'VPS is not running.'
else:
return 0,'Failed to obtain virtual machine object.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def setupNetworkingFiles(vmName, ipAddress, netmask, gateway, hostName):
try:
if logLevel.debug == True:
logger.operationsLog('Setting up network for: ' + vmName + '.', 'Debug', stack()[0][3])
uploadSource = []
###### /etc/sysconfig/network-scripts/ifcfg-eth0
eth0 = "ifcfg-eth0_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('DEVICE="eth0"\n')
eth0File.writelines('NM_CONTROLLED="yes"\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('BOOTPROTO=static\n')
eth0File.writelines('NAME="System eth0"\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + netmask + '\n')
eth0File.close()
uploadSource.append(eth0)
###### /etc/sysconfig/network
network = "network_" + str(randint(10000, 99999) + 1)
networkFile = open(network, 'w')
networkFile.writelines('NETWORKING=yes\n')
networkFile.writelines('HOSTNAME=' + hostName + '\n')
networkFile.writelines('GATEWAY=' + gateway + '\n')
networkFile.close()
uploadSource.append(network)
###### /etc/resolv.conf
resolv = "resolv_" + str(randint(10000, 99999) + 2)
resolvFile = open(resolv, 'w')
resolvFile.writelines("nameserver 8.8.8.8\n")
resolvFile.close()
uploadSource.append(resolv)
if logLevel.debug == True:
logger.operationsLog('Network settings installed for: ' + vmName + '.', 'Debug', stack()[0][3])
return uploadSource
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
'''
vmName = Usually IP Address.
osName = Examples operatingSystem-X.xx.x86
uploadSource = An array containing complete path of files to be uploaded to the image after creation.
rootPassword = Virtual Machine root password.
'''
@staticmethod
def setupVMDisk(vmName, package, uploadSource, rootPassword):
try:
if logLevel.debug == True:
logger.operationsLog('Creating disk image for: ' + vmName + '.', 'Debug', stack()[0][3])
sourcePath = join(virtualMachineAPI.templatesPath, package + ".qcow2")
finalPath = join(virtualMachineAPI.imagesPath, vmName + ".qcow2")
## Build upload command
uploadCommand = ""
uploadCommand = " --upload " + uploadSource[0] + ":" + "/etc/sysconfig/network-scripts/ifcfg-eth0"
uploadCommand = uploadCommand + " --upload " + uploadSource[1] + ":" + "/etc/sysconfig/network"
uploadCommand = uploadCommand + " --upload " + uploadSource[2] + ":" + "/etc/resolv.conf"
## Creating temporary disk image.
command = "qemu-img create -b " + sourcePath + " -f qcow2 " + finalPath
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Temporary image created for: " + vmName + ".", "Debug", stack()[0][3])
## Setup network and customize root password
command = "virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand
call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Root password and network configured for: " + vmName + ".", "Debug",
stack()[0][3])
return 1
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
"""
vmName = Name of the virtual machine, usually the IP Address.
vmRam = Ram to be assigned to this virtual machine.
vmVCPUs = Virtual CPUs to be assigned to this virtual machine.
vmDestination = Path where VM image will be housed.
format = Examples, qcow2, img, qcow, recommend is qcow2.
vncPort = VNC Port for this virtual machine.
osType = OS Type e.g. linux,windows.
osVariant = OS Variant e.g. centos 6, centos 7.
bridgeName = Bridge name to which the interface of this VM will be attached.
debug = Enable or disable extended debug logging. Defaults to false.
"""
@staticmethod
def bootVirtualMachine(vmName, vmVCPUs, vmRam, vncHost, vncPort, bridgeName, webSocketPort, vncPassword):
try:
if logLevel.debug == True:
logger.operationsLog('Booting: ' + vmName + '.', 'Debug', stack()[0][3])
finalImageLocation = join(virtualMachineAPI.imagesPath, vmName + ".qcow2")
# virt-install --name 109.238.12.214 --ram 2048 --vcpus=1 --disk 109.238.12.214.qcow2 --graphics vnc,listen=localhost,port=5500 --noautoconsole --hvm --import --os-type=linux --os-variant=rhel7 --network bridge=virbr0
command = "virt-install --name " + vmName + " --ram " + vmRam + " --vcpu " + vmVCPUs + " --disk " + \
finalImageLocation + " --graphics vnc,listen=" + vncHost + ",port=" + vncPort + ",password=" + vncPassword + \
' --qemu-commandline=' + '"' + '-vnc :' + webSocketPort + ',websocket' + '"' + \
" --noautoconsole --hvm --import --autostart --os-type=linux " \
+ "--network bridge=" + bridgeName
logger.writeToFile(command,"Info", stack()[0][3])
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Successfully booted: " + vmName + ".", "Debug", stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
"""
osName = Name of OS, with which this image should be created.
imgDestination = Destination on disk where this image should be placed.
imgName = Name of vps, this will be combined with imgDestination.
size = Size in GBs.
format = Examples, qcow2, img, qcow, recommend is qcow2.
uploadSource = An array containing complete path of files to be uploaded to the image after creation.
UploadDestination = Corressponding array of upload source, defining upload destination of files.
--
vmName = Name of the virtual machine, usually the IP Address.
vmRam = Ram to be assigned to this virtual machine.
vmVCPUs = Virtual CPUs to be assigned to this virtual machine.
diskImage = A complete path to disk image for this virtual machine.
vncPort = VNC Port for this virtual machine.
osType = OS Type e.g. linux,windows.
osVariant = OS Variant e.g. centos 6, centos 7.
bridgeName = Bridge name to which the interface of this VM will be attached.
"""
@staticmethod
def createVirtualMachine(vmName, package, rootPassword, vmVCPUs, vmRam, vncHost, vncPort, bridgeName, ipAddress, netmask, gateway, hostName, webSocketPort, vncPassword):
try:
logger.operationsLog('Starting to create virtual machine: ' + vmName, 'Info', stack()[0][3])
##
uploadSource = virtualMachineAPI.setupNetworkingFiles(vmName, ipAddress, netmask, gateway, hostName)
##
if virtualMachineAPI.setupVMDisk(vmName, package, uploadSource, rootPassword) == 0:
return 0
##
if virtualMachineAPI.bootVirtualMachine(vmName, vmVCPUs, vmRam, vncHost, vncPort, bridgeName, webSocketPort, vncPassword) == 0:
return 0
##
logger.operationsLog('Virtual machine ' + vmName + ' successfully created.', 'Success', stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
#virtualMachineAPI.createVirtualMachine('192.111.145.237', 'forthPlan', 'litespeed12', '2', '2048', '192.111.145.234', '5904','virbr0','192.111.145.237','255.255.255.248','192.111.145.233','usman.cybertronproject.com')
#print virtualMachineAPI.deleteVirtualMachine('109.238.12.214')
#print virtualMachineAPI.revertToSnapshot('109.238.12.214','CyberPanel')
#virtualMachineAPI.softReboot('109.238.12.214')
@staticmethod
def isActive(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.isActive():
return 1
else:
return 0
else:
return 0
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def getCurrentUsedRam(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.isActive():
memStats = virtualMachine.memoryStats()
return int(memStats['unused']/1024)
else:
return 0
else:
return 0
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def getBandwidthUsage(virtualMachineName):
try:
obtainStatus, virtualMachine = virtualMachineAPI.obtainVirtualMachineObject(virtualMachineName)
if obtainStatus == 1:
if virtualMachine.isActive():
tree = ElementTree.fromstring(virtualMachine.XMLDesc())
iface = tree.find('devices/interface/target').get('dev')
memStats = virtualMachine.interfaceStats(iface)
## memStats[0] are read bytes, memStats[4] write bytes
return (memStats[0] + memStats[4])/(1024 * 1024)
else:
return 0
else:
return 0
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def calculateDiskPercentage(virtualMachineName, actualDisk):
try:
vpsImagePath = '/var/lib/libvirt/images/' + virtualMachineName + ".qcow2"
sizeInMB = float(path.getsize(vpsImagePath)) / (1024.0 * 1024)
diskUsagePercentage = float(100) / float((int(actualDisk.rstrip('GB')) * 1024))
diskUsagePercentage = float(diskUsagePercentage) * float(sizeInMB)
diskUsagePercentage = int(diskUsagePercentage)
if diskUsagePercentage > 100:
return 100, sizeInMB
return diskUsagePercentage, sizeInMB
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0,0
@staticmethod
def calculateRamPercentage(virtualMachineName, actualRam):
try:
unUsedRam = virtualMachineAPI.getCurrentUsedRam(virtualMachineName)
usedRam = int(actualRam.rstrip('MB')) - unUsedRam
ramUsagePercentage = float(100) / int(actualRam.rstrip('MB'))
ramUsagePercentage = int(float(ramUsagePercentage) * float(usedRam))
if ramUsagePercentage > 100:
return 100
return ramUsagePercentage
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def calculateBWPercentage(virtualMachineName, actualBW):
try:
usedBW = virtualMachineAPI.getBandwidthUsage(virtualMachineName)
availBW = int(actualBW.rstrip('TB')) * 1024 * 1024
bwPercentage = float(100) / availBW
bwPercentage = int(float(bwPercentage) * usedBW)
if bwPercentage > 100:
return 100
return bwPercentage
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def changeHostname(virtualMachineName, newHostname):
try:
command = "virt-customize -d " + virtualMachineName + " --hostname " + newHostname
call(split(command))
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def changeRootPassword(virtualMachineName, newPassword):
try:
command = "virt-customize -d " + virtualMachineName + " --root-password password:" + newPassword
call(split(command))
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def createSnapshot(virtualMachineName, snapshotName):
try:
command = "virsh snapshot-create-as --domain " + virtualMachineName + " --name " + snapshotName
call(split(command))
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def deleteSnapshot(virtualMachineName, snapshotName):
try:
command = "virsh snapshot-delete --domain " + virtualMachineName + " --snapshotname " + snapshotName
call(split(command))
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)

View File

@@ -0,0 +1,668 @@
from CyberTronLogger import CyberTronLogger as logger
from inspect import stack
from shlex import split
from subprocess import call, CalledProcessError
from os.path import join
from os import remove,path
from random import randint
from shutil import move
from time import sleep
from logLevel import logLevel
from multiprocessing import Process
class virtualMachineAPIOpenVZ:
## os.path.join
templatesPath = join('/var', 'lib', 'libvirt', 'templates')
imagesPath = join('/vz', 'root')
defaultInterface = 'eth0'
backupPath = join('/vz','dump')
@staticmethod
def setupNetworkingFiles(vmName, osName, ipAddress, netmask, gateway, hostName):
try:
if logLevel.debug == True:
logger.operationsLog('Setting up network for: ' + vmName + '.', 'Debug', stack()[0][3])
uploadSource = []
if osName.find("centos") > -1:
###### /etc/sysconfig/network-scripts/ifcfg-eth0
eth0 = "ifcfg-eth0_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('DEVICE="eth0"\n')
eth0File.writelines('NM_CONTROLLED="yes"\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('BOOTPROTO=static\n')
eth0File.writelines('NAME="System eth0"\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + netmask + '\n')
eth0File.close()
uploadSource.append(eth0)
###### /etc/sysconfig/network
network = "network_" + str(randint(10000, 99999) + 1)
networkFile = open(network, 'w')
networkFile.writelines('NETWORKING=yes\n')
networkFile.writelines('HOSTNAME=' + hostName + '\n')
networkFile.writelines('GATEWAY=' + gateway + '\n')
networkFile.close()
uploadSource.append(network)
###### /etc/resolv.conf
resolv = "resolv_" + str(randint(10000, 99999) + 2)
resolvFile = open(resolv, 'w')
resolvFile.writelines("nameserver 8.8.8.8\n")
resolvFile.close()
uploadSource.append(resolv)
elif osName.find("debian") > -1 or osName.find("ubuntu") > -1:
###### /etc/network/interfaces
eth0 = "interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('# This file describes the network interfaces available on your system\n')
eth0File.writelines('# and how to activate them. For more information, see interfaces(5).\n')
eth0File.writelines('\n')
eth0File.writelines('# The loopback network interface\n')
eth0File.writelines('auto lo\n')
eth0File.writelines('iface lo inet loopback\n')
eth0File.writelines('\n')
## To deal with Debian 9.3 and ubuntu 16.04 issue.
eth0File.writelines('# The primary network interface\n')
eth0File.writelines('allow-hotplug eth0\n')
eth0File.writelines('iface eth0 inet static\n')
eth0File.writelines(' address ' + ipAddress + '\n')
eth0File.writelines(' netmask ' + netmask + '\n')
eth0File.writelines(' gateway ' + gateway + '\n')
eth0File.writelines('# dns-* options are implemented by the resolvconf package, if installed\n')
eth0File.writelines('dns-nameservers 8.8.8.8\n')
eth0File.writelines('dns-search com\n')
eth0File.close()
uploadSource.append(eth0)
elif osName.find("fedora") > -1:
###### /etc/sysconfig/network-scripts/ifcfg-ens3
eth0 = "interfaces_" + str(randint(10000, 99999))
eth0File = open(eth0, 'w')
eth0File.writelines('TYPE=Ethernet\n')
eth0File.writelines('PROXY_METHOD=none\n')
eth0File.writelines('BROWSER_ONLY=no\n')
eth0File.writelines('BOOTPROTO=none\n')
eth0File.writelines('DEFROUTE=yes\n')
eth0File.writelines('IPV4_FAILURE_FATAL=no\n')
eth0File.writelines('IPV6INIT=yes\n')
eth0File.writelines('IPV6_AUTOCONF=yes\n')
eth0File.writelines('IPV6_DEFROUTE=yes\n')
eth0File.writelines('IPV6_FAILURE_FATAL=no\n')
eth0File.writelines('IPV6_ADDR_GEN_MODE=stable-privacy\n')
eth0File.writelines('NAME=eth0\n')
eth0File.writelines('ONBOOT=yes\n')
eth0File.writelines('AUTOCONNECT_PRIORITY=-999\n')
eth0File.writelines('DEVICE=eth0\n')
eth0File.writelines('IPADDR=' + ipAddress + '\n')
eth0File.writelines('NETMASK=' + netmask + '\n')
eth0File.writelines('GATEWAY=' + gateway + '\n')
eth0File.writelines('DNS1=8.8.8.8\n')
eth0File.writelines('IPV6_PRIVACY=no\n')
eth0File.close()
uploadSource.append(eth0)
if logLevel.debug == True:
logger.operationsLog('Network settings installed for: ' + vmName + '.', 'Debug', stack()[0][3])
return uploadSource
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def createContainer(vmName, containerID, osTemplate):
try:
command = "vzctl create " + containerID + " --ostemplate " + osTemplate
result = call(split(command))
if result == 1:
raise CalledProcessError
if logLevel.debug == True:
logger.operationsLog("Container successfully created for: " + vmName + ".", "Debug",
stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def bootVirtualMachine(vmName, osTemplate, containerID, rootPassword, hostName, macAddress, uploadSource, cpuUnits,
cpuPercentage, vmVCPUs, vmRam, vmSwap, burstVMRam, size,
dnsNSOne="8.8.8.8", dnsNSTwo="8.8.4.4",
ioPriority=3, uploadSpeed=0, bandwidthSuspend=1, debug=False):
try:
ioPriority = str(ioPriority)
command = "vzctl set " + containerID + " --save --name " + vmName + " --onboot yes --hostname " + hostName + \
" --netif_add eth0,,," + macAddress + " --nameserver " + dnsNSOne + " --nameserver " + dnsNSTwo + \
" --cpus " + vmVCPUs + " --ram " + vmRam + " --swap " + vmSwap + " --diskspace " + size + \
" --userpasswd root:" + rootPassword + " --ioprio " + ioPriority + " --cpuunits " + cpuUnits + \
" --cpulimit " + cpuPercentage
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
command = "vzctl start " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
sleep(2)
finalVMPath = join(virtualMachineAPIOpenVZ.imagesPath,containerID)
if osTemplate.find('centos') > -1:
move(uploadSource[0],finalVMPath + '/etc/sysconfig/network-scripts/ifcfg-eth0')
move(uploadSource[1], finalVMPath + '/etc/sysconfig/network')
move(uploadSource[2], finalVMPath + '/etc/resolv.conf')
elif osTemplate.find('debian') > -1:
move(uploadSource[0], finalVMPath + '/etc/network/interfaces')
elif osTemplate.find('ubuntu') > -1:
move(uploadSource[0], finalVMPath + '/etc/network/interfaces')
elif osTemplate.find('fedora') > -1:
move(uploadSource[0], finalVMPath + '/etc/sysconfig/network-scripts/ifcfg-eth0')
command = "vzctl exec " + containerID + " /etc/init.d/network restart"
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
"""
vmName = Name of the virtual machine, usually the IP Address.
containerID = Container ID of VPS, which usually identify OpenVZ VPS. Starts 100 and above.
osTemplate = osTemplate that will be used to boot OpenVZ Container.
rootPassword = VPS Root Password.
size = Size in GBs of OpenVZ Container.
vmRam = Guranteed dedicated virtual machine ram.
burstVMRam = Burstable ram, ram that VM can acquire if it is avaiable by host node.
bandwidth = Bandwidth allowed to container.
"""
@staticmethod
def createVirtualMachine(vmName, containerID, osTemplate, rootPassword, size, vmRam, vmSwap, burstVMRam, bandwidth, cpuUnits,
vmVCPUs,cpuPercentage, ipAddress, netmask, gateway, hostName, macAddress,
dnsNSOne = "8.8.8.8", dnsNSTwo = "8.8.4.4", networkSpeed = '0',
ioPriority = 3, uploadSpeed = 0, bandwidthSuspend = 1):
try:
logger.operationsLog('Starting to create virtual machine: ' + vmName, 'Info', stack()[0][3])
##
uploadSource = virtualMachineAPIOpenVZ.setupNetworkingFiles(vmName, osTemplate, ipAddress, netmask, gateway, hostName)
##
if virtualMachineAPIOpenVZ.createContainer(vmName, containerID, osTemplate) == 0:
raise BaseException("Failed to create container.")
##
if virtualMachineAPIOpenVZ.bootVirtualMachine(vmName, osTemplate, containerID, rootPassword, hostName, macAddress, uploadSource,
cpuUnits, cpuPercentage, vmVCPUs, vmRam, vmSwap, burstVMRam,
size, dnsNSOne, dnsNSTwo,
ioPriority, uploadSpeed,bandwidthSuspend) == 0:
raise BaseException("Failed to boot container.")
#if virtualMachineAPIOpenVZ.limitContainerSpeed(containerID, ipAddress, virtualMachineAPIOpenVZ.defaultInterface, networkSpeed) == 0:
# raise BaseException("Failed to set network limits.")
##
logger.operationsLog('Virtual machine ' + vmName + ' successfully created.', 'Success', stack()[0][3])
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def deleteVirtualMachine(containerID):
try:
result = virtualMachineAPIOpenVZ.hardShutdown(containerID)
if result[0] == 1:
command = "vzctl destroy " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1,'No error.'
else:
return 0, 'Failed to stop virtual machine.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def softReboot(containerID):
try:
command = "vzctl restart " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1,'No error.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def hardShutdown(containerID):
try:
command = "vzctl stop " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1,'No error.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def startContainer(containerID):
try:
command = "vzctl start " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1,'No error.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def suspendContainer(containerID):
try:
command = "vzctl suspend " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1,'No error.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def resumeContainer(containerID):
try:
command = "vzctl resume " + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1, 'No error.'
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0, str(msg)
@staticmethod
def limitContainerSpeed(containerID, containerIP, interface, interfaceLimit):
try:
## Creating class
command = 'tc class add dev ' + interface + ' parent 2:1 classid ' + '2:' + containerID + ' htb rate '+ interfaceLimit
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
## Create IP Filter.
command = 'tc filter add dev ' + interface + ' parent 2:0 protocol ip prio 1 u32 match ip src ' + containerIP + ' flowid 2:' + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def removeContainerSpeedLimit(containerID, interface):
try:
## Removing filter.
command = 'tc filter del dev ' + interface + ' parent 2:0 protocol ip prio 1 u32 flowid 2:' + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
## Removing class.
command = 'tc class del dev ' + interface + ' classid 2:' + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def createBackup(containerID, suspend = False , stop = False):
try:
statusFilePath = join(virtualMachineAPIOpenVZ.backupPath, 'vzdump-' + containerID + '.log')
if path.exists(statusFilePath):
remove(statusFilePath)
if suspend == True:
command = 'vzdump --compress --suspend ' + containerID
elif stop == True:
command = 'vzdump --compress --stop ' + containerID
else:
command = 'vzdump --compress ' + containerID
result = call(split(command))
if result == 1:
raise CalledProcessError
else:
pass
return 1
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def initiateBackup(containerID, suspend=False, stop=False):
try:
p = Process(target=virtualMachineAPIOpenVZ.createBackup, args=(containerID, suspend, stop,))
p.start()
# pid = open(backupPath + 'pid', "w")
# pid.write(str(p.pid))
# pid.close()
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
@staticmethod
def checkBackupCreationStatus(containerID):
try:
statusFilePath = join(virtualMachineAPIOpenVZ.backupPath,'vzdump-' + containerID + '.log')
statusFile = open(statusFilePath, 'r')
dataInStatusFile = statusFile.read()
statusFile.close()
if dataInStatusFile.find('Finished Backup of') > -1:
return 1,dataInStatusFile
else:
return 0,dataInStatusFile
except BaseException, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
except CalledProcessError, msg:
if logLevel.debug == True:
logger.operationsLog(str(msg), "Error", stack()[0][3])
logger.writeToFile(str(msg), "Error", stack()[0][3])
return 0
def main():
virtualMachineAPIOpenVZ.initiateBackup('105')
while(1):
retValue = virtualMachineAPIOpenVZ.checkBackupCreationStatus('105')
if retValue[0] == 0:
print retValue[1]
else:
print "Completed"
break
#main()
virtualMachineAPIOpenVZ.createVirtualMachine('192.111.145.235','102',"centos-7-x86_64-minimal","litespeed12",
'70G','4G','2G','6G','100GB','900','2','20%','192.111.145.235','255.255.255.248',
'192.111.145.233','cybertronproject.com','FE:FF:FF:FF:FF:FF', '8.8.8.8', '8.8.4.4',
'2Mbit', 4, 0, 1)
#virtualMachineAPIOpenVZ.removeContainerSpeedLimit('105','eth0')
#virtualMachineAPIOpenVZ.limitContainerSpeed('105','192.111.145.238','eth0','256Kbit')
#print virtualMachineAPI.deleteVirtualMachine('109.238.12.214')
#print virtualMachineAPI.revertToSnapshot('109.238.12.214','CyberPanel')
#virtualMachineAPIOpenVZ.deleteVirtualMachine('102')
#virtualMachineAPIOpenVZ.softReboot('102')
#virtualMachineAPIOpenVZ.hardShutdown('102')
#virtualMachineAPIOpenVZ.startContainer('102')

View File

@@ -1550,4 +1550,480 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) {
});
///** Backup site ends **///
///** Backup site ends **///
/////////////// Snapshots
/* Java script code for Snapshots */
app.controller('snapshotsCTRL', function($scope,$http) {
$scope.getCurrentSnapshots = function(){
$scope.tronLoading = false;
var url = "/backup/fetchCurrentSnapshots";
var data = {
hostName: $("#hostname").text()
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
$scope.snapshotTable = false;
if(response.data.success === 1){
$scope.snapshots = JSON.parse(response.data.data);
}
else
{
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page',
type:'error'
});
}
};
$scope.getCurrentSnapshots();
/// Administrative Tasks
$scope.tronLoading = true;
$scope.createSnapshotBox = true;
$scope.showSnapshotForm = function () {
$scope.createSnapshotBox = false;
$scope.createSnapshotBTN = true;
$scope.snapshotTable = true;
};
$scope.createSnapShot = function(){
$scope.tronLoading = false;
var url = "/backup/submitSnapshotCreation";
var data = {
hostName: $("#hostname").text(),
snapshotName: $scope.snapshotName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
$scope.getCurrentSnapshots();
$scope.createSnapshotBox = true;
$scope.createSnapshotBTN = false;
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.deleteSnapshot = function(snapshotName){
$scope.tronLoading = false;
var url = "/backup/deletSnapshot";
var data = {
hostName: $("#hostname").text(),
snapshotName: snapshotName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
$scope.getCurrentSnapshots();
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.revertToSnapshot = function(snapshotName){
$scope.tronLoading = false;
var url = "/backup/revertToSnapshot";
var data = {
hostName: $("#hostname").text(),
snapshotName: snapshotName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.changeRootPassword = function(vpsID){
$scope.tronLoading = false;
var url = "/vps/changeRootPassword";
var data = {
hostName: $("#vpsHostname").text(),
newPassword: $scope.newPassword
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
$scope.successMessage = response.data.successMessage;
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.reinstallOS = function(vpsID){
$scope.tronLoading = false;
var url = "/vps/reInstallOS";
var data = {
hostName: $("#vpsHostname").text(),
rootPassword: $scope.reinstallPassword
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
$scope.successMessage = response.data.successMessage;
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.restartVPS = function(vpsID){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/vps/restartVPS";
var data = {vpsID: vpsID};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
$scope.successMessage = response.data.successMessage;
$scope.getFurtherVPS(currentPageNumber);
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
$scope.shutdownVPS = function(vpsID){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/vps/shutdownVPS";
var data = {vpsID: vpsID};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
$scope.successMessage = response.data.successMessage;
$scope.getFurtherVPS(currentPageNumber);
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
});
/* Java script code for Snapshots ends here */

View File

@@ -0,0 +1,99 @@
{% extends "baseTemplate/index.html" %}
{% load i18n %}
{% block title %}{% trans "Create Snapshots - CyberTron" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div ng-controller="snapshotsCTRL" class="container">
<div id="page-title">
<h2>{% trans "Snapshots" %}</h2>
<p>{% trans "On this page you can create, delete or revert to Virtual Machine Snapshot." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Snapshots for" %} <span id="hostname">{{ hostName }}</span> <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row">
<!------ Modification form that appears after a click --------------->
<div ng-hide="createSnapshotBTN" class="form-group">
<div class="col-sm-4">
<button ng-click="showSnapshotForm()" class="btn ra-100 btn-blue-alt">{% trans 'Create Snapshot' %}</button>
</div>
</div>
<table ng-hide="snapshotTable" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" ng-hide="aliasTable">
<thead>
<tr>
<th>{% trans "ID" %}</th>
<th>{% trans "VPS Name" %}</th>
<th>{% trans "Snapshot Name" %}</th>
<th>{% trans "Creation Time" %}</th>
<th>{% trans "Operations" %}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="snapshot in snapshots track by $index">
<td ng-bind="snapshot.id"></td>
<td ng-bind="snapshot.hostname"></td>
<td ng-bind="snapshot.name"></td>
<td ng-bind="snapshot.creationTime"></td>
<td>
<button type="button" ng-click="revertToSnapshot(snapshot.name)" class="btn ra-100 btn-purple">{% trans "Revert" %}</button>
<button type="button" ng-click="deleteSnapshot(snapshot.name)" class="btn ra-100 btn-purple">{% trans "Delete" %}</button>
</td>
</tr>
</tbody>
</table>
<!------ Modification form that appears after a click --------------->
<hr>
<div ng-hide="createSnapshotBox">
<form action="/" class="form-horizontal bordered-row ng-scope ng-dirty ng-valid-parse ng-valid ng-valid-required">
<input type="hidden" ng-value="line" required="">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Snapshot Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control ng-pristine ng-untouched ng-not-empty ng-valid ng-valid-required" ng-model="snapshotName" required="">
</div>
</div>
<hr>
</form>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="createSnapShot()" class="btn btn-primary btn-lg btn-block">{% trans "Create Snapshot" %}</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -46,6 +46,14 @@ urlpatterns = [
url(r'^cancelRemoteBackup', views.cancelRemoteBackup, name='cancelRemoteBackup'),
## Snapshots
url(r'^revertToSnapshot$', views.revertToSnapshot, name='revertToSnapshot'),
url(r'^deletSnapshot$', views.deletSnapshot, name='deletSnapshot'),
url(r'^submitSnapshotCreation$', views.submitSnapshotCreation, name='submitSnapshotCreation'),
url(r'^fetchCurrentSnapshots$', views.fetchCurrentSnapshots, name='fetchCurrentSnapshots'),
url(r'^(?P<hostName>(.*))/snapshots$', views.createSnapshots, name='createSnapshots'),

View File

@@ -1,12 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import redirect
# Create your views here.
from django.shortcuts import redirect, HttpResponse, render
import json
from loginSystem.views import loadLoginPage
from plogical.backupManager import BackupManager
from loginSystem.models import Administrator
import plogical.CyberCPLogFileWriter as logging
from vpsManagement.vpsManager import VPSManager
def loadBackupHome(request):
try:
@@ -213,3 +214,46 @@ def cancelRemoteBackup(request):
return wm.cancelRemoteBackup(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)
## Snapshots
def createSnapshots(request, hostName):
try:
userID = request.session['userID']
vmm = VPSManager()
return vmm.createSnapshots(request, userID, hostName)
except KeyError:
return redirect(loadLoginPage)
def fetchCurrentSnapshots(request):
try:
userID = request.session['userID']
vmm = VPSManager()
return vmm.fetchCurrentSnapshots(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)
def submitSnapshotCreation(request):
try:
userID = request.session['userID']
vmm = VPSManager()
return vmm.submitSnapshotCreation(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)
def deletSnapshot(request):
try:
userID = request.session['userID']
vmm = VPSManager()
return vmm.deletSnapshot(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)
def revertToSnapshot(request):
try:
userID = request.session['userID']
vmm = VPSManager()
return vmm.revertToSnapshot(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)

View File

@@ -0,0 +1,85 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Home - CyberPanel" %}{% endblock %}
{% block content %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Home" %}</h2>
<p>{% trans "Use the tabs to navigate through the control panel." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Available Functions" %}
</h3>
<div class="example-box-wrapper">
<div class="row">
<div class="col-md-4">
<a href="{% url 'loadHVHome' %}" title="{% trans 'Servers' %}" class="tile-box tile-box-shortcut btn-primary">
<span class="bs-badge badge-absolute">2</span>
<div class="tile-header">
{% trans "Servers" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'packagesHomeVMM' %}" title="{% trans 'Packages' %}" class="tile-box tile-box-shortcut btn-primary">
<span class="bs-badge badge-absolute">3</span>
<div class="tile-header">
{% trans "Packages" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'listIPHome' %}" title="{% trans 'IP Management' %}" class="tile-box tile-box-shortcut btn-primary">
<span class="bs-badge badge-absolute">2</span>
<div class="tile-header">
{% trans "IP Management" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'vpsHome' %}" title="{% trans 'VPS Management' %}" class="tile-box tile-box-shortcut btn-primary">
<span class="bs-badge badge-absolute">3</span>
<div class="tile-header">
{% trans "VPS Management" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -68,10 +68,8 @@
</head>
<body>
<div id="sb-site">
<div id="sb-site">
@@ -281,11 +279,15 @@
<i class="glyph-icon tooltip-button icon-laptop" title="{% trans 'Server IP Address' %}" data-original-title=".icon-laptop"></i>
<span style="color: #db6868;font-weight: bold;" id="serverIPAddress"></span>
</a>
<a href="{% url 'index' %}" title="{% trans 'Dashboard' %}">
<a href="{% url 'index' %}" title="{% trans 'CyberPanel' %}">
<i class="glyph-icon icon-linecons-tv"></i>
<span>{% trans "Dashboard" %}</span>
<span>{% trans "CyberPanel" %}</span>
</a>
<a class="versionManagement" href="{% url 'versionManagment' %}" title="{% trans 'Version Management' %}">
<a href="{% url 'VMM' %}" title="{% trans 'CyberTron' %}">
<i class="glyph-icon tooltip-button icon-hdd-o"></i>
<span>{% trans "CyberTron" %}</span>
</a>
<a id="versionManagement" href="{% url 'versionManagment' %}" title="{% trans 'Version Management' %}">
<i class="glyph-icon tooltip-button icon-cloud-upload" title="{% trans 'Version Management' %}" data-original-title=".icon-cloud-upload" aria-describedby="tooltip896208"></i>
<span>{% trans "Version Management" %}</span>
</a>
@@ -651,5 +653,5 @@
<script src="{% static 'manageSSL/manageSSL.js' %}"></script>
<script src="{% static 'manageServices/manageServices.js' %}"></script>
</div>
</body>
</body>
</html>

View File

@@ -0,0 +1,392 @@
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!DOCTYPE html>
<html lang="en" ng-app="CyberCP">
<head>
<style>
/* Loading Spinner */
.spinner{margin:0;width:70px;height:18px;margin:-35px 0 0 -9px;position:absolute;top:50%;left:50%;text-align:center}.spinner > div{width:18px;height:18px;background-color:#333;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;animation-fill-mode:both}.spinner .bounce1{-webkit-animation-delay:-.32s;animation-delay:-.32s}.spinner .bounce2{-webkit-animation-delay:-.16s;animation-delay:-.16s}@-webkit-keyframes bouncedelay{0%,80%,100%{-webkit-transform:scale(0.0)}40%{-webkit-transform:scale(1.0)}}@keyframes bouncedelay{0%,80%,100%{transform:scale(0.0);-webkit-transform:scale(0.0)}40%{transform:scale(1.0);-webkit-transform:scale(1.0)}}
</style>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->
<title>{% block title %}Page Title{% endblock %}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Favicons -->
{% load static %}
<script src = "https://code.angularjs.org/1.6.5/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- HELPERS -->
<link rel="stylesheet" type="text/css" href="{% static 'baseTemplate/assets/finalBase/finalBase.css' %}">
<!-- ELEMENTS -->
<!-- ICONS -->
<!-- WIDGETS -->
<!-- SNIPPETS -->
<!-- APPLICATIONS -->
<!-- Admin theme -->
<link rel="stylesheet" type="text/css" href="{% static 'baseTemplate/assets/finalBase/finalBaseTheme.css' %}">
<link rel="stylesheet" type="text/css" href="/static/baseTemplate/assets/themes/admin/layout.css">
<link rel="stylesheet" type="text/css" href="/static/baseTemplate/assets/themes/admin/color-schemes/default.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<link rel="stylesheet" type="text/css" href="{% static 'baseTemplate/custom-js/pnotify.custom.min.css' %}">
<!-- Components theme, component below was above three CSS files. -->
<!-- Admin responsive -->
<!-- Packages -->
<!-- JS Core -->
<script type="text/javascript" src="{% static 'baseTemplate/assets/js-core/jquery-core.min.js' %}"></script>
<script type="text/javascript">
$(window).load(function(){
setTimeout(function() {
$('#loading').fadeOut( 400, "linear" );
}, 300);
});
</script>
<!-- JS Ends -->
</head>
<body>
<div id="sb-site">
<!------- ng-controller="systemStatusInfo" ------------>
<div class="sb-slidebar bg-black sb-right sb-style-overlay">
<div class="scrollable-content scrollable-slim-sidebar">
<div class="pad15A">
<div class="clear"></div>
<div ng-controller="systemStatusInfo" id="sidebar-toggle-3" class="collapse in">
<ul class="progress-box">
<li>
<div class="progress-title">
{% trans "CPU Usage" %}
<b>{$ cpuUsage $}%</b>
</div>
<div class="progressbar-small progressbar" data-value="{$ cpuUsage $}">
<div class="progressbar-value bg-yellow tooltip-button" title="{$ cpuUsage $}%">
</div>
</div>
</li>
<li>
<b class="pull-right">{$ ramUsage $}%</b>
<div class="progress-title">
{% trans "Ram Usage" %}
</div>
<div class="progressbar-small progressbar" data-value="{$ ramUsage $}">
<div class="progressbar-value bg-red tooltip-button" title="{$ ramUsage $}%"></div>
</div>
</li>
<li>
<div class="progress-title">
{% trans "Disk Usage" %}
<b>{$ diskUsage $}%</b>
</div>
<div class="progressbar" data-value="{$ diskUsage $}">
<div class="progressbar-value bg-green">
<div class="progress-label">{$ diskUsage $}%</div>
</div>
</div>
</li>
</ul>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<div id="loading">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
<div id="page-wrapper">
<div id="page-header" class="bg-gradient-9">
<div id="mobile-navigation">
<button id="nav-toggle" class="collapsed" data-toggle="collapse" data-target="#page-sidebar"><span></span></button>
<a href="{% url "index" %}" class="logo-content-small" title="{% trans 'CyberPanel' %}"></a>
</div>
<div id="header-logo" class="logo-bg">
<a href="{% url "index" %}" class="logo-content-big" title="{% trans 'CyberPanel' %}">
Cyber <i>Panel</i>
<span>{% trans "Web Hosting Control Panel" %}</span>
</a>
<a href="{% url "index" %}" class="logo-content-small" title="{% trans 'CyberPanel' %}">
Cyber <i>Panel</i>
<span>{% trans "Web Hosting Control Panel" %}</span>
</a>
<a id="close-sidebar" href="#" title="{% trans 'Close sidebar' %}">
<i class="glyph-icon icon-angle-left"></i>
</a>
</div>
<div id="header-nav-left">
<div ng-controller="adminController" class="user-account-btn dropdown">
<a href="#" title="{% trans 'My Account' %}" class="user-profile clearfix" data-toggle="dropdown">
<img width="28" src="{% static 'baseTemplate/assets/image-resources/gravatar.png' %}" alt="Profile image">
<span>{$ currentAdmin $}</span>
<i class="glyph-icon icon-angle-down"></i>
</a>
<div class="dropdown-menu float-left">
<div class="box-sm">
<div class="login-box clearfix">
<div class="user-img">
<a href="#" title="{% trans '' %}" class="change-img">Change photo</a>
<img src="{% static 'baseTemplate/assets/image-resources/gravatar.png' %}" alt="">
</div>
<div class="user-info">
<span>
{$ currentAdmin $}
<i>{$ admin_type $}</i>
</span>
<a href="{% url 'modifyUsers' %}" title="{% trans 'Edit profile' %}">{% trans "Edit profile" %}</a>
<a href="{% url 'viewProfile' %}" title="{% trans 'View Profile' %}">{% trans "View Profile" %}</a>
</div>
</div>
<div class="divider"></div>
<div class="pad5A button-pane button-pane-alt text-center">
<a href="{% url 'logout' %}" class="btn display-block font-normal btn-danger">
<i class="glyph-icon icon-power-off"></i>
{% trans "Logout" %}
</a>
</div>
</div>
</div>
</div>
</div><!-- #header-nav-left -->
<div ng-controller="loadAvg" id="header-nav-right">
<a class="hide-on-phone" style="background-color: none;width: 33px" href="#" class="hdr-btn" title="{% trans 'CPU Load Average' %}" data-placement="bottom" >
<span class="badge bg-yellow">{$ one $}</span>
</a>
<a class="hide-on-phone" style="background-color: none;width: 33px" href="#" class="hdr-btn" title="{% trans 'CPU Load Average' %}" data-placement="bottom" >
<span class="badge bg-yellow">{$ two $}</span>
</a>
<a class="hide-on-phone" style="background-color: none;width: 33px" href="#" class="hdr-btn" title="{% trans 'CPU Load Average' %}" data-placement="bottom">
<span class="badge bg-yellow">{$ three $}</span>
</a>
<div class="dropdown" id="dashnav-btn">
<a href="#" data-toggle="dropdown" data-placement="bottom" class="popover-button-header tooltip-button" title="{% trans 'Dashboard Quick Menu' %}">
<i class="glyph-icon icon-linecons-cog"></i>
</a>
<div class="dropdown-menu float-right">
<div class="box-sm">
<div class="pad5T pad5B pad10L pad10R dashboard-buttons clearfix">
<a href="{% url 'loadWebsitesHome' %}" class="btn vertical-button remove-border btn-info" title="{% trans '' %}">
<span class="glyph-icon icon-separator-vertical pad0A medium">
<i class="glyph-icon icon-dashboard opacity-80 font-size-20"></i>
</span>
{% trans "Websites" %}
</a>
<a href="{% url 'packagesHome' %}" class="btn vertical-button remove-border btn-danger" title="{% trans '' %}">
<span class="glyph-icon icon-separator-vertical pad0A medium">
<i class="glyph-icon icon-tags opacity-80 font-size-20"></i>
</span>
{% trans "Packages" %}
</a>
<a href="{% url 'dnsHome' %}" class="btn vertical-button remove-border btn-purple" title="{% trans '' %}">
<span class="glyph-icon icon-separator-vertical pad0A medium">
<i class="glyph-icon icon-fire opacity-80 font-size-20"></i>
</span>
{% trans "DNS" %}
</a>
<a href="{% url 'loadFTPHome' %}" class="btn vertical-button remove-border btn-azure" title="{% trans '' %}">
<span class="glyph-icon icon-separator-vertical pad0A medium">
<i class="glyph-icon icon-bar-chart-o opacity-80 font-size-20"></i>
</span>
{% trans "FTP" %}
</a>
<a href="{% url 'loadTuningHome' %}" class="btn vertical-button remove-border btn-yellow" title="{% trans '' %}">
<span class="glyph-icon icon-separator-vertical pad0A medium">
<i class="glyph-icon icon-laptop opacity-80 font-size-20"></i>
</span>
{% trans "Tuning" %}
</a>
<a href="{% url 'serverStatusHome' %}" class="btn vertical-button remove-border btn-warning" title="{% trans '' %}">
<span class="glyph-icon icon-separator-vertical pad0A medium">
<i class="glyph-icon icon-code opacity-80 font-size-20"></i>
</span>
{% trans "Status" %}
</a>
</div>
</div>
</div>
</div>
<a class="header-btn" id="logout-btn" href="{% url 'logout' %}" title="{% trans 'Logout' %}">
<i class="glyph-icon icon-linecons-lock"></i>
</a>
</div><!-- #header-nav-right -->
</div>
<div id="page-sidebar">
<div class="scroll-sidebar">
<ul id="sidebar-menu">
<li class="header"><span>{% trans "Overview" %}</span></li>
<li>
<a href="#" title="{% trans 'Server IP Address' %}">
<i class="glyph-icon tooltip-button icon-laptop" title="{% trans 'Server IP Address' %}" data-original-title=".icon-laptop"></i>
<span style="color: #db6868;font-weight: bold;" id="serverIPAddress"></span>
</a>
<a href="{% url 'index' %}" title="{% trans 'CyberPanel' %}">
<i class="glyph-icon icon-linecons-tv"></i>
<span>{% trans "CyberPanel" %}</span>
</a>
<a href="{% url 'VMM' %}" title="{% trans 'CyberTron' %}">
<i class="glyph-icon tooltip-button icon-hdd-o"></i>
<span>{% trans "CyberTron" %}</span>
</a>
<a id="versionManagement" href="{% url 'versionManagment' %}" title="{% trans 'Version Management' %}">
<i class="glyph-icon tooltip-button icon-cloud-upload" title="{% trans 'Version Management' %}" data-original-title=".icon-cloud-upload" aria-describedby="tooltip896208"></i>
<span>{% trans "Version Management" %}</span>
</a>
</li>
<li class="divider"></li>
<li class="header"><span>{% trans "Main" %}</span></li>
<li>
<a id="packageHome" href="#" title="{% trans 'Servers' %}">
<i class="glyph-icon tooltip-button icon-laptop"></i>
<span>{% trans "Servers" %}</span>
</a>
<div id="packageSub" class="sidebar-submenu">
<ul>
<li id="createPackage"><a href="{% url 'createHypervisor' %}" title="{% trans 'Create Server' %}"><span>{% trans "Create Server" %}</span></a></li>
<li id="deletePackage"><a href="{% url 'listHVs' %}" title="{% trans 'List Servers' %}"><span>{% trans "List Servers" %}</span></a></li>
</ul>
</div><!-- .sidebar-submenu -->
</li>
<li>
<a id="packageHome" href="{% url 'packagesHome' %}" title="{% trans 'Packages' %}">
<i class="glyph-icon icon-cubes"></i>
<span>{% trans "Packages" %}</span>
</a>
<div id="packageSub" class="sidebar-submenu">
<ul>
<li id="createPackage"><a href="{% url 'createPackageVMM' %}" title="{% trans 'Create Package' %}"><span>{% trans "Create Package" %}</span></a></li>
<li id="deletePackage"><a href="{% url 'deletePackageVMM' %}" title="{% trans 'Delete Package' %}"><span>{% trans "Delete Package" %}</span></a></li>
<li id="modifyPackage"><a href="{% url 'modifyPackageVMM' %}" title="{% trans 'Modify Package' %}"><span>{% trans "Modify Package" %}</span></a></li>
</ul>
</div><!-- .sidebar-submenu -->
</li>
<li>
<a href="{% url 'loadUsersHome' %}" title="{% trans 'IP Management' %}">
<i class="glyph-icon tooltip-button icon-wifi" title="{% trans 'IP Management' %}"></i>
<span>{% trans "IP Management" %}</span>
</a>
<div class="sidebar-submenu">
<ul>
<li><a href="{% url 'createIPPool' %}" title="{% trans 'Create IP Pool' %}"><span>{% trans "Create IP Pool" %}</span></a></li>
<li><a href="{% url 'listIPPools' %}" title="{% trans 'List IP Pools' %}"><span>{% trans "List IP Pools" %}</span></a></li>
</ul>
</div><!-- .sidebar-submenu -->
</li>
<li>
<a href="" title="{% trans 'VPS Management' %}">
<div class="glyph-icon tooltip-button icon-tasks" title="{% trans 'VPS Management' %}"></div>
<span>{% trans "VPS Management" %}</span>
</a>
<div class="sidebar-submenu">
<ul>
<li><a href="{% url 'createVPS' %}" title="{% trans 'Create VPS' %}"><span>{% trans "Create VPS" %}</span></a></li>
<li><a href="{% url 'listVPSs' %}" title="{% trans 'List VPS' %}"><span>{% trans "List VPS" %}</span></a></li>
<li><a href="{% url 'sshKeys' %}" title="{% trans 'SSH Keys' %}"><span>{% trans "SSH Keys" %}</span></a></li>
</ul>
</div><!-- .sidebar-submenu -->
</li>
</ul><!-- #sidebar-menu -->
</div>
</div>
<div id="page-content-wrapper">
<div id="page-content">
{% block content %}
{% endblock %}
</div>
</div>
</div>
<script src="{% static 'baseTemplate/custom-js/pnotify.custom.min.js' %}"></script>
<script src="{% static 'baseTemplate/custom-js/system-status.js' %}"></script>
<script src="{% static 'packages/packages.js' %}"></script>
<script src="{% static 'hypervisor/hypervisor.js' %}"></script>
<script type="text/javascript" src="{% static 'baseTemplate/assets/finalJS/final.js' %}"></script>
<script src="{% static 'backup/backup.js' %}"></script>
<script src="{% static 'baseTemplate/bootstrap-toggle.min.js' %}"></script>
<script src="{% static 'ipManagement/ipManagement.js' %}"></script>
<script src="{% static 'vpsManagement/vpsManagement.js' %}"></script>
</div>
</body>
</html>

View File

@@ -11,9 +11,14 @@ urlpatterns = [
#url(r'^upgrade',views.upgrade, name='upgrade'),
url(r'^UpgradeStatus',views.upgradeStatus, name='UpgradeStatus'),
url(r'^upgradeVersion',views.upgradeVersion, name='upgradeVersion'),
## VMM
url(r'^VMM$',views.VMM, name='VMM'),
]

View File

@@ -4,7 +4,6 @@ from __future__ import unicode_literals
from django.shortcuts import render,redirect
from django.http import HttpResponse
from plogical.getSystemInformation import SystemInformation
from loginSystem.models import Administrator, ACL
import json
from loginSystem.views import loadLoginPage
import re
@@ -15,6 +14,7 @@ import shlex
import os
import plogical.CyberCPLogFileWriter as logging
from plogical.acl import ACLManager
from plogical.aclVMM import vmmACLManager
# Create your views here.
@@ -36,6 +36,29 @@ def renderBase(request):
except KeyError:
return redirect(loadLoginPage)
def VMM(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.inspectHyperVisor() == 0:
return vmmACLManager.loadError()
if currentACL['admin'] == 1:
admin = 1
else:
admin = 0
cpuRamDisk = SystemInformation.cpuRamDisk()
finaData = {"admin": admin,'ramUsage':cpuRamDisk['ramUsage'],'cpuUsage':cpuRamDisk['cpuUsage'],'diskUsage':cpuRamDisk['diskUsage'] }
return render(request, 'baseTemplate/homePageVMM.html', finaData)
except KeyError:
return redirect(loadLoginPage)
def getAdminStatus(request):
try:
val = request.session['userID']

0
hypervisor/__init__.py Normal file
View File

6
hypervisor/admin.py Normal file
View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.

8
hypervisor/apps.py Normal file
View File

@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class HypervisorConfig(AppConfig):
name = 'hypervisor'

144
hypervisor/hypervisor.py Normal file
View File

@@ -0,0 +1,144 @@
#!/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
import subprocess
import shlex
from django.shortcuts import HttpResponse, render
from loginSystem.models import Administrator
from plogical.aclVMM import vmmACLManager
from plogical.acl import ACLManager
from models import HyberVisors
class HVManager:
def loadHVHome(self, request = None, userID = None,):
try:
return render(request, 'hypervisor/indexVMM.html', {})
except BaseException, msg:
return HttpResponse(str(msg))
def createHypervisor(self, request = None, userID = None,):
try:
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.currentContextPermission(currentACL, 'createHypervisor') == 0:
return ACLManager.loadError()
ownerNames = ACLManager.loadAllUsers(userID)
return render(request, 'hypervisor/createHyperVisor.html', {'ownerNames' : ownerNames})
except BaseException, msg:
return HttpResponse(str(msg))
def listHVs(self, request = None, userID = None,):
try:
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.currentContextPermission(currentACL, 'listHV') == 0:
return ACLManager.loadError()
serverObjs = vmmACLManager.findServersObjs(currentACL, userID)
hvs = vmmACLManager.prepareServers(serverObjs)
ownerNames = ACLManager.loadAllUsers(userID)
return render(request, 'hypervisor/listHV.html', {'hvs' : hvs, 'ownerNames' : ownerNames})
except BaseException, msg:
return HttpResponse(str(msg))
def submitCreateHyperVisor(self, userID = None, data = None):
try:
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.currentContextPermission(currentACL, 'createHypervisor') == 0:
return ACLManager.loadErrorJson()
if HyberVisors.objects.all().count() == 1:
final_json = json.dumps({'status': 0, 'errorMessage': "Only one server is allowed at this time."})
return HttpResponse(final_json)
name = data['name']
serverOwner = data['serverOwner']
serverIP = data['serverIP']
userName = data['userName']
password = data['password']
storagePath = data['storagePath']
hvOwner = Administrator.objects.get(userName=serverOwner)
newHV = HyberVisors(hypervisorOwner=hvOwner,
hypervisorName=name,
hypervisorIP=serverIP,
hypervisorUserName=userName,
hypervisorPassword=password,
hypervisorStoragePath=storagePath)
newHV.save()
final_json = json.dumps({'status': 1, 'errorMessage': "None"})
return HttpResponse(final_json)
except BaseException, msg:
final_json = json.dumps({'status': 0, 'errorMessage': str(msg)})
return HttpResponse(final_json)
def submitHyperVisorChanges(self, userID = None, data = None):
try:
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.currentContextPermission(currentACL, 'listHV') == 0:
return ACLManager.loadErrorJson()
name = data['name']
serverOwner = data['serverOwner']
userName = data['userName']
password = data['password']
storagePath = data['storagePath']
hvOwner = Administrator.objects.get(userName=serverOwner)
modifyHV = HyberVisors.objects.get(hypervisorName=name)
modifyHV.hypervisorOwner = hvOwner
modifyHV.hypervisorUserName = userName
modifyHV.hypervisorPassword = password
modifyHV.hypervisorStoragePath = storagePath
modifyHV.save()
final_json = json.dumps({'status': 1, 'errorMessage': "None"})
return HttpResponse(final_json)
except BaseException, msg:
final_json = json.dumps({'status': 0, 'errorMessage': str(msg)})
return HttpResponse(final_json)
def controlCommands(self, userID = None, data = None):
try:
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.currentContextPermission(currentACL, 'listHV') == 0:
return ACLManager.loadErrorJson()
hypervisorIP = data['hypervisorIP']
action = data['action']
hv = HyberVisors.objects.get(hypervisorIP=hypervisorIP)
if hypervisorIP == '127.0.0.1':
if action == 'restart':
command = 'sudo reboot'
ACLManager.executeCall(command)
elif action == 'shutdown':
command = 'sudo shutdown'
ACLManager.executeCall(command)
elif action == 'delete':
final_json = json.dumps({'status': 0, 'errorMessage': "Local Server can not be deleted."})
return HttpResponse(final_json)
final_json = json.dumps({'status': 1, 'errorMessage': "None"})
return HttpResponse(final_json)
except BaseException, msg:
final_json = json.dumps({'status': 0, 'errorMessage': str(msg)})
return HttpResponse(final_json)

View File

13
hypervisor/models.py Normal file
View File

@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from loginSystem.models import Administrator
class HyberVisors(models.Model):
hypervisorOwner = models.ForeignKey(Administrator)
hypervisorName = models.CharField(max_length=50, unique=True)
hypervisorIP = models.CharField(max_length=50, unique=True)
hypervisorUserName = models.CharField(max_length=50)
hypervisorPassword = models.CharField(max_length=100)
hypervisorStoragePath = models.CharField(max_length=500)

View File

@@ -0,0 +1,287 @@
/**
* Created by usman on 9/5/17.
*/
/* Java script code for HV */
app.controller('addHyperVisorCTRL', function($scope,$http) {
$scope.tronLoading = true;
$scope.submitCreateHyperVisor = function(){
$scope.rulesLoading = false;
url = "/hv/submitCreateHyperVisor";
var data = {
name : $scope.name,
serverOwner : $scope.serverOwner,
serverIP : $scope.serverIP,
userName : $scope.userName,
password : $scope.password,
storagePath : $scope.storagePath
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.status === 1){
new PNotify({
title: 'Success!',
text: 'Server successfully added.',
type:'success'
});
}
else{
new PNotify({
title: 'Error!',
text: response.data.errorMessage,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Error!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
});
/* Java script code for HV */
/* Java script code for List HVs */
app.controller('listHVCTRL', function($scope,$http) {
$scope.tronLoading = true;
$scope.hvTable = false;
$scope.hvForm = true;
$scope.submitCreateHyperVisor = function(){
$scope.tronLoading = false;
url = "/hv/submitCreateHyperVisor";
var data = {
name : $scope.name,
serverOwner : $scope.serverOwner,
serverIP : $scope.serverIP,
userName : $scope.userName,
password : $scope.password,
storagePath : $scope.storagePath
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.status === 1){
new PNotify({
title: 'Success!',
text: 'Server successfully added.',
type:'success'
});
}
else{
new PNotify({
title: 'Error!',
text: response.data.errorMessage,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Error!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
$scope.manageServer = function (hypervisorName) {
$scope.hvTable = true;
$scope.hvForm = false;
$scope.name = hypervisorName;
};
$scope.submitHyperVisorChanges = function(){
$scope.tronLoading = false;
url = "/hv/submitHyperVisorChanges";
var data = {
name : $scope.name,
serverOwner : $scope.serverOwner,
userName : $scope.userName,
password : $scope.password,
storagePath : $scope.storagePath
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.status === 1){
new PNotify({
title: 'Success!',
text: 'Changes successfully saved.',
type:'success'
});
}
else{
new PNotify({
title: 'Error!',
text: response.data.errorMessage,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Error!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
$scope.hidehvForm = function (hypervisorIP) {
$scope.hvTable = false;
$scope.hvForm = true;
};
$scope.setValues = function (hypervisorIP, action) {
$scope.hypervisorIP = hypervisorIP;
$scope.action = action;
};
$scope.controlCommands = function(){
$scope.tronLoading = false;
url = "/hv/controlCommands";
var data = {
hypervisorIP : $scope.hypervisorIP,
action : $scope.action
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.status === 1){
new PNotify({
title: 'Success!',
text: 'Changes successfully saved.',
type:'success'
});
}
else{
new PNotify({
title: 'Error!',
text: response.data.errorMessage,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Error!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
});
/* Java script code for List HVs */

View File

@@ -0,0 +1,91 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Add Server - CyberTron" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div ng-controller="addHyperVisorCTRL" class="container">
<div id="page-title">
<h2>{% trans "Add Server" %}</h2>
<p>{% trans "On this page you can add remote servers who have CyberPanel already installed!" %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Server Details" %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Server Owner" %}</label>
<div class="col-sm-6">
<select ng-model="serverOwner" class="form-control">
{% for items in ownerNames %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "IP Addresses" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="serverIP">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "User name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="userName">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Password" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="password" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Storage Path" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="storagePath">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="submitCreateHyperVisor()" class="btn btn-primary btn-lg btn-block">{% trans "Add Server" %}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,56 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Servers - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Servers" %}</h2>
<p>{% trans "Servers are needed to host virtual machine, you can add and delete servers through this page." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Available Functions" %}
</h3>
<div class="example-box-wrapper">
<div class="row">
<div class="col-md-4">
<a href="{% url 'createHypervisor' %}" title="{% trans 'Create Server' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Create Server" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'listHVs' %}" title="{% trans 'List Servers' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "List Servers" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,147 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "List Servers - CyberTron" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div ng-controller="listHVCTRL" class="container">
<div id="page-title">
<h2 id="domainNamePage">{% trans "List Servers" %}</h2>
<p>{% trans "Manage your servers on this page." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Servers" %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<table ng-hide="hvTable" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="datatable-example">
<thead>
<tr>
<th>{% trans 'ID' %}</th>
<th>{% trans 'Owner' %}</th>
<th>{% trans 'Name' %}</th>
<th>{% trans 'IP Address' %}</th>
<th>{% trans 'VMs' %}</th>
<th>{% trans 'Storage Path' %}</th>
<th>{% trans 'Operations' %}</th>
</tr>
</thead>
<tbody>
{% for items in hvs %}
<tr>
<td>{{ items.id }}</td>
<td>{{ items.hypervisorOwner }}</td>
<td>{{ items.hypervisorName }}</td>
<td>{{ items.hypervisorIP }}</td>
<td>{{ items.vms }}</td>
<td>{{ items.hypervisorStoragePath }}</td>
<td>
<a data-toggle="modal" data-target="#myModal" style="margin-right: 2%;" title="{% trans 'Restart Server' %}" ng-click="setValues('{{ items.hypervisorIP }}', 'restart')" href=""><img src="{% static 'vpsManagement/restart.png' %}"></a>
<a data-toggle="modal" data-target="#myModal" style="margin-right: 2%;" title="{% trans 'Power Off Server' %}" ng-click="setValues('{{ items.hypervisorIP }}', 'shutdown')" href=""><img src="{% static 'vpsManagement/powerOff.png' %}"></a>
<a data-toggle="modal" data-target="#myModal" style="margin-right: 2%;" title="{% trans 'Delete Server' %}" ng-click="setValues('{{ items.hypervisorIP }}', 'delete')" href=""><img src="{% static 'vpsManagement/delete.png' %}"></a>
<a data-toggle="modal" data-target="#myModal" href="" title="{% trans 'Edit Server' %}" ng-click="setValues('{{ items.hypervisorName }}')"><img src="{% static 'vpsManagement/settings-gears.png' %}"></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<!--- Modal Body --->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title">{$ action $} {$ hypervisorIP $} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}"></h4>
</div>
<div class="modal-body">
<p>{% trans 'Are you sure?' %}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans 'Close' %}</button>
<button data-dismiss="modal" ng-click="controlCommands()" type="button" class="btn btn-primary">{% trans 'Confirm' %}</button>
</div>
</div>
</div>
</div>
<!--- Modal Body --->
<form ng-hide="hvForm" action="/" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="name" readonly>
</div>
<a style="margin-right: 2%;" title="{% trans 'Go Back' %}" ng-click="hidehvForm()" href=""><img src="{% static 'vpsManagement/delete.png' %}"></a>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Server Owner" %}</label>
<div class="col-sm-6">
<select ng-model="serverOwner" class="form-control">
{% for items in ownerNames %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "User name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="userName">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Password" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="password" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Storage Path" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="storagePath">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="submitHyperVisorChanges()" class="btn btn-primary btn-lg btn-block">{% trans "Save Changes" %}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

6
hypervisor/tests.py Normal file
View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.

12
hypervisor/urls.py Normal file
View File

@@ -0,0 +1,12 @@
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$', views.loadHVHome, name='loadHVHome'),
url(r'^createHypervisor$', views.createHypervisor, name='createHypervisor'),
url(r'^submitCreateHyperVisor$', views.submitCreateHyperVisor, name='submitCreateHyperVisor'),
url(r'^listHVs$', views.listHVs, name='listHVs'),
url(r'^submitHyperVisorChanges$', views.submitHyperVisorChanges, name='submitHyperVisorChanges'),
url(r'^controlCommands$', views.controlCommands, name='controlCommands'),
]

56
hypervisor/views.py Normal file
View File

@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from hypervisor import HVManager
from loginSystem.views import loadLoginPage
import json
# Create your views here.
def loadHVHome(request):
try:
userID = request.session['userID']
hvm = HVManager()
return hvm.loadHVHome(request, userID)
except KeyError:
return redirect(loadLoginPage)
def createHypervisor(request):
try:
userID = request.session['userID']
hvm = HVManager()
return hvm.createHypervisor(request, userID)
except KeyError:
return redirect(loadLoginPage)
def listHVs(request):
try:
userID = request.session['userID']
hvm = HVManager()
return hvm.listHVs(request, userID)
except KeyError:
return redirect(loadLoginPage)
def submitCreateHyperVisor(request):
try:
userID = request.session['userID']
hvm = HVManager()
return hvm.submitCreateHyperVisor(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)
def submitHyperVisorChanges(request):
try:
userID = request.session['userID']
hvm = HVManager()
return hvm.submitHyperVisorChanges(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)
def controlCommands(request):
try:
userID = request.session['userID']
hvm = HVManager()
return hvm.controlCommands(userID, json.loads(request.body))
except KeyError:
return redirect(loadLoginPage)

View File

@@ -15,14 +15,19 @@ import random
class preFlightsChecks:
cyberPanelMirror = "mirror.cyberpanel.net/pip"
templates = 'images.cyberpanel.net/templates'
def __init__(self,rootPath,ip,path,cwd,cyberPanelPath):
def __init__(self, rootPath, ip, path , cwd , cyberPanelPath, interfaceName, netmask, gateway):
self.ipAddr = ip
self.path = path
self.cwd = cwd
self.server_root_path = rootPath
self.cyberPanelPath = cyberPanelPath
self.interfaceName = interfaceName
self.netmask = netmask
self.gateway = gateway
@staticmethod
def stdOut(message):
print("\n\n")
@@ -622,6 +627,35 @@ class preFlightsChecks:
preFlightsChecks.stdOut("psutil successfully installed!")
break
def installLibvirtPython(self):
try:
count = 0
while (1):
command = "pip install libvirt-python"
res = subprocess.call(shlex.split(command))
if res == 1:
count = count + 1
preFlightsChecks.stdOut("Unable to install libvirt-python, trying again, try number: " + str(count))
if count == 3:
logging.InstallLog.writeToFile("Unable to install libvirt-python, exiting installer! [install_psutil]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
os._exit(0)
else:
logging.InstallLog.writeToFile("libvirt-python successfully installed!")
preFlightsChecks.stdOut("libvirt-python successfully installed!")
break
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installLibvirtPython]")
return 0
except subprocess.CalledProcessError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installLibvirtPython]")
return 0
def fix_selinux_issue(self):
try:
cmd = []
@@ -687,7 +721,7 @@ class preFlightsChecks:
count = 0
while (1):
command = "wget http://cyberpanel.net/CyberPanel.1.7.1.tar.gz"
command = "wget http://cyberpanel.net/CyberPanelTron.tar.gz"
#command = "wget http://cyberpanel.net/CyberPanelTemp.tar.gz"
res = subprocess.call(shlex.split(command))
@@ -707,7 +741,7 @@ class preFlightsChecks:
count = 0
while(1):
command = "tar zxf CyberPanel.1.7.1.tar.gz"
command = "tar zxf CyberPanelTron.tar.gz"
#command = "tar zxf CyberPanelTemp.tar.gz"
res = subprocess.call(shlex.split(command))
@@ -776,6 +810,8 @@ class preFlightsChecks:
logging.InstallLog.writeToFile("settings.py updated!")
self.setupVirtualEnv()
### Applying migrations
@@ -784,7 +820,7 @@ class preFlightsChecks:
count = 0
while(1):
command = "python manage.py makemigrations"
command = "/usr/local/CyberCP/bin/python2 manage.py makemigrations"
res = subprocess.call(shlex.split(command))
if res == 1:
@@ -804,7 +840,7 @@ class preFlightsChecks:
count = 0
while(1):
command = "python manage.py migrate"
command = "/usr/local/CyberCP/bin/python2 manage.py migrate"
res = subprocess.call(shlex.split(command))
@@ -871,7 +907,6 @@ class preFlightsChecks:
preFlightsChecks.stdOut("Owner for '/usr/local/CyberCP' successfully changed!")
break
def install_unzip(self):
try:
@@ -1106,7 +1141,6 @@ class preFlightsChecks:
return 1
def setup_email_Passwords(self,mysqlPassword, mysql):
try:
@@ -1221,7 +1255,6 @@ class preFlightsChecks:
return 1
def setup_postfix_davecot_config(self, mysql):
try:
logging.InstallLog.writeToFile("Configuring postfix and dovecot...")
@@ -1844,7 +1877,6 @@ class preFlightsChecks:
return 1
def downoad_and_install_raindloop(self):
try:
###########
@@ -2023,7 +2055,6 @@ class preFlightsChecks:
return 0
return 1
def installFirewalld(self):
try:
@@ -2718,9 +2749,7 @@ milter_default_action = accept
@staticmethod
def setupVirtualEnv():
try:
##
count = 0
while (1):
command = "yum install -y libattr-devel xz-devel gpgme-devel mariadb-devel curl-devel"
@@ -2900,8 +2929,222 @@ milter_default_action = accept
logging.InstallLog.writeToFile(str(msg) + " [enableDisableEmail]")
return 0
@staticmethod
def setupPipPacks():
try:
##
count = 0
while (1):
command = "pip install -r /usr/local/CyberCP/requirments.txt"
res = subprocess.call(shlex.split(command))
if res == 1:
count = count + 1
preFlightsChecks.stdOut(
"Trying to install project dependant modules, trying again, try number: " + str(count))
if count == 3:
logging.InstallLog.writeToFile(
"Failed to install project dependant modules! [setupPipPacks]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
os._exit(0)
else:
logging.InstallLog.writeToFile("Project dependant modules installed successfully!")
preFlightsChecks.stdOut("Project dependant modules installed successfully!!")
break
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [setupPipPacks]")
return 0
########### KVM
def installKVM(self):
try:
count = 0
while (1):
command = 'yum -y install qemu-kvm qemu-img libvirt libvirt-client virt-install libguestfs-tools libvirt-devel'
cmd = shlex.split(command)
res = subprocess.call(cmd)
if res == 1:
count = count + 1
preFlightsChecks.stdOut("Trying to install KVM, trying again, try number: " + str(count))
if count == 3:
logging.InstallLog.writeToFile(
"Unable to install KVM, installation abored. [installKVM]")
preFlightsChecks.stdOut("Installation failed, consult: /var/log/installLogs.txt")
sys.exit()
break
else:
command = 'systemctl start libvirtd'
cmd = shlex.split(command)
res = subprocess.call(cmd)
command = 'systemctl enable libvirtd'
cmd = shlex.split(command)
res = subprocess.call(cmd)
logging.InstallLog.writeToFile("Succcessfully installed KVM!")
preFlightsChecks.stdOut("Succcessfully installed KVM!")
break
return 1
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installKVM]")
return 0
except ValueError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installKVM]")
return 0
def setupBridge(self):
try:
preFlightsChecks.stdOut('Setting up network Bridge!')
device = 'DEVICE="virbr0"\n'
bootProto = 'BOOTPROTO="static"\n'
ipAddress = 'IPADDR="' + self.ipAddr + '"\n'
netmask = 'NETMASK="' + self.netmask + '"\n'
gateway = 'GATEWAY="' + self.gateway + '"\n'
dns1 = "DNS1=8.8.8.8\n"
onBoot = 'ONBOOT="yes"\n'
type = 'TYPE="Bridge"\n'
nmControlled = 'NM_CONTROLLED="no"\n'
path = "/etc/sysconfig/network-scripts/ifcfg-virbr0"
writeToFile = open(path, 'w')
writeToFile.writelines(device)
writeToFile.writelines(bootProto)
writeToFile.writelines(ipAddress)
writeToFile.writelines(netmask)
writeToFile.writelines(gateway)
writeToFile.writelines(dns1)
writeToFile.writelines(onBoot)
writeToFile.writelines(type)
writeToFile.writelines(nmControlled)
writeToFile.close()
###
path = "/etc/sysconfig/network-scripts/ifcfg-" + self.interfaceName
writeToFile = open(path, 'w')
writeToFile.writelines('DEVICE=' + self.interfaceName + "\n")
writeToFile.writelines('TYPE=Ethernet\n')
writeToFile.writelines('BOOTPROTO=none\n')
writeToFile.writelines('ONBOOT=yes\n')
writeToFile.writelines('NM_CONTROLLED=no\n')
writeToFile.writelines('BRIDGE=virbr0\n')
writeToFile.close()
##
command = 'systemctl restart network'
subprocess.call(shlex.split(command))
preFlightsChecks.stdOut('Network bridge is up and running.')
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [setupBridge]")
return 0
except ValueError, msg:
logging.InstallLog.writeToFile(str(msg) + " [setupBridge]")
return 0
def downloadImages(self):
try:
imagesPath = "/var/lib/libvirt/templates"
if not os.path.exists(imagesPath):
os.mkdir(imagesPath)
os.chdir(imagesPath)
command = 'wget ' + preFlightsChecks.templates + "/debian-9.img"
subprocess.call(shlex.split(command))
command = 'wget ' + preFlightsChecks.templates + "/fedora-28.img"
subprocess.call(shlex.split(command))
command = 'wget ' + preFlightsChecks.templates + "/ubuntu-16.04.img"
subprocess.call(shlex.split(command))
os.chdir(self.cwd)
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [downloadImages]")
return 0
except ValueError, msg:
logging.InstallLog.writeToFile(str(msg) + " [downloadImages]")
return 0
def installNoVNC(self):
try:
vncPath = "/usr/local/lscp/cyberpanel"
os.chdir(vncPath)
command = 'yum install git -y'
subprocess.call(shlex.split(command))
command = 'git clone https://github.com/novnc/noVNC'
subprocess.call(shlex.split(command))
os.chdir(self.cwd)
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installNoVNC]")
return 0
except ValueError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installNoVNC]")
return 0
def downloadAndInstallE2fsprogs(self):
try:
e2fs = "/e2fs"
if not os.path.exists(e2fs):
os.mkdir(e2fs)
os.chdir(e2fs)
command = 'wget https://excellmedia.dl.sourceforge.net/project/e2fsprogs/e2fsprogs/v1.44.4/e2fsprogs-1.44.4.tar.gz'
subprocess.call(shlex.split(command))
command = 'tar zxf e2fsprogs-1.44.4.tar.gz'
subprocess.call(shlex.split(command))
os.chdir('e2fsprogs-1.44.4')
command = './configure'
subprocess.call(shlex.split(command))
command = 'make'
subprocess.call(shlex.split(command))
command = 'make install'
subprocess.call(shlex.split(command))
os.chdir(self.cwd)
except OSError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installNoVNC]")
return 0
except ValueError, msg:
logging.InstallLog.writeToFile(str(msg) + " [installNoVNC]")
return 0
def main():
@@ -2912,22 +3155,33 @@ def main():
parser.add_argument('--postfix', help='Enable or disable Email Service.')
parser.add_argument('--powerdns', help='Enable or disable DNS Service.')
parser.add_argument('--ftp', help='Enable or disable ftp Service.')
parser.add_argument('--gateway', help='Gateway of main server IP.')
parser.add_argument('--netmask', help='Netmask of main server IP.')
parser.add_argument('--interfaceName', help='Interface name that you want to enslave.')
args = parser.parse_args()
logging.InstallLog.writeToFile("Starting CyberPanel installation..")
preFlightsChecks.stdOut("Starting CyberPanel installation..")
## Writing public IP
os.mkdir("/etc/cyberpanel")
#### KVM Args
interfaceName = open("/etc/cyberpanel/interfaceName", "w")
interfaceName.writelines(args.interfaceName)
interfaceName.close()
## Writing public IP
machineIP = open("/etc/cyberpanel/machineIP", "w")
machineIP.writelines(args.publicip)
machineIP.close()
cwd = os.getcwd()
checks = preFlightsChecks("/usr/local/lsws/",args.publicip,"/usr/local",cwd,"/usr/local/CyberCP")
checks = preFlightsChecks("/usr/local/lsws/",args.publicip,"/usr/local",cwd,"/usr/local/CyberCP", args.interfaceName, args.netmask, args.gateway)
if args.mysql == None:
mysql = 'One'
@@ -2978,6 +3232,17 @@ def main():
checks.install_python_requests()
checks.install_default_keys()
## KVM
checks.installKVM()
checks.setupBridge()
#checks.downloadImages()
checks.installNoVNC()
checks.downloadAndInstallE2fsprogs()
checks.installLibvirtPython()
##
checks.installCertBot()
checks.test_Requests()
checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
@@ -2992,9 +3257,9 @@ def main():
checks.configureOpenDKIM()
checks.modSecPreReqs()
checks.setupVirtualEnv()
checks.setupPHPAndComposer()
if args.postfix != None:
checks.enableDisableEmail(args.postfix)
else:

Binary file not shown.

0
ipManagement/__init__.py Normal file
View File

6
ipManagement/admin.py Normal file
View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.

8
ipManagement/apps.py Normal file
View File

@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class IpmanagementConfig(AppConfig):
name = 'ipManagement'

View File

20
ipManagement/models.py Normal file
View File

@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from loginSystem.models import Administrator
from hypervisor.models import HyberVisors
# Create your models here.
class IPPool(models.Model):
hv = models.ForeignKey(HyberVisors, on_delete=models.CASCADE)
poolName = models.CharField(unique=True, max_length = 50)
gateway = models.CharField(max_length = 50)
netmask = models.CharField(max_length=50)
class IPAddresses(models.Model):
pool = models.ForeignKey(IPPool, on_delete=models.CASCADE)
ipAddr = models.CharField(max_length=50, unique=True)
used = models.IntegerField(default=0)
macAddress = models.CharField(max_length=50, default='Auto')

View File

@@ -0,0 +1,458 @@
/**
* Created by usman on 5/18/18.
*/
/* Java script code to create IP Pool */
app.controller('createIPPoolCTRL', function($scope,$http) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.createIPPool = function(){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/ip/submitIPPoolCreation";
var data = {
poolName: $scope.poolName,
poolGateway: $scope.poolGateway,
poolNetmask: $scope.poolNetmask,
poolStartingIP: $scope.poolStartingIP,
poolEndingIP: $scope.poolEndingIP,
hvName: $scope.hvName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
$scope.successMessage = response.data.successMessage;
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
});
/* Java script code to create IP Pool ends here */
/* Java script code to List IP Pools */
app.controller('listIPPoolsCTRL', function($scope,$http) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
// Special
$scope.currentRecords = true;
$scope.macBox = true;
$scope.fetchRecords = function(){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/ip/fetchIPsInPool";
var data = {
poolName: $scope.poolName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
//
$scope.currentRecords = false;
$scope.successMessage = response.data.successMessage;
$scope.records = JSON.parse(response.data.data);
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
$scope.changeMac = function(ipAddr){
// Special
$scope.macIP = ipAddr;
$scope.macBox = false;
};
$scope.changeMacFinal = function(){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/ip/submitNewMac";
var data = {
macIP: $scope.macIP,
newMac: $scope.newMac
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
//
$scope.currentRecords = false;
$scope.successMessage = response.data.successMessage;
$scope.fetchRecords();
$scope.macBox = true;
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
$scope.deleteIP = function(id){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/ip/deleteIP";
var data = {
id: id
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
//
$scope.currentRecords = false;
$scope.successMessage = response.data.successMessage;
$scope.fetchRecords();
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
$scope.deletePool = function(){
$scope.tronLoading = false;
var url = "/ip/deletePool";
var data = {
poolName: $scope.poolName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
//
new PNotify({
title: 'Success!',
text: 'Pool successfully deleted.',
type:'success'
});
}
else
{
$scope.tronLoading = true;
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
$scope.addSingleIP = function(){
$scope.tronLoading = false;
var url = "/ip/addSingleIP";
var data = {
poolName: $scope.poolName,
newIP: $scope.newIP
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
//
new PNotify({
title: 'Success!',
text: 'IP successfully added.',
type:'success'
});
$scope.fetchRecords();
}
else
{
$scope.tronLoading = true;
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
$scope.addMultipleIP = function(){
$scope.tronLoading = false;
var url = "/ip/addMultipleIP";
var data = {
poolName: $scope.poolName,
startingIP: $scope.startingIP,
endingIP: $scope.endingIP
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
//
new PNotify({
title: 'Success!',
text: 'IP successfully added.',
type:'success'
});
$scope.fetchRecords();
}
else
{
$scope.tronLoading = true;
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page.',
type:'error'
});
}
};
});
/* Java script code to List IP Pools ends here */

View File

@@ -0,0 +1,114 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Create IP Pool - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Create IP Pool" %}</h2>
<p>{% trans "Create IP Pool on this page." %}</p>
</div>
<div ng-controller="createIPPoolCTRL" class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Pool Details" %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Server" %}</label>
<div class="col-sm-6">
<select ng-model="hvName" class="form-control">
{% for items in hvNames %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Pool Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="poolName" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Gateway" %}</label>
<div class="col-sm-6">
<input name="dspace" type="text" class="form-control" ng-model="poolGateway" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "NetMask" %}</label>
<div class="col-sm-6">
<input name="dspace" type="text" class="form-control" ng-model="poolNetmask" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Starting IP" %}</label>
<div class="col-sm-6">
<input name="bwidth" type="text" class="form-control" ng-model="poolStartingIP" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Ending IP" %}</label>
<div class="col-sm-6">
<input name="eaccts" type="text" class="form-control" ng-model="poolEndingIP" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="createIPPool()" class="btn btn-primary btn-lg btn-block">{% trans "Create Pool" %}</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<div ng-hide="poolCreationFailed" class="alert alert-danger">
<p>{% trans "Error message:" %} {$ errorMessage $}</p>
</div>
<div ng-hide="poolCreated" class="alert alert-success">
<p>{$ successMessage $}</p>
</div>
<div ng-hide="couldNotConnect" class="alert alert-danger">
<p>{% trans "Could not connect to server, please refresh this page." %}</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,56 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "IP Management - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "IP Management" %}</h2>
<p>{% trans "IPs are needed to create virtual machines, navigate through this page to manage IPs." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Available Functions" %}
</h3>
<div class="example-box-wrapper">
<div class="row">
<div class="col-md-4">
<a href="{% url 'createIPPool' %}" title="{% trans 'Create IP Pool' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Create IP Pool" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'listIPPools' %}" title="{% trans 'List IP Pools' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "List IP Pools" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,209 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "List IP Pools - CyberTron" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "List IP Pools" %}</h2>
<p>{% trans "On this page you list IP pools to view their IP addresses or assign MAC." %}</p>
</div>
<div ng-controller="listIPPoolsCTRL" class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "List Pools" %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Pool" %} </label>
<div class="col-sm-6">
<select ng-change="fetchRecords()" ng-model="poolName" class="form-control">
{% for items in ipPools %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<div ng-hide="currentRecords" class="form-group">
<label class="col-sm-1 control-label"></label>
<div class="col-sm-3">
<button data-toggle="modal" data-target="#deletePool" class="btn ra-100 btn-danger">{% trans 'Delete Pool' %}</button>
<!--- Delete Pool --->
<div class="modal fade" id="deletePool" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title">{% trans "You are doing to delete an IP Pool.." %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}"></h4>
</div>
<div class="modal-body">
<p>{% trans 'Are you sure?' %}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans 'Close' %}</button>
<button data-dismiss="modal" ng-click="deletePool()" type="button" class="btn btn-primary">{% trans 'Confirm' %}</button>
</div>
</div>
</div>
</div>
<!--- Delete Pool --->
</div>
<div class="col-sm-3">
<button data-toggle="modal" data-target="#singleIP" class="btn ra-100 btn-blue-alt">{% trans 'Add Single IP' %}</button>
<!--- Add Single IP --->
<div class="modal fade" id="singleIP" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title">{% trans "Add single IP to this pool." %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}"></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label style="color: green" class="col-sm-3 control-label">{% trans "IP Address " %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="newIP" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans 'Close' %}</button>
<button data-dismiss="modal" ng-click="addSingleIP()" type="button" class="btn btn-primary">{% trans 'Add IP' %}</button>
</div>
</div>
</div>
</div>
<!--- Delete Pool --->
</div>
<div class="col-sm-3">
<button data-toggle="modal" data-target="#multipleIPs" class="btn ra-100 btn-blue-alt">{% trans 'Add Multiple IPs' %}</button>
<!--- Add Mutiple IPs --->
<div class="modal fade" id="multipleIPs" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title">{% trans "Add Multiple IPs to this pool." %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}"></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label style="color: green" class="col-sm-3 control-label">{% trans "Starting IP" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="startingIP" required>
</div>
</div>
</div>
<div class="modal-body">
<div class="form-group">
<label style="color: green" class="col-sm-3 control-label">{% trans "Ending IP" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="endingIP" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans 'Close' %}</button>
<button data-dismiss="modal" ng-click="addMultipleIP()" type="button" class="btn btn-primary">{% trans 'Add IPs' %}</button>
</div>
</div>
</div>
</div>
<!--- Add Multiple IPs --->
</div>
</div>
<div ng-hide="macBox" class="form-group">
<label style="color: green" class="col-sm-3 control-label">{% trans "Changing MAC for: " %} {$ macIP $}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="newMac" required>
</div>
</div>
<div ng-hide="macBox" class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button ng-click="changeMacFinal()" type="button" class="btn btn-primary btn-lg btn-block">{% trans "Change MAC" %}</button>
</div>
</div>
<!------ List of records --------------->
<div ng-hide="currentRecords" class="form-group">
<div class="col-sm-12">
<table class="table">
<thead>
<tr>
<th>{% trans "ID" %}</th>
<th>{% trans "IP" %}</th>
<th>{% trans "Assignment" %}</th>
<th>{% trans "MAC" %}</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="record in records track by $index">
<td ng-bind="record.id"></td>
<td ng-bind="record.ipAddr"></td>
<td ng-bind="record.used"></td>
<td ng-bind="record.macAddress"></td>
<td >
<button type="button" ng-click="changeMac(record.ipAddr)" class="btn ra-100 btn-purple">{% trans "Edit Mac" %}</button>
<button type="button" ng-click="deleteIP(record.id)" class="btn ra-100 btn-purple">{% trans "Delete IP" %}</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!------ List of records --------------->
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<div ng-hide="poolCreationFailed" class="alert alert-danger">
<p>{% trans "Error message:" %} {$ errorMessage $}</p>
</div>
<div ng-hide="poolCreated" class="alert alert-success">
<p>{$ successMessage $}</p>
</div>
<div ng-hide="couldNotConnect" class="alert alert-danger">
<p>{% trans "Could not connect to server, please refresh this page." %}</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

6
ipManagement/tests.py Normal file
View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.

23
ipManagement/urls.py Normal file
View File

@@ -0,0 +1,23 @@
"""
CyberTron URL Configuration
"""
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$', views.listIPHome, name='listIPHome'),
url(r'^createIPPool$', views.createIPPool, name='createIPPool'),
url(r'^submitIPPoolCreation$', views.submitIPPoolCreation, name='submitIPPoolCreation'),
url(r'^listIPPools$', views.listIPPools, name='listIPPools'),
url(r'^fetchIPsInPool$', views.fetchIPsInPool, name='fetchIPsInPool'),
url(r'^submitNewMac$', views.submitNewMac, name='submitNewMac'),
url(r'^deleteIP$', views.deleteIP, name='deleteIP'),
url(r'^deletePool$', views.deletePool, name='deletePool'),
url(r'^addSingleIP$', views.addSingleIP, name='addSingleIP'),
url(r'^addMultipleIP$', views.addMultipleIP, name='addMultipleIP'),
]

335
ipManagement/views.py Normal file
View File

@@ -0,0 +1,335 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse,redirect
from loginSystem.models import Administrator
from CyberTronAPI.CyberTronLogger import CyberTronLogger as logging
from loginSystem.views import loadLoginPage
import json
from .models import IPPool, IPAddresses
from inspect import stack
from plogical.aclVMM import vmmACLManager
from plogical.acl import ACLManager
from hypervisor.models import HyberVisors
from vpsManagement.models import VPS
# Create your views here.
def listIPHome(request):
try:
userID = request.session['userID']
try:
return render(request, 'ipManagement/indexVMM.html', )
except BaseException, msg:
logging.writeToFile(str(msg))
return HttpResponse(str(msg))
except KeyError:
return redirect(loadLoginPage)
def createIPPool(request):
try:
userID = request.session['userID']
try:
currentACL = ACLManager.loadedACL(userID)
if vmmACLManager.currentContextPermission(currentACL, 'createIPPool') == 0:
return ACLManager.loadError()
hvNames = vmmACLManager.findHyperVisorNames(currentACL, userID)
data = {'hvNames': hvNames}
return render(request, 'ipManagement/createIPPool.html', data)
except BaseException, msg:
logging.writeToFile(str(msg))
return HttpResponse(str(msg))
except KeyError:
return redirect(loadLoginPage)
def submitIPPoolCreation(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
poolName = data['poolName']
poolGateway = data['poolGateway']
poolNetmask = data['poolNetmask']
poolStartingIP = data['poolStartingIP']
poolEndingIP = data['poolEndingIP']
hvName = data['hvName']
hv = HyberVisors.objects.get(hypervisorName=hvName)
newIPPool = IPPool(poolName=poolName, gateway=poolGateway, netmask=poolNetmask, hv=hv)
newIPPool.save()
## Adding IPs -- Getting 192.168.100. from 192.168.100.100
index = poolStartingIP.rindex('.')
ipValue = poolStartingIP[:index + 1]
## Calculating range and adding to database.
startingValue = int(poolStartingIP.split('.')[-1])
endingValue = int(poolEndingIP.split('.')[-1])
for ips in range(startingValue, endingValue + 1):
newIPAddress = IPAddresses(pool=newIPPool, ipAddr=ipValue + str(ips))
newIPAddress.save()
data_ret = {"success": 1, 'error_message': "None", 'successMessage' : 'Pool successfully created.'}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def listIPPools(request):
try:
val = request.session['userID']
try:
admin = Administrator.objects.get(pk=val)
poolNames = []
if admin.type == 1:
ipPools = IPPool.objects.all()
for pool in ipPools:
poolNames.append(pool.poolName)
return render(request, 'ipManagement/listIPPools.html', {'ipPools' : poolNames})
except BaseException, msg:
logging.writeToFile(str(msg), "Error", stack()[0][3])
return HttpResponse(str(msg))
except KeyError:
return redirect(loadLoginPage)
def fetchIPsInPool(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
poolName = data['poolName']
pool = IPPool.objects.get(poolName=poolName)
ipAddresses = pool.ipaddresses_set.all()
json_data = "["
checker = 0
for ips in ipAddresses:
if ips.used == 0:
used = 'Not Assigned'
else:
vps = VPS.objects.get(ipAddr=ips)
used = vps.hostName
dic = {
'id': ips.id,
'ipAddr': ips.ipAddr,
'used': used,
'macAddress': ips.macAddress,
}
if checker == 0:
json_data = json_data + json.dumps(dic)
checker = 1
else:
json_data = json_data + ',' + json.dumps(dic)
json_data = json_data + ']'
data_ret = {"success": 1, 'error_message': "None", 'successMessage' : 'Records successfully fetched.', "data" : json_data}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def submitNewMac(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
macIP = data['macIP']
newMac = data['newMac']
ip = IPAddresses.objects.get(ipAddr=macIP)
ip.macAddress = newMac
ip.save()
data_ret = {"success": 1, 'error_message': "None", 'successMessage' : 'MAC Address successfully updated.'}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def deleteIP(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
id = data['id']
ip = IPAddresses.objects.get(id=id)
if ip.used == 0:
ip.delete()
data_ret = {"success": 1, 'error_message': "None",
'successMessage': 'IP Address successfully deleted.'}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
data_ret = {"success": 0, 'error_message': "IP is used by a VPS.",
}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def deletePool(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
poolName = data['poolName']
delPool = IPPool.objects.get(poolName=poolName)
delPool.delete()
data_ret = {"success": 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': 'One or more IPs inside this pool is assigned to a VPS.'}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError, msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def addSingleIP(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
poolName = data['poolName']
newIP = data['newIP']
relatedPool = IPPool.objects.get(poolName=poolName)
newIPAddress = IPAddresses(pool=relatedPool, ipAddr=newIP)
newIPAddress.save()
data_ret = {"success": 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError, msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def addMultipleIP(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
poolName = data['poolName']
startingIP = data['startingIP']
endingIP = data['endingIP']
relatedPool = IPPool.objects.get(poolName=poolName)
index = startingIP.rindex('.')
ipValue = startingIP[:index + 1]
## Calculating range and adding to database.
startingValue = int(startingIP.split('.')[-1])
endingValue = int(endingIP.split('.')[-1])
for ips in range(startingValue, endingValue + 1):
newIPAddress = IPAddresses(pool=relatedPool, ipAddr=ipValue + str(ips))
newIPAddress.save()
data_ret = {"success": 1, 'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError, msg:
data_ret = {"success": 0,
'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)

View File

@@ -15,3 +15,12 @@ class Package(models.Model):
dataBases = models.IntegerField(default=0)
ftpAccounts = models.IntegerField(default=0)
allowedDomains = models.IntegerField(default=0)
class VMPackage(models.Model):
admin = models.ForeignKey(Administrator,on_delete=models.CASCADE)
packageName = models.CharField(max_length=50,unique=True)
diskSpace = models.CharField(max_length=50)
bandwidth = models.CharField(max_length=50)
guaranteedRam = models.CharField(max_length=50, default='1024')
cpuCores = models.CharField(max_length=50, default='1')

View File

@@ -4,12 +4,6 @@
/**
* Created by usman on 7/25/17.
*/
/* Utilities */
function getCookie(name) {
@@ -31,15 +25,11 @@ function getCookie(name) {
/* Utilities ends here */
/* Java script code to create Pacakge */
$("#packageCreationFailed").hide();
$("#packageCreated").hide();
app.controller('createPackage', function($scope,$http) {
//$scope.pname = /([A-Z]){3,10}/gi;
@@ -103,20 +93,15 @@ app.controller('createPackage', function($scope,$http) {
});
/* Java script code to to create Pacakge ends here */
/* Java script code to delete Pacakge */
$("#deleteFailure").hide();
$("#deleteSuccess").hide();
$("#deletePackageButton").hide();
app.controller('deletePackage', function($scope,$http) {
@@ -179,12 +164,8 @@ app.controller('deletePackage', function($scope,$http) {
});
/* Java script code to delete package ends here */
/* Java script code modify package */
$("#packageDetailsToBeModified").hide();
@@ -336,7 +317,294 @@ app.controller('modifyPackages', function($scope,$http) {
};
});
/* Java script code to Modify Pacakge ends here */
/**** VMM */
/* Java script code to create Pacakge */
app.controller('createPackageVMM', function($scope,$http) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.insertPackInDB = function(){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/packages/submitPackageVMM";
var data = {
packageName: $scope.packageName,
diskSpace: $scope.diskSpace,
guaranteedRam: $scope.guaranteedRam,
bandwidth: $scope.bandwidth,
cpuCores: $scope.cpuCores,
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
$scope.successMessage = response.data.successMessage;
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
});
/* Java script code to to create Pacakge ends here */
/* Java script code to delete Pacakge */
$("#deleteFailure").hide();
$("#deleteSuccess").hide();
$("#deletePackageButton").hide();
app.controller('deletePackageVMM', function($scope,$http) {
$scope.deletePackage = function(){
$("#deletePackageButton").fadeIn();
};
$scope.deletePackageFinal = function(){
var packageName = $scope.packageToBeDeleted;
url = "/packages/submitDeleteVMM";
var data = {
packageName: packageName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if (response.data.deleteStatus === 0)
{
$scope.errorMessage = response.data.error_message;
$("#deleteFailure").fadeIn();
$("#deleteSuccess").hide();
$("#deletePackageButton").hide();
}
else{
$("#deleteFailure").hide();
$("#deleteSuccess").fadeIn();
$("#deletePackageButton").hide();
$scope.deletedPackage = packageName;
}
}
function cantLoadInitialDatas(response) {
console.log("not good");
}
};
});
/* Java script code to delete package ends here */
$("#packageDetailsToBeModified").hide();
$("#modifyFailure").hide();
$("#modifySuccess").hide();
$("#modifyButton").hide();
$("#packageLoading").hide();
$("#successfullyModified").hide();
app.controller('modifyPackagesVMM', function($scope,$http) {
$scope.fetchDetails = function(){
$("#packageLoading").show();
$("#successfullyModified").hide();
var packageName = $scope.packageToBeModified;
console.log(packageName);
url = "/packages/submitModifyVMM";
var data = {
packageName: packageName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if (response.data.modifyStatus === 0)
{
$scope.errorMessage = response.data.error_message;
$("#modifyFailure").fadeIn();
$("#modifySuccess").hide();
$("#modifyButton").hide();
$("#packageLoading").hide();
}
else{
$("#modifyButton").show();
$scope.packageName = response.data.packageName;
$scope.diskSpace = response.data.diskSpace;
$scope.guaranteedRam = response.data.guaranteedRam;
$scope.bandwidth = response.data.bandwidth;
$scope.cpuCores = response.data.cpuCores;
$scope.modifyButton = "Save Details";
$("#packageDetailsToBeModified").fadeIn();
$("#modifyFailure").hide();
$("#modifySuccess").fadeIn();
$("#packageLoading").hide();
}
}
function cantLoadInitialDatas(response) {
console.log("not good");
}
};
$scope.modifyPackageFunc = function () {
$("#modifyFailure").hide();
$("#modifySuccess").hide();
$("#packageLoading").show();
$("#packageDetailsToBeModified").hide();
url = "/packages/saveChangesVMM";
var data = {
packageName: $scope.packageToBeModified,
diskSpace:$scope.diskSpace,
bandwidth:$scope.bandwidth,
guaranteedRam:$scope.guaranteedRam,
cpuCores:$scope.cpuCores
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if (response.data.saveStatus == 0)
{
$scope.errorMessage = response.data.error_message;
$("#modifyFailure").fadeIn();
$("#modifySuccess").hide();
$("#modifyButton").hide();
$("#packageLoading").hide();
}
else{
$("#modifyButton").hide();
$("#successfullyModified").fadeIn();
$("#modifyFailure").hide();
$("#packageLoading").hide();
$scope.packageModified = packageName;
}
}
function cantLoadInitialDatas(response) {
console.log("not good");
}
};
});

View File

@@ -0,0 +1,102 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Create Package - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div ng-controller="createPackageVMM" class="container">
<div id="page-title">
<h2>{% trans "Create Package" %}</h2>
<p>{% trans "Packages define resources for your VPS, you need to add package before creating a VPS." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Package Details" %} <img ng-hide="tronLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Package Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="packageName" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Disk Space" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="diskSpace" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Guranteed Ram" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="guaranteedRam" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Bandwidth" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="bandwidth" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "CPU Cores" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="cpuCores" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="insertPackInDB()" class="btn btn-primary btn-lg btn-block">{% trans "Create Package" %}</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<div ng-hide="poolCreationFailed" class="alert alert-danger">
<p>{% trans "Error message:" %} {$ errorMessage $}</p>
</div>
<div ng-hide="poolCreated" class="alert alert-success">
<p>{$ successMessage $}</p>
</div>
<div ng-hide="couldNotConnect" class="alert alert-danger">
<p>{% trans "Could not connect to server, please refresh this page." %}</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,85 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Delete Package - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Delete Package" %}</h2>
<p>{% trans "Packages define resources for your websites, you need to add package before creating a website." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Delete Package" %}
</h3>
<div ng-controller="deletePackageVMM" class="example-box-wrapper">
<form action="/" id="deletePackage" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Package" %}</label>
<div class="col-sm-6">
<select ng-model="packageToBeDeleted" class="form-control">
{% for items in packageList %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="deletePackage()" class="btn btn-primary btn-lg btn-block">{% trans "Delete Package" %}</button>
</div>
</div>
<div id="deletePackageButton" class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="deletePackageFinal()" class="btn btn-primary btn-lg btn-block">{% trans "Are you sure?" %}</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<div id="deleteFailure" class="alert alert-danger">
<p>{% trans "Cannot delete package. Error message:" %} {$ errorMessage $}</p>
</div>
<div id="deleteSuccess" class="alert alert-success">
<p>{% trans "Package" %} <strong>{$ deletedPackage $}</strong>{% trans " Successfully Deleted" %}"</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,70 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Packages - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Packages" %}</h2>
<p>{% trans "Packages define resources for your virtual machines, you need to add package before creating a virtual machine." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Available Functions" %}
</h3>
<div class="example-box-wrapper">
<div class="row">
<div class="col-md-4">
<a href="{% url 'createPackageVMM' %}" title="{% trans 'Create Package' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Create Package" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'deletePackageVMM' %}" title="{% trans 'Delete Package' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Delete Package" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'modifyPackageVMM' %}" title="{% trans 'Modify Package' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Modify Package" %}
</div>
<div class="tile-content-wrapper">
<i class="glyph-icon icon-dashboard"></i>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,122 @@
{% extends "baseTemplate/indexVMM.html" %}
{% load i18n %}
{% block title %}{% trans "Modify Package - CyberPanel" %}{% endblock %}
{% block content %}
{% load static %}
<div class="container">
<div id="page-title">
<h2>{% trans "Modify Package" %}</h2>
<p>{% trans "Packages define resources for your websites, you need to add package before creating a website." %}</p>
</div>
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "Modify Package" %} <img id="packageLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">
<form ng-controller="modifyPackagesVMM" action="/" id="modifyPackageForm" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Package" %} </label>
<div class="col-sm-6">
<select ng-change="fetchDetails()" ng-model="packageToBeModified" class="form-control">
{% for items in packList %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
<!------ Modification form that appears after a click --------------->
<div id="packageDetailsToBeModified">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Disk Space" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="diskSpace" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Guranteed Ram" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="guaranteedRam" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Bandwidth" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="bandwidth" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "CPU Cores" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="cpuCores" required>
</div>
</div>
</div>
<!------ Modification form that appears after a click --------------->
<div id="modifyButton" class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="modifyPackageFunc()" class="btn btn-primary btn-lg btn-block">{% trans "Modify Package" %}</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<div id="modifyFailure" class="alert alert-danger">
<p>{% trans "Cannot fetch package details. Error message:" %} {$ errorMessage $}</p>
</div>
<div id="modifySuccess" class="alert alert-success">
<p>{% trans "Package Details Successfully Fetched" %}</p>
</div>
<div id="successfullyModified" class="alert alert-success">
<p>{% trans "Package" %} <strong>{$ packageModified $}</strong> {% trans "Successfully Modified" %}</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -3,6 +3,7 @@ import views
urlpatterns = [
url(r'^$', views.packagesHome, name='packagesHome'),
url(r'^VMM$', views.packagesHomeVMM, name='packagesHomeVMM'),
url(r'^createPackage$', views.createPacakge, name='createPackage'),
url(r'^deletePacakge$', views.deletePacakge, name='deletePackage'),
url(r'^modifyPackage$', views.modifyPackage, name='modifyPackage'),
@@ -10,10 +11,24 @@ urlpatterns = [
# Pacakge Modification URLs
url(r'^submitPackage', views.submitPackage, name='submitPackage'),
url(r'^submitDelete', views.submitDelete, name='submitDelete'),
url(r'^submitModify', views.submitModify, name='submitModify'),
url(r'^saveChanges', views.saveChanges, name='saveChanges'),
url(r'^submitPackage$', views.submitPackage, name='submitPackage'),
url(r'^submitDelete$', views.submitDelete, name='submitDelete'),
url(r'^submitModify$', views.submitModify, name='submitModify'),
url(r'^saveChanges$', views.saveChanges, name='saveChanges'),
###
url(r'^createPackageVMM$', views.createPacakgeVMM, name='createPackageVMM'),
url(r'^deletePacakgeVMM$', views.deletePacakgeVMM, name='deletePackageVMM'),
url(r'^modifyPackageVMM$', views.modifyPackageVMM, name='modifyPackageVMM'),
# Pacakge Modification URLs
url(r'^submitPackageVMM$', views.submitPackageVMM, name='submitPackageVMM'),
url(r'^submitDeleteVMM$', views.submitDeleteVMM, name='submitDeleteVMM'),
url(r'^submitModifyVMM$', views.submitModifyVMM, name='submitModifyVMM'),
url(r'^saveChangesVMM$', views.saveChangesVMM, name='saveChangesVMM'),
]

View File

@@ -6,7 +6,7 @@ from django.http import HttpResponse
from loginSystem.views import loadLoginPage
from loginSystem.models import Administrator
import json
from .models import Package
from .models import Package, VMPackage
import plogical.CyberCPLogFileWriter as logging
from plogical.acl import ACLManager
@@ -16,11 +16,10 @@ from plogical.acl import ACLManager
def packagesHome(request):
try:
val = request.session['userID']
return render(request, 'packages/index.html', {})
except KeyError:
return redirect(loadLoginPage)
return render(request,'packages/index.html',{})
def createPacakge(request):
try:
@@ -256,3 +255,210 @@ def saveChanges(request):
data_ret = {'saveStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
##
def packagesHomeVMM(request):
try:
val = request.session['userID']
return render(request, 'packages/indexVMM.html', {})
except KeyError:
return redirect(loadLoginPage)
def createPacakgeVMM(request):
try:
val = request.session['userID']
admin = Administrator.objects.get(pk=val)
if admin.type == 3:
return HttpResponse("You don't have enough privileges to access this page.")
except KeyError:
return redirect(loadLoginPage)
return render(request,'packages/createPackageVMM.html',{"admin":admin.userName})
def deletePacakgeVMM(request):
try:
val = request.session['userID']
try:
admin = Administrator.objects.get(pk=val)
if admin.type == 3:
return HttpResponse("You don't have enough privileges to access this page.")
if admin.type == 1:
packages = VMPackage.objects.all()
else:
packages = VMPackage.objects.filter(admin=admin)
packageList = []
for items in packages:
packageList.append(items.packageName)
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse("Please see CyberCP Main Log File")
except KeyError:
return redirect(loadLoginPage)
return render(request,'packages/deletePackageVMM.html',{"packageList" : packageList})
def submitPackageVMM(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
packageName = data['packageName']
diskSpace = data['diskSpace']
guaranteedRam = data['guaranteedRam']
bandwidth = data['bandwidth']
cpuCores = data['cpuCores']
admin = Administrator.objects.get(pk=request.session['userID'])
packageName = packageName
package = VMPackage(admin=admin,
packageName=packageName,
diskSpace=diskSpace,
guaranteedRam=guaranteedRam,
bandwidth=bandwidth,
cpuCores=cpuCores,
)
package.save()
data_ret = {'success': 1,'error_message': "None", 'successMessage': 'Package successfully created!'}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {'success': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError:
return redirect(loadLoginPage)
def submitDeleteVMM(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
packageName = data['packageName']
delPackage = VMPackage.objects.get(packageName=packageName)
delPackage.delete()
data_ret = {'deleteStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {'deleteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError,msg:
data_ret = {'deleteStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def modifyPackageVMM(request):
try:
val = request.session['userID']
try:
admin = Administrator.objects.get(pk=val)
if admin.type == 3:
return HttpResponse("You don't have enough privileges to access this page.")
if admin.type == 1:
packages = VMPackage.objects.all()
else:
packages = VMPackage.objects.filter(admin=admin)
packageList = []
for items in packages:
packageList.append(items.packageName)
return render(request, 'packages/modifyPackageVMM.html', {"packList": packageList})
except BaseException,msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse("Please see CyberCP Main Log File")
except KeyError:
return redirect(loadLoginPage)
def submitModifyVMM(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
packageName = data['packageName']
modifyPack = VMPackage.objects.get(packageName=packageName)
diskSpace = modifyPack.diskSpace
guaranteedRam = modifyPack.guaranteedRam
bandwidth = modifyPack.bandwidth
cpuCores = modifyPack.cpuCores
data_ret = {'modifyStatus': 1,
'error_message': "None",
'packageName' : packageName,
'diskSpace':diskSpace,
'guaranteedRam':guaranteedRam,
'bandwidth': bandwidth,
'cpuCores': cpuCores,
}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {'modifyStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError,msg:
data_ret = {'modifyStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
def saveChangesVMM(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
data = json.loads(request.body)
packageName = data['packageName']
modifyPack = VMPackage.objects.get(packageName=packageName)
modifyPack.diskSpace = data['diskSpace']
modifyPack.bandwidth = data['bandwidth']
modifyPack.guaranteedRam = data['guaranteedRam']
modifyPack.cpuCores = data['cpuCores']
modifyPack.save()
data_ret = {'saveStatus': 1,'error_message': "None"}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except BaseException,msg:
data_ret = {'saveStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
except KeyError,msg:
data_ret = {'saveStatus': 0, 'error_message': str(msg)}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)

0
plogical/.my.cnf.4370 Normal file → Executable file
View File

0
plogical/.mysql.4370 Normal file → Executable file
View File

0
plogical/CyberCPLogFileWriter.py Normal file → Executable file
View File

0
plogical/__init__.py Normal file → Executable file
View File

0
plogical/acl.py Normal file → Executable file
View File

277
plogical/aclVMM.py Executable file
View File

@@ -0,0 +1,277 @@
#!/usr/local/CyberCP/bin/python2
import os,sys
sys.path.append('/usr/local/CyberCP')
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
from loginSystem.models import Administrator
from django.shortcuts import HttpResponse
from hypervisor.models import HyberVisors
from vpsManagement.models import SSHKeys, VPS
import json
from packages.models import VMPackage as Package
class vmmACLManager:
@staticmethod
def inspectHyperVisor():
return 1
@staticmethod
def loadError():
try:
return HttpResponse('You are not authorized to access this resource.')
except:
pass
@staticmethod
def currentContextPermission(currentACL, context):
return 1
@staticmethod
def findServersObjs(currentACL, userID):
if currentACL['admin'] == 1:
return HyberVisors.objects.all()
else:
hvList = []
admin = Administrator.objects.get(pk=userID)
hvs = admin.hybervisors_set.all()
for items in hvs:
hvList.append(items)
admins = Administrator.objects.filter(owner=admin.pk)
for items in admins:
hvs = items.hybervisors_set.all()
for hv in hvs:
hvList.append(hv)
return hvList
@staticmethod
def prepareServers(serverObjs):
preparedServers = []
for items in serverObjs:
data = {}
data['id'] = items.id
data['hypervisorOwner'] = items.hypervisorOwner.userName
data['hypervisorName'] = items.hypervisorName
data['hypervisorIP'] = items.hypervisorIP
data['vms'] = items.vps_set.all().count()
data['hypervisorStoragePath'] = items.hypervisorStoragePath
preparedServers.append(data)
return preparedServers
@staticmethod
def fetchSSHkeys(currentACL, userID):
if currentACL['admin'] == 1:
allKeys = SSHKeys.objects.all()
json_data = "["
checker = 0
for items in allKeys:
dic = {
'keyName': items.keyName,
'key': items.key,
}
if checker == 0:
json_data = json_data + json.dumps(dic)
checker = 1
else:
json_data = json_data + ',' + json.dumps(dic)
json_data = json_data + ']'
return json_data
else:
admin = Administrator.objects.get(pk=userID)
sshkeys = admin.sshkeys_set.all()
json_data = "["
checker = 0
for items in sshkeys:
dic = {
'keyName': items.keyName,
'key': items.key,
}
if checker == 0:
json_data = json_data + json.dumps(dic)
checker = 1
else:
json_data = json_data + ',' + json.dumps(dic)
admins = Administrator.objects.filter(owner=admin.pk)
for items in admins:
sshkeys = items.sshkeys_set.all()
for items in sshkeys:
dic = {
'keyName': items.keyName,
'key': items.key,
}
if checker == 0:
json_data = json_data + json.dumps(dic)
checker = 1
else:
json_data = json_data + ',' + json.dumps(dic)
json_data = json_data + ']'
return json_data
@staticmethod
def fetchSSHkeysObjects(currentACL, userID):
if currentACL['admin'] == 1:
return SSHKeys.objects.all()
else:
keysObjects = []
admin = Administrator.objects.get(pk=userID)
sshkeys = admin.sshkeys_set.all()
for items in sshkeys:
keysObjects.append(items)
admins = Administrator.objects.filter(owner=admin.pk)
for items in admins:
sshkeys = items.sshkeys_set.all()
for items in sshkeys:
keysObjects.append(items)
return keysObjects
@staticmethod
def findSSHkeyNames(currentACL, userID):
sshKeysObjects = vmmACLManager.fetchSSHkeysObjects(currentACL, userID)
keyNames = []
for items in sshKeysObjects:
keyNames.append(items.keyName)
return keyNames
@staticmethod
def fetchHyperVisorObjects(currentACL, userID):
if currentACL['admin'] == 1:
return HyberVisors.objects.all()
else:
hvObjects = []
admin = Administrator.objects.get(pk=userID)
hvs = admin.hybervisors_set.all()
for items in hvs:
hvObjects.append(items)
admins = Administrator.objects.filter(owner=admin.pk)
for items in admins:
hvs = items.hybervisors_set.all()
for items in hvs:
hvObjects.append(items)
return hvObjects
@staticmethod
def findHyperVisorNames(currentACL, userID):
hvs = vmmACLManager.fetchHyperVisorObjects(currentACL, userID)
hvNames = []
for items in hvs:
hvNames.append(items.hypervisorName)
return hvNames
@staticmethod
def findAllIPObjs(hv):
ipObjs = []
allPools = hv.ippool_set.all()
for ipPool in allPools:
allIPs = ipPool.ipaddresses_set.all()
for ip in allIPs:
ipObjs.append(ip)
return ipObjs
@staticmethod
def findAllIPs(hv):
allIps = vmmACLManager.findAllIPObjs(hv)
ipAddresses = []
for items in allIps:
if items.used == 1:
continue
ipAddresses.append(items.ipAddr)
return ipAddresses
@staticmethod
def jsonIPs(hv):
allIPs = vmmACLManager.findAllIPs(hv)
json_data = "["
checker = 0
for items in allIPs:
dic = {'ipAddr': items}
if checker == 0:
json_data = json_data + json.dumps(dic)
checker = 1
else:
json_data = json_data + ',' + json.dumps(dic)
json_data = json_data + ']'
return json_data
@staticmethod
def findAllPackages(currentACL, userID):
if currentACL['admin'] == 1:
packageNames = []
packages = Package.objects.all()
for package in packages:
packageNames.append(package.packageName)
return packageNames
@staticmethod
def checkOwner(currentACL, userID):
return 1
@staticmethod
def findAllVPSOBjs(currentACL, userID):
if currentACL['admin'] == 1:
return VPS.objects.all()
else:
vmObjects = []
admin = Administrator.objects.get(pk=userID)
hvs = admin.vps_set.all()
for items in hvs:
vmObjects.append(items)
admins = Administrator.objects.filter(owner=admin.pk)
for items in admins:
hvs = items.vps_set.all()
for items in hvs:
vmObjects.append(items)
return vmObjects

0
plogical/adminPass.py Normal file → Executable file
View File

0
plogical/alias.py Normal file → Executable file
View File

0
plogical/applicationInstaller.py Normal file → Executable file
View File

3
plogical/backupManager.py Normal file → Executable file
View File

@@ -293,6 +293,7 @@ class BackupManager:
execPath = "sudo 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"}
@@ -1181,9 +1182,11 @@ class BackupManager:
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)

0
plogical/backupSchedule.py Normal file → Executable file
View File

0
plogical/backupScheduleLocal.py Normal file → Executable file
View File

0
plogical/backupUtilities.py Normal file → Executable file
View File

0
plogical/childDomain.py Normal file → Executable file
View File

0
plogical/dnsUtilities.py Normal file → Executable file
View File

0
plogical/domain.xml Normal file → Executable file
View File

0
plogical/filemanager.py Normal file → Executable file
View File

0
plogical/findBWUsage.py Normal file → Executable file
View File

0
plogical/firewallManager.py Normal file → Executable file
View File

0
plogical/firewallUtilities.py Normal file → Executable file
View File

0
plogical/ftpUtilities.py Normal file → Executable file
View File

0
plogical/getSystemInformation.py Normal file → Executable file
View File

0
plogical/hashPassword.py Normal file → Executable file
View File

0
plogical/installUtilities.py Normal file → Executable file
View File

0
plogical/letsEncrypt.py Normal file → Executable file
View File

0
plogical/mailUtilities.py Normal file → Executable file
View File

0
plogical/modSec.py Normal file → Executable file
View File

1
plogical/mysqlUtilities.py Normal file → Executable file
View File

@@ -138,7 +138,6 @@ class mysqlUtilities:
cmd = shlex.split(command)
with open(tempStoragePath + "/" + databaseName + '.sql', 'r') as f:
res = subprocess.call(cmd, stdin=f)

0
plogical/phpUtilities.py Normal file → Executable file
View File

0
plogical/processUtilities.py Normal file → Executable file
View File

0
plogical/randomPassword.py Normal file → Executable file
View File

0
plogical/remoteBackup.py Normal file → Executable file
View File

0
plogical/remoteTransferUtilities.py Normal file → Executable file
View File

0
plogical/serverLogs.py Normal file → Executable file
View File

0
plogical/sslUtilities.py Normal file → Executable file
View File

0
plogical/test.py Normal file → Executable file
View File

0
plogical/tuning.py Normal file → Executable file
View File

0
plogical/upgrade.py Normal file → Executable file
View File

0
plogical/vhost.py Normal file → Executable file
View File

21
plogical/virtualHostUtilities.py Normal file → Executable file
View File

@@ -453,6 +453,27 @@ class virtualHostUtilities:
cmd = shlex.split(command)
subprocess.call(cmd)
command = 'hostname ' + virtualHost
cmd = shlex.split(command)
subprocess.call(cmd)
hostNamePath = '/etc/cyberpanel/hostname'
hostname = open(hostNamePath, 'w')
hostname.write(virtualHost)
hostname.close()
f = open(pathToStoreSSLPrivKey)
key = f.read()
f = open(pathToStoreSSLFullChain)
cert = f.read()
f= open('/usr/local/lscp/cyberpanel/noVNC/utils/self.pem', 'w')
f.write(key)
f.write(cert)
f.close()
print "1,None"
return 1,'None'

4
plogical/website.py Normal file → Executable file
View File

@@ -161,14 +161,14 @@ class WebsiteManager:
## Create Configurations
execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = "sudo " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py"
execPath = execPath + " createVirtualHost --virtualHostName " + domain + \
" --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \
"' --virtualHostUser " + externalApp + " --ssl " + str(data['ssl']) + " --dkimCheck " \
+ str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + \
' --websiteOwner ' + websiteOwner + ' --package ' + packageName + ' --tempStatusPath ' + tempStatusPath
logging.CyberCPLogFileWriter.writeToFile(execPath)
subprocess.Popen(shlex.split(execPath))
time.sleep(2)

View File

@@ -52,3 +52,4 @@ urllib3==1.22
zope.component==4.4.1
zope.event==4.3.0
zope.interface==4.5.0
libvirt-python==4.6.0

View File

@@ -1550,4 +1550,480 @@ app.controller('remoteBackupControl', function($scope, $http, $timeout) {
});
///** Backup site ends **///
///** Backup site ends **///
/////////////// Snapshots
/* Java script code for Snapshots */
app.controller('snapshotsCTRL', function($scope,$http) {
$scope.getCurrentSnapshots = function(){
$scope.tronLoading = false;
var url = "/backup/fetchCurrentSnapshots";
var data = {
hostName: $("#hostname").text()
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
$scope.snapshotTable = false;
if(response.data.success === 1){
$scope.snapshots = JSON.parse(response.data.data);
}
else
{
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page',
type:'error'
});
}
};
$scope.getCurrentSnapshots();
/// Administrative Tasks
$scope.tronLoading = true;
$scope.createSnapshotBox = true;
$scope.showSnapshotForm = function () {
$scope.createSnapshotBox = false;
$scope.createSnapshotBTN = true;
$scope.snapshotTable = true;
};
$scope.createSnapShot = function(){
$scope.tronLoading = false;
var url = "/backup/submitSnapshotCreation";
var data = {
hostName: $("#hostname").text(),
snapshotName: $scope.snapshotName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
$scope.getCurrentSnapshots();
$scope.createSnapshotBox = true;
$scope.createSnapshotBTN = false;
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.deleteSnapshot = function(snapshotName){
$scope.tronLoading = false;
var url = "/backup/deletSnapshot";
var data = {
hostName: $("#hostname").text(),
snapshotName: snapshotName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
$scope.getCurrentSnapshots();
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.revertToSnapshot = function(snapshotName){
$scope.tronLoading = false;
var url = "/backup/revertToSnapshot";
var data = {
hostName: $("#hostname").text(),
snapshotName: snapshotName
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.changeRootPassword = function(vpsID){
$scope.tronLoading = false;
var url = "/vps/changeRootPassword";
var data = {
hostName: $("#vpsHostname").text(),
newPassword: $scope.newPassword
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
$scope.successMessage = response.data.successMessage;
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.reinstallOS = function(vpsID){
$scope.tronLoading = false;
var url = "/vps/reInstallOS";
var data = {
hostName: $("#vpsHostname").text(),
rootPassword: $scope.reinstallPassword
};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
$scope.tronLoading = true;
if(response.data.success === 1){
$scope.successMessage = response.data.successMessage;
new PNotify({
title: 'Operation Successfull!',
text: response.data.successMessage,
type:'success'
});
}
else
{
new PNotify({
title: 'Operation failed!',
text: response.data.error_message,
type:'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
new PNotify({
title: 'Operation failed!',
text: "Could not connect to server. Please refresh this page.",
type:'error'
});
}
};
$scope.restartVPS = function(vpsID){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/vps/restartVPS";
var data = {vpsID: vpsID};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
$scope.successMessage = response.data.successMessage;
$scope.getFurtherVPS(currentPageNumber);
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
$scope.shutdownVPS = function(vpsID){
$scope.tronLoading = false;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
var url = "/vps/shutdownVPS";
var data = {vpsID: vpsID};
var config = {
headers : {
'X-CSRFToken': getCookie('csrftoken')
}
};
$http.post(url, data,config).then(ListInitialDatas, cantLoadInitialDatas);
function ListInitialDatas(response) {
if(response.data.success === 1){
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = false;
$scope.couldNotConnect = true;
$scope.successMessage = response.data.successMessage;
$scope.getFurtherVPS(currentPageNumber);
}
else
{
$scope.tronLoading = true;
$scope.poolCreationFailed = false;
$scope.poolCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
$scope.poolCreationFailed = true;
$scope.poolCreated = true;
$scope.couldNotConnect = false;
}
};
});
/* Java script code for Snapshots ends here */

Some files were not shown because too many files have changed in this diff Show More