Inspect non-raw images for safety
When IPA gets a non-raw image, it performs an on-the-fly conversion using qemu-img convert, as well as running qemu-img frequently to get basic information about the image before validating it. Now, we ensure that before any qemu-img calls are made, that we have inspected the image for safety and pass through the detected format. If given a disk_format=raw image and image streaming is enabled (default), we retain the existing behavior of not inspecting it in any way and streaming it bit-perfect to the device. In this case, we never use qemu-based tools on the image at all. If given a disk_format=raw image and image streaming is disabled, this change fixes a bug where the image may have been converted if it was not actually raw in the first place. We now stream these bit-perfect to the device. Adds two config options: - [DEFAULT]/disable_deep_image_inspection, which can be set to "True" in order to disable all security features. Do not do this. - [DEFAULT]/permitted_image_formats, default raw,qcow2, for image types IPA should accept. Both of these configuration options are wired up to be set by the lookup data returned by Ironic at lookup time. This uses a image format inspection module imported from Nova; this inspector will eventually live in oslo.utils, at which point we'll migrate our usage of the inspector to it. Closes-Bug: #2071740 Change-Id: I5254b80717cb5a7f9084e3eff32a00b968f987b7
This commit is contained in:
parent
4822b3203a
commit
be8ee50ea1
@ -467,6 +467,12 @@ class IronicPythonAgent(base.ExecuteCommandMixin):
|
||||
if config.get('metrics_statsd'):
|
||||
for opt, val in config.items():
|
||||
setattr(cfg.CONF.metrics_statsd, opt, val)
|
||||
if config.get('disable_deep_image_inspection') is not None:
|
||||
cfg.CONF.set_override('disable_deep_image_inspection',
|
||||
config['disable_deep_image_inspection'])
|
||||
if config.get('permitted_image_formats') is not None:
|
||||
cfg.CONF.set_override('permitted_image_formats',
|
||||
config['permitted_image_formats'])
|
||||
md5_allowed = config.get('agent_md5_checksum_enable')
|
||||
if md5_allowed is not None:
|
||||
cfg.CONF.set_override('md5_enabled', md5_allowed)
|
||||
|
@ -370,6 +370,21 @@ cli_opts = [
|
||||
help='If the agent should rebuild the configuration drive '
|
||||
'using a local filesystem, instead of letting Ironic '
|
||||
'determine if this action is necessary.'),
|
||||
cfg.BoolOpt('disable_deep_image_inspection',
|
||||
default=False,
|
||||
help='This disables the additional deep image inspection '
|
||||
'the agent does before converting and writing an image. '
|
||||
'Generally, this should remain enabled for maximum '
|
||||
'security, but this option allows disabling it if there '
|
||||
'is a compatability concern.'),
|
||||
cfg.ListOpt('permitted_image_formats',
|
||||
default='raw,qcow2',
|
||||
help='The supported list of image formats which are '
|
||||
'permitted for deployment with Ironic Python Agent. If '
|
||||
'an image format outside of this list is detected, the '
|
||||
'image validation logic will fail the deployment '
|
||||
'process. This check is skipped if deep image '
|
||||
'inspection is disabled.'),
|
||||
]
|
||||
|
||||
disk_utils_opts = [
|
||||
@ -395,6 +410,13 @@ disk_utils_opts = [
|
||||
default=10,
|
||||
help='Maximum number of attempts to try to read the '
|
||||
'partition.'),
|
||||
cfg.IntOpt('image_convert_memory_limit',
|
||||
default=2048,
|
||||
help='Memory limit for "qemu-img convert" in MiB. Implemented '
|
||||
'via the address space resource limit.'),
|
||||
cfg.IntOpt('image_convert_attempts',
|
||||
default=3,
|
||||
help='Number of attempts to convert an image.'),
|
||||
]
|
||||
|
||||
disk_part_opts = [
|
||||
@ -412,10 +434,6 @@ disk_part_opts = [
|
||||
' having failed.')
|
||||
]
|
||||
|
||||
CONF.register_cli_opts(cli_opts)
|
||||
CONF.register_opts(disk_utils_opts, group='disk_utils')
|
||||
CONF.register_opts(disk_part_opts, group='disk_partitioner')
|
||||
|
||||
|
||||
def list_opts():
|
||||
return [('DEFAULT', cli_opts),
|
||||
@ -423,6 +441,13 @@ def list_opts():
|
||||
('disk_partitioner', disk_part_opts)]
|
||||
|
||||
|
||||
def populate_config():
|
||||
"""Populate configuration. In a method so tests can easily utilize it."""
|
||||
CONF.register_cli_opts(cli_opts)
|
||||
CONF.register_opts(disk_utils_opts, group='disk_utils')
|
||||
CONF.register_opts(disk_part_opts, group='disk_partitioner')
|
||||
|
||||
|
||||
def override(params):
|
||||
"""Override configuration with values from a dictionary.
|
||||
|
||||
@ -447,3 +472,6 @@ def override(params):
|
||||
LOG.warning('Unable to override configuration option %(key)s '
|
||||
'with %(value)r: %(exc)s',
|
||||
{'key': key, 'value': value, 'exc': exc})
|
||||
|
||||
|
||||
populate_config()
|
||||
|
@ -28,7 +28,6 @@ import time
|
||||
|
||||
from ironic_lib.common.i18n import _
|
||||
from ironic_lib import exception
|
||||
from ironic_lib import qemu_img
|
||||
from ironic_lib import utils
|
||||
from oslo_concurrency import processutils
|
||||
from oslo_config import cfg
|
||||
@ -36,6 +35,9 @@ from oslo_utils import excutils
|
||||
import tenacity
|
||||
|
||||
from ironic_python_agent import disk_partitioner
|
||||
from ironic_python_agent import errors
|
||||
from ironic_python_agent import format_inspector
|
||||
from ironic_python_agent import qemu_img
|
||||
|
||||
CONF = cfg.CONF
|
||||
|
||||
@ -389,12 +391,97 @@ def dd(src, dst, conv_flags=None):
|
||||
*extra_args)
|
||||
|
||||
|
||||
def populate_image(src, dst, conv_flags=None):
|
||||
data = qemu_img.image_info(src)
|
||||
if data.file_format == 'raw':
|
||||
def _image_inspection(filename):
|
||||
try:
|
||||
inspector_cls = format_inspector.detect_file_format(filename)
|
||||
if (not inspector_cls
|
||||
or not hasattr(inspector_cls, 'safety_check')
|
||||
or not inspector_cls.safety_check()):
|
||||
err = "Security: Image failed safety check"
|
||||
LOG.error(err)
|
||||
raise errors.InvalidImage(details=err)
|
||||
|
||||
except (format_inspector.ImageFormatError, AttributeError):
|
||||
# NOTE(JayF): Because we already validated the format is OK and matches
|
||||
# expectation, it should be impossible for us to get an
|
||||
# ImageFormatError or AttributeError. We handle it anyway
|
||||
# for completeness.
|
||||
msg = "Security: Unable to safety check image"
|
||||
LOG.error(msg)
|
||||
raise errors.InvalidImage(details=msg)
|
||||
|
||||
return inspector_cls
|
||||
|
||||
|
||||
def get_and_validate_image_format(filename, ironic_disk_format):
|
||||
"""Get the format of a given image file and ensure it's allowed.
|
||||
|
||||
This method uses the format inspector originally written for glance to
|
||||
safely detect the image format. It also sanity checks to ensure any
|
||||
specified format matches the provided one (except raw; which in some
|
||||
cases is a request to convert to raw) and that the format is in the
|
||||
allowed list of formats.
|
||||
|
||||
It also performs a basic safety check on the image.
|
||||
|
||||
This entire process can be bypassed, and the older code path used,
|
||||
by setting CONF.disable_deep_image_inspection to True.
|
||||
|
||||
See https://bugs.launchpad.net/ironic/+bug/2071740 for full details on
|
||||
why this must always happen.
|
||||
|
||||
:param filename: The name of the image file to validate.
|
||||
:param ironic_disk_format: The ironic-provided expected format of the image
|
||||
:returns: tuple of validated img_format (str) and size (int)
|
||||
"""
|
||||
if CONF.disable_deep_image_inspection:
|
||||
data = qemu_img.image_info(filename)
|
||||
img_format = data.file_format
|
||||
size = data.virtual_size
|
||||
else:
|
||||
if ironic_disk_format == 'raw':
|
||||
# NOTE(JayF): IPA unconditionally writes raw images to disk without
|
||||
# conversion with dd or raw python, not qemu-img, it's
|
||||
# not required to safety check raw images.
|
||||
img_format = ironic_disk_format
|
||||
size = os.path.getsize(filename)
|
||||
else:
|
||||
img_format_cls = _image_inspection(filename)
|
||||
img_format = str(img_format_cls)
|
||||
size = img_format_cls.virtual_size
|
||||
if img_format not in CONF.permitted_image_formats:
|
||||
msg = ("Security: Detected image format was %s, but only %s "
|
||||
"are allowed")
|
||||
fmts = ', '.join(CONF.permitted_image_formats)
|
||||
LOG.error(msg, img_format, fmts)
|
||||
raise errors.InvalidImage(
|
||||
details=msg % (img_format, fmts)
|
||||
)
|
||||
elif ironic_disk_format and ironic_disk_format != img_format:
|
||||
msg = ("Security: Expected format was %s, but image was "
|
||||
"actually %s" % (ironic_disk_format, img_format))
|
||||
LOG.error(msg)
|
||||
raise errors.InvalidImage(details=msg)
|
||||
|
||||
return img_format, size
|
||||
|
||||
|
||||
def populate_image(src, dst, conv_flags=None,
|
||||
source_format=None, is_raw=False):
|
||||
"""Populate a provided destination device with the image
|
||||
|
||||
:param src: An image already security checked in format disk_format
|
||||
:param dst: A location, usually a partition or block device,
|
||||
to write the image
|
||||
:param conv_flags: Conversion flags to pass to dd if provided
|
||||
:param source_format: format of the image
|
||||
:param is_raw: Ironic indicates image is raw; do not convert!
|
||||
"""
|
||||
if is_raw:
|
||||
dd(src, dst, conv_flags=conv_flags)
|
||||
else:
|
||||
qemu_img.convert_image(src, dst, 'raw', True, sparse_size='0')
|
||||
qemu_img.convert_image(src, dst, 'raw', True,
|
||||
sparse_size='0', source_format=source_format)
|
||||
|
||||
|
||||
def block_uuid(dev):
|
||||
@ -412,20 +499,6 @@ def block_uuid(dev):
|
||||
return info.get('PARTUUID', '')
|
||||
|
||||
|
||||
def get_image_mb(image_path, virtual_size=True):
|
||||
"""Get size of an image in Megabyte."""
|
||||
mb = 1024 * 1024
|
||||
if not virtual_size:
|
||||
image_byte = os.path.getsize(image_path)
|
||||
else:
|
||||
data = qemu_img.image_info(image_path)
|
||||
image_byte = data.virtual_size
|
||||
|
||||
# round up size to MB
|
||||
image_mb = int((image_byte + mb - 1) / mb)
|
||||
return image_mb
|
||||
|
||||
|
||||
def get_dev_byte_size(dev):
|
||||
"""Get the device size in bytes."""
|
||||
byte_sz, cmderr = utils.execute('blockdev', '--getsize64', dev)
|
||||
|
@ -376,3 +376,12 @@ class ProtectedDeviceError(CleaningError):
|
||||
|
||||
self.message = details
|
||||
super(CleaningError, self).__init__(details)
|
||||
|
||||
|
||||
class InvalidImage(DeploymentError):
|
||||
"""Error raised when an image fails validation for any reason."""
|
||||
|
||||
message = 'The provided image is not valid for use'
|
||||
|
||||
def __init__(self, details=None):
|
||||
super(InvalidImage, self).__init__(details)
|
||||
|
@ -20,10 +20,10 @@ import time
|
||||
from urllib import parse as urlparse
|
||||
|
||||
from ironic_lib import exception
|
||||
from ironic_lib import qemu_img
|
||||
from oslo_concurrency import processutils
|
||||
from oslo_config import cfg
|
||||
from oslo_log import log
|
||||
from oslo_utils import units
|
||||
import requests
|
||||
|
||||
from ironic_python_agent import disk_utils
|
||||
@ -31,6 +31,7 @@ from ironic_python_agent import errors
|
||||
from ironic_python_agent.extensions import base
|
||||
from ironic_python_agent import hardware
|
||||
from ironic_python_agent import partition_utils
|
||||
from ironic_python_agent import qemu_img
|
||||
from ironic_python_agent import utils
|
||||
|
||||
CONF = cfg.CONF
|
||||
@ -277,7 +278,8 @@ def _fetch_checksum(checksum, image_info):
|
||||
checksum, "Checksum file does not contain name %s" % expected_fname)
|
||||
|
||||
|
||||
def _write_partition_image(image, image_info, device, configdrive=None):
|
||||
def _write_partition_image(image, image_info, device, configdrive=None,
|
||||
source_format=None, is_raw=False, size=0):
|
||||
"""Call disk_util to create partition and write the partition image.
|
||||
|
||||
:param image: Local path to image file to be written to the partition.
|
||||
@ -288,6 +290,10 @@ def _write_partition_image(image, image_info, device, configdrive=None):
|
||||
:param configdrive: A string containing the location of the config
|
||||
drive as a URL OR the contents (as gzip/base64)
|
||||
of the configdrive. Optional, defaults to None.
|
||||
:param source_format: The actual format of the partition image.
|
||||
Must be provided if deep image inspection is enabled.
|
||||
:param is_raw: Ironic indicates the image is raw; do not convert it
|
||||
:param size: Virtual size, in MB, of provided image.
|
||||
|
||||
:raises: InvalidCommandParamsError if the partition is too small for the
|
||||
provided image.
|
||||
@ -307,10 +313,9 @@ def _write_partition_image(image, image_info, device, configdrive=None):
|
||||
cpu_arch = hardware.dispatch_to_managers('get_cpus').architecture
|
||||
|
||||
if image is not None:
|
||||
image_mb = disk_utils.get_image_mb(image)
|
||||
if image_mb > int(root_mb):
|
||||
if size > int(root_mb):
|
||||
msg = ('Root partition is too small for requested image. Image '
|
||||
'virtual size: {} MB, Root size: {} MB').format(image_mb,
|
||||
'virtual size: {} MB, Root size: {} MB').format(size,
|
||||
root_mb)
|
||||
raise errors.InvalidCommandParamsError(msg)
|
||||
|
||||
@ -324,12 +329,15 @@ def _write_partition_image(image, image_info, device, configdrive=None):
|
||||
configdrive=configdrive,
|
||||
boot_mode=boot_mode,
|
||||
disk_label=disk_label,
|
||||
cpu_arch=cpu_arch)
|
||||
cpu_arch=cpu_arch,
|
||||
source_format=source_format,
|
||||
is_raw=is_raw)
|
||||
except processutils.ProcessExecutionError as e:
|
||||
raise errors.ImageWriteError(device, e.exit_code, e.stdout, e.stderr)
|
||||
|
||||
|
||||
def _write_whole_disk_image(image, image_info, device):
|
||||
def _write_whole_disk_image(image, image_info, device, source_format=None,
|
||||
is_raw=False):
|
||||
"""Writes a whole disk image to the specified device.
|
||||
|
||||
:param image: Local path to image file to be written to the disk.
|
||||
@ -337,22 +345,40 @@ def _write_whole_disk_image(image, image_info, device):
|
||||
This parameter is currently unused by the function.
|
||||
:param device: The device name, as a string, on which to store the image.
|
||||
Example: '/dev/sda'
|
||||
|
||||
:param source_format: The format of the whole disk image to be written.
|
||||
:param is_raw: Ironic indicates the image is raw; do not convert it
|
||||
:raises: ImageWriteError if the command to write the image encounters an
|
||||
error.
|
||||
:raises: InvalidImage if asked to write an image without a format when
|
||||
not permitted
|
||||
"""
|
||||
# FIXME(dtantsur): pass the real node UUID for logging
|
||||
disk_utils.destroy_disk_metadata(device, '')
|
||||
disk_utils.udev_settle()
|
||||
|
||||
command = ['qemu-img', 'convert',
|
||||
'-t', 'directsync', '-S', '0', '-O', 'host_device', '-W',
|
||||
image, device]
|
||||
LOG.info('Writing image with command: %s', ' '.join(command))
|
||||
try:
|
||||
qemu_img.convert_image(image, device, out_format='host_device',
|
||||
cache='directsync', out_of_order=True,
|
||||
sparse_size='0')
|
||||
if is_raw:
|
||||
# TODO(JayF): We should unify all these dd/convert_image calls
|
||||
# into disk_utils.populate_image().
|
||||
# NOTE(JayF): Since we do not safety check raw images, we must use
|
||||
# dd to write them to ensure maximum security. This may cause
|
||||
# failures in situations where images are configured as raw but
|
||||
# are actually in need of conversion. Those cases can no longer
|
||||
# be transparently handled safely.
|
||||
LOG.info('Writing raw image %s to device %s', image, device)
|
||||
disk_utils.dd(image, device)
|
||||
else:
|
||||
command = ['qemu-img', 'convert',
|
||||
'-t', 'directsync', '-S', '0', '-O', 'host_device',
|
||||
'-W']
|
||||
if source_format:
|
||||
command += ['-f', source_format]
|
||||
command += [image, device]
|
||||
LOG.info('Writing image with command: %s', ' '.join(command))
|
||||
qemu_img.convert_image(image, device, out_format='host_device',
|
||||
cache='directsync', out_of_order=True,
|
||||
sparse_size='0',
|
||||
source_format=source_format)
|
||||
except processutils.ProcessExecutionError as e:
|
||||
raise errors.ImageWriteError(device, e.exit_code, e.stdout, e.stderr)
|
||||
|
||||
@ -370,14 +396,28 @@ def _write_image(image_info, device, configdrive=None):
|
||||
of the configdrive. Optional, defaults to None.
|
||||
:raises: ImageWriteError if the command to write the image encounters an
|
||||
error.
|
||||
:raises: InvalidImage if the image does not pass security inspection
|
||||
"""
|
||||
starttime = time.time()
|
||||
image = _image_location(image_info)
|
||||
ironic_disk_format = image_info.get('disk_format')
|
||||
is_raw = ironic_disk_format == 'raw'
|
||||
# NOTE(JayF): The below method call performs a required security check
|
||||
# and must remain in place. See bug #2071740
|
||||
source_format, size = disk_utils.get_and_validate_image_format(
|
||||
image, ironic_disk_format)
|
||||
size_mb = int((size + units.Mi - 1) / units.Mi)
|
||||
|
||||
uuids = {}
|
||||
if image_info.get('image_type') == 'partition':
|
||||
uuids = _write_partition_image(image, image_info, device, configdrive)
|
||||
uuids = _write_partition_image(image, image_info, device,
|
||||
configdrive,
|
||||
source_format=source_format,
|
||||
is_raw=is_raw, size=size_mb)
|
||||
else:
|
||||
_write_whole_disk_image(image, image_info, device)
|
||||
_write_whole_disk_image(image, image_info, device,
|
||||
source_format=source_format,
|
||||
is_raw=is_raw)
|
||||
totaltime = time.time() - starttime
|
||||
LOG.info('Image %(image)s written to device %(device)s in %(totaltime)s '
|
||||
'seconds', {'image': image, 'device': device,
|
||||
@ -907,16 +947,20 @@ class StandbyExtension(base.BaseAgentExtension):
|
||||
device = hardware.dispatch_to_managers('get_os_install_device',
|
||||
permit_refresh=True)
|
||||
|
||||
disk_format = image_info.get('disk_format')
|
||||
requested_disk_format = image_info.get('disk_format')
|
||||
|
||||
stream_raw_images = image_info.get('stream_raw_images', False)
|
||||
|
||||
# don't write image again if already cached
|
||||
if self.cached_image_id != image_info['id']:
|
||||
if self.cached_image_id is not None:
|
||||
LOG.debug('Already had %s cached, overwriting',
|
||||
self.cached_image_id)
|
||||
|
||||
if stream_raw_images and disk_format == 'raw':
|
||||
if stream_raw_images and requested_disk_format == 'raw':
|
||||
if image_info.get('image_type') == 'partition':
|
||||
# NOTE(JayF): This only creates partitions due to image
|
||||
# being None
|
||||
self.partition_uuids = _write_partition_image(None,
|
||||
image_info,
|
||||
device,
|
||||
@ -926,6 +970,9 @@ class StandbyExtension(base.BaseAgentExtension):
|
||||
self.partition_uuids = {}
|
||||
stream_to = device
|
||||
|
||||
# NOTE(JayF): Images that claim to be raw are not inspected at
|
||||
# all, as they never interact with qemu-img and are
|
||||
# streamed directly to disk unmodified.
|
||||
self._stream_raw_image_onto_device(image_info, stream_to)
|
||||
else:
|
||||
self._cache_and_write_image(image_info, device, configdrive)
|
||||
|
1044
ironic_python_agent/format_inspector.py
Normal file
1044
ironic_python_agent/format_inspector.py
Normal file
File diff suppressed because it is too large
Load Diff
@ -187,7 +187,8 @@ def get_labelled_partition(device_path, label, node_uuid):
|
||||
def work_on_disk(dev, root_mb, swap_mb, ephemeral_mb, ephemeral_format,
|
||||
image_path, node_uuid, preserve_ephemeral=False,
|
||||
configdrive=None, boot_mode="bios",
|
||||
tempdir=None, disk_label=None, cpu_arch="", conv_flags=None):
|
||||
tempdir=None, disk_label=None, cpu_arch="", conv_flags=None,
|
||||
source_format=None, is_raw=False):
|
||||
"""Create partitions and copy an image to the root partition.
|
||||
|
||||
:param dev: Path for the device to work on.
|
||||
@ -218,6 +219,9 @@ def work_on_disk(dev, root_mb, swap_mb, ephemeral_mb, ephemeral_format,
|
||||
:param conv_flags: Flags that need to be sent to the dd command, to control
|
||||
the conversion of the original file when copying to the host. It can
|
||||
contain several options separated by commas.
|
||||
:param source_format: The format of the disk image to be written.
|
||||
If set, must be "raw" or the actual disk format of the image.
|
||||
:param is_raw: Ironic indictor image is raw; not to be converted
|
||||
:returns: a dictionary containing the following keys:
|
||||
'root uuid': UUID of root partition
|
||||
'efi system partition uuid': UUID of the uefi system partition
|
||||
@ -295,7 +299,8 @@ def work_on_disk(dev, root_mb, swap_mb, ephemeral_mb, ephemeral_format,
|
||||
utils.unlink_without_raise(configdrive_file)
|
||||
|
||||
if image_path is not None:
|
||||
disk_utils.populate_image(image_path, root_part, conv_flags=conv_flags)
|
||||
disk_utils.populate_image(image_path, root_part, conv_flags=conv_flags,
|
||||
source_format=source_format, is_raw=is_raw)
|
||||
LOG.info("Image for %(node)s successfully populated",
|
||||
{'node': node_uuid})
|
||||
else:
|
||||
|
153
ironic_python_agent/qemu_img.py
Normal file
153
ironic_python_agent/qemu_img.py
Normal file
@ -0,0 +1,153 @@
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from ironic_lib import utils
|
||||
from oslo_concurrency import processutils
|
||||
from oslo_config import cfg
|
||||
from oslo_utils import imageutils
|
||||
from oslo_utils import units
|
||||
import tenacity
|
||||
|
||||
from ironic_python_agent import errors
|
||||
|
||||
"""
|
||||
Imported from ironic_lib/qemu-img.py from commit
|
||||
c3d59dfffc9804273b49c0556ee09419a35917c1
|
||||
|
||||
See https://bugs.launchpad.net/ironic/+bug/2071740 for more details as to why
|
||||
it moved.
|
||||
|
||||
This module also exists in the Ironic repo. Do not modify this module
|
||||
without also modifying that module.
|
||||
"""
|
||||
|
||||
CONF = cfg.CONF
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
# Limit the memory address space to 1 GiB when running qemu-img
|
||||
QEMU_IMG_LIMITS = None
|
||||
|
||||
|
||||
def _qemu_img_limits():
|
||||
global QEMU_IMG_LIMITS
|
||||
if QEMU_IMG_LIMITS is None:
|
||||
QEMU_IMG_LIMITS = processutils.ProcessLimits(
|
||||
address_space=CONF.disk_utils.image_convert_memory_limit
|
||||
* units.Mi)
|
||||
return QEMU_IMG_LIMITS
|
||||
|
||||
|
||||
def _retry_on_res_temp_unavailable(exc):
|
||||
if (isinstance(exc, processutils.ProcessExecutionError)
|
||||
and ('Resource temporarily unavailable' in exc.stderr
|
||||
or 'Cannot allocate memory' in exc.stderr)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def image_info(path, source_format=None):
|
||||
"""Return an object containing the parsed output from qemu-img info.
|
||||
|
||||
This must only be called on images already validated as safe by the
|
||||
format inspector.
|
||||
|
||||
:param path: The path to an image you need information on
|
||||
:param source_format: The format of the source image. If this is omitted
|
||||
when deep inspection is enabled, this will raise
|
||||
InvalidImage.
|
||||
"""
|
||||
# NOTE(JayF): This serves as a final exit hatch: if we have deep
|
||||
# image inspection enabled, but someone calls this method without an
|
||||
# explicit disk_format, there's no way for us to do the call securely.
|
||||
if not source_format and not CONF.disable_deep_image_inspection:
|
||||
msg = ("Security: qemu_img.image_info called unsafely while deep "
|
||||
"image inspection is enabled. This should not be possible, "
|
||||
"please contact Ironic developers.")
|
||||
raise errors.InvalidImage(details=msg)
|
||||
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError("File %s does not exist" % path)
|
||||
|
||||
cmd = [
|
||||
'env', 'LC_ALL=C', 'LANG=C',
|
||||
'qemu-img', 'info', path,
|
||||
'--output=json'
|
||||
]
|
||||
|
||||
if source_format:
|
||||
cmd += ['-f', source_format]
|
||||
|
||||
out, err = utils.execute(cmd, prlimit=_qemu_img_limits())
|
||||
return imageutils.QemuImgInfo(out, format='json')
|
||||
|
||||
|
||||
@tenacity.retry(
|
||||
retry=tenacity.retry_if_exception(_retry_on_res_temp_unavailable),
|
||||
stop=tenacity.stop_after_attempt(CONF.disk_utils.image_convert_attempts),
|
||||
reraise=True)
|
||||
def convert_image(source, dest, out_format, run_as_root=False, cache=None,
|
||||
out_of_order=False, sparse_size=None, source_format=None):
|
||||
"""Convert image to other format.
|
||||
|
||||
This method is only to be run against images who have passed
|
||||
format_inspector's safety check, and with the format reported by it
|
||||
passed in. Any other usage is a major security risk.
|
||||
"""
|
||||
cmd = ['qemu-img', 'convert', '-O', out_format]
|
||||
if cache is not None:
|
||||
cmd += ['-t', cache]
|
||||
if sparse_size is not None:
|
||||
cmd += ['-S', sparse_size]
|
||||
|
||||
if source_format is not None:
|
||||
cmd += ['-f', source_format]
|
||||
elif not CONF.disable_deep_image_inspection:
|
||||
# NOTE(JayF): This serves as a final exit hatch: if we have deep
|
||||
# image inspection enabled, but someone calls this method without an
|
||||
# explicit disk_format, there's no way for us to do the conversion
|
||||
# securely.
|
||||
msg = ("Security: qemu_img.convert_image called unsafely while deep "
|
||||
"image inspection is enabled. This should not be possible, "
|
||||
"please notify Ironic developers.")
|
||||
LOG.error(msg)
|
||||
raise errors.InvalidImage(details=msg)
|
||||
|
||||
if out_of_order:
|
||||
cmd.append('-W')
|
||||
cmd += [source, dest]
|
||||
# NOTE(TheJulia): Statically set the MALLOC_ARENA_MAX to prevent leaking
|
||||
# and the creation of new malloc arenas which will consume the system
|
||||
# memory. If limited to 1, qemu-img consumes ~250 MB of RAM, but when
|
||||
# another thread tries to access a locked section of memory in use with
|
||||
# another thread, then by default a new malloc arena is created,
|
||||
# which essentially balloons the memory requirement of the machine.
|
||||
# Default for qemu-img is 8 * nCPU * ~250MB (based on defaults +
|
||||
# thread/code/process/library overhead. In other words, 64 GB. Limiting
|
||||
# this to 3 keeps the memory utilization in happy cases below the overall
|
||||
# threshold which is in place in case a malicious image is attempted to
|
||||
# be passed through qemu-img.
|
||||
env_vars = {'MALLOC_ARENA_MAX': '3'}
|
||||
try:
|
||||
utils.execute(*cmd, run_as_root=run_as_root,
|
||||
prlimit=_qemu_img_limits(),
|
||||
use_standard_locale=True,
|
||||
env_variables=env_vars)
|
||||
except processutils.ProcessExecutionError as e:
|
||||
if ('Resource temporarily unavailable' in e.stderr
|
||||
or 'Cannot allocate memory' in e.stderr):
|
||||
LOG.debug('Failed to convert image, retrying. Error: %s', e)
|
||||
# Sync disk caches before the next attempt
|
||||
utils.execute('sync')
|
||||
raise
|
@ -25,6 +25,7 @@ from oslo_log import log
|
||||
from oslo_service import sslutils
|
||||
from oslotest import base as test_base
|
||||
|
||||
from ironic_python_agent import config
|
||||
from ironic_python_agent.extensions import base as ext_base
|
||||
from ironic_python_agent import hardware
|
||||
|
||||
@ -40,6 +41,7 @@ class IronicAgentTest(test_base.BaseTestCase):
|
||||
def setUp(self):
|
||||
super(IronicAgentTest, self).setUp()
|
||||
|
||||
config.populate_config()
|
||||
self._set_config()
|
||||
|
||||
# Ban running external processes via 'execute' like functions. If the
|
||||
|
@ -20,6 +20,7 @@ from unittest import mock
|
||||
from ironic_lib import exception
|
||||
from oslo_concurrency import processutils
|
||||
from oslo_config import cfg
|
||||
from oslo_utils import units
|
||||
import requests
|
||||
|
||||
from ironic_python_agent import errors
|
||||
@ -33,6 +34,11 @@ from ironic_python_agent import utils
|
||||
CONF = cfg.CONF
|
||||
|
||||
|
||||
def _virtual_size(size=1):
|
||||
"""Convert a virtual size in mb to bytes"""
|
||||
return (size * units.Mi) + 1 - units.Mi
|
||||
|
||||
|
||||
def _build_fake_image_info(url='http://example.org'):
|
||||
return {
|
||||
'id': 'fake_id',
|
||||
@ -41,6 +47,7 @@ def _build_fake_image_info(url='http://example.org'):
|
||||
'image_type': 'whole-disk-image',
|
||||
'os_hash_algo': 'sha256',
|
||||
'os_hash_value': 'fake-checksum',
|
||||
'disk_format': 'qcow2'
|
||||
}
|
||||
|
||||
|
||||
@ -60,7 +67,9 @@ def _build_fake_partition_image_info():
|
||||
'disk_label': 'msdos',
|
||||
'deploy_boot_mode': 'bios',
|
||||
'os_hash_algo': 'sha256',
|
||||
'os_hash_value': 'fake-checksum'}
|
||||
'os_hash_value': 'fake-checksum',
|
||||
'disk_format': 'qcow2'
|
||||
}
|
||||
|
||||
|
||||
class TestStandbyExtension(base.IronicAgentTest):
|
||||
@ -279,18 +288,23 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
None,
|
||||
image_info['id'])
|
||||
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.fix_gpt_partition',
|
||||
autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.trigger_device_rescan',
|
||||
autospec=True)
|
||||
@mock.patch('ironic_lib.qemu_img.convert_image', autospec=True)
|
||||
@mock.patch('ironic_python_agent.qemu_img.convert_image', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.udev_settle', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.destroy_disk_metadata',
|
||||
autospec=True)
|
||||
def test_write_image(self, wipe_mock, udev_mock, convert_mock,
|
||||
rescan_mock, fix_gpt_mock):
|
||||
rescan_mock, fix_gpt_mock, validate_mock):
|
||||
image_info = _build_fake_image_info()
|
||||
device = '/dev/sda'
|
||||
source_format = image_info['disk_format']
|
||||
validate_mock.return_value = (source_format, 0)
|
||||
location = standby._image_location(image_info)
|
||||
|
||||
standby._write_image(image_info, device)
|
||||
@ -299,7 +313,9 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
out_format='host_device',
|
||||
cache='directsync',
|
||||
out_of_order=True,
|
||||
sparse_size='0')
|
||||
sparse_size='0',
|
||||
source_format=source_format)
|
||||
validate_mock.assert_called_once_with(location, source_format)
|
||||
wipe_mock.assert_called_once_with(device, '')
|
||||
udev_mock.assert_called_once_with()
|
||||
rescan_mock.assert_called_once_with(device)
|
||||
@ -309,24 +325,33 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.trigger_device_rescan',
|
||||
autospec=True)
|
||||
@mock.patch('ironic_lib.qemu_img.convert_image', autospec=True)
|
||||
@mock.patch('ironic_python_agent.qemu_img.convert_image', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.udev_settle', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.destroy_disk_metadata',
|
||||
autospec=True)
|
||||
def test_write_image_gpt_fails(self, wipe_mock, udev_mock, convert_mock,
|
||||
rescan_mock, fix_gpt_mock):
|
||||
image_info = _build_fake_image_info()
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
def test_write_image_gpt_fails(self, validate_mock, wipe_mock, udev_mock,
|
||||
convert_mock, rescan_mock, fix_gpt_mock):
|
||||
device = '/dev/sda'
|
||||
image_info = _build_fake_image_info()
|
||||
validate_mock.return_value = (image_info['disk_format'], 0)
|
||||
|
||||
fix_gpt_mock.side_effect = exception.InstanceDeployFailure
|
||||
standby._write_image(image_info, device)
|
||||
|
||||
@mock.patch('ironic_lib.qemu_img.convert_image', autospec=True)
|
||||
@mock.patch('ironic_python_agent.qemu_img.convert_image', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.udev_settle', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.destroy_disk_metadata',
|
||||
autospec=True)
|
||||
def test_write_image_fails(self, wipe_mock, udev_mock, convert_mock):
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
def test_write_image_fails(self, validate_mock, wipe_mock, udev_mock,
|
||||
convert_mock):
|
||||
image_info = _build_fake_image_info()
|
||||
validate_mock.return_value = (image_info['disk_format'], 0)
|
||||
device = '/dev/sda'
|
||||
convert_mock.side_effect = processutils.ProcessExecutionError
|
||||
|
||||
@ -339,10 +364,12 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
@mock.patch.object(hardware, 'dispatch_to_managers', autospec=True)
|
||||
@mock.patch('builtins.open', autospec=True)
|
||||
@mock.patch('ironic_python_agent.utils.execute', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.get_image_mb', autospec=True)
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
@mock.patch.object(partition_utils, 'work_on_disk', autospec=True)
|
||||
def test_write_partition_image_exception(self, work_on_disk_mock,
|
||||
image_mb_mock,
|
||||
validate_mock,
|
||||
execute_mock, open_mock,
|
||||
dispatch_mock):
|
||||
image_info = _build_fake_partition_image_info()
|
||||
@ -355,11 +382,13 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
pr_ep = image_info['preserve_ephemeral']
|
||||
boot_mode = image_info['deploy_boot_mode']
|
||||
disk_label = image_info['disk_label']
|
||||
source_format = image_info['disk_format']
|
||||
cpu_arch = self.fake_cpu.architecture
|
||||
|
||||
image_path = standby._image_location(image_info)
|
||||
|
||||
image_mb_mock.return_value = 1
|
||||
validate_mock.return_value = (image_info['disk_format'],
|
||||
_virtual_size(1))
|
||||
dispatch_mock.return_value = self.fake_cpu
|
||||
exc = errors.ImageWriteError
|
||||
Exception_returned = processutils.ProcessExecutionError
|
||||
@ -367,7 +396,7 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
|
||||
self.assertRaises(exc, standby._write_image, image_info,
|
||||
device, 'configdrive')
|
||||
image_mb_mock.assert_called_once_with(image_path)
|
||||
validate_mock.assert_called_once_with(image_path, source_format)
|
||||
work_on_disk_mock.assert_called_once_with(device, root_mb, swap_mb,
|
||||
ephemeral_mb,
|
||||
ephemeral_format,
|
||||
@ -377,16 +406,20 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
preserve_ephemeral=pr_ep,
|
||||
boot_mode=boot_mode,
|
||||
disk_label=disk_label,
|
||||
cpu_arch=cpu_arch)
|
||||
cpu_arch=cpu_arch,
|
||||
source_format=source_format,
|
||||
is_raw=False)
|
||||
|
||||
@mock.patch.object(utils, 'get_node_boot_mode', lambda self: 'bios')
|
||||
@mock.patch.object(hardware, 'dispatch_to_managers', autospec=True)
|
||||
@mock.patch('builtins.open', autospec=True)
|
||||
@mock.patch('ironic_python_agent.utils.execute', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.get_image_mb', autospec=True)
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
@mock.patch.object(partition_utils, 'work_on_disk', autospec=True)
|
||||
def test_write_partition_image_no_node_uuid(self, work_on_disk_mock,
|
||||
image_mb_mock,
|
||||
validate_mock,
|
||||
execute_mock, open_mock,
|
||||
dispatch_mock):
|
||||
image_info = _build_fake_partition_image_info()
|
||||
@ -400,19 +433,19 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
pr_ep = image_info['preserve_ephemeral']
|
||||
boot_mode = image_info['deploy_boot_mode']
|
||||
disk_label = image_info['disk_label']
|
||||
source_format = image_info['disk_format']
|
||||
cpu_arch = self.fake_cpu.architecture
|
||||
|
||||
image_path = standby._image_location(image_info)
|
||||
|
||||
image_mb_mock.return_value = 1
|
||||
validate_mock.return_value = (source_format, _virtual_size(1))
|
||||
dispatch_mock.return_value = self.fake_cpu
|
||||
uuids = {'root uuid': 'root_uuid'}
|
||||
expected_uuid = {'root uuid': 'root_uuid'}
|
||||
image_mb_mock.return_value = 1
|
||||
work_on_disk_mock.return_value = uuids
|
||||
|
||||
standby._write_image(image_info, device, 'configdrive')
|
||||
image_mb_mock.assert_called_once_with(image_path)
|
||||
validate_mock.assert_called_once_with(image_path, source_format)
|
||||
work_on_disk_mock.assert_called_once_with(device, root_mb, swap_mb,
|
||||
ephemeral_mb,
|
||||
ephemeral_format,
|
||||
@ -422,7 +455,9 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
preserve_ephemeral=pr_ep,
|
||||
boot_mode=boot_mode,
|
||||
disk_label=disk_label,
|
||||
cpu_arch=cpu_arch)
|
||||
cpu_arch=cpu_arch,
|
||||
source_format=source_format,
|
||||
is_raw=False)
|
||||
|
||||
self.assertEqual(expected_uuid, work_on_disk_mock.return_value)
|
||||
self.assertIsNone(node_uuid)
|
||||
@ -430,26 +465,29 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
@mock.patch.object(hardware, 'dispatch_to_managers', autospec=True)
|
||||
@mock.patch('builtins.open', autospec=True)
|
||||
@mock.patch('ironic_python_agent.utils.execute', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.get_image_mb', autospec=True)
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
@mock.patch.object(partition_utils, 'work_on_disk', autospec=True)
|
||||
def test_write_partition_image_exception_image_mb(self,
|
||||
work_on_disk_mock,
|
||||
image_mb_mock,
|
||||
validate_mock,
|
||||
execute_mock,
|
||||
open_mock,
|
||||
dispatch_mock):
|
||||
dispatch_mock.return_value = self.fake_cpu
|
||||
image_info = _build_fake_partition_image_info()
|
||||
device = '/dev/sda'
|
||||
source_format = image_info['disk_format']
|
||||
image_path = standby._image_location(image_info)
|
||||
|
||||
image_mb_mock.return_value = 20
|
||||
validate_mock.return_value = (source_format, _virtual_size(20))
|
||||
|
||||
exc = errors.InvalidCommandParamsError
|
||||
|
||||
self.assertRaises(exc, standby._write_image, image_info,
|
||||
device)
|
||||
image_mb_mock.assert_called_once_with(image_path)
|
||||
validate_mock.assert_called_once_with(image_path, source_format)
|
||||
self.assertFalse(work_on_disk_mock.called)
|
||||
|
||||
@mock.patch.object(utils, 'get_node_boot_mode', lambda self: 'bios')
|
||||
@ -457,8 +495,10 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
@mock.patch('builtins.open', autospec=True)
|
||||
@mock.patch('ironic_python_agent.utils.execute', autospec=True)
|
||||
@mock.patch.object(partition_utils, 'work_on_disk', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.get_image_mb', autospec=True)
|
||||
def test_write_partition_image(self, image_mb_mock, work_on_disk_mock,
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
def test_write_partition_image(self, validate_mock, work_on_disk_mock,
|
||||
execute_mock, open_mock, dispatch_mock):
|
||||
image_info = _build_fake_partition_image_info()
|
||||
device = '/dev/sda'
|
||||
@ -470,17 +510,18 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
pr_ep = image_info['preserve_ephemeral']
|
||||
boot_mode = image_info['deploy_boot_mode']
|
||||
disk_label = image_info['disk_label']
|
||||
source_format = image_info['disk_format']
|
||||
cpu_arch = self.fake_cpu.architecture
|
||||
|
||||
image_path = standby._image_location(image_info)
|
||||
uuids = {'root uuid': 'root_uuid'}
|
||||
expected_uuid = {'root uuid': 'root_uuid'}
|
||||
image_mb_mock.return_value = 1
|
||||
validate_mock.return_value = (source_format, _virtual_size(1))
|
||||
dispatch_mock.return_value = self.fake_cpu
|
||||
work_on_disk_mock.return_value = uuids
|
||||
|
||||
standby._write_image(image_info, device, 'configdrive')
|
||||
image_mb_mock.assert_called_once_with(image_path)
|
||||
validate_mock.assert_called_once_with(image_path, source_format)
|
||||
work_on_disk_mock.assert_called_once_with(device, root_mb, swap_mb,
|
||||
ephemeral_mb,
|
||||
ephemeral_format,
|
||||
@ -490,7 +531,9 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
preserve_ephemeral=pr_ep,
|
||||
boot_mode=boot_mode,
|
||||
disk_label=disk_label,
|
||||
cpu_arch=cpu_arch)
|
||||
cpu_arch=cpu_arch,
|
||||
source_format=source_format,
|
||||
is_raw=False)
|
||||
|
||||
self.assertEqual(expected_uuid, work_on_disk_mock.return_value)
|
||||
|
||||
@ -1578,11 +1621,13 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
@mock.patch.object(hardware, 'dispatch_to_managers', autospec=True)
|
||||
@mock.patch('builtins.open', autospec=True)
|
||||
@mock.patch('ironic_python_agent.utils.execute', autospec=True)
|
||||
@mock.patch('ironic_python_agent.disk_utils.get_image_mb', autospec=True)
|
||||
@mock.patch(
|
||||
'ironic_python_agent.disk_utils.get_and_validate_image_format',
|
||||
autospec=True)
|
||||
@mock.patch.object(partition_utils, 'work_on_disk', autospec=True)
|
||||
def test_write_partition_image_no_node_uuid_uefi(
|
||||
self, work_on_disk_mock,
|
||||
image_mb_mock,
|
||||
validate_mock,
|
||||
execute_mock, open_mock,
|
||||
dispatch_mock):
|
||||
image_info = _build_fake_partition_image_info()
|
||||
@ -1594,19 +1639,19 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
ephemeral_format = image_info['ephemeral_format']
|
||||
node_uuid = image_info['node_uuid']
|
||||
pr_ep = image_info['preserve_ephemeral']
|
||||
source_format = image_info['disk_format']
|
||||
validate_mock.return_value = (source_format, _virtual_size(1))
|
||||
cpu_arch = self.fake_cpu.architecture
|
||||
|
||||
image_path = standby._image_location(image_info)
|
||||
|
||||
image_mb_mock.return_value = 1
|
||||
dispatch_mock.return_value = self.fake_cpu
|
||||
uuids = {'root uuid': 'root_uuid'}
|
||||
expected_uuid = {'root uuid': 'root_uuid'}
|
||||
image_mb_mock.return_value = 1
|
||||
work_on_disk_mock.return_value = uuids
|
||||
|
||||
standby._write_image(image_info, device, 'configdrive')
|
||||
image_mb_mock.assert_called_once_with(image_path)
|
||||
validate_mock.assert_called_once_with(image_path, source_format)
|
||||
work_on_disk_mock.assert_called_once_with(device, root_mb, swap_mb,
|
||||
ephemeral_mb,
|
||||
ephemeral_format,
|
||||
@ -1616,7 +1661,9 @@ class TestStandbyExtension(base.IronicAgentTest):
|
||||
preserve_ephemeral=pr_ep,
|
||||
boot_mode='uefi',
|
||||
disk_label='gpt',
|
||||
cpu_arch=cpu_arch)
|
||||
cpu_arch=cpu_arch,
|
||||
source_format=source_format,
|
||||
is_raw=False)
|
||||
|
||||
self.assertEqual(expected_uuid, work_on_disk_mock.return_value)
|
||||
self.assertIsNone(node_uuid)
|
||||
|
@ -13,22 +13,54 @@
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from unittest import mock
|
||||
|
||||
from ironic_lib import exception
|
||||
from ironic_lib import qemu_img
|
||||
from ironic_lib.tests import base
|
||||
from ironic_lib import utils
|
||||
from oslo_concurrency import processutils
|
||||
from oslo_config import cfg
|
||||
from oslo_utils.imageutils import QemuImgInfo
|
||||
from oslo_utils import units
|
||||
|
||||
from ironic_python_agent import disk_utils
|
||||
from ironic_python_agent.errors import InvalidImage
|
||||
from ironic_python_agent import format_inspector
|
||||
from ironic_python_agent import qemu_img
|
||||
|
||||
CONF = cfg.CONF
|
||||
|
||||
|
||||
class MockFormatInspectorCls(object):
|
||||
def __init__(self, img_format='qcow2', virtual_size_mb=0, safe=False):
|
||||
self.img_format = img_format
|
||||
self.virtual_size_mb = virtual_size_mb
|
||||
self.safe = safe
|
||||
|
||||
def __str__(self):
|
||||
return self.img_format
|
||||
|
||||
@property
|
||||
def virtual_size(self):
|
||||
# NOTE(JayF): Allow the mock-user to input MBs but
|
||||
# backwards-calculate so code in _write_image can still work
|
||||
if self.virtual_size_mb == 0:
|
||||
return 0
|
||||
else:
|
||||
return (self.virtual_size_mb * units.Mi) + 1 - units.Mi
|
||||
|
||||
def safety_check(self):
|
||||
return self.safe
|
||||
|
||||
|
||||
def _get_fake_qemu_image_info(file_format='qcow2', virtual_size=0):
|
||||
fake_data = {'format': file_format, 'virtual-size': virtual_size, }
|
||||
return QemuImgInfo(cmd_output=json.dumps(fake_data), format='json')
|
||||
|
||||
|
||||
@mock.patch.object(utils, 'execute', autospec=True)
|
||||
class ListPartitionsTestCase(base.IronicLibTestCase):
|
||||
|
||||
@ -484,31 +516,24 @@ class GetDeviceByteSizeTestCase(base.IronicLibTestCase):
|
||||
|
||||
|
||||
@mock.patch.object(disk_utils, 'dd', autospec=True)
|
||||
@mock.patch.object(qemu_img, 'image_info', autospec=True)
|
||||
@mock.patch.object(qemu_img, 'convert_image', autospec=True)
|
||||
class PopulateImageTestCase(base.IronicLibTestCase):
|
||||
|
||||
def test_populate_raw_image(self, mock_cg, mock_qinfo, mock_dd):
|
||||
type(mock_qinfo.return_value).file_format = mock.PropertyMock(
|
||||
return_value='raw')
|
||||
disk_utils.populate_image('src', 'dst')
|
||||
def test_populate_raw_image(self, mock_cg, mock_dd):
|
||||
source_format = 'raw'
|
||||
disk_utils.populate_image('src', 'dst',
|
||||
source_format=source_format,
|
||||
is_raw=True)
|
||||
mock_dd.assert_called_once_with('src', 'dst', conv_flags=None)
|
||||
self.assertFalse(mock_cg.called)
|
||||
|
||||
def test_populate_raw_image_with_convert(self, mock_cg, mock_qinfo,
|
||||
mock_dd):
|
||||
type(mock_qinfo.return_value).file_format = mock.PropertyMock(
|
||||
return_value='raw')
|
||||
disk_utils.populate_image('src', 'dst', conv_flags='sparse')
|
||||
mock_dd.assert_called_once_with('src', 'dst', conv_flags='sparse')
|
||||
self.assertFalse(mock_cg.called)
|
||||
|
||||
def test_populate_qcow2_image(self, mock_cg, mock_qinfo, mock_dd):
|
||||
type(mock_qinfo.return_value).file_format = mock.PropertyMock(
|
||||
return_value='qcow2')
|
||||
disk_utils.populate_image('src', 'dst')
|
||||
def test_populate_qcow2_image(self, mock_cg, mock_dd):
|
||||
source_format = 'qcow2'
|
||||
disk_utils.populate_image('src', 'dst',
|
||||
source_format=source_format, is_raw=False)
|
||||
mock_cg.assert_called_once_with('src', 'dst', 'raw', True,
|
||||
sparse_size='0')
|
||||
sparse_size='0',
|
||||
source_format=source_format)
|
||||
self.assertFalse(mock_dd.called)
|
||||
|
||||
|
||||
@ -542,32 +567,6 @@ class OtherFunctionTestCase(base.IronicLibTestCase):
|
||||
disk_utils.is_block_device, device)
|
||||
mock_os.assert_has_calls([mock.call(device)] * 2)
|
||||
|
||||
@mock.patch.object(os.path, 'getsize', autospec=True)
|
||||
@mock.patch.object(qemu_img, 'image_info', autospec=True)
|
||||
def test_get_image_mb(self, mock_qinfo, mock_getsize):
|
||||
mb = 1024 * 1024
|
||||
|
||||
mock_getsize.return_value = 0
|
||||
type(mock_qinfo.return_value).virtual_size = mock.PropertyMock(
|
||||
return_value=0)
|
||||
self.assertEqual(0, disk_utils.get_image_mb('x', False))
|
||||
self.assertEqual(0, disk_utils.get_image_mb('x', True))
|
||||
mock_getsize.return_value = 1
|
||||
type(mock_qinfo.return_value).virtual_size = mock.PropertyMock(
|
||||
return_value=1)
|
||||
self.assertEqual(1, disk_utils.get_image_mb('x', False))
|
||||
self.assertEqual(1, disk_utils.get_image_mb('x', True))
|
||||
mock_getsize.return_value = mb
|
||||
type(mock_qinfo.return_value).virtual_size = mock.PropertyMock(
|
||||
return_value=mb)
|
||||
self.assertEqual(1, disk_utils.get_image_mb('x', False))
|
||||
self.assertEqual(1, disk_utils.get_image_mb('x', True))
|
||||
mock_getsize.return_value = mb + 1
|
||||
type(mock_qinfo.return_value).virtual_size = mock.PropertyMock(
|
||||
return_value=mb + 1)
|
||||
self.assertEqual(2, disk_utils.get_image_mb('x', False))
|
||||
self.assertEqual(2, disk_utils.get_image_mb('x', True))
|
||||
|
||||
def _test_count_mbr_partitions(self, output, mock_execute):
|
||||
mock_execute.return_value = (output, '')
|
||||
out = disk_utils.count_mbr_partitions('/dev/fake')
|
||||
@ -960,3 +959,104 @@ class WaitForDisk(base.IronicLibTestCase):
|
||||
fuser_call = mock.call(*fuser_cmd, check_exit_code=[0, 1])
|
||||
self.assertEqual(2, mock_exc.call_count)
|
||||
mock_exc.assert_has_calls([fuser_call, fuser_call])
|
||||
|
||||
|
||||
class GetAndValidateImageFormat(base.IronicLibTestCase):
|
||||
@mock.patch.object(disk_utils, '_image_inspection', autospec=True)
|
||||
@mock.patch('os.path.getsize', autospec=True)
|
||||
def test_happy_raw(self, mock_size, mock_ii):
|
||||
"""Valid raw image"""
|
||||
CONF.set_override('disable_deep_image_inspection', False)
|
||||
mock_size.return_value = 13
|
||||
fmt = 'raw'
|
||||
self.assertEqual(
|
||||
(fmt, 13),
|
||||
disk_utils.get_and_validate_image_format('/fake/path', fmt))
|
||||
mock_ii.assert_not_called()
|
||||
mock_size.assert_called_once_with('/fake/path')
|
||||
|
||||
@mock.patch.object(disk_utils, '_image_inspection', autospec=True)
|
||||
def test_happy_qcow2(self, mock_ii):
|
||||
"""Valid qcow2 image"""
|
||||
CONF.set_override('disable_deep_image_inspection', False)
|
||||
fmt = 'qcow2'
|
||||
mock_ii.return_value = MockFormatInspectorCls(fmt, 0, True)
|
||||
self.assertEqual(
|
||||
(fmt, 0),
|
||||
disk_utils.get_and_validate_image_format('/fake/path', fmt)
|
||||
)
|
||||
mock_ii.assert_called_once_with('/fake/path')
|
||||
|
||||
@mock.patch.object(disk_utils, '_image_inspection', autospec=True)
|
||||
def test_format_type_disallowed(self, mock_ii):
|
||||
"""qcow3 images are not allowed in default config"""
|
||||
CONF.set_override('disable_deep_image_inspection', False)
|
||||
fmt = 'qcow3'
|
||||
mock_ii.return_value = MockFormatInspectorCls(fmt, 0, True)
|
||||
self.assertRaises(InvalidImage,
|
||||
disk_utils.get_and_validate_image_format,
|
||||
'/fake/path', fmt)
|
||||
mock_ii.assert_called_once_with('/fake/path')
|
||||
|
||||
@mock.patch.object(disk_utils, '_image_inspection', autospec=True)
|
||||
def test_format_mismatch(self, mock_ii):
|
||||
"""ironic_disk_format=qcow2, but we detect it as a qcow3"""
|
||||
CONF.set_override('disable_deep_image_inspection', False)
|
||||
fmt = 'qcow2'
|
||||
mock_ii.return_value = MockFormatInspectorCls('qcow3', 0, True)
|
||||
self.assertRaises(InvalidImage,
|
||||
disk_utils.get_and_validate_image_format,
|
||||
'/fake/path', fmt)
|
||||
|
||||
@mock.patch.object(disk_utils, '_image_inspection', autospec=True)
|
||||
@mock.patch.object(qemu_img, 'image_info', autospec=True)
|
||||
def test_format_mismatch_but_disabled(self, mock_info, mock_ii):
|
||||
"""qcow3 ironic_disk_format ignored because deep inspection disabled"""
|
||||
CONF.set_override('disable_deep_image_inspection', True)
|
||||
fmt = 'qcow2'
|
||||
fake_info = _get_fake_qemu_image_info(file_format=fmt, virtual_size=0)
|
||||
qemu_img.image_info.return_value = fake_info
|
||||
# note the input is qcow3, the output is qcow2: this mismatch is
|
||||
# forbidden if CONF.disable_deep_image_inspection is False
|
||||
self.assertEqual(
|
||||
(fmt, 0),
|
||||
disk_utils.get_and_validate_image_format('/fake/path', 'qcow3'))
|
||||
mock_ii.assert_not_called()
|
||||
mock_info.assert_called_once()
|
||||
|
||||
@mock.patch.object(disk_utils, '_image_inspection', autospec=True)
|
||||
@mock.patch.object(qemu_img, 'image_info', autospec=True)
|
||||
def test_safety_check_fail_but_disabled(self, mock_info, mock_ii):
|
||||
"""unsafe image ignored because inspection is disabled"""
|
||||
CONF.set_override('disable_deep_image_inspection', True)
|
||||
fmt = 'qcow2'
|
||||
fake_info = _get_fake_qemu_image_info(file_format=fmt, virtual_size=0)
|
||||
qemu_img.image_info.return_value = fake_info
|
||||
# note the input is qcow3, the output is qcow2: this mismatch is
|
||||
# forbidden if CONF.disable_deep_image_inspection is False
|
||||
self.assertEqual(
|
||||
(fmt, 0),
|
||||
disk_utils.get_and_validate_image_format('/fake/path', 'qcow3'))
|
||||
mock_ii.assert_not_called()
|
||||
mock_info.assert_called_once()
|
||||
|
||||
|
||||
class ImageInspectionTest(base.IronicLibTestCase):
|
||||
@mock.patch.object(format_inspector, 'detect_file_format', autospec=True)
|
||||
def test_image_inspection_pass(self, mock_fi):
|
||||
inspector = MockFormatInspectorCls('qcow2', 0, True)
|
||||
mock_fi.return_value = inspector
|
||||
self.assertEqual(inspector, disk_utils._image_inspection('/fake/path'))
|
||||
|
||||
@mock.patch.object(format_inspector, 'detect_file_format', autospec=True)
|
||||
def test_image_inspection_fail_safety_check(self, mock_fi):
|
||||
inspector = MockFormatInspectorCls('qcow2', 0, False)
|
||||
mock_fi.return_value = inspector
|
||||
self.assertRaises(InvalidImage, disk_utils._image_inspection,
|
||||
'/fake/path')
|
||||
|
||||
@mock.patch.object(format_inspector, 'detect_file_format', autospec=True)
|
||||
def test_image_inspection_fail_format_error(self, mock_fi):
|
||||
mock_fi.side_effect = format_inspector.ImageFormatError
|
||||
self.assertRaises(InvalidImage, disk_utils._image_inspection,
|
||||
'/fake/path')
|
||||
|
664
ironic_python_agent/tests/unit/test_format_inspector.py
Normal file
664
ironic_python_agent/tests/unit/test_format_inspector.py
Normal file
@ -0,0 +1,664 @@
|
||||
# Copyright 2020 Red Hat, Inc
|
||||
# All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
# not use this file except in compliance with the License. You may obtain
|
||||
# a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
# License for the specific language governing permissions and limitations
|
||||
# under the License.
|
||||
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
from unittest import mock
|
||||
|
||||
from oslo_utils import units
|
||||
|
||||
from ironic_python_agent import format_inspector
|
||||
from ironic_python_agent.tests.unit.base import IronicAgentTest
|
||||
|
||||
|
||||
TEST_IMAGE_PREFIX = 'ironic-unittest-formatinspector-'
|
||||
|
||||
|
||||
def get_size_from_qemu_img(filename):
|
||||
output = subprocess.check_output('qemu-img info "%s"' % filename,
|
||||
shell=True)
|
||||
for line in output.split(b'\n'):
|
||||
m = re.search(b'^virtual size: .* .([0-9]+) bytes', line.strip())
|
||||
if m:
|
||||
return int(m.group(1))
|
||||
|
||||
raise Exception('Could not find virtual size with qemu-img')
|
||||
|
||||
|
||||
class TestFormatInspectors(IronicAgentTest):
|
||||
|
||||
block_execute = False
|
||||
|
||||
def setUp(self):
|
||||
super(TestFormatInspectors, self).setUp()
|
||||
self._created_files = []
|
||||
|
||||
def tearDown(self):
|
||||
super(TestFormatInspectors, self).tearDown()
|
||||
for fn in self._created_files:
|
||||
try:
|
||||
os.remove(fn)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _create_iso(self, image_size, subformat='9660'):
|
||||
"""Create an ISO file of the given size.
|
||||
|
||||
:param image_size: The size of the image to create in bytes
|
||||
:param subformat: The subformat to use, if any
|
||||
"""
|
||||
|
||||
# these tests depend on mkisofs
|
||||
# being installed and in the path,
|
||||
# if it is not installed, skip
|
||||
try:
|
||||
subprocess.check_output('mkisofs --version', shell=True)
|
||||
except Exception:
|
||||
self.skipTest('mkisofs not installed')
|
||||
|
||||
size = image_size // units.Mi
|
||||
base_cmd = "mkisofs"
|
||||
if subformat == 'udf':
|
||||
# depending on the distribution mkisofs may not support udf
|
||||
# and may be provided by genisoimage instead. As a result we
|
||||
# need to check if the command supports udf via help
|
||||
# instead of checking the installed version.
|
||||
# mkisofs --help outputs to stderr so we need to
|
||||
# redirect it to stdout to use grep.
|
||||
try:
|
||||
subprocess.check_output( |