Skip to content

Commit 85b3507

Browse files
Zuulopenstack-gerrit
authored andcommitted
Merge "Add type hints to 'nova.virt.libvirt.utils'"
2 parents fa374dc + 6f1f716 commit 85b3507

File tree

3 files changed

+86
-39
lines changed

3 files changed

+86
-39
lines changed

mypy-files.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ nova/virt/hardware.py
66
nova/virt/libvirt/__init__.py
77
nova/virt/libvirt/driver.py
88
nova/virt/libvirt/host.py
9+
nova/virt/libvirt/utils.py

nova/virt/libvirt/driver.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4157,7 +4157,9 @@ def _create_and_inject_local_root(self, context, instance,
41574157
if instance.task_state == task_states.RESIZE_FINISH:
41584158
backend.create_snap(libvirt_utils.RESIZE_SNAPSHOT_NAME)
41594159
if backend.SUPPORTS_CLONE:
4160-
def clone_fallback_to_fetch(*args, **kwargs):
4160+
def clone_fallback_to_fetch(
4161+
context, target, image_id, trusted_certs=None,
4162+
):
41614163
refuse_fetch = (
41624164
CONF.libvirt.images_type == 'rbd' and
41634165
CONF.workarounds.never_download_image_if_on_rbd)
@@ -4176,10 +4178,13 @@ def clone_fallback_to_fetch(*args, **kwargs):
41764178
'never_download_image_if_on_rbd=True;'
41774179
' refusing to fetch and upload.',
41784180
disk_images['image_id'])
4179-
libvirt_utils.fetch_image(*args, **kwargs)
4181+
libvirt_utils.fetch_image(
4182+
context, target, image_id, trusted_certs,
4183+
)
41804184
fetch_func = clone_fallback_to_fetch
41814185
else:
41824186
fetch_func = libvirt_utils.fetch_image
4187+
41834188
self._try_fetch_image_cache(backend, fetch_func, context,
41844189
root_fname, disk_images['image_id'],
41854190
instance, size, fallback_from_host)
@@ -11117,8 +11122,9 @@ def _get_cpu_feature_traits(self) -> ty.Dict[str, bool]:
1111711122
caps = deepcopy(self._host.get_capabilities())
1111811123
if cpu.mode in ('host-model', 'host-passthrough'):
1111911124
# Account for features in cpu_model_extra_flags conf
11120-
host_features = [f.name for f in
11121-
caps.host.cpu.features | cpu.features]
11125+
host_features: ty.Set[str] = {
11126+
f.name for f in caps.host.cpu.features | cpu.features
11127+
}
1112211128
return libvirt_utils.cpu_features_to_traits(host_features)
1112311129

1112411130
def _resolve_features(cpu):

nova/virt/libvirt/utils.py

Lines changed: 75 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import errno
2222
import os
2323
import re
24+
import typing as ty
2425
import uuid
2526

2627
import os_traits
@@ -29,6 +30,7 @@
2930
from oslo_utils import fileutils
3031

3132
import nova.conf
33+
from nova import context as nova_context
3234
from nova.i18n import _
3335
from nova import objects
3436
from nova.objects import fields as obj_fields
@@ -39,6 +41,7 @@
3941
from nova import utils
4042
from nova.virt import images
4143
from nova.virt.libvirt import config as vconfig
44+
from nova.virt.libvirt import guest as libvirt_guest
4245
from nova.virt.libvirt.volume import remotefs
4346

4447
CONF = nova.conf.CONF
@@ -96,7 +99,9 @@
9699
TRAITS_CPU_MAPPING = {v: k for k, v in CPU_TRAITS_MAPPING.items()}
97100

98101

99-
def create_image(disk_format, path, size):
102+
def create_image(
103+
disk_format: str, path: str, size: ty.Union[str, int],
104+
) -> None:
100105
"""Create a disk image
101106
102107
:param disk_format: Disk image format (as known by qemu-img)
@@ -111,7 +116,9 @@ def create_image(disk_format, path, size):
111116
processutils.execute('qemu-img', 'create', '-f', disk_format, path, size)
112117

113118

114-
def create_cow_image(backing_file, path, size=None):
119+
def create_cow_image(
120+
backing_file: ty.Optional[str], path: str, size: ty.Optional[int] = None,
121+
) -> None:
115122
"""Create COW image
116123
117124
Creates a COW image with the given backing file
@@ -144,7 +151,9 @@ def create_cow_image(backing_file, path, size=None):
144151
processutils.execute(*cmd)
145152

