1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2024-12-24 15:15:22 +00:00

pep8 style code corrections

This commit is contained in:
catborise 2019-09-10 09:48:31 +03:00
parent fdbb6739c1
commit 828a271789
18 changed files with 69 additions and 64 deletions

View file

@ -2,7 +2,6 @@ from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from accounts.models import *
from instances.models import Instance
@ -11,7 +10,6 @@ from django.conf import settings
from django.core.validators import ValidationError
@login_required
def profile(request):
"""
@ -70,6 +68,7 @@ def profile(request):
return HttpResponseRedirect(request.get_full_path())
return render(request, 'profile.html', locals())
@login_required
def accounts(request):
"""
@ -154,6 +153,7 @@ def accounts(request):
def account(request, user_id):
"""
:param request:
:param user_id:
:return:
"""

View file

@ -1,4 +1,3 @@
import time
import json
from django.utils import timezone
from django.http import HttpResponse, HttpResponseRedirect
@ -140,6 +139,7 @@ def computes(request):
def overview(request, compute_id):
"""
:param request:
:param compute_id:
:return:
"""
@ -171,6 +171,7 @@ def overview(request, compute_id):
def compute_graph(request, compute_id):
"""
:param request:
:param compute_id:
:return:
"""
compute = get_object_or_404(Compute, pk=compute_id)
@ -207,17 +208,16 @@ def get_compute_disk_buses(request, compute_id, disk):
compute.type)
disk_device_types = conn.get_disk_device_types()
disk_bus_types = conn.get_disk_bus_types()
if disk in disk_device_types:
if disk == 'disk':
data['bus'] = sorted(disk_device_types)
elif disk == 'cdrom':
data['bus'] = ['ide', 'sata', 'scsi',]
data['bus'] = ['ide', 'sata', 'scsi']
elif disk == 'floppy':
data['bus'] = ['fdc',]
data['bus'] = ['fdc']
elif disk == 'lun':
data['bus'] = ['scsi',]
data['bus'] = ['scsi']
except libvirtError:
pass

View file

@ -120,7 +120,7 @@ def get_connection_infos(token):
console_host = conn.get_console_listen_addr()
console_port = conn.get_console_port()
console_socket = conn.get_console_socket()
except Exception, e:
except Exception as e:
logging.error('Fail to retrieve console connection infos for token %s : %s' % (token, e))
raise
return (connhost, connport, connuser, conntype, console_host,

View file

@ -1,7 +1,5 @@
import re
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from instances.models import Instance
from vrtManager.instance import wvmInstance

View file

@ -21,6 +21,7 @@ from logs.views import addlogmsg
def create_instance(request, compute_id):
"""
:param request:
:param compute_id:
:return:
"""
@ -109,7 +110,7 @@ def create_instance(request, compute_id):
msg = _("A virtual machine with this name already exists")
error_messages.append(msg)
if Instance.objects.filter(name__exact=data['name']):
messages.warning(request,_("There is an instance with same name. Are you sure?"))
messages.warning(request, _("There is an instance with same name. Are you sure?"))
if not error_messages:
if data['hdd_size']:
if not data['mac']:
@ -175,7 +176,7 @@ def create_instance(request, compute_id):
addlogmsg(request.user.username, create_instance.name, msg)
return HttpResponseRedirect(reverse('instance', args=[compute_id, data['name']]))
except libvirtError as lib_err:
if data['hdd_size'] or volume_list.count() > 0:
if data['hdd_size'] or len(volume_list) > 0:
for vol in volume_list:
conn.delete_volume(vol['path'])
error_messages.append(lib_err)

View file

@ -26,7 +26,7 @@ def os_metadata_json(request, version):
if version == 'latest':
ip = get_client_ip(request)
hostname = get_hostname_by_ip(ip)
response = { 'uuid': OS_UUID, 'hostname': hostname }
response = {'uuid': OS_UUID, 'hostname': hostname}
return HttpResponse(json.dumps(response))
else:
err = 'Invalid version: {}'.format(version)
@ -70,8 +70,8 @@ def get_client_ip(request):
def get_hostname_by_ip(ip):
try:
addrs = socket.gethostbyaddr(ip)
except Exception:
addrs = [ip,]
except:
addrs = [ip]
return addrs[0]

View file

@ -12,6 +12,7 @@ from libvirt import libvirtError
def interfaces(request, compute_id):
"""
:param request:
:param compute_id:
:return:
"""
@ -60,6 +61,7 @@ def interfaces(request, compute_id):
def interface(request, compute_id, iface):
"""
:param request:
:param iface:
:return:
"""

View file

@ -10,7 +10,9 @@ import json
def addlogmsg(user, instance, message):
"""
:param request:
:param user:
:param instance:
:param message:
:return:
"""
add_log_msg = Logs(user=user, instance=instance, message=message)
@ -21,6 +23,7 @@ def addlogmsg(user, instance, message):
def showlogs(request, page=1):
"""
:param request:
:param page:
:return:
"""
@ -36,11 +39,12 @@ def showlogs(request, page=1):
return render(request, 'showlogs.html', locals())
@login_required
def vm_logs(request, vname):
"""
:param request:
:param vm:
:param vname:
:return:
"""
@ -51,7 +55,7 @@ def vm_logs(request, vname):
logs_ = Logs.objects.filter(instance=vm.name, date__gte=vm.created).order_by('-date')
logs = []
for l in logs_:
log = {}
log = dict()
log['user'] = l.user
log['instance'] = l.instance
log['message'] = l.message

View file

@ -15,6 +15,7 @@ from django.contrib import messages
def networks(request, compute_id):
"""
:param request:
:param compute_id:
:return:
"""
@ -64,6 +65,8 @@ def networks(request, compute_id):
def network(request, compute_id, pool):
"""
:param request:
:param compute_id:
:param pool:
:return:
"""
@ -154,9 +157,9 @@ def network(request, compute_id, pool):
if edit_xml:
try:
new_conn = wvmNetworks(compute.hostname,
compute.login,
compute.password,
compute.type)
compute.login,
compute.password,
compute.type)
conn.define_network(edit_xml)
if conn.is_active():
messages.success(request, _("Network XML is changed. Stop and start network to activate new config."))

