Commit 2cfbc784 authored by Iustin Pop's avatar Iustin Pop

Fix uses of OpPrereqError without code info

A while back, we did cleanup the code and ensured (manually) that use
of OpPrereqError includes an errors.ECODE_* field as second
argument. Since we cannot automate the check for this, it turns out
that more and more such usage has crept over the years, including in
the master code (the use on the CLI side is not as important).

Note that this also uncovered a few errors in ovf.py where the errors
messages were wrongly constructed.

Still looking for a way to automate this check…
Signed-off-by: default avatarIustin Pop <iustin@google.com>
Reviewed-by: default avatarGuido Trotter <ultrotter@google.com>
parent 619e89c8
......@@ -318,12 +318,13 @@ def InitCluster(cluster_name, mac_prefix, # pylint: disable=R0913, R0914
ipcls = netutils.IPAddress.GetClassFromIpVersion(primary_ip_version)
except errors.ProgrammerError:
raise errors.OpPrereqError("Invalid primary ip version: %d." %
primary_ip_version)
primary_ip_version, errors.ECODE_INVAL)
hostname = netutils.GetHostname(family=ipcls.family)
if not ipcls.IsValid(hostname.ip):
raise errors.OpPrereqError("This host's IP (%s) is not a valid IPv%d"
" address." % (hostname.ip, primary_ip_version))
" address." % (hostname.ip, primary_ip_version),
errors.ECODE_INVAL)
if ipcls.IsLoopback(hostname.ip):
raise errors.OpPrereqError("This host's IP (%s) resolves to a loopback"
......@@ -363,7 +364,8 @@ def InitCluster(cluster_name, mac_prefix, # pylint: disable=R0913, R0914
if master_netmask is not None:
if not ipcls.ValidateNetmask(master_netmask):
raise errors.OpPrereqError("CIDR netmask (%s) not valid for IPv%s " %
(master_netmask, primary_ip_version))
(master_netmask, primary_ip_version),
errors.ECODE_INVAL)
else:
master_netmask = ipcls.iplen
......@@ -461,7 +463,8 @@ def InitCluster(cluster_name, mac_prefix, # pylint: disable=R0913, R0914
unknown_params = param_keys - default_param_keys
raise errors.OpPrereqError("Invalid parameters for disk template %s:"
" %s" % (template,
utils.CommaJoin(unknown_params)))
utils.CommaJoin(unknown_params)),
errors.ECODE_INVAL)
utils.ForceDictType(dt_params, constants.DISK_DT_TYPES)
try:
utils.VerifyDictOptions(diskparams, constants.DISK_DT_DEFAULTS)
......
......@@ -416,7 +416,8 @@ def _ExtractTagsObject(opts, args):
constants.TAG_NODE,
constants.TAG_INSTANCE):
if not args:
raise errors.OpPrereqError("no arguments passed to the command")
raise errors.OpPrereqError("no arguments passed to the command",
errors.ECODE_INVAL)
name = args.pop(0)
retval = kind, name
else:
......@@ -483,7 +484,7 @@ def AddTags(opts, args):
kind, name = _ExtractTagsObject(opts, args)
_ExtendTags(opts, args)
if not args:
raise errors.OpPrereqError("No tags to be added")
raise errors.OpPrereqError("No tags to be added", errors.ECODE_INVAL)
op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
SubmitOrSend(op, opts)
......@@ -500,7 +501,7 @@ def RemoveTags(opts, args):
kind, name = _ExtractTagsObject(opts, args)
_ExtendTags(opts, args)
if not args:
raise errors.OpPrereqError("No tags to be removed")
raise errors.OpPrereqError("No tags to be removed", errors.ECODE_INVAL)
op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
SubmitOrSend(op, opts)
......@@ -2091,13 +2092,14 @@ def GetClient():
ss.GetMasterNode()
except errors.ConfigurationError:
raise errors.OpPrereqError("Cluster not initialized or this machine is"
" not part of a cluster")
" not part of a cluster",
errors.ECODE_INVAL)
master, myself = ssconf.GetMasterAndMyself(ss=ss)
if master != myself:
raise errors.OpPrereqError("This is not the master node, please connect"
" to node '%s' and rerun the command" %
master)
master, errors.ECODE_INVAL)
raise
return client
......@@ -2271,7 +2273,8 @@ def ParseNicOption(optvalue):
try:
nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
except (TypeError, ValueError), err:
raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
errors.ECODE_INVAL)
nics = [{}] * nic_max
for nidx, ndict in optvalue:
......@@ -2279,7 +2282,7 @@ def ParseNicOption(optvalue):
if not isinstance(ndict, dict):
raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
" got %s" % (nidx, ndict))
" got %s" % (nidx, ndict), errors.ECODE_INVAL)
utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
......@@ -2323,15 +2326,16 @@ def GenericInstanceCreate(mode, opts, args):
if opts.disk_template == constants.DT_DISKLESS:
if opts.disks or opts.sd_size is not None:
raise errors.OpPrereqError("Diskless instance but disk"
" information passed")
" information passed", errors.ECODE_INVAL)
disks = []
else:
if (not opts.disks and not opts.sd_size
and mode == constants.INSTANCE_CREATE):
raise errors.OpPrereqError("No disk information specified")
raise errors.OpPrereqError("No disk information specified",
errors.ECODE_INVAL)
if opts.disks and opts.sd_size is not None:
raise errors.OpPrereqError("Please use either the '--disk' or"
" '-s' option")
" '-s' option", errors.ECODE_INVAL)
if opts.sd_size is not None:
opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
......@@ -2339,7 +2343,8 @@ def GenericInstanceCreate(mode, opts, args):
try:
disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
except ValueError, err:
raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
errors.ECODE_INVAL)
disks = [{}] * disk_max
else:
disks = []
......@@ -2347,25 +2352,25 @@ def GenericInstanceCreate(mode, opts, args):
didx = int(didx)
if not isinstance(ddict, dict):
msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
raise errors.OpPrereqError(msg)
raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
elif constants.IDISK_SIZE in ddict:
if constants.IDISK_ADOPT in ddict:
raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
" (disk %d)" % didx)
" (disk %d)" % didx, errors.ECODE_INVAL)
try:
ddict[constants.IDISK_SIZE] = \
utils.ParseUnit(ddict[constants.IDISK_SIZE])
except ValueError, err:
raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
(didx, err))
(didx, err), errors.ECODE_INVAL)
elif constants.IDISK_ADOPT in ddict:
if mode == constants.INSTANCE_IMPORT:
raise errors.OpPrereqError("Disk adoption not allowed for instance"
" import")
" import", errors.ECODE_INVAL)
ddict[constants.IDISK_SIZE] = 0
else:
raise errors.OpPrereqError("Missing size or adoption source for"
" disk %d" % didx)
" disk %d" % didx, errors.ECODE_INVAL)
disks[didx] = ddict
if opts.tags is not None:
......@@ -3074,7 +3079,8 @@ def ParseTimespec(value):
"""
value = str(value)
if not value:
raise errors.OpPrereqError("Empty time specification passed")
raise errors.OpPrereqError("Empty time specification passed",
errors.ECODE_INVAL)
suffix_map = {
"s": 1,
"m": 60,
......@@ -3086,17 +3092,19 @@ def ParseTimespec(value):
try:
value = int(value)
except (TypeError, ValueError):
raise errors.OpPrereqError("Invalid time specification '%s'" % value)
raise errors.OpPrereqError("Invalid time specification '%s'" % value,
errors.ECODE_INVAL)
else:
multiplier = suffix_map[value[-1]]
value = value[:-1]
if not value: # no data left after stripping the suffix
raise errors.OpPrereqError("Invalid time specification (only"
" suffix passed)")
" suffix passed)", errors.ECODE_INVAL)
try:
value = int(value) * multiplier
except (TypeError, ValueError):
raise errors.OpPrereqError("Invalid time specification '%s'" % value)
raise errors.OpPrereqError("Invalid time specification '%s'" % value,
errors.ECODE_INVAL)
return value
......
......@@ -614,7 +614,7 @@ def RecreateDisks(opts, args):
if not ht.TDict(ddict):
msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
raise errors.OpPrereqError(msg)
raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
if constants.IDISK_SIZE in ddict:
try:
......@@ -622,7 +622,7 @@ def RecreateDisks(opts, args):
utils.ParseUnit(ddict[constants.IDISK_SIZE])
except ValueError, err:
raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
(didx, err))
(didx, err), errors.ECODE_INVAL)
disks.append((didx, ddict))
......
......@@ -1655,7 +1655,7 @@ def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
" cluster-wide default iallocator found;"
" please specify either an iallocator or a"
" node, or set a cluster-wide default"
" iallocator")
" iallocator", errors.ECODE_INVAL)
def _GetDefaultIAllocator(cfg, iallocator):
......@@ -3827,10 +3827,10 @@ def _ValidateNetmask(cfg, netmask):
ipcls = netutils.IPAddress.GetClassFromIpFamily(ip_family)
except errors.ProgrammerError:
raise errors.OpPrereqError("Invalid primary ip family: %s." %
ip_family)
ip_family, errors.ECODE_INVAL)
if not ipcls.ValidateNetmask(netmask):
raise errors.OpPrereqError("CIDR netmask (%s) not valid" %
(netmask))
(netmask), errors.ECODE_INVAL)
class LUClusterSetParams(LogicalUnit):
......@@ -4029,7 +4029,7 @@ class LUClusterSetParams(LogicalUnit):
" address" % (instance.name, nic_idx))
if nic_errors:
raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
"\n".join(nic_errors))
"\n".join(nic_errors), errors.ECODE_INVAL)
# hypervisor list/parameters
self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
......@@ -5957,11 +5957,12 @@ class LUNodeSetParams(LogicalUnit):
self.op.powered == True):
raise errors.OpPrereqError(("Node %s needs to be turned on before its"
" offline status can be reset") %
self.op.node_name)
self.op.node_name, errors.ECODE_STATE)
elif self.op.powered is not None:
raise errors.OpPrereqError(("Unable to change powered state for node %s"
" as it does not support out-of-band"
" handling") % self.op.node_name)
" handling") % self.op.node_name,
errors.ECODE_STATE)
# If we're being deofflined/drained, we'll MC ourself if needed
if (self.op.drained == False or self.op.offline == False or
......@@ -6038,10 +6039,10 @@ class LUNodeSetParams(LogicalUnit):
if node.offline:
if affected_instances:
raise errors.OpPrereqError("Cannot change secondary IP address:"
" offline node has instances (%s)"
" configured to use it" %
utils.CommaJoin(affected_instances.keys()))
msg = ("Cannot change secondary IP address: offline node has"
" instances (%s) configured to use it" %
utils.CommaJoin(affected_instances.keys()))
raise errors.OpPrereqError(msg, errors.ECODE_STATE)
else:
# On online nodes, check that no instances are running, and that
# the node has the new ip and we can reach it.
......@@ -8142,7 +8143,8 @@ class TLMigrateInstance(Tasklet):
if self.target_node == instance.primary_node:
raise errors.OpPrereqError("Cannot migrate instance %s"
" to its primary (%s)" %
(instance.name, instance.primary_node))
(instance.name, instance.primary_node),
errors.ECODE_STATE)
if len(self.lu.tasklets) == 1:
# It is safe to release locks only when we're the only tasklet
......@@ -9670,7 +9672,9 @@ class LUInstanceCreate(LogicalUnit):
if self.op.disk_template not in constants.DISK_TEMPLATES:
raise errors.OpPrereqError("Disk template specified in configuration"
" file is not one of the allowed values:"
" %s" % " ".join(constants.DISK_TEMPLATES))
" %s" %
" ".join(constants.DISK_TEMPLATES),
errors.ECODE_INVAL)
else:
raise errors.OpPrereqError("No disk template specified and the export"
" is missing the disk_template information",
......@@ -9783,7 +9787,8 @@ class LUInstanceCreate(LogicalUnit):
cfg_storagedir = get_fsd_fn()
if not cfg_storagedir:
raise errors.OpPrereqError("Cluster file storage dir not defined")
raise errors.OpPrereqError("Cluster file storage dir not defined",
errors.ECODE_STATE)
joinargs.append(cfg_storagedir)
if self.op.file_storage_dir is not None:
......@@ -12654,8 +12659,7 @@ class LUInstanceSetParams(LogicalUnit):
raise errors.OpPrereqError("This change will prevent the instance"
" from starting, due to %d MB of memory"
" missing on its primary node" %
miss_mem,
errors.ECODE_NORES)
miss_mem, errors.ECODE_NORES)
if be_new[constants.BE_AUTO_BALANCE]:
for node, nres in nodeinfo.items():
......@@ -12681,8 +12685,8 @@ class LUInstanceSetParams(LogicalUnit):
instance.hypervisor)
remote_info.Raise("Error checking node %s" % instance.primary_node)
if not remote_info.payload: # not running already
raise errors.OpPrereqError("Instance %s is not running" % instance.name,
errors.ECODE_STATE)
raise errors.OpPrereqError("Instance %s is not running" %
instance.name, errors.ECODE_STATE)
current_memory = remote_info.payload["memory"]
if (not self.op.force and
......@@ -12704,8 +12708,7 @@ class LUInstanceSetParams(LogicalUnit):
if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
raise errors.OpPrereqError("Disk operations not supported for"
" diskless instances",
errors.ECODE_INVAL)
" diskless instances", errors.ECODE_INVAL)
def _PrepareNicCreate(_, params, private):
self._PrepareNicModification(params, private, None, {}, cluster, pnode)
......@@ -13212,8 +13215,7 @@ class LUInstanceChangeGroup(LogicalUnit):
raise errors.OpPrereqError("Can't compute solution for changing group of"
" instance '%s' using iallocator '%s': %s" %
(self.op.instance_name, self.op.iallocator,
ial.info),
errors.ECODE_NORES)
ial.info), errors.ECODE_NORES)
jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
......@@ -13442,7 +13444,7 @@ class LUBackupExport(LogicalUnit):
self.instance.admin_state == constants.ADMINST_UP and
not self.op.shutdown):
raise errors.OpPrereqError("Can not remove instance without shutting it"
" down before")
" down before", errors.ECODE_STATE)
if self.op.mode == constants.EXPORT_MODE_LOCAL:
self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
......@@ -13472,7 +13474,8 @@ class LUBackupExport(LogicalUnit):
try:
(key_name, hmac_digest, hmac_salt) = self.x509_key_name
except (TypeError, ValueError), err:
raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err,
errors.ECODE_INVAL)
if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
raise errors.OpPrereqError("HMAC for X509 key name is wrong",
......@@ -14227,9 +14230,8 @@ class LUGroupRemove(LogicalUnit):
# Verify the cluster would not be left group-less.
if len(self.cfg.GetNodeGroupList()) == 1:
raise errors.OpPrereqError("Group '%s' is the only group,"
" cannot be removed" %
self.op.group_name,
raise errors.OpPrereqError("Group '%s' is the only group, cannot be"
" removed" % self.op.group_name,
errors.ECODE_STATE)
def BuildHooksEnv(self):
......
#!/usr/bin/python
#
# Copyright (C) 2011 Google Inc.
# Copyright (C) 2011, 2012 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
......@@ -152,7 +152,7 @@ def CheckQemuImg():
"""
if not constants.QEMUIMG_PATH:
raise errors.OpPrereqError("qemu-img not found at build time, unable"
" to continue")
" to continue", errors.ECODE_STATE)
def LinkFile(old_path, prefix=None, suffix=None, directory=None):
......@@ -191,7 +191,8 @@ def LinkFile(old_path, prefix=None, suffix=None, directory=None):
counter += 1
else:
raise errors.OpPrereqError("Error moving the file %s to %s location:"
" %s" % (old_path, new_path, err))
" %s" % (old_path, new_path, err),
errors.ECODE_ENVIRON)
return new_path
......@@ -228,7 +229,7 @@ class OVFReader(object):
self.tree.parse(input_path)
except (ParseError, xml.parsers.expat.ExpatError), err:
raise errors.OpPrereqError("Error while reading %s file: %s" %
(OVF_EXT, err))
(OVF_EXT, err), errors.ECODE_ENVIRON)
# Create a list of all files in the OVF package
(input_dir, input_file) = os.path.split(input_path)
......@@ -245,7 +246,8 @@ class OVFReader(object):
for file_name in files_list:
file_path = utils.PathJoin(input_dir, file_name)
if not os.path.exists(file_path):
raise errors.OpPrereqError("File does not exist: %s" % file_path)
raise errors.OpPrereqError("File does not exist: %s" % file_path,
errors.ECODE_ENVIRON)
logging.info("Files in the OVF package: %s", " ".join(files_list))
self.files_list = files_list
self.input_dir = input_dir
......@@ -360,7 +362,8 @@ class OVFReader(object):
for file_name, value in manifest_files.iteritems():
if sha1_sums.get(utils.PathJoin(self.input_dir, file_name)) != value:
raise errors.OpPrereqError("SHA1 checksum of %s does not match the"
" value in manifest file" % file_name)
" value in manifest file" % file_name,
errors.ECODE_ENVIRON)
logging.info("SHA1 checksums verified")
def GetInstanceName(self):
......@@ -451,8 +454,8 @@ class OVFReader(object):
matching_units = [units for units, variants in
ALLOCATION_UNITS.iteritems() if alloc_units.lower() in variants]
if matching_units == []:
raise errors.OpPrereqError("Unit %s for RAM memory unknown",
alloc_units)
raise errors.OpPrereqError("Unit %s for RAM memory unknown" %
alloc_units, errors.ECODE_INVAL)
units = matching_units[0]
memory_raw = int(memory.findtext("{%s}VirtualQuantity" % RASD_SCHEMA,
default=constants.VALUE_AUTO))
......@@ -579,7 +582,8 @@ class OVFReader(object):
disk_elem = self._GetElementMatchingAttr(disk_search, disk_match)
if disk_elem is None:
raise errors.OpPrereqError("%s file corrupted - disk %s not found in"
" references" % (OVF_EXT, disk))
" references" % (OVF_EXT, disk),
errors.ECODE_ENVIRON)
disk_name = disk_elem.get("{%s}href" % OVF_SCHEMA)
disk_compression = disk_elem.get("{%s}compression" % OVF_SCHEMA)
results.append((disk_name, disk_compression))
......@@ -860,7 +864,8 @@ class Converter(object):
"""
input_path = os.path.abspath(input_path)
if not os.path.isfile(input_path):
raise errors.OpPrereqError("File does not exist: %s" % input_path)
raise errors.OpPrereqError("File does not exist: %s" % input_path,
errors.ECODE_ENVIRON)
self.options = options
self.temp_file_manager = utils.TemporaryFileManager()
self.temp_dir = None
......@@ -896,7 +901,7 @@ class Converter(object):
# For now we only support gzip, as it is used in ovftool
if compression != COMPRESSION_TYPE:
raise errors.OpPrereqError("Unsupported compression type: %s"
% compression)
% compression, errors.ECODE_INVAL)
disk_file = os.path.basename(disk_path)
if action == DECOMPRESS:
(disk_name, _) = os.path.splitext(disk_file)
......@@ -910,7 +915,8 @@ class Converter(object):
run_result = utils.RunCmd(args, output=new_path)
if run_result.failed:
raise errors.OpPrereqError("Disk %s failed with output: %s"
% (action, run_result.stderr))
% (action, run_result.stderr),
errors.ECODE_ENVIRON)
logging.info("The %s of the disk is completed", action)
return (COMPRESSION_EXT, new_path)
......@@ -948,7 +954,8 @@ class Converter(object):
run_result = utils.RunCmd(args, cwd=os.getcwd())
if run_result.failed:
raise errors.OpPrereqError("Convertion to %s failed, qemu-img output was"
": %s" % (disk_format, run_result.stderr))
": %s" % (disk_format, run_result.stderr),
errors.ECODE_ENVIRON)
return (".%s" % disk_format, new_disk_path)
@staticmethod
......@@ -970,7 +977,8 @@ class Converter(object):
run_result = utils.RunCmd(args, cwd=os.getcwd())
if run_result.failed:
raise errors.OpPrereqError("Gathering info about the disk using qemu-img"
" failed, output was: %s" % run_result.stderr)
" failed, output was: %s" % run_result.stderr,
errors.ECODE_ENVIRON)
result = run_result.output
regexp = r"%s" % regexp
match = re.search(regexp, result)
......@@ -978,7 +986,8 @@ class Converter(object):
disk_format = match.group(1)
else:
raise errors.OpPrereqError("No file information matching %s found in:"
" %s" % (regexp, result))
" %s" % (regexp, result),
errors.ECODE_ENVIRON)
return disk_format
def Parse(self):
......@@ -1063,7 +1072,8 @@ class OVFImporter(Converter):
self._UnpackOVA(input_path)
else:
raise errors.OpPrereqError("Unknown file extension; expected %s or %s"
" file" % (OVA_EXT, OVF_EXT))
" file" % (OVA_EXT, OVF_EXT),
errors.ECODE_INVAL)
assert ((input_extension == OVA_EXT and self.temp_dir) or
(input_extension == OVF_EXT and not self.temp_dir))
assert self.input_dir in self.input_path
......@@ -1095,7 +1105,7 @@ class OVFImporter(Converter):
input_name = None
if not tarfile.is_tarfile(input_path):
raise errors.OpPrereqError("The provided %s file is not a proper tar"
" archive", OVA_EXT)
" archive" % OVA_EXT, errors.ECODE_ENVIRON)
ova_content = tarfile.open(input_path)
temp_dir = tempfile.mkdtemp()
self.temp_dir = temp_dir
......@@ -1105,12 +1115,12 @@ class OVFImporter(Converter):
utils.PathJoin(temp_dir, file_normname)
except ValueError, err:
raise errors.OpPrereqError("File %s inside %s package is not safe" %
(file_name, OVA_EXT))
(file_name, OVA_EXT), errors.ECODE_ENVIRON)
if file_name.endswith(OVF_EXT):
input_name = file_name
if not input_name:
raise errors.OpPrereqError("No %s file in %s package found" %
(OVF_EXT, OVA_EXT))
(OVF_EXT, OVA_EXT), errors.ECODE_ENVIRON)
logging.warning("Unpacking the %s archive, this may take a while",
input_path)
self.input_dir = temp_dir
......@@ -1126,7 +1136,7 @@ class OVFImporter(Converter):
extract(self.temp_dir)
except tarfile.TarError, err:
raise errors.OpPrereqError("Error while extracting %s archive: %s" %
(OVA_EXT, err))
(OVA_EXT, err), errors.ECODE_ENVIRON)
logging.info("OVA package extracted to %s directory", self.temp_dir)
def Parse(self):
......@@ -1142,14 +1152,15 @@ class OVFImporter(Converter):
self.results_name = self._GetInfo("instance name", self.options.name,
self._ParseNameOptions, self.ovf_reader.GetInstanceName)
if not self.results_name:
raise errors.OpPrereqError("Name of instance not provided")
raise errors.OpPrereqError("Name of instance not provided",
errors.ECODE_INVAL)
self.output_dir = utils.PathJoin(self.output_dir, self.results_name)
try:
utils.Makedirs(self.output_dir)
except OSError, err:
raise errors.OpPrereqError("Failed to create directory %s: %s" %
(self.output_dir, err))
(self.output_dir, err), errors.ECODE_ENVIRON)
self.results_template = self._GetInfo("disk template",
self.options.disk_template, self._ParseTemplateOptions,
......@@ -1167,7 +1178,8 @@ class OVFImporter(Converter):
self.results_os = self._GetInfo("OS", self.options.os,
self._ParseOSOptions, self.ovf_reader.GetOSData)
if not self.results_os.get("os_name"):
raise errors.OpPrereqError("OS name must be provided")
raise errors.OpPrereqError("OS name must be provided",
errors.ECODE_INVAL)
self.results_backend = self._GetInfo("backend", self.options.beparams,
self._ParseBackendOptions, self.ovf_reader.GetBackendData)
......@@ -1194,7 +1206,8 @@ class OVFImporter(Converter):
if not self.results_disk and not self.results_network:
raise errors.OpPrereqError("Either disk specification or network"
" description must be present")
" description must be present",
errors.ECODE_STATE)
@staticmethod
def _GetInfo(name, cmd_arg, cmd_function, nocmd_function,
......@@ -1340,7 +1353,8 @@ class OVFImporter(Converter):
disk_size = utils.ParseUnit(disk_desc["size"])
except ValueError:
raise errors.OpPrereqError("Invalid disk size for disk %s: %s" %
(disk_id, disk_desc["size"]))
(disk_id, disk_desc["size"]),
errors.ECODE_INVAL)
new_path = utils.PathJoin(self.output_dir, str(disk_id))
args = [
constants.QEMUIMG_PATH,
......@@ -1353,12 +1367,14 @@ class OVFImporter(Converter):
run_result = utils.RunCmd(args)
if run_result.failed:
raise errors.OpPrereqError("Creation of disk %s failed, output was:"
" %s" % (new_path, run_result.stderr))
" %s" % (new_path, run_result.stderr),
errors.ECODE_ENVIRON)
results["disk%s_size" % disk_id] = str(disk_size)
results["disk%s_dump" % disk_id] = "disk%s.raw" % disk_id
else:
raise errors.OpPrereqError("Disks created for import must have their"
" size specified")
" size specified",
errors.ECODE_INVAL)
results["disk_count"] = str(len(self.options.disks))
return results
......@@ -1376,7 +1392,8 @@ class OVFImporter(Converter):
for (counter, (disk_name, disk_compression)) in enumerate(disks_list):
if os.path.dirname(disk_name):
raise errors.OpPrereqError("Disks are not allowed to have absolute"
" paths or paths outside main OVF directory")
" paths or paths outside main OVF"
" directory", errors.ECODE_ENVIRON)
disk, _ = os.path.splitext(disk_name)
disk_path = utils.PathJoin(self.input_dir, disk_name)
if disk_compression not in NO_COMPRESSION:
......@@ -1451,7 +1468,8 @@ class OVFImporter(Converter):
try:
utils.WriteFile(output_file_name, data=output_contents)
except errors.ProgrammerError, err:
raise errors.OpPrereqError("Saving the config file failed: %s" % err)
raise errors.OpPrereqError("Saving the config file failed: %s" % err,
errors.ECODE_ENVIRON)
self.Cleanup()
......@@ -1531,7 +1549,7 @@ class OVFExporter(Converter):
self.config_parser.read(input_path)
except ConfigParser.MissingSectionHeaderError, err:
raise errors.OpPrereqError("Error when trying to read %s: %s" %
(input_path, err))
(input_path, err), errors.ECODE_ENVIRON)
if self.options.ova_package:
self.temp_dir = tempfile.mkdtemp()
self.packed_dir = self.output_dir
......@@ -1553,7 +1571,8 @@ class OVFExporter(Converter):
else:
name = self.config_parser.get(constants.INISECT_INS, NAME)
if name is None:
raise errors.OpPrereqError("No instance name found")
raise errors.OpPrereqError("No instance name found",