146153

147-
def create_ploop_image(disk_format, path, size, fs_type):
154+
def create_ploop_image(
155+
disk_format: str, path: str, size: ty.Union[int, str], fs_type: str,
156+
) -> None:
148157
"""Create ploop image
149158
150159
:param disk_format: Disk image format (as known by ploop)
@@ -165,7 +174,9 @@ def create_ploop_image(disk_format, path, size, fs_type):
165174
nova.privsep.libvirt.ploop_init(size, disk_format, fs_type, disk_path)
166175

167176

168-
def pick_disk_driver_name(hypervisor_version, is_block_dev=False):
177+
def pick_disk_driver_name(
178+
hypervisor_version: int, is_block_dev: bool = False,
179+
) -> ty.Optional[str]:
169180
"""Pick the libvirt primary backend driver name
170181
171182
If the hypervisor supports multiple backend drivers we have to tell libvirt
@@ -221,7 +232,7 @@ def pick_disk_driver_name(hypervisor_version, is_block_dev=False):
221232
return None
222233

223234

224-
def get_disk_size(path, format=None):
235+
def get_disk_size(path: str, format: ty.Optional[str] = None) -> int:
225236
"""Get the (virtual) size of a disk image
226237
227238
:param path: Path to the disk image
@@ -233,7 +244,9 @@ def get_disk_size(path, format=None):
233244
return int(size)
234245

235246

236-
def get_disk_backing_file(path, basename=True, format=None):
247+
def get_disk_backing_file(
248+
path: str, basename: bool = True, format: ty.Optional[str] = None,
249+
) -> ty.Optional[str]:
237250
"""Get the backing file of a disk image
238251
239252
:param path: Path to the disk image
@@ -246,9 +259,15 @@ def get_disk_backing_file(path, basename=True, format=None):
246259
return backing_file
247260

248261

249-
def copy_image(src, dest, host=None, receive=False,
250-
on_execute=None, on_completion=None,
251-
compression=True):
262+
def copy_image(
263+
src: str,
264+
dest: str,
265+
host: ty.Optional[str] = None,
266+
receive: bool = False,
267+
on_execute: ty.Callable = None,
268+
on_completion: ty.Callable = None,
269+
compression: bool = True,
270+
) -> None:
252271
"""Copy a disk image to an existing directory
253272
254273
:param src: Source image
@@ -280,7 +299,8 @@ def copy_image(src, dest, host=None, receive=False,
280299
compression=compression)
281300

282301

283-
def write_to_file(path, contents):
302+
# TODO(stephenfin): This is dumb; remove it.
303+
def write_to_file(path: str, contents: str) -> None:
284304
"""Write the given contents to a file
285305
286306
:param path: Destination file
@@ -290,7 +310,9 @@ def write_to_file(path, contents):
290310
f.write(contents)
291311

292312

293-
def chown_for_id_maps(path, id_maps):
313+
def chown_for_id_maps(
314+
path: str, id_maps: ty.List[vconfig.LibvirtConfigGuestIDMap],
315+
) -> None:
294316
"""Change ownership of file or directory for an id mapped
295317
environment
296318
@@ -304,7 +326,9 @@ def chown_for_id_maps(path, id_maps):
304326
nova.privsep.idmapshift.shift(path, uid_maps, gid_maps)
305327

306328

307-
def extract_snapshot(disk_path, source_fmt, out_path, dest_fmt):
329+
def extract_snapshot(
330+
disk_path: str, source_fmt: str, out_path: str, dest_fmt: str,
331+
) -> None:
308332
"""Extract a snapshot from a disk image.
309333
Note that nobody should write to the disk image during this operation.
310334
@@ -322,7 +346,8 @@ def extract_snapshot(disk_path, source_fmt, out_path, dest_fmt):
322346
compress=compress)
323347

324348

325-
def load_file(path):
349+
# TODO(stephenfin): This is dumb; remove it.
350+
def load_file(path: str) -> str:
326351
"""Read contents of file
327352
328353
:param path: File to read
@@ -331,6 +356,8 @@ def load_file(path):
331356
return fp.read()
332357

333358

359+
# TODO(stephenfin): Remove this; we have suitably powerful mocking abilities
360+
# nowadays
334361
def file_open(*args, **kwargs):
335362
"""Open file
336363
@@ -343,7 +370,7 @@ def file_open(*args, **kwargs):
343370
return open(*args, **kwargs)
344371

345372

346-
def find_disk(guest):
373+
def find_disk(guest: libvirt_guest.Guest) -> ty.Tuple[str, ty.Optional[str]]:
347374
"""Find root device path for instance
348375
349376
May be file or device
@@ -384,7 +411,7 @@ def find_disk(guest):
384411
return (disk_path, disk_format)
385412

386413

387-
def get_disk_type_from_path(path):
414+
def get_disk_type_from_path(path: str) -> ty.Optional[str]:
388415
"""Retrieve disk type (raw, qcow2, lvm, ploop) for given file."""
389416
if path.startswith('/dev'):
390417
return 'lvm'
@@ -398,7 +425,7 @@ def get_disk_type_from_path(path):
398425
return None
399426

400427

401-
def get_fs_info(path):
428+
def get_fs_info(path: str) -> ty.Dict[str, int]:
402429
"""Get free/used/total space info for a filesystem
403430
404431
:param path: Any dirent on the filesystem
@@ -412,12 +439,15 @@ def get_fs_info(path):
412439
total = hddinfo.f_frsize * hddinfo.f_blocks
413440
free = hddinfo.f_frsize * hddinfo.f_bavail
414441
used = hddinfo.f_frsize * (hddinfo.f_blocks - hddinfo.f_bfree)
415-
return {'total': total,
416-
'free': free,
417-
'used': used}
442+
return {'total': total, 'free': free, 'used': used}
418443

419444

420-
def fetch_image(context, target, image_id, trusted_certs=None):
445+
def fetch_image(
446+
context: nova_context.RequestContext,
447+
target: str,
448+
image_id: str,
449+
trusted_certs: ty.Optional['objects.TrustedCerts'] = None,
450+
) -> None:
421451
"""Grab image.
422452
423453
:param context: nova.context.RequestContext auth request context
@@ -428,7 +458,12 @@ def fetch_image(context, target, image_id, trusted_certs=None):
428458
images.fetch_to_raw(context, image_id, target, trusted_certs)
429459

430460

431-
def fetch_raw_image(context, target, image_id, trusted_certs=None):
461+
def fetch_raw_image(
462+
context: nova_context.RequestContext,
463+
target: str,
464+
image_id: str,
465+
trusted_certs: ty.Optional['objects.TrustedCerts'] = None,
466+
) -> None:
432467
"""Grab initrd or kernel image.
433468
434469
This function does not attempt raw conversion, as these images will
@@ -442,7 +477,9 @@ def fetch_raw_image(context, target, image_id, trusted_certs=None):
442477
images.fetch(context, image_id, target, trusted_certs)
443478

444479

445-
def get_instance_path(instance, relative=False):
480+
def get_instance_path(
481+
instance: 'objects.Instance', relative: bool = False,
482+
) -> str:
446483
"""Determine the correct path for instance storage.
447484
448485
This method determines the directory name for instance storage.
@@ -457,7 +494,10 @@ def get_instance_path(instance, relative=False):
457494
return os.path.join(CONF.instances_path, instance.uuid)
458495

459496

460-
def get_instance_path_at_destination(instance, migrate_data=None):
497+
def get_instance_path_at_destination(
498+
instance: 'objects.Instance',
499+
migrate_data: ty.Optional['objects.LibvirtLiveMigrateData'] = None,
500+
) -> str:
461501
"""Get the instance path on destination node while live migration.
462502
463503
This method determines the directory name for instance storage on
@@ -484,7 +524,7 @@ def get_instance_path_at_destination(instance, migrate_data=None):
484524
return instance_dir
485525

486526

