add boot script to vm

This commit is contained in:
usmannasir
2018-09-11 17:56:16 +05:00
parent 88b95d511f
commit 2f2f552252
12 changed files with 111 additions and 103 deletions

View File

@@ -8,7 +8,7 @@ import threading as multi
from CyberTronLogger import CyberTronLogger as logger
from inspect import stack
from shlex import split
from subprocess import call,CalledProcessError
from subprocess import call,CalledProcessError, Popen
from os.path import join
from random import randint
from logLevel import logLevel
@@ -227,7 +227,7 @@ class CyberTron(multi.Thread):
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
def buildCustomDisk(self, vmName, osName, size, rootPassword, uploadCommand, tempStatusPath):
def buildCustomDisk(self, vmName, osName, size, rootPassword, uploadCommand, tempStatusPath, sshKey = None, initialScript = None):
try:
sourcePath = join(virtualMachineAPI.templatesPath, osName + ".img")
@@ -267,8 +267,23 @@ class CyberTron(multi.Thread):
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 sshKey == None:
if initialScript == None:
command = "sudo virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand
call(split(command))
else:
command = "sudo virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand \
+ ' --commands-from-file ' + initialScript
call(split(command))
else:
if initialScript == None:
command = "sudo virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand + " --ssh-inject 'root:string:" + sshKey + "'"
call(split(command))
else:
command = "sudo virt-customize -a " + finalPath + " --root-password password:" + rootPassword + uploadCommand \
+ ' --commands-from-file ' + initialScript + " --ssh-inject 'root:string:" + sshKey + "'"
call(split(command))
if result == 1:
raise CalledProcessError
@@ -291,7 +306,7 @@ class CyberTron(multi.Thread):
logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + ' [404]')
return 0
def setupVMDisk(self, vmName, osName, uploadSource, rootPassword, package, tempStatusPath, sshKey = None):
def setupVMDisk(self, vmName, osName, uploadSource, rootPassword, package, tempStatusPath, sshKey = None, initialScript = None):
try:
size = package.diskSpace + 'G'
@@ -308,17 +323,26 @@ class CyberTron(multi.Thread):
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)
self.buildCustomDisk(vmName, osName, size, rootPassword, uploadCommand, tempStatusPath, sshKey, initialScript)
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 + "'"
if initialScript == 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 + " --ssh-inject 'root:string:" + sshKey + "'" + ' --commands-from-file ' + initialScript
else:
command = "sudo virt-builder " + osName + " -o " + finalImageLocation + " --size " + size + \
" --format qcow2 --root-password password:" + rootPassword + uploadCommand
if initialScript == None:
command = "sudo virt-builder " + osName + " -o " + finalImageLocation + " --size " + size + \
" --format qcow2 --root-password password:" + rootPassword + uploadCommand
else:
command = "sudo virt-builder " + osName + " -o " + finalImageLocation + " --size " + size + \
" --format qcow2 --root-password password:" + rootPassword + uploadCommand + ' --commands-from-file ' + initialScript
result = call(split(command))
@@ -400,6 +424,11 @@ class CyberTron(multi.Thread):
except:
sshKey = None
try:
initialScript = data['initialScript']
except:
initialScript = None
owner = Administrator.objects.get(userName=vpsOwner)
package = Package.objects.get(packageName=vpsPackage)
@@ -428,7 +457,7 @@ class CyberTron(multi.Thread):
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'],
'Creating virtual machine disk..,20')
if self.setupVMDisk(hostname, osName, uploadSource, rootPassword, package, data['tempStatusPath'], sshKey) == 0:
if self.setupVMDisk(hostname, osName, uploadSource, rootPassword, package, data['tempStatusPath'], sshKey, initialScript) == 0:
logging.CyberCPLogFileWriter.statusWriter(data['tempStatusPath'], 'Failed to setup virtual machine disk. [404]')
return 0
@@ -485,5 +514,4 @@ class CyberTron(multi.Thread):
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
return 0

View File

@@ -13,7 +13,6 @@ ExecStart=/usr/local/CyberCP/bin/gunicorn --pid /run/gunicorn/gucpid \
--bind 127.0.0.1:5003 CyberCP.wsgi
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