View file

@ -10,10 +10,12 @@ from libvirt import libvirtError
from django.contrib import messages
import json
@login_required
def storages(request, compute_id):
"""
:param request:
:param compute_id:
:return:
"""
@ -72,6 +74,8 @@ def storages(request, compute_id):
def storage(request, compute_id, pool):
"""
:param request:
:param compute_id:
:param pool:
:return:
"""

View file

@ -2,7 +2,7 @@ import libvirt
import threading
import socket
from vrtManager import util
from rwlock import ReadWriteLock
from vrtManager.rwlock import ReadWriteLock
from django.conf import settings
from libvirt import libvirtError

View file

@ -2,7 +2,6 @@ import string
from vrtManager import util
from vrtManager.connection import wvmConnect
from webvirtcloud.settings import QEMU_CONSOLE_DEFAULT_TYPE
from webvirtcloud.settings import QEMU_CONSOLE_LISTEN_ADDRESSES
from webvirtcloud.settings import INSTANCE_VOLUME_DEFAULT_OWNER as default_owner
from webvirtcloud.settings import INSTANCE_VOLUME_DEFAULT_FORMAT
@ -107,7 +106,7 @@ class wvmCreate(wvmConnect):
if not pool:
storages = self.get_storages(only_actives=True)
else:
storages = [pool,]
storages = [pool]
for storage in storages:
stg = self.get_storage(storage)
if stg.info()[0] != 0:
@ -204,7 +203,6 @@ class wvmCreate(wvmConnect):
hd_disk_letters = list(string.lowercase)
sd_disk_letters = list(string.lowercase)
add_cd = True
#for image, img_type in images.items():
for volume in images:
stg = self.get_storage_by_vol_path(volume['path'])
stg_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type")
@ -283,8 +281,4 @@ class wvmCreate(wvmConnect):
<memballoon model='virtio'/>
</devices>
</domain>""" % video
self._defineXML(xml)

View file

@ -58,13 +58,13 @@ class wvmHostDetails(wvmConnect):
"""
Function return host server information: hostname, cpu, memory, ...
"""
info = []
info.append(self.wvm.getHostname()) # hostname
info.append(self.wvm.getInfo()[0]) # architecture
info.append(self.wvm.getInfo()[1] * 1048576) # memory
info.append(self.wvm.getInfo()[2]) # cpu core count
info.append(get_xml_path(self.wvm.getSysinfo(0), func=cpu_version)) # cpu version
info.append(self.wvm.getURI()) #uri
info = list()
info.append(self.wvm.getHostname()) # hostname
info.append(self.wvm.getInfo()[0]) # architecture
info.append(self.wvm.getInfo()[1] * 1048576) # memory
info.append(self.wvm.getInfo()[2]) # cpu core count
info.append(get_xml_path(self.wvm.getSysinfo(0), func=cpu_version)) # cpu version
info.append(self.wvm.getURI()) # uri
return info

View file

@ -96,7 +96,7 @@ class wvmInstances(wvmConnect):
if listen_addr is None:
listen_addr = util.get_xml_path(inst.XMLDesc(0), "/domain/devices/graphics/listen/@address")
if listen_addr is None:
return "None"
return "None"
return listen_addr
def graphics_port(self, name):
@ -237,9 +237,9 @@ class wvmInstance(wvmConnect):
try:
net = self.get_network(network_host)
ip = get_mac_ipaddr(net, mac_host)
except libvirtError as e:
except libvirtError:
ip = None
result.append({'mac': mac_host, 'nic': network_host, 'target': target_host,'ip': ip, 'filterref': filterref_host})
result.append({'mac': mac_host, 'nic': network_host, 'target': target_host, 'ip': ip, 'filterref': filterref_host})
return result
return util.get_xml_path(self._XMLDesc(0), func=networks)
@ -322,7 +322,7 @@ class wvmInstance(wvmConnect):
os = tree.find('os')
menu = os.find("bootmenu")
if menu == None:
if menu is None:
bootmenu = ElementTree.fromstring("<bootmenu enable='yes'/>")
os.append(bootmenu)
menu = os.find("bootmenu")
@ -365,7 +365,7 @@ class wvmInstance(wvmConnect):
for dev in devices:
dev_target = dev_type = dev_device = dev_alias = None
boot_dev = dev.find('boot')
if boot_dev != None:
if boot_dev is not None:
idx = boot_dev.get('order')
dev_type = dev.get('type')
dev_device = dev.get('device')
@ -398,7 +398,7 @@ class wvmInstance(wvmConnect):
# Remove rest of them
for dev in tree.find('devices'):
boot_dev = dev.find('boot')
if boot_dev != None:
if boot_dev is not None:
dev.remove(boot_dev)
return tree
@ -410,19 +410,19 @@ class wvmInstance(wvmConnect):
devices = tree.findall("./devices/disk[@device='disk']")
for d in devices:
device = d.find("./target[@dev='{}']".format(dev['dev']))
if device != None:
if device is not None:
d.append(order)
elif dev['type'] == 'cdrom':
devices = tree.findall("./devices/disk[@device='cdrom']")
for d in devices:
device = d.find("./target[@dev='{}']".format(dev['dev']))
if device != None:
if device is not None:
d.append(order)
elif dev['type'] == 'network':
devices = tree.findall("./devices/interface[@type='network']")
for d in devices:
device = d.find("mac[@address='{}']".format(dev['dev']))
if device != None:
if device is not None:
d.append(order)
else:
raise Exception('Invalid Device Type for boot order')
@ -478,7 +478,6 @@ class wvmInstance(wvmConnect):
self._defineXML(xmldom)
def attach_disk(self, source, target, sourcetype='file', device='disk', driver='qemu', subdriver='raw', cache='none', targetbus='ide'):
tree = ElementTree.fromstring(self._XMLDesc(0))
xml_disk = "<disk type='%s' device='%s'>" % (sourcetype, device)
if device == 'cdrom':
xml_disk += "<driver name='%s' type='%s'/>" % (driver, subdriver)
@ -622,7 +621,7 @@ class wvmInstance(wvmConnect):
if listen_addr is None:
listen_addr = util.get_xml_path(self._XMLDesc(0), "/domain/devices/graphics/listen/@address")
if listen_addr is None:
return "127.0.0.1"
return "127.0.0.1"
return listen_addr
def set_console_listen_addr(self, listen_addr):
@ -656,7 +655,7 @@ class wvmInstance(wvmConnect):
return socket
def get_console_type(self):
console_type = util.get_xml_path(self._XMLDesc(0),"/domain/devices/graphics/@type")
console_type = util.get_xml_path(self._XMLDesc(0), "/domain/devices/graphics/@type")
return console_type
def set_console_type(self, console_type):
@ -805,7 +804,7 @@ class wvmInstance(wvmConnect):
new_xml = ElementTree.tostring(tree)
self._defineXML(new_xml)
def resize_disk(self, disks=[]):
def resize_disk(self, disks):
"""
Function change disks on vds.
"""
@ -1007,7 +1006,6 @@ class wvmInstance(wvmConnect):
return bridge_name
def add_network(self, mac_address, source, source_type='net', interface_type='bridge', model='virtio', nwfilter=None):
tree = ElementTree.fromstring(self._XMLDesc(0))
bridge_name = self.get_bridge_name(source, source_type)
xml_interface = """
<interface type='%s'>
@ -1029,7 +1027,6 @@ class wvmInstance(wvmConnect):
def delete_network(self, mac_address):
tree = ElementTree.fromstring(self._XMLDesc(0))
devices = tree.find('devices')
for interface in tree.findall('devices/interface'):
source = interface.find('mac')
if source.get('address', '') == mac_address:
@ -1089,7 +1086,7 @@ class wvmInstance(wvmConnect):
option = tree.find(o)
option_value = options.get(o, '').strip()
if not option_value:
if not option is None:
if option is not None:
tree.remove(option)
else:
if option is None:

