mirror of
https://github.com/retspen/webvirtcloud
synced 2026-11-09 19:56:48 +00:00
chore: remove code nothing uses
Each was checked with git grep across every tracked file (templates, JS, shell, unit files and the extensionless console daemons) and for dynamic use (URL names, template names, registries): - vrtManager: host_is_up, is_kvm_supported, get_emulators, get_file_extensions, both get_network_forward, get_snapshots, get_storages_images, get_os_type, get_host_arch, the get_pretty_* trio and, in util, is_kvm_available, randomMAC, get_max_vcpus, compareMAC, pretty_mem, pretty_bytes and validate_uuid; with them the port constants only host_is_up read. Some were reached only by their tests, which go too. - The flavor edit page: nothing linked to it; flavors are created and deleted on the Flavors page and edited through the API. - computes.validate_name, UserForm.identity_has_errors, the has_perm template tag, the ALLOW_EMPTY_PASSWORD setting nothing reads, hidePleaseWaitDialog, default_app_config (ignored since Django 4.1) and the Python < 3.6 lines of secret_generator.py.
This commit is contained in:
parent
02412b7ea5
commit
764cbb3c43
26 changed files with 307 additions and 690 deletions
|
|
@ -3,8 +3,6 @@ import contextlib
|
|||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
|
@ -23,9 +21,6 @@ CONN_SOCKET = 4
|
|||
CONN_TLS = 3
|
||||
CONN_SSH = 2
|
||||
CONN_TCP = 1
|
||||
TLS_PORT = 16514
|
||||
SSH_PORT = 22
|
||||
TCP_PORT = 16509
|
||||
|
||||
# libvirt has no timeout for opening a connection: an unreachable host
|
||||
# blocks for the kernel's TCP connect timeout (about 2 minutes), a daemon
|
||||
|
|
@ -457,34 +452,6 @@ class wvmConnectionManager(object):
|
|||
raise util.ConnectionFailed(error["text"], **error["values"])
|
||||
return live
|
||||
|
||||
def host_is_up(self, conn_type, hostname, timeout=1):
|
||||
"""True if the libvirt endpoint of hostname accepts a TCP (or Unix
|
||||
socket) connection. This is a reachability probe only: it does not
|
||||
check credentials or libvirt itself. hostname may carry a port
|
||||
("host:port", "[v6]:port")."""
|
||||
if conn_type == CONN_SOCKET:
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.settimeout(timeout)
|
||||
sock.connect("/var/run/libvirt/libvirt-sock")
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
sock.close()
|
||||
default_port = {CONN_SSH: SSH_PORT, CONN_TCP: TCP_PORT, CONN_TLS: TLS_PORT}.get(conn_type)
|
||||
if default_port is None:
|
||||
return False
|
||||
host, port = str(hostname), default_port
|
||||
match = re.fullmatch(r"\[?([^\[\]]+?)\]?:(\d+)", host)
|
||||
if match and (host.startswith("[") or host.count(":") == 1):
|
||||
host, port = match.group(1), int(match.group(2))
|
||||
try:
|
||||
with socket.create_connection((host.strip("[]"), port), timeout=timeout):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
connection_manager = wvmConnectionManager(
|
||||
settings.LIBVIRT_KEEPALIVE_INTERVAL if hasattr(settings, "LIBVIRT_KEEPALIVE_INTERVAL") else 5,
|
||||
settings.LIBVIRT_KEEPALIVE_COUNT if hasattr(settings, "LIBVIRT_KEEPALIVE_COUNT") else 5,
|
||||
|
|
@ -633,12 +600,6 @@ class wvmConnect(object):
|
|||
release = ver
|
||||
return f"{major}.{minor}.{release}"
|
||||
|
||||
def is_kvm_supported(self):
|
||||
"""
|
||||
:return: kvm support or not
|
||||
"""
|
||||
return util.is_kvm_available(self.get_cap_xml())
|
||||
|
||||
def get_storages(self, only_actives=False):
|
||||
"""
|
||||
:return: list of active or all storages
|
||||
|
|
@ -776,21 +737,6 @@ class wvmConnect(object):
|
|||
|
||||
return util.get_xml_path(self.get_cap_xml(), func=machines)
|
||||
|
||||
def get_emulators(self):
|
||||
"""
|
||||
:return: host emulators list
|
||||
"""
|
||||
|
||||
def emulators(ctx):
|
||||
result = {}
|
||||
for arch in ctx.xpath("/capabilities/guest/arch"):
|
||||
emulator = arch.xpath("emulator")
|
||||
arch_name = arch.xpath("@name")[0]
|
||||
result[arch_name] = emulator
|
||||
return result
|
||||
|
||||
return util.get_xml_path(self.get_cap_xml(), func=emulators)
|
||||
|
||||
def get_os_loaders(self, arch="x86_64", machine="pc"):
|
||||
"""
|
||||
:param arch: architecture
|
||||
|
|
@ -922,12 +868,6 @@ class wvmConnect(object):
|
|||
"""
|
||||
return ["raw", "qcow", "qcow2"]
|
||||
|
||||
def get_file_extensions(self):
|
||||
"""
|
||||
:return: available image filename extensions
|
||||
"""
|
||||
return ["img", "qcow", "qcow2"]
|
||||
|
||||
def get_video_models(self, arch, machine):
|
||||
"""
|
||||
:param arch: architecture
|
||||
|
|
@ -1105,15 +1045,6 @@ class wvmConnect(object):
|
|||
def get_network(self, net):
|
||||
return self.wvm.networkLookupByName(net)
|
||||
|
||||
def get_network_forward(self, net_name):
|
||||
def get_forward(doc):
|
||||
forward_mode = util.get_xpath(doc, "/network/forward/@mode")
|
||||
return forward_mode or "isolated"
|
||||
|
||||
net = self.get_network(net_name)
|
||||
xml = net.XMLDesc(0)
|
||||
return util.get_xml_path(xml, func=get_forward)
|
||||
|
||||
def get_nwfilter(self, name):
|
||||
return self.wvm.nwfilterLookupByName(name)
|
||||
|
||||
|
|
@ -1229,18 +1160,6 @@ class wvmConnect(object):
|
|||
paths += [v for v in (source.get("file"), source.get("dev"), source.get("name")) if v]
|
||||
return paths
|
||||
|
||||
def get_snapshots(self):
|
||||
instance = []
|
||||
for snap_id in self.wvm.listDomainsID():
|
||||
dom = self.wvm.lookupByID(int(snap_id))
|
||||
if dom.snapshotNum(0) != 0:
|
||||
instance.append(dom.name())
|
||||
for name in self.wvm.listDefinedDomains():
|
||||
dom = self.wvm.lookupByName(name)
|
||||
if dom.snapshotNum(0) != 0:
|
||||
instance.append(dom.name())
|
||||
return instance
|
||||
|
||||
def can_change_interfaces(self):
|
||||
"""Whether the host's libvirt can define interfaces: the udev backend
|
||||
only reads them. The definition sent is invalid, so nothing is
|
||||
|
|
|
|||
|
|
@ -60,27 +60,6 @@ def get_rbd_storage_data(stg):
|
|||
|
||||
|
||||
class wvmCreate(wvmConnect):
|
||||
def get_storages_images(self):
|
||||
"""
|
||||
Function return all images on all storages
|
||||
"""
|
||||
images = []
|
||||
storages = self.get_storages(only_actives=True)
|
||||
for storage in storages:
|
||||
stg = self.get_storage(storage)
|
||||
with contextlib.suppress(Exception):
|
||||
stg.refresh(0)
|
||||
images.extend(img for img in stg.listVolumes() if not img.lower().endswith(".iso"))
|
||||
return images
|
||||
|
||||
def get_os_type(self):
|
||||
"""Get guest os type"""
|
||||
return util.get_xml_path(self.get_cap_xml(), "/capabilities/guest/os_type")
|
||||
|
||||
def get_host_arch(self):
|
||||
"""Get host architecture"""
|
||||
return util.get_xml_path(self.get_cap_xml(), "/capabilities/host/cpu/arch")
|
||||
|
||||
def create_volume(self, storage, name, size, image_format, metadata=False, disk_owner_uid=0, disk_owner_gid=0):
|
||||
size = int(size) * 1073741824
|
||||
stg = self.get_storage(storage)
|
||||
|
|
|
|||
|
|
@ -326,11 +326,6 @@ class wvmNetwork(wvmConnect):
|
|||
def get_network_mac(self):
|
||||
return self.tree.xpath("string(mac/@address)")
|
||||
|
||||
def get_network_forward(self):
|
||||
"""Its forward mode (None: isolated) and the device it forwards through."""
|
||||
forward = self.tree.find("forward")
|
||||
return [forward.get("mode"), forward.get("dev")] if forward is not None else [None, None]
|
||||
|
||||
def _ip(self, index):
|
||||
"""The saved <ip> of that index, and what ip_networks tells of it."""
|
||||
tree = self.config()
|
||||
|
|
|
|||
|
|
@ -253,15 +253,6 @@ class wvmStorage(wvmConnect):
|
|||
|
||||
return util.get_xml_path(self._XMLDesc(0), func=hosts)
|
||||
|
||||
def get_pretty_allocation(self):
|
||||
return util.pretty_bytes(self.get_allocation())
|
||||
|
||||
def get_pretty_available(self):
|
||||
return util.pretty_bytes(self.get_available())
|
||||
|
||||
def get_pretty_capacity(self):
|
||||
return util.pretty_bytes(self.get_capacity())
|
||||
|
||||
def get_volumes(self):
|
||||
return self.pool.listVolumes()
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
import contextlib
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
|
@ -21,29 +20,6 @@ from vrtManager import connection
|
|||
from vrtManager.connection import CONN_SSH, CONN_TCP, SSH_COMMAND, wvmConnectionManager
|
||||
|
||||
|
||||
def closed_port():
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
return port
|
||||
|
||||
|
||||
class HostIsUpTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.manager = wvmConnectionManager.__new__(wvmConnectionManager)
|
||||
|
||||
def test_reachable_host_is_true(self):
|
||||
server = socket.socket()
|
||||
server.bind(("127.0.0.1", 0))
|
||||
server.listen(1)
|
||||
self.addCleanup(server.close)
|
||||
self.assertIs(self.manager.host_is_up(CONN_TCP, f"127.0.0.1:{server.getsockname()[1]}"), True)
|
||||
|
||||
def test_unreachable_host_is_false_not_an_exception(self):
|
||||
self.assertIs(self.manager.host_is_up(CONN_TCP, f"127.0.0.1:{closed_port()}"), False)
|
||||
|
||||
|
||||
class ConnectionManagerTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
patcher = patch("vrtManager.connection.wvmEventLoop")
|
||||
|
|
|
|||
|
|
@ -6,16 +6,10 @@ if not settings.configured:
|
|||
settings.configure(MAC_OUI="52:54:10")
|
||||
|
||||
from vrtManager.util import (
|
||||
compareMAC,
|
||||
get_xml_path,
|
||||
is_kvm_available,
|
||||
pretty_bytes,
|
||||
pretty_mem,
|
||||
randomMAC,
|
||||
randomPasswd,
|
||||
randomUUID,
|
||||
validate_macaddr,
|
||||
validate_uuid,
|
||||
vol_dev_type,
|
||||
vol_driver_type,
|
||||
xml_escape,
|
||||
|
|
@ -31,38 +25,6 @@ class TestVrtManagerUtil(unittest.TestCase):
|
|||
# Ensure successive UUIDs are distinct
|
||||
self.assertNotEqual(uuid_str, randomUUID())
|
||||
|
||||
def test_validate_uuid(self):
|
||||
valid_dashed = "c9a646d3-9c61-4cd8-8024-f6b72a6642d9"
|
||||
self.assertEqual(validate_uuid(valid_dashed), valid_dashed)
|
||||
|
||||
valid_no_dash = "c9a646d39c614cd88024f6b72a6642d9"
|
||||
self.assertEqual(validate_uuid(valid_no_dash), valid_dashed)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
validate_uuid("invalid-uuid-too-short")
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
validate_uuid(12345)
|
||||
|
||||
def test_random_mac(self):
|
||||
mac = randomMAC()
|
||||
self.assertTrue(mac.startswith("52:54:10:"))
|
||||
parts = mac.split(":")
|
||||
self.assertEqual(len(parts), 6)
|
||||
for part in parts:
|
||||
self.assertEqual(len(part), 2)
|
||||
int(part, 16) # valid hex
|
||||
|
||||
def test_compare_mac(self):
|
||||
mac1 = "52:54:10:00:00:01"
|
||||
mac2 = "52:54:10:00:00:02"
|
||||
self.assertEqual(compareMAC(mac1, mac1), 0)
|
||||
self.assertEqual(compareMAC(mac1, mac2), -1)
|
||||
self.assertEqual(compareMAC(mac2, mac1), 1)
|
||||
# Different lengths
|
||||
self.assertEqual(compareMAC("52:54", "52:54:10"), -1)
|
||||
self.assertEqual(compareMAC("52:54:10", "52:54"), 1)
|
||||
|
||||
def test_validate_macaddr(self):
|
||||
self.assertIsNone(validate_macaddr(None))
|
||||
self.assertIsNone(validate_macaddr("52:54:10:aa:bb:cc"))
|
||||
|
|
@ -103,23 +65,6 @@ class TestVrtManagerUtil(unittest.TestCase):
|
|||
with self.assertRaises(ValueError):
|
||||
get_xml_path(xml)
|
||||
|
||||
def test_is_kvm_available(self):
|
||||
kvm_xml = "<capabilities><guest><arch name='x86_64'><domain type='kvm'/></arch></guest></capabilities>"
|
||||
qemu_xml = "<capabilities><guest><arch name='x86_64'><domain type='qemu'/></arch></guest></capabilities>"
|
||||
self.assertTrue(is_kvm_available(kvm_xml))
|
||||
self.assertFalse(is_kvm_available(qemu_xml))
|
||||
|
||||
def test_pretty_mem(self):
|
||||
# Value in KB
|
||||
self.assertEqual(pretty_mem(1024), " 1 MB")
|
||||
self.assertEqual(pretty_mem(1024 * 1024), "1024 MB")
|
||||
self.assertEqual(pretty_mem(16 * 1024 * 1024), "16.00 GB")
|
||||
|
||||
def test_pretty_bytes(self):
|
||||
# Value in Bytes
|
||||
self.assertEqual(pretty_bytes(10 * 1024 * 1024), "10.00 MB")
|
||||
self.assertEqual(pretty_bytes(2 * 1024 * 1024 * 1024), "2.00 GB")
|
||||
|
||||
def test_vol_dev_type(self):
|
||||
self.assertEqual(vol_dev_type("ide"), "hd")
|
||||
self.assertEqual(vol_dev_type("fdc"), "fd")
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
from django.utils.translation import gettext_noop
|
||||
import ipaddress
|
||||
import random
|
||||
import secrets
|
||||
import re
|
||||
import string
|
||||
|
|
@ -8,7 +7,6 @@ import string
|
|||
import libvirt
|
||||
import lxml.etree as etree
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils.translation import gettext
|
||||
|
||||
|
||||
|
|
@ -61,22 +59,6 @@ class HostBusy(ConnectionFailed):
|
|||
(HOST_REQUESTS) still wait for its answers."""
|
||||
|
||||
|
||||
def is_kvm_available(xml):
|
||||
kvm_domains = get_xml_path(xml, "//domain/@type='kvm'")
|
||||
return kvm_domains > 0
|
||||
|
||||
|
||||
def randomMAC():
|
||||
"""Generate a random MAC address."""
|
||||
# qemu MAC
|
||||
mac = settings.MAC_OUI + ":%02x:%02x:%02x" % (
|
||||
random.randint(0x00, 0xFF),
|
||||
random.randint(0x00, 0xFF),
|
||||
random.randint(0x00, 0xFF),
|
||||
)
|
||||
return mac
|
||||
|
||||
|
||||
def randomUUID():
|
||||
"""Generate a random UUID."""
|
||||
u = [secrets.randbelow(256) for _ in range(16)]
|
||||
|
|
@ -90,18 +72,6 @@ def randomPasswd(length=12, alphabet=string.ascii_letters + string.digits):
|
|||
return "".join([secrets.choice(alphabet) for _ in range(length)])
|
||||
|
||||
|
||||
def get_max_vcpus(conn, guest_type=None):
|
||||
"""@param conn: libvirt connection to poll for max possible vcpus
|
||||
@param guest_type: optional guest type (kvm, etc.)"""
|
||||
if type is None:
|
||||
guest_type = conn.getType()
|
||||
try:
|
||||
m = conn.getMaxVcpus(guest_type.lower())
|
||||
except libvirt.libvirtError:
|
||||
m = 32
|
||||
return m
|
||||
|
||||
|
||||
def xml_escape(xml_str):
|
||||
"""Replaces chars ' " < > & with xml safe counterparts"""
|
||||
if xml_str is None:
|
||||
|
|
@ -115,26 +85,6 @@ def xml_escape(xml_str):
|
|||
return xml_str
|
||||
|
||||
|
||||
def compareMAC(p, q):
|
||||
"""Compare two MAC addresses"""
|
||||
pa = p.split(":")
|
||||
qa = q.split(":")
|
||||
|
||||
if len(pa) != len(qa):
|
||||
if p > q:
|
||||
return 1
|
||||
else:
|
||||
return -1
|
||||
|
||||
for i in range(len(pa)):
|
||||
n = int(pa[i], 0x10) - int(qa[i], 0x10)
|
||||
if n > 0:
|
||||
return 1
|
||||
elif n < 0:
|
||||
return -1
|
||||
return 0
|
||||
|
||||
|
||||
def parse_xml(xml):
|
||||
"""XML a user entered, read for the panel's checks: its entities not
|
||||
expanded, nothing fetched and no DTD; libvirt gets the text itself."""
|
||||
|
|
@ -181,41 +131,6 @@ def get_xpath(doc, path):
|
|||
return result
|
||||
|
||||
|
||||
def pretty_mem(val):
|
||||
val = int(val)
|
||||
if val > (10 * 1024 * 1024):
|
||||
return "%2.2f GB" % (val / (1024.0 * 1024.0))
|
||||
else:
|
||||
return "%2.0f MB" % (val / 1024.0)
|
||||
|
||||
|
||||
def pretty_bytes(val):
|
||||
val = int(val)
|
||||
if val > (1024 * 1024 * 1024):
|
||||
return "%2.2f GB" % (val / (1024.0 * 1024.0 * 1024.0))
|
||||
else:
|
||||
return "%2.2f MB" % (val / (1024.0 * 1024.0))
|
||||
|
||||
|
||||
def validate_uuid(val):
|
||||
if not isinstance(val, str):
|
||||
raise ValueError("UUID must be a string.")
|
||||
|
||||
form = re.match("[a-fA-F0-9]{8}[-]([a-fA-F0-9]{4}[-]){3}[a-fA-F0-9]{12}$", val)
|
||||
if form is None:
|
||||
form = re.match("[a-fA-F0-9]{32}$", 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."
|
||||
)
|
||||
|
||||
else: # UUID had no dashes, so add them in
|
||||
val = val[0:8] + "-" + val[8:12] + "-" + val[12:16] + "-" + val[16:20] + "-" + val[20:32]
|
||||
return val
|
||||
|
||||
|
||||
def validate_macaddr(val):
|
||||
if val is None:
|
||||
return
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue