diff --git a/dev/libvirt-bootstrap.sh b/dev/libvirt-bootstrap.sh index 603b189..8a3cdfe 100644 --- a/dev/libvirt-bootstrap.sh +++ b/dev/libvirt-bootstrap.sh @@ -45,7 +45,7 @@ echowarn() { # DESCRIPTION: Echo debug information to stdout. #------------------------------------------------------------------------------- echodebug() { - if [ "${_ECHO_DEBUG}" -eq "${BS_TRUE}" ]; then + if [ $_ECHO_DEBUG -eq $BS_TRUE ]; then printf "${BC} * DEBUG${EC}: %s\n" "$@"; fi } @@ -154,7 +154,8 @@ __gather_linux_system_info() { DISTRO_VERSION="" # Let's test if the lsb_release binary is available - if lsb_release >/dev/null 2>&1; then + rv=$(lsb_release >/dev/null 2>&1) + if [ $? -eq 0 ]; then DISTRO_NAME=$(lsb_release -si) if [ "x$(echo "$DISTRO_NAME" | grep RedHat)" != "x" ]; then # Let's convert CamelCase to Camel Case @@ -207,7 +208,7 @@ __gather_linux_system_info() { ;; arch ) n="Arch Linux" ;; centos ) n="CentOS" ;; - almalinux ) n="AlmaLinux" ;; + almalinux ) n="AlmaLinux" ;; debian ) n="Debian" ;; ubuntu ) n="Ubuntu" ;; fedora ) n="Fedora" ;; @@ -247,7 +248,7 @@ __gather_linux_system_info() { ;; esac ;; - * ) ;; + * ) n="${n}" ; esac DISTRO_NAME=$n DISTRO_VERSION=$v @@ -778,7 +779,8 @@ if [ "$INSTALL_FUNC" = "null" ]; then exit 1 else echoinfo "Running ${INSTALL_FUNC}()" - if ! $INSTALL_FUNC; then + $INSTALL_FUNC + if [ $? -ne 0 ]; then echoerror "Failed to run ${INSTALL_FUNC}()!!!" exit 1 fi @@ -801,7 +803,8 @@ if [ "$POST_INSTALL_FUNC" = "null" ]; then exit 1 else echoinfo "Running ${POST_INSTALL_FUNC}()" - if ! $POST_INSTALL_FUNC; then + $POST_INSTALL_FUNC + if [ $? -ne 0 ]; then echoerror "Failed to run ${POST_INSTALL_FUNC}()!!!" exit 1 fi @@ -824,7 +827,8 @@ if [ "$DAEMONS_RUNNING_FUNC" = "null" ]; then exit 1 else echoinfo "Running ${DAEMONS_RUNNING_FUNC}()" - if ! $DAEMONS_RUNNING_FUNC; then + $DAEMONS_RUNNING_FUNC + if [ $? -ne 0 ]; then echoerror "Failed to run ${DAEMONS_RUNNING_FUNC}()!!!" exit 1 fi diff --git a/gunicorn.conf.py b/gunicorn.conf.py index 7fab982..90bd54e 100644 --- a/gunicorn.conf.py +++ b/gunicorn.conf.py @@ -75,7 +75,10 @@ backlog = 2048 def get_workers(): procs = os.sysconf('SC_NPROCESSORS_ONLN') - return procs * 2 + 1 if procs > 0 else 3 + if procs > 0: + return procs * 2 + 1 + else: + return 3 workers = get_workers() diff --git a/vrtManager/IPy.py b/vrtManager/IPy.py index 099ac90..3cddf29 100644 --- a/vrtManager/IPy.py +++ b/vrtManager/IPy.py @@ -181,7 +181,10 @@ class IPint(object): if isinstance(data, INT_TYPES): self.ip = int(data) if ipversion == 0: - ipversion = 4 if self.ip <= MAX_IPV4_ADDRESS else 6 + if self.ip <= MAX_IPV4_ADDRESS: + ipversion = 4 + else: + ipversion = 6 if ipversion == 4: if self.ip > MAX_IPV4_ADDRESS: raise ValueError("IPv4 Address can't be larger than %x: %x" % (MAX_IPV4_ADDRESS, self.ip)) diff --git a/vrtManager/create.py b/vrtManager/create.py index 99ec7e7..61d5040 100644 --- a/vrtManager/create.py +++ b/vrtManager/create.py @@ -1,5 +1,4 @@ import string -import contextlib from vrtManager import util from vrtManager.connection import wvmConnect @@ -31,13 +30,19 @@ class wvmCreate(wvmConnect): """ Function return all images on all storages """ - images = [] + images = list() storages = self.get_storages(only_actives=True) for storage in storages: stg = self.get_storage(storage) - with contextlib.suppress(Exception): + try: stg.refresh(0) - images.extend(img for img in stg.listVolumes() if not img.lower().endswith(".iso")) + except Exception: + pass + for img in stg.listVolumes(): + if img.lower().endswith(".iso"): + pass + else: + images.append(img) return images def get_os_type(self): @@ -53,7 +58,10 @@ class wvmCreate(wvmConnect): stg = self.get_storage(storage) storage_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type") if storage_type == "dir": - name += f".{image_format}" if image_format in ("qcow", "qcow2") else ".img" + if image_format in ("qcow", "qcow2"): + name += "." + image_format + else: + name += ".img" alloc = 0 else: image_format = 'raw' @@ -79,19 +87,28 @@ class wvmCreate(wvmConnect): """ stg.createXML(xml, metadata) - - with contextlib.suppress(Exception): + try: stg.refresh(0) + except: + pass vol = stg.storageVolLookupByName(name) return vol.path() def get_volume_format_type(self, path): vol = self.get_volume_by_path(path) vol_type = util.get_xml_path(vol.XMLDesc(0), "/volume/target/format/@type") - return "raw" if vol_type in ["unknown", "iso"] else vol_type or "raw" + if vol_type == "unknown" or vol_type == "iso": + return "raw" + if vol_type: + return vol_type + else: + return "raw" def get_volume_path(self, volume, pool=None): - storages = [pool] if pool else self.get_storages(only_actives=True) + if not pool: + storages = self.get_storages(only_actives=True) + else: + storages = [pool] for storage in storages: stg = self.get_storage(storage) if stg.info()[0] != 0: @@ -107,7 +124,10 @@ class wvmCreate(wvmConnect): def clone_from_template(self, clone, template, storage=None, metadata=False, disk_owner_uid=0, disk_owner_gid=0): vol = self.get_volume_by_path(template) - stg = self.get_storage(storage) if storage else vol.storagePoolLookupByVolume() + if not storage: + stg = vol.storagePoolLookupByVolume() + else: + stg = self.get_storage(storage) storage_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type") format = util.get_xml_path(vol.XMLDesc(0), "/volume/target/format/@type") @@ -206,8 +226,12 @@ class wvmCreate(wvmConnect): if caps["features"]: xml += """""" - for feat in [x for x in ("acpi", "apic", "pae",) if x in caps["features"]]: - xml += f"""<{feat}/>""" + if "acpi" in caps["features"]: + xml += """""" + if "apic" in caps["features"]: + xml += """""" + if "pae" in caps["features"]: + xml += """""" if firmware.get("secure", "no") == "yes": xml += """""" xml += """""" @@ -216,7 +240,9 @@ class wvmCreate(wvmConnect): xml += """""" elif vcpu_mode == "host-passthrough": xml += """""" - elif vcpu_mode != "": + elif vcpu_mode == "": + pass + else: xml += f""" {vcpu_mode}""" xml += """""" @@ -280,7 +306,7 @@ class wvmCreate(wvmConnect): xml += """""" % (hd_disk_letters.pop(0), volume.get("bus")) elif volume.get("bus") == "fdc": xml += """""" % (fd_disk_letters.pop(0), volume.get("bus")) - elif volume.get("bus") in ["sata", "scsi"]: + elif volume.get("bus") == "sata" or volume.get("bus") == "scsi": xml += """""" % (sd_disk_letters.pop(0), volume.get("bus")) else: xml += """""" % sd_disk_letters.pop(0) @@ -319,13 +345,14 @@ class wvmCreate(wvmConnect): if console_pass == "random": console_pass = "passwd='" + util.randomPasswd() + "'" - elif console_pass != "": - console_pass = "passwd='" + console_pass + "'" + else: + if not console_pass == "": + console_pass = "passwd='" + console_pass + "'" if "usb" in dom_caps["disk_bus"]: - xml += f"""""" - xml += f"""""" - xml += f"""""" + xml += """""".format("virtio" if virtio else "usb") + xml += """""".format("virtio" if virtio else "usb") + xml += """""".format("virtio" if virtio else "usb") else: xml += """""" xml += """""" diff --git a/vrtManager/hostdetails.py b/vrtManager/hostdetails.py index 6ee97fb..2996904 100644 --- a/vrtManager/hostdetails.py +++ b/vrtManager/hostdetails.py @@ -21,11 +21,12 @@ class wvmHostDetails(wvmConnect): freemem = self.wvm.getMemoryStats(-1, 0) if isinstance(freemem, dict): free = (freemem["buffers"] + freemem["free"] + freemem["cached"]) * 1024 - percent = abs(100 - free * 100 // all_mem) + percent = abs(100 - ((free * 100) // all_mem)) usage = all_mem - free - return {"total": all_mem, "usage": usage, "percent": percent} + mem_usage = {"total": all_mem, "usage": usage, "percent": percent} else: - return {"total": None, "usage": None, "percent": None} + mem_usage = {"total": None, "usage": None, "percent": None} + return mem_usage def get_cpu_usage(self): """ @@ -34,30 +35,30 @@ class wvmHostDetails(wvmConnect): prev_idle = 0 prev_total = 0 cpu = self.wvm.getCPUStats(-1, 0) - if not isinstance(cpu, dict): + if isinstance(cpu, dict): + for num in range(2): + idle = self.wvm.getCPUStats(-1, 0)["idle"] + total = sum(self.wvm.getCPUStats(-1, 0).values()) + diff_idle = idle - prev_idle + diff_total = total - prev_total + diff_usage = (1000 * (diff_total - diff_idle) / diff_total + 5) / 10 + prev_total = total + prev_idle = idle + if num == 0: + time.sleep(1) + else: + if diff_usage < 0: + diff_usage = 0 + else: return {"usage": None} - - for num in range(2): - idle = self.wvm.getCPUStats(-1, 0)["idle"] - total = sum(self.wvm.getCPUStats(-1, 0).values()) - diff_idle = idle - prev_idle - diff_total = total - prev_total - diff_usage = (1000 * (diff_total - diff_idle) / - diff_total + 5) / 10 - prev_total = total - prev_idle = idle - if num == 0: - time.sleep(1) - else: - diff_usage = max(diff_usage, 0) - return {"usage": diff_usage} def get_node_info(self): """ Function return host server information: hostname, cpu, memory, ... """ - info = [self.wvm.getHostname()] # hostname + 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 diff --git a/vrtManager/interface.py b/vrtManager/interface.py index a2eb777..14ddebc 100644 --- a/vrtManager/interface.py +++ b/vrtManager/interface.py @@ -57,7 +57,7 @@ class wvmInterface(wvmConnect): try: xml = self._XMLDesc(VIR_INTERFACE_XML_INACTIVE) return util.get_xml_path(xml, "/interface/start/@mode") - except Exception: + except: return None def is_active(self): @@ -65,7 +65,10 @@ class wvmInterface(wvmConnect): def get_mac(self): mac = self.iface.MACString() - return mac or None + if mac: + return mac + else: + return None def get_type(self): xml = self._XMLDesc() @@ -75,8 +78,11 @@ class wvmInterface(wvmConnect): try: xml = self._XMLDesc(VIR_INTERFACE_XML_INACTIVE) ipaddr = util.get_xml_path(xml, "/interface/protocol[@family='ipv4']/ip/@address") - return "static" if ipaddr else "dhcp" - except Exception: + if ipaddr: + return "static" + else: + return "dhcp" + except: return None def get_ipv4(self): @@ -86,14 +92,17 @@ class wvmInterface(wvmConnect): if not int_ipv4_ip or not int_ipv4_mask: return None else: - return f"{int_ipv4_ip}/{int_ipv4_mask}" + return int_ipv4_ip + "/" + int_ipv4_mask def get_ipv6_type(self): try: xml = self._XMLDesc(VIR_INTERFACE_XML_INACTIVE) ipaddr = util.get_xml_path(xml, "/interface/protocol[@family='ipv6']/ip/@address") - return "static" if ipaddr else "dhcp" - except Exception: + if ipaddr: + return "static" + else: + return "dhcp" + except: return None def get_ipv6(self): @@ -103,39 +112,40 @@ class wvmInterface(wvmConnect): if not int_ipv6_ip or not int_ipv6_mask: return None else: - return f"{int_ipv6_ip}/{int_ipv6_mask}" + return int_ipv6_ip + "/" + int_ipv6_mask def get_bridge(self): bridge = None - if self.get_type() != "bridge": + if self.get_type() == "bridge": + bridge = util.get_xml_path(self._XMLDesc(), "/interface/bridge/interface/@name") + for iface in self.get_bridge_slave_ifaces(): + if iface.get("state") == "up" and iface.get("speed") != "unknown": + bridge = iface.get("name") + return bridge + return bridge + else: return None - bridge = util.get_xml_path(self._XMLDesc(), "/interface/bridge/interface/@name") - for iface in self.get_bridge_slave_ifaces(): - if iface.get("state") == "up" and iface.get("speed") != "unknown": - bridge = iface.get("name") - return bridge - return bridge def get_bridge_slave_ifaces(self): - if self.get_type() != "bridge": + ifaces = list() + if self.get_type() == "bridge": + tree = ElementTree.fromstring(self._XMLDesc()) + for iface in tree.findall("./bridge/"): + address = state = speed = None + name = iface.get("name") + if_type = iface.get("type") + link = iface.find("link") + if link is not None: + state = link.get("state") + speed = link.get("speed") + mac = iface.find("mac") + if mac is not None: + address = mac.get("address") + ifaces.append({"name": name, "type": if_type, "state": state, "speed": speed, "mac": address}) + return ifaces + else: return None - ifaces = [] - tree = ElementTree.fromstring(self._XMLDesc()) - for iface in tree.findall("./bridge/"): - address = state = speed = None - name = iface.get("name") - if_type = iface.get("type") - link = iface.find("link") - if link is not None: - state = link.get("state") - speed = link.get("speed") - mac = iface.find("mac") - if mac is not None: - address = mac.get("address") - ifaces.append({"name": name, "type": if_type, "state": state, "speed": speed, "mac": address}) - return ifaces - def get_details(self): mac = self.get_mac() itype = self.get_type() diff --git a/vrtManager/network.py b/vrtManager/network.py index 45467f8..9a5a149 100644 --- a/vrtManager/network.py +++ b/vrtManager/network.py @@ -23,8 +23,10 @@ def network_size(subnet, dhcp=None): if addr.version() == 6: mask = mask.lstrip("/") if "/" in mask else mask dhcp_pool = [IP(addr[0].strCompressed() + hex(256)), IP(addr[0].strCompressed() + hex(512 - 1))] - - return (gateway, mask, dhcp_pool) if dhcp else (gateway, mask, None) + if dhcp: + return gateway, mask, dhcp_pool + else: + return gateway, mask, None class wvmNetworks(wvmConnect): @@ -41,7 +43,6 @@ class wvmNetworks(wvmConnect): net_forward = util.get_xml_path(net.XMLDesc(0), "/network/forward/@mode") networks.append({"name": network, "status": net_status, "device": net_bridge, "forward": net_forward}) - return networks def define_network(self, xml): @@ -136,7 +137,7 @@ class wvmNetwork(wvmConnect): def get_bridge_device(self): try: return self.net.bridgeName() - except Exception: + except: return util.get_xml_path(self._XMLDesc(0), "/network/forward/interface/@dev") def start(self): @@ -152,7 +153,7 @@ class wvmNetwork(wvmConnect): return self.net.update(command, section, parentIndex, xml, flags) def get_ip_networks(self): - ip_networks = {} + ip_networks = dict() xml = self._XMLDesc(0) if util.get_xml_path(xml, "/network/ip") is None: return ip_networks @@ -163,10 +164,10 @@ class wvmNetwork(wvmConnect): netmask_str = ip.get("netmask") prefix = ip.get("prefix") family = ip.get("family", "ipv4") + base = 32 if family == "ipv4" else 128 if prefix: prefix = int(prefix) - base = 32 if family == "ipv4" else 128 - binstr = prefix * "1" + (base - prefix) * "0" + binstr = (prefix * "1") + ((base - prefix) * "0") netmask_str = str(IP(int(binstr, base=2))) if netmask_str: @@ -182,7 +183,8 @@ class wvmNetwork(wvmConnect): def get_network_mac(self): xml = self._XMLDesc(0) - return util.get_xml_path(xml, "/network/mac/@address") + mac = util.get_xml_path(xml, "/network/mac/@address") + return mac def get_network_forward(self): xml = self._XMLDesc(0) @@ -199,15 +201,22 @@ class wvmNetwork(wvmConnect): dhcpstart = util.get_xml_path(xml, "/network/ip[@family='ipv6']/dhcp/range[1]/@start") dhcpend = util.get_xml_path(xml, "/network/ip[@family='ipv6']/dhcp/range[1]/@end") - return None if not dhcpstart or not dhcpend else [IP(dhcpstart), IP(dhcpend)] + if not dhcpstart or not dhcpend: + return None + + return [IP(dhcpstart), IP(dhcpend)] def get_dhcp_range_start(self, family="ipv4"): dhcp = self.get_dhcp_range(family) - return dhcp[0] if dhcp else None + if not dhcp: + return None + return dhcp[0] def get_dhcp_range_end(self, family="ipv4"): dhcp = self.get_dhcp_range(family) - return dhcp[1] if dhcp else None + if not dhcp: + return None + return dhcp[1] def can_pxe(self): xml = self._XMLDesc(0) @@ -217,19 +226,21 @@ class wvmNetwork(wvmConnect): return bool(util.get_xml_path(xml, "/network/ip/dhcp/bootp/@file")) def get_dhcp_host_addr(self, family="ipv4"): - result = [] + result = list() tree = etree.fromstring(self._XMLDesc(0)) + for ipdhcp in tree.findall("./ip"): if family == "ipv4": - if ipdhcp.get("family") is not None: + if ipdhcp.get("family") is None: + hosts = ipdhcp.findall("./dhcp/host") + for host in hosts: + host_ip = host.get("ip") + mac = host.get("mac") + name = host.get("name", "") + result.append({"ip": host_ip, "mac": mac, "name": name}) + return result + else: continue - hosts = ipdhcp.findall("./dhcp/host") - for host in hosts: - host_ip = host.get("ip") - mac = host.get("mac") - name = host.get("name", "") - result.append({"ip": host_ip, "mac": mac, "name": name}) - return result if family == "ipv6": hosts = tree.xpath("./ip[@family='ipv6']/dhcp/host") for host in hosts: @@ -261,9 +272,9 @@ class wvmNetwork(wvmConnect): for h in hosts: if h.get("ip") == ip: if family == "ipv4": - new_xml = f'' + new_xml = ''.format(h.get("mac"), h.get("name"), ip) if family == "ipv6": - new_xml = f'' + new_xml = ''.format(h.get("id"), h.get("name"), ip) self.update( VIR_NETWORK_UPDATE_COMMAND_DELETE, @@ -287,7 +298,12 @@ class wvmNetwork(wvmConnect): compare_var = "id" parent_index = self.parent_count - 1 new_host_xml = etree.fromstring(new_xml) - host = next((h for h in hosts if h.get(compare_var) == mac_duid), None) + + host = None + for h in hosts: + if h.get(compare_var) == mac_duid: + host = h + break if host is None: self.update( VIR_NETWORK_UPDATE_COMMAND_ADD_LAST, @@ -310,7 +326,7 @@ class wvmNetwork(wvmConnect): ) def get_qos(self): - qos_values = {} + qos_values = dict() tree = etree.fromstring(self._XMLDesc(0)) qos = tree.xpath("/network/bandwidth") if qos: @@ -332,10 +348,13 @@ class wvmNetwork(wvmConnect): return qos_values def set_qos(self, direction, average, peak, burst): - if direction not in ("inbound","outbound"): + if direction == "inbound": + xml = f"" + elif direction == "outbound": + xml = f"" + else: raise Exception("Direction must be inbound or outbound") - xml = f"<{direction} average='{average}' peak='{peak}' burst='{burst}'/>" tree = etree.fromstring(self._XMLDesc(0)) band = tree.xpath("/network/bandwidth") @@ -369,7 +388,7 @@ class wvmNetwork(wvmConnect): self.leases = self.net.DHCPLeases() except Exception as e: self.leases = [] - raise f"Error getting {self} DHCP leases: {e}" from e + raise "Error getting {} DHCP leases: {}".format(self, e) def get_dhcp_leases(self): if self.leases is None: diff --git a/vrtManager/nwfilters.py b/vrtManager/nwfilters.py index 8b8d1b9..627e571 100644 --- a/vrtManager/nwfilters.py +++ b/vrtManager/nwfilters.py @@ -47,8 +47,11 @@ class wvmNWFilter(wvmConnect): return ElementTree.tostring(tree).decode() def get_filter_refs(self): + refs = [] tree = ElementTree.fromstring(self._XMLDesc(0)) - return [ref.get("filter") for ref in tree.findall("./filterref")] + for ref in tree.findall("./filterref"): + refs.append(ref.get("filter")) + return refs def get_rules(self): rules = [] diff --git a/vrtManager/storage.py b/vrtManager/storage.py index d2346ce..c7b37f8 100644 --- a/vrtManager/storage.py +++ b/vrtManager/storage.py @@ -1,5 +1,3 @@ -import contextlib - from vrtManager import util from vrtManager.connection import wvmConnect @@ -12,7 +10,10 @@ class wvmStorages(wvmConnect): stg = self.get_storage(pool) stg_status = stg.isActive() stg_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type") - stg_vol = len(stg.listVolumes()) if stg_status else None + if stg_status: + stg_vol = len(stg.listVolumes()) + else: + stg_vol = None stg_size = stg.info()[1] storages.append( {"name": pool, "status": stg_status, "type": stg_type, "volumes": stg_vol, "size": stg_size} @@ -32,7 +33,7 @@ class wvmStorages(wvmConnect): """ if stg_type == "logical": - target = f"/dev/{name}" + target = "/dev/" + name xml += f""" {target} @@ -227,12 +228,23 @@ class wvmStorage(wvmConnect): self.pool.refresh(0) def update_volumes(self): - with contextlib.suppress(Exception): + try: self.refresh() + except Exception: + pass vols = self.get_volumes() - return [{"name": volname, "size": self.get_volume_size(volname), - "allocation": self.get_volume_allocation(volname), - "type": self.get_volume_format_type(volname)} for volname in vols] + vol_list = [] + + for volname in vols: + vol_list.append( + { + "name": volname, + "size": self.get_volume_size(volname), + "allocation": self.get_volume_allocation(volname), + "type": self.get_volume_format_type(volname), + } + ) + return vol_list def create_volume(self, name, size, vol_fmt="qcow2", metadata=False, disk_owner_uid=0, disk_owner_gid=0): size = int(size) * 1073741824 @@ -241,7 +253,10 @@ class wvmStorage(wvmConnect): if vol_fmt == "unknown": vol_fmt = "raw" if storage_type == "dir": - name += f".{vol_fmt}" if vol_fmt in ("qcow", "qcow2") else ".img" + if vol_fmt in ("qcow", "qcow2"): + name += "." + vol_fmt + else: + name += ".img" alloc = 0 xml = f""" @@ -285,9 +300,9 @@ class wvmStorage(wvmConnect): storage_type = self.get_type() if storage_type == "dir": if vol_fmt in ["qcow", "qcow2"]: - target_file += f".{vol_fmt}" + target_file += "." + vol_fmt else: - suffix = f".{file_suffix}" + suffix = "." + file_suffix target_file += suffix if len(suffix) > 1 else "" xml = f""" diff --git a/vrtManager/util.py b/vrtManager/util.py index d618896..1f15b37 100644 --- a/vrtManager/util.py +++ b/vrtManager/util.py @@ -9,7 +9,10 @@ import lxml.etree as etree def is_kvm_available(xml): kvm_domains = get_xml_path(xml, "//domain/@type='kvm'") - return kvm_domains > 0 + if kvm_domains > 0: + return True + else: + return False def randomMAC(): @@ -23,40 +26,40 @@ def randomMAC(): def randomUUID(): """Generate a random UUID.""" - u = [secrets.randbelow(256) for _ in range(16)] - u[6] = u[6] & 15 | 4 << 4 - u[8] = u[8] & 63 | 2 << 6 + u = [secrets.randbelow(256) for ignore in range(0, 16)] + u[6] = (u[6] & 0x0F) | (4 << 4) + u[8] = (u[8] & 0x3F) | (2 << 6) return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2, "%02x" * 6]) % tuple(u) def randomPasswd(length=12, alphabet=string.ascii_letters + string.digits): """Generate a random password""" - return "".join([secrets.choice(alphabet) for _ in range(length)]) + return "".join([secrets.choice(alphabet) for i in range(length)]) -def get_max_vcpus(conn, guest_type=None): +def get_max_vcpus(conn, type=None): """@param conn: libvirt connection to poll for max possible vcpus - @param guest_type: optional guest type (kvm, etc.)""" + @type type: optional guest type (kvm, etc.)""" if type is None: - guest_type = conn.getType() + type = conn.getType() try: - m = conn.getMaxVcpus(guest_type.lower()) + m = conn.getMaxVcpus(type.lower()) except libvirt.libvirtError: m = 32 return m -def xml_escape(xml_str): +def xml_escape(str): """Replaces chars ' " < > & with xml safe counterparts""" - if xml_str is None: + if str is None: return None - xml_str = xml_str.replace("&", "&") - xml_str = xml_str.replace("'", "'") - xml_str = xml_str.replace('"', """) - xml_str = xml_str.replace("<", "<") - xml_str = xml_str.replace(">", ">") - return xml_str + str = str.replace("&", "&") + str = str.replace("'", "'") + str = str.replace('"', """) + str = str.replace("<", "<") + str = str.replace(">", ">") + return str def compareMAC(p, q): @@ -105,7 +108,10 @@ def get_xpath(doc, path): if ret is not None: if isinstance(ret, list): if len(ret) >= 1: - result = ret[0].text if hasattr(ret[0], "text") else ret[0] + if hasattr(ret[0], "text"): + result = ret[0].text + else: + result = ret[0] else: result = ret diff --git a/webvirtcloud/common_tags.py b/webvirtcloud/common_tags.py index 4b85df7..7197800 100644 --- a/webvirtcloud/common_tags.py +++ b/webvirtcloud/common_tags.py @@ -7,20 +7,28 @@ register = template.Library() @register.simple_tag def app_active(request, app_name): - return "active" if request.resolver_match.app_name == app_name else "" + if request.resolver_match.app_name == app_name: + return "active" + return "" @register.simple_tag def view_active(request, view_name): - return "active" if request.resolver_match.view_name == view_name else "" + if request.resolver_match.view_name == view_name: + return "active" + return "" @register.simple_tag def class_active(request, pattern): - # Not sure why 'class="active"' returns class=""active"" - return "active" if re.search(pattern, request.path) else "" + if re.search(pattern, request.path): + # Not sure why 'class="active"' returns class=""active"" + return "active" + return "" @register.simple_tag def has_perm(user, permission_codename): - return bool(user.has_perm(permission_codename)) + if user.has_perm(permission_codename): + return True + return False diff --git a/webvirtcloud/ldapbackend.py b/webvirtcloud/ldapbackend.py index 0f7a797..15c0834 100644 --- a/webvirtcloud/ldapbackend.py +++ b/webvirtcloud/ldapbackend.py @@ -42,49 +42,48 @@ try: def authenticate(self, request, username=None, password=None, **kwargs): if not settings.LDAP_ENABLED: - return None + return None print("authenticate_ldap") # Get the user information from the LDAP if he can be authenticated isAdmin = False isStaff = False isTechnician = False - + requeteLdap = self.get_LDAP_user(username, password, settings.LDAP_SEARCH_GROUP_FILTER_ADMINS) - isAdmin = requeteLdap is not None - isStaff = requeteLdap is not None - if requeteLdap is None: requeteLdap = self.get_LDAP_user(username, password, settings.LDAP_SEARCH_GROUP_FILTER_STAFF) - isStaff = requeteLdap is not None - - if requeteLdap is None: - requeteLdap = self.get_LDAP_user(username, password, settings.LDAP_SEARCH_GROUP_FILTER_TECHNICIANS) - isTechnician = requeteLdap is not None - - if requeteLdap is None: - requeteLdap = self.get_LDAP_user(username, password, settings.LDAP_SEARCH_GROUP_FILTER_USERS) - - if requeteLdap is None: - print("User does not belong to any search group. Check LDAP_SEARCH_GROUP_FILTER in settings.") - return None + if requeteLdap is None: + requeteLdap = self.get_LDAP_user(username, password, settings.LDAP_SEARCH_GROUP_FILTER_TECHNICIANS) + if requeteLdap is None: + requeteLdap = self.get_LDAP_user(username, password, settings.LDAP_SEARCH_GROUP_FILTER_USERS) + if requeteLdap is None: + print("User does not belong to any search group. Check LDAP_SEARCH_GROUP_FILTER in settings.") + return None + else: + isTechnician = True + else: + isStaff = True + else: + isAdmin = True + isStaff = True techniciansGroup = Group.objects.get(name='Technicians') - + try: user = User.objects.get(username=username) attributes = UserAttributes.objects.get(user=user) user.is_staff = isStaff user.is_superuser = isAdmin - if not isTechnician and user.groups.filter(name='Technicians').exists(): + if isTechnician is False and user.groups.filter(name='Technicians').exists(): user.groups.remove(techniciansGroup) - elif isTechnician and not user.groups.filter(name='Technicians').exists(): + elif isTechnician is True and user.groups.filter(name='Technicians').exists() is False: user.groups.add(techniciansGroup) else: print("The user is already in the Technicians group") user.save() # TODO VERIFY except User.DoesNotExist: - print(f"authenticate-create new user: {username}") + print("authenticate-create new user: {}".format(username)) user = User(username=username) user.first_name = requeteLdap[1] user.last_name = requeteLdap[2] @@ -94,7 +93,7 @@ try: user.is_superuser = isAdmin user.set_password(uuid.uuid4().hex) user.save() - if isTechnician: + if isTechnician is True: user.groups.add(techniciansGroup) maxInstances = 1 maxCpus = 1