View File

@@ -271,6 +271,12 @@ class vmmACLManager:
return vmObjects
@staticmethod
def findOsNames():
path = '/home/cyberpanel/os'
data = open(path, 'r').readlines()
return data

View File

@@ -24,7 +24,7 @@ class mysqlUtilities:
data = f.read()
password = data.split('\n', 1)[0]
createDB = "CREATE DATABASE "+dbname
createDB = "CREATE DATABASE " + dbname
command = 'sudo mysql -u root -p' + password + ' -e "' + createDB + '"'
cmd = shlex.split(command)
@@ -142,7 +142,7 @@ class mysqlUtilities:
res = subprocess.call(cmd, stdin=f)
if res == 1:
logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " +databaseName +"! [restoreDatabaseBackup]")
logging.CyberCPLogFileWriter.writeToFile("Could not restore MYSQL database: " + databaseName +"! [restoreDatabaseBackup]")
return 0
passwordCMD = "use mysql;SET PASSWORD FOR '"+databaseName+"'@'localhost' = '"+dbPassword+"';FLUSH PRIVILEGES;"

View File

@@ -1,45 +0,0 @@
import sys
import subprocess
import shutil
import argparse
import os
import shlex
import time
import string
import random
def setupVirtualEnv():
##
command = "yum install -y libattr-devel xz-devel gpgme-devel mariadb-devel curl-devel"
res = subprocess.call(shlex.split(command))
##
command = "pip install virtualenv"
res = subprocess.call(shlex.split(command))
####
command = "virtualenv /usr/local/CyberCP"
res = subprocess.call(shlex.split(command))
##
env_path = '/usr/local/CyberCP'
if not os.path.exists(env_path):
subprocess.call(['virtualenv', env_path])
activate_this = os.path.join(env_path, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
command = "pip install -r /usr/local/CyberCP/requirments.txt"
res = subprocess.call(shlex.split(command))
##
command = "systemctl restart gunicorn.socket"
res = subprocess.call(shlex.split(command))
setupVirtualEnv()

View File

@@ -185,7 +185,6 @@ ExecStart=/usr/local/CyberCP/bin/gunicorn --pid /run/gunicorn/gucpid \
--bind 127.0.0.1:5003 CyberCP.wsgi
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target"""

View File

@@ -366,21 +366,13 @@ class vhost:
confFile.writelines(php_admin_value)
confFile.writelines(endPHPIniOverride)
slashContext = """
context / {
location $DOC_ROOT/
allowBrowse 1
rewrite {
enable 1
RewriteFile .htaccess
}
addDefaultCharset off
htaccessAutoLoad = """
rewrite {
enable 1
autoLoadHtaccess 1
}
"""
confFile.write(slashContext)
confFile.write(htaccessAutoLoad)
confFile.close()
@@ -945,20 +937,13 @@ RewriteFile .htaccess
confFile.writelines(procHardLimit)
confFile.writelines(extprocessorEnd)
slashContext = """
context / {
location $DOC_ROOT/
allowBrowse 1
rewrite {
enable 1
RewriteFile .htaccess
}
addDefaultCharset off
htaccessAutoLoad = """
rewrite {
enable 1
autoLoadHtaccess 1
}
"""
confFile.write(slashContext)
confFile.write(htaccessAutoLoad)
confFile.close()

View File

@@ -65,7 +65,8 @@ app.controller('createVPSCTRL', function($scope, $http, $timeout) {
rootPassword: $scope.rootPassword,
networkSpeed: $scope.networkSpeed,
osName: $scope.osName,
sshKey: $scope.sshKey
sshKey: $scope.sshKey,
initialScript: $scope.initialScript
};
var config = {
@@ -883,6 +884,35 @@ app.controller('manageVPSCTRL', function($scope, $http, $timeout) {
};
$scope.setupVNC = function(){
$scope.tronLoading = false;
var url = "/vps/startWebsocketServer";
var data = {hostname: $("#vpsHostname").text()};
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){
window.open(response.data.finalURL);
}
}
function cantLoadInitialDatas(response) {
$scope.tronLoading = true;
}
};
});
/* Java script code to Manage VPS ends here */

View File

@@ -65,7 +65,8 @@ app.controller('createVPSCTRL', function($scope, $http, $timeout) {
rootPassword: $scope.rootPassword,
networkSpeed: $scope.networkSpeed,
osName: $scope.osName,
sshKey: $scope.sshKey
sshKey: $scope.sshKey,
initialScript: $scope.initialScript
};
var config = {

View File

@@ -60,12 +60,9 @@
<label class="col-sm-3 control-label">{% trans "Operating System" %}</label>
<div class="col-sm-6">
<select ng-model="osName" class="form-control">
<option>centos-6</option>
<option>centos-7.2</option>
<option>debian-9</option>
<option>ubuntu-16.04</option>
<option>ubuntu-18.04</option>
<option>fedora-28</option>
{% for items in osNames %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
</div>
@@ -100,6 +97,13 @@
</div>
</div>
<div ng-hide="installationDetailsForm" class="form-group">
<label class="col-sm-3 control-label">{% trans "Initial Script (Optional)" %}</label>
<div class="col-sm-6">
<input placeholder="Path to initial script." type="text" class="form-control" ng-model="initialScript" required>
</div>
</div>
<div ng-hide="installationDetailsForm" class="form-group">
<label class="col-sm-3 control-label">{% trans "Root Password" %}</label>
<div class="col-sm-6">

View File

@@ -227,10 +227,9 @@
<label class="col-sm-3 control-label">{% trans "Operating System" %}</label>
<div class="col-sm-6">
<select ng-model="osName" class="form-control">
<option>centos-6</option>
<option>centos-7.2</option>
<option>debian-8</option>
<option>ubuntu-16.04</option>
{% for items in osNames %}
<option>{{ items }}</option>
{% endfor %}
</select>
</div>
<a ng-click="hideAdminTasks()" href=""><img src="{% static 'vpsManagement/close-32.png' %}"></a>

View File

@@ -39,8 +39,9 @@ class VPSManager:
sshKeys = vmmACLManager.findSSHkeyNames(currentACL, userID)
packageNames = vmmACLManager.findAllPackages(currentACL, userID)
ownerNames = ACLManager.loadAllUsers(userID)
osNames = vmmACLManager.findOsNames()
data = {'hvNames': hvNames, 'sshKeys': sshKeys, 'packageNames': packageNames, 'ownerNames': ownerNames}
data = {'hvNames': hvNames, 'sshKeys': sshKeys, 'packageNames': packageNames, 'ownerNames': ownerNames, 'osNames': osNames}
return render(request, 'vpsManagement/createVPS.html', data)
@@ -242,6 +243,7 @@ class VPSManager:
snapshotsURL = '/backup/' + hostName + '/snapshots'
sshKeys = vmmACLManager.findSSHkeyNames(currentACL, userID)
osNames = vmmACLManager.findOsNames()
return render(request, 'vpsManagement/manageVPS.html', {'hostName':hostName,
@@ -256,7 +258,8 @@ class VPSManager:
'bwUsage':bwPercentage,
'consoleURL':consoleURL,
'snapshotsURL':snapshotsURL,
'sshKeys' : sshKeys
'sshKeys' : sshKeys,
'osNames': osNames
})
else:
return render(request, 'vpsManagement/manageVPS.html',
@@ -616,7 +619,6 @@ class VPSManager:
final_json = json.dumps({'status': 0, 'errorMessage': str(msg)})
return HttpResponse(final_json)
def startWebsocketServer(self, userID = None, data = None):
try:
currentACL = ACLManager.loadedACL(userID)
@@ -641,7 +643,7 @@ class VPSManager:
backVNCPort = str(vps.websocketPort + 5900)
command = '/usr/local/lscp/cyberpanel/noVNC/utils/launch.sh --listen ' + frontVNCPort + ' --vnc ' \
command = 'sudo /usr/local/lscp/cyberpanel/noVNC/utils/launch.sh --listen ' + frontVNCPort + ' --vnc ' \
+ vncHostIP + ':' + backVNCPort + ' --cert /usr/local/lscp/cyberpanel/noVNC/utils/self.pem'
subprocess.Popen(shlex.split(command))