487-
def get_arch(image_meta):
527+
def get_arch(image_meta: 'objects.ImageMeta') -> str:
488528
"""Determine the architecture of the guest (or host).
489529
490530
This method determines the CPU architecture that must be supported by
@@ -504,7 +544,7 @@ def get_arch(image_meta):
504544
return obj_fields.Architecture.from_host()
505545

506546

507-
def is_mounted(mount_path, source=None):
547+
def is_mounted(mount_path: str, source: ty.Optional[str] = None) -> bool:
508548
"""Check if the given source is mounted at given destination point."""
509549
if not os.path.ismount(mount_path):
510550
return False
@@ -517,16 +557,16 @@ def is_mounted(mount_path, source=None):
517557
return any(mnt[0] == source and mnt[1] == mount_path for mnt in mounts)
518558

519559

520-
def is_valid_hostname(hostname):
521-
return re.match(r"^[\w\-\.:]+$", hostname)
560+
def is_valid_hostname(hostname: str) -> bool:
561+
return bool(re.match(r"^[\w\-\.:]+$", hostname))
522562

523563

524-
def version_to_string(version):
564+
def version_to_string(version: ty.Tuple[int, int, int]) -> str:
525565
"""Returns string version based on tuple"""
526566
return '.'.join([str(x) for x in version])
527567

528568

529-
def cpu_features_to_traits(features):
569+
def cpu_features_to_traits(features: ty.Set[str]) -> ty.Dict[str, bool]:
530570
"""Returns this driver's CPU traits dict where keys are trait names from
531571
CPU_TRAITS_MAPPING, values are boolean indicates whether the trait should
532572
be set in the provider tree.
@@ -539,7 +579,7 @@ def cpu_features_to_traits(features):
539579
return traits
540580

541581

542-
def get_cpu_model_from_arch(arch):
582+
def get_cpu_model_from_arch(arch: str) -> str:
543583
mode = 'qemu64'
544584
if arch == obj_fields.Architecture.I686:
545585
mode = 'qemu32'
@@ -552,7 +592,7 @@ def get_cpu_model_from_arch(arch):
552592
return mode
553593

554594

555-
def get_machine_type(image_meta):
595+
def get_machine_type(image_meta: 'objects.ImageMeta') -> ty.Optional[str]:
556596
"""The guest machine type can be set as an image metadata property, or
557597
otherwise based on architecture-specific defaults. If no defaults are
558598
found then None will be returned. This will ultimately lead to QEMU using
@@ -565,7 +605,7 @@ def get_machine_type(image_meta):
565605
return get_default_machine_type(get_arch(image_meta))
566606

567607

568-
def get_default_machine_type(arch):
608+
def get_default_machine_type(arch: str) -> ty.Optional[str]:
569609
# NOTE(lyarwood): Values defined in [libvirt]/hw_machine_type take
570610
# precedence here if available for the provided arch.
571611
for mapping in CONF.libvirt.hw_machine_type or {}:
@@ -595,21 +635,21 @@ def get_default_machine_type(arch):
595635
return default_mtypes.get(arch)
596636

597637

598-
def mdev_name2uuid(mdev_name):
638+
def mdev_name2uuid(mdev_name: str) -> str:
599639
"""Convert an mdev name (of the form mdev_<uuid_with_underscores>) to a
600640
uuid (of the form 8-4-4-4-12).
601641
"""
602642
return str(uuid.UUID(mdev_name[5:].replace('_', '-')))
603643

604644

605-
def mdev_uuid2name(mdev_uuid):
645+
def mdev_uuid2name(mdev_uuid: str) -> str:
606646
"""Convert an mdev uuid (of the form 8-4-4-4-12) to a name (of the form
607647
mdev_<uuid_with_underscores>).
608648
"""
609649
return "mdev_" + mdev_uuid.replace('-', '_')
610650

611651

612-
def get_flags_by_flavor_specs(flavor):
652+
def get_flags_by_flavor_specs(flavor: 'objects.Flavor') -> ty.Set[str]:
613653
req_spec = objects.RequestSpec(flavor=flavor)
614654
resource_request = scheduler_utils.ResourceRequest(req_spec)
615655
required_traits = resource_request.all_required_traits

0 commit comments

Comments
 (0)