View file

@ -22,6 +22,7 @@ def network_size(net, dhcp=None):
class wvmNetworks(wvmConnect):
def get_networks_info(self):
get_networks = self.get_networks()
networks = []
@ -166,7 +167,7 @@ class wvmNetwork(wvmConnect):
return dhcp[1]
def can_pxe(self):
xml = self.get_xml()
xml = self._XMLDesc(0)
forward = self.get_ipv4_forward()[0]
if forward and forward != "nat":
return True
@ -204,14 +205,14 @@ class wvmNetwork(wvmConnect):
break
if host is None:
self.update(VIR_NETWORK_UPDATE_COMMAND_ADD_LAST, VIR_NETWORK_SECTION_IP_DHCP_HOST, -1, new_xml,
VIR_NETWORK_UPDATE_AFFECT_LIVE|VIR_NETWORK_UPDATE_AFFECT_CONFIG)
VIR_NETWORK_UPDATE_AFFECT_LIVE | VIR_NETWORK_UPDATE_AFFECT_CONFIG)
else:
# change the host
if host.get('name') == new_host_xml.get('name') and host.get('ip') == new_host_xml.get('ip'):
return False
else:
self.update(VIR_NETWORK_UPDATE_COMMAND_MODIFY, VIR_NETWORK_SECTION_IP_DHCP_HOST, -1, new_xml,
VIR_NETWORK_UPDATE_AFFECT_LIVE|VIR_NETWORK_UPDATE_AFFECT_CONFIG)
VIR_NETWORK_UPDATE_AFFECT_LIVE | VIR_NETWORK_UPDATE_AFFECT_CONFIG)
def delete_fixed_address(self, mac):
util.validate_macaddr(mac)
@ -222,7 +223,7 @@ class wvmNetwork(wvmConnect):
if h.get('mac') == mac:
new_xml = '<host mac="{}" name="{}" ip="{}"/>'.format(mac, h.get('name'), h.get('ip'))
self.update(VIR_NETWORK_UPDATE_COMMAND_DELETE, VIR_NETWORK_SECTION_IP_DHCP_HOST, -1, new_xml,
VIR_NETWORK_UPDATE_AFFECT_LIVE|VIR_NETWORK_UPDATE_AFFECT_CONFIG)
VIR_NETWORK_UPDATE_AFFECT_LIVE | VIR_NETWORK_UPDATE_AFFECT_CONFIG)
break
def modify_dhcp_range(self, range_start, range_end):

View file

@ -12,7 +12,7 @@ class wvmNWFilters(wvmConnect):
def create_nwfilter(self, xml):
self.wvm.nwfilterDefineXML(xml)
def clone_nwfilter(self,name, cln_name):
def clone_nwfilter(self, name, cln_name):
nwfilter = self.get_nwfilter(name)
if nwfilter:
tree = ElementTree.fromstring(nwfilter.XMLDesc(0))

View file

@ -7,11 +7,11 @@ class wvmSecrets(wvmConnect):
xml = """<secret ephemeral='%s' private='%s'>
<usage type='%s'>""" % (ephemeral, private, secret_type)
if secret_type == 'ceph':
xml += """<name>%s</name>""" % (data)
xml += """<name>%s</name>""" % data
if secret_type == 'volume':
xml += """<volume>%s</volume>""" % (data)
xml += """<volume>%s</volume>""" % data
if secret_type == 'iscsi':
xml += """<target>%s</target>""" % (data)
xml += """<target>%s</target>""" % data
xml += """</usage>
</secret>"""
self.wvm.secretDefineXML(xml)

View file

@ -110,7 +110,7 @@ def get_xpath(doc, path):
if ret is not None:
if type(ret) == list:
if len(ret) >= 1:
if hasattr(ret[0],'text'):
if hasattr(ret[0], 'text'):
result = ret[0].text
else:
result = ret[0]
@ -119,6 +119,7 @@ def get_xpath(doc, path):
return result
def pretty_mem(val):
val = int(val)
if val > (10 * 1024 * 1024):
@ -146,8 +147,8 @@ def validate_uuid(val):
if form is None:
raise ValueError(
"UUID must be a 32-digit hexadecimal number. It may take "
"the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx or may "
"omit hyphens altogether.")
"the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx or may "
"omit hyphens altogether.")
else: # UUID had no dashes, so add them in
val = (val[0:8] + "-" + val[8:12] + "-" + val[12:16] +