Commit debac808 authored by Iustin Pop's avatar Iustin Pop
Browse files

Convert the rest of the OpPrereqError users



This finishes the conversion of OpPrereqError creation to two-argument
style. Any leftovers as one-argument are not breaking anything, just
losing information about the errors.
Signed-off-by: default avatarIustin Pop <iustin@google.com>
Reviewed-by: default avatarMichael Hanselmann <hansmi@google.com>
parent 045dd6d9
......@@ -256,7 +256,8 @@ class ClientOps:
(names, fields, use_locking) = args
logging.info("Received instance query request for %s", names)
if use_locking:
raise errors.OpPrereqError("Sync queries are not allowed")
raise errors.OpPrereqError("Sync queries are not allowed",
errors.ECODE_INVAL)
op = opcodes.OpQueryInstances(names=names, output_fields=fields,
use_locking=use_locking)
return self._Query(op)
......@@ -265,7 +266,8 @@ class ClientOps:
(names, fields, use_locking) = args
logging.info("Received node query request for %s", names)
if use_locking:
raise errors.OpPrereqError("Sync queries are not allowed")
raise errors.OpPrereqError("Sync queries are not allowed",
errors.ECODE_INVAL)
op = opcodes.OpQueryNodes(names=names, output_fields=fields,
use_locking=use_locking)
return self._Query(op)
......@@ -273,7 +275,8 @@ class ClientOps:
elif method == luxi.REQ_QUERY_EXPORTS:
nodes, use_locking = args
if use_locking:
raise errors.OpPrereqError("Sync queries are not allowed")
raise errors.OpPrereqError("Sync queries are not allowed",
errors.ECODE_INVAL)
logging.info("Received exports query request")
op = opcodes.OpQueryExports(nodes=nodes, use_locking=use_locking)
return self._Query(op)
......
......@@ -160,43 +160,48 @@ def InitCluster(cluster_name, mac_prefix,
"""
# TODO: complete the docstring
if config.ConfigWriter.IsCluster():
raise errors.OpPrereqError("Cluster is already initialised")
raise errors.OpPrereqError("Cluster is already initialised",
errors.ECODE_STATE)
if not enabled_hypervisors:
raise errors.OpPrereqError("Enabled hypervisors list must contain at"
" least one member")
" least one member", errors.ECODE_INVAL)
invalid_hvs = set(enabled_hypervisors) - constants.HYPER_TYPES
if invalid_hvs:
raise errors.OpPrereqError("Enabled hypervisors contains invalid"
" entries: %s" % invalid_hvs)
" entries: %s" % invalid_hvs,
errors.ECODE_INVAL)
hostname = utils.HostInfo()
if hostname.ip.startswith("127."):
raise errors.OpPrereqError("This host's IP resolves to the private"
" range (%s). Please fix DNS or %s." %
(hostname.ip, constants.ETC_HOSTS))
(hostname.ip, constants.ETC_HOSTS),
errors.ECODE_ENVIRON)
if not utils.OwnIpAddress(hostname.ip):
raise errors.OpPrereqError("Inconsistency: this host's name resolves"
" to %s,\nbut this ip address does not"
" belong to this host."
" Aborting." % hostname.ip)
" belong to this host. Aborting." %
hostname.ip, errors.ECODE_ENVIRON)
clustername = utils.HostInfo(cluster_name)
if utils.TcpPing(clustername.ip, constants.DEFAULT_NODED_PORT,
timeout=5):
raise errors.OpPrereqError("Cluster IP already active. Aborting.")
raise errors.OpPrereqError("Cluster IP already active. Aborting.",
errors.ECODE_NOTUNIQUE)
if secondary_ip:
if not utils.IsValidIP(secondary_ip):
raise errors.OpPrereqError("Invalid secondary ip given")
raise errors.OpPrereqError("Invalid secondary ip given",
errors.ECODE_INVAL)
if (secondary_ip != hostname.ip and
not utils.OwnIpAddress(secondary_ip)):
raise errors.OpPrereqError("You gave %s as secondary IP,"
" but it does not belong to this host." %
secondary_ip)
secondary_ip, errors.ECODE_ENVIRON)
else:
secondary_ip = hostname.ip
......@@ -206,39 +211,43 @@ def InitCluster(cluster_name, mac_prefix,
constants.MIN_VG_SIZE)
if vgstatus:
raise errors.OpPrereqError("Error: %s\nspecify --no-lvm-storage if"
" you are not using lvm" % vgstatus)
" you are not using lvm" % vgstatus,
errors.ECODE_INVAL)
file_storage_dir = os.path.normpath(file_storage_dir)
if not os.path.isabs(file_storage_dir):
raise errors.OpPrereqError("The file storage directory you passed is"
" not an absolute path.")
" not an absolute path.", errors.ECODE_INVAL)
if not os.path.exists(file_storage_dir):
try:
os.makedirs(file_storage_dir, 0750)
except OSError, err:
raise errors.OpPrereqError("Cannot create file storage directory"
" '%s': %s" %
(file_storage_dir, err))
" '%s': %s" % (file_storage_dir, err),
errors.ECODE_ENVIRON)
if not os.path.isdir(file_storage_dir):
raise errors.OpPrereqError("The file storage directory '%s' is not"
" a directory." % file_storage_dir)
" a directory." % file_storage_dir,
errors.ECODE_ENVIRON)
if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$", mac_prefix):
raise errors.OpPrereqError("Invalid mac prefix given '%s'" % mac_prefix)
raise errors.OpPrereqError("Invalid mac prefix given '%s'" % mac_prefix,
errors.ECODE_INVAL)
result = utils.RunCmd(["ip", "link", "show", "dev", master_netdev])
if result.failed:
raise errors.OpPrereqError("Invalid master netdev given (%s): '%s'" %
(master_netdev,
result.output.strip()))
result.output.strip()), errors.ECODE_INVAL)
if not (os.path.isfile(constants.NODE_INITD_SCRIPT) and
os.access(constants.NODE_INITD_SCRIPT, os.X_OK)):
raise errors.OpPrereqError("Init.d script '%s' missing or not"
" executable." % constants.NODE_INITD_SCRIPT)
" executable." % constants.NODE_INITD_SCRIPT,
errors.ECODE_ENVIRON)
dirs = [(constants.RUN_GANETI_DIR, constants.RUN_DIRS_MODE)]
utils.EnsureDirs(dirs)
......@@ -449,7 +458,7 @@ def MasterFailover(no_voting=False):
raise errors.OpPrereqError("This commands must be run on the node"
" where you want the new master to be."
" %s is already the master" %
old_master)
old_master, errors.ECODE_INVAL)
if new_master not in mc_list:
mc_no_master = [name for name in mc_list if name != old_master]
......@@ -457,7 +466,8 @@ def MasterFailover(no_voting=False):
" as master candidates. Only these nodes"
" can become masters. Current list of"
" master candidates is:\n"
"%s" % ('\n'.join(mc_no_master)))
"%s" % ('\n'.join(mc_no_master)),
errors.ECODE_STATE)
if not no_voting:
vote_list = GatherMasterVotes(node_list)
......@@ -466,13 +476,14 @@ def MasterFailover(no_voting=False):
voted_master = vote_list[0][0]
if voted_master is None:
raise errors.OpPrereqError("Cluster is inconsistent, most nodes did"
" not respond.")
" not respond.", errors.ECODE_ENVIRON)
elif voted_master != old_master:
raise errors.OpPrereqError("I have a wrong configuration, I believe"
" the master is %s but the other nodes"
" voted %s. Please resync the configuration"
" of this node." %
(old_master, voted_master))
(old_master, voted_master),
errors.ECODE_STATE)
# end checks
rcode = 0
......
......@@ -387,7 +387,8 @@ class Processor(object):
except errors.LockError:
raise errors.OpPrereqError(
"Couldn't add locks (%s), probably because of a race condition"
" with another job, who added them first" % add_locks)
" with another job, who added them first" % add_locks,
errors.ECODE_FAULT)
acquired = add_locks
......
......@@ -734,10 +734,12 @@ class Instance(TaggableObject):
idx = int(idx)
return self.disks[idx]
except ValueError, err:
raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err))
raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
errors.ECODE_INVAL)
except IndexError:
raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
" 0 to %d" % (idx, len(self.disks)))
" 0 to %d" % (idx, len(self.disks)),
errors.ECODE_INVAL)
def ToDict(self):
"""Instance-specific conversion to standard python types.
......
......@@ -280,7 +280,8 @@ def ClusterCopyFile(opts, args):
"""
filename = args[0]
if not os.path.exists(filename):
raise errors.OpPrereqError("No such filename '%s'" % filename)
raise errors.OpPrereqError("No such filename '%s'" % filename,
errors.ECODE_INVAL)
cl = GetClient()
......@@ -550,7 +551,8 @@ def QueueOps(opts, args):
val = "unset"
ToStdout("The drain flag is %s" % val)
else:
raise errors.OpPrereqError("Command '%s' is not valid." % command)
raise errors.OpPrereqError("Command '%s' is not valid." % command,
errors.ECODE_INVAL)
return 0
......@@ -581,7 +583,7 @@ def WatcherOps(opts, args):
elif command == "pause":
if len(args) < 2:
raise errors.OpPrereqError("Missing pause duration")
raise errors.OpPrereqError("Missing pause duration", errors.ECODE_INVAL)
result = client.SetWatcherPause(time.time() + ParseTimespec(args[1]))
_ShowWatcherPause(result)
......@@ -591,7 +593,8 @@ def WatcherOps(opts, args):
_ShowWatcherPause(result)
else:
raise errors.OpPrereqError("Command '%s' is not valid." % command)
raise errors.OpPrereqError("Command '%s' is not valid." % command,
errors.ECODE_INVAL)
return 0
......
......@@ -79,7 +79,8 @@ def _ExpandMultiNames(mode, names, client=None):
client = GetClient()
if mode == _SHUTDOWN_CLUSTER:
if names:
raise errors.OpPrereqError("Cluster filter mode takes no arguments")
raise errors.OpPrereqError("Cluster filter mode takes no arguments",
errors.ECODE_INVAL)
idata = client.QueryInstances([], ["name"], False)
inames = [row[0] for row in idata]
......@@ -87,7 +88,7 @@ def _ExpandMultiNames(mode, names, client=None):
_SHUTDOWN_NODES_PRI,
_SHUTDOWN_NODES_SEC):
if not names:
raise errors.OpPrereqError("No node names passed")
raise errors.OpPrereqError("No node names passed", errors.ECODE_INVAL)
ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"],
False)
ipri = [row[1] for row in ndata]
......@@ -105,12 +106,13 @@ def _ExpandMultiNames(mode, names, client=None):
elif mode == _SHUTDOWN_INSTANCES:
if not names:
raise errors.OpPrereqError("No instance names passed")
raise errors.OpPrereqError("No instance names passed",
errors.ECODE_INVAL)
idata = client.QueryInstances(names, ["name"], False)
inames = [row[0] for row in idata]
else:
raise errors.OpPrereqError("Unknown mode '%s'" % mode)
raise errors.OpPrereqError("Unknown mode '%s'" % mode, errors.ECODE_INVAL)
return inames
......@@ -171,7 +173,8 @@ def _EnsureInstancesExist(client, names):
result = client.QueryInstances(names, ["name"], False)
for orig_name, row in zip(names, result):
if row[0] is None:
raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name)
raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name,
errors.ECODE_NOENT)
def GenericManyOps(operation, fn):
......@@ -190,7 +193,7 @@ def GenericManyOps(operation, fn):
inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
if not inames:
raise errors.OpPrereqError("Selection filter does not match"
" any instances")
" any instances", errors.ECODE_INVAL)
multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
if not (opts.force_multi or not multi_on
or _ConfirmOperation(inames, operation)):
......@@ -371,20 +374,23 @@ def BatchCreate(opts, args):
for required_field in ('os', 'template'):
if required_field not in spec:
raise errors.OpPrereqError('Required field "%s" is missing.' %
required_field)
required_field, errors.ECODE_INVAL)
# Validate special fields
if spec['primary_node'] is not None:
if (spec['template'] in constants.DTS_NET_MIRROR and
spec['secondary_node'] is None):
raise errors.OpPrereqError('Template requires secondary node, but'
' there was no secondary provided.')
' there was no secondary provided.',
errors.ECODE_INVAL)
elif spec['iallocator'] is None:
raise errors.OpPrereqError('You have to provide at least a primary_node'
' or an iallocator.')
' or an iallocator.',
errors.ECODE_INVAL)
if (spec['hvparams'] and
not isinstance(spec['hvparams'], dict)):
raise errors.OpPrereqError('Hypervisor parameters must be a dict.')
raise errors.OpPrereqError('Hypervisor parameters must be a dict.',
errors.ECODE_INVAL)
json_filename = args[0]
try:
......@@ -414,7 +420,7 @@ def BatchCreate(opts, args):
except ValueError, err:
raise errors.OpPrereqError("Invalid disk size '%s' for"
" instance %s: %s" %
(elem, name, err))
(elem, name, err), errors.ECODE_INVAL)
disks.append({"size": size})
utils.ForceDictType(specs['backend'], constants.BES_PARAMETER_TYPES)
......@@ -429,7 +435,8 @@ def BatchCreate(opts, args):
if specs['nics'] is not None and tmp_nics:
raise errors.OpPrereqError("'nics' list incompatible with using"
" individual nic fields as well")
" individual nic fields as well",
errors.ECODE_INVAL)
elif specs['nics'] is not None:
tmp_nics = specs['nics']
elif not tmp_nics:
......@@ -478,7 +485,8 @@ def ReinstallInstance(opts, args):
inames = _ExpandMultiNames(opts.multi_mode, args)
if not inames:
raise errors.OpPrereqError("Selection filter does not match any instances")
raise errors.OpPrereqError("Selection filter does not match any instances",
errors.ECODE_INVAL)
# second, if requested, ask for an OS
if opts.select_os is True:
......@@ -672,7 +680,8 @@ def GrowDisk(opts, args):
try:
disk = int(disk)
except ValueError, err:
raise errors.OpPrereqError("Invalid disk index: %s" % str(err))
raise errors.OpPrereqError("Invalid disk index: %s" % str(err),
errors.ECODE_INVAL)
amount = utils.ParseUnit(args[2])
op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
wait_for_sync=opts.wait_for_sync)
......@@ -752,12 +761,13 @@ def ReplaceDisks(opts, args):
try:
disks = [int(i) for i in opts.disks.split(",")]
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)
cnt = [opts.on_primary, opts.on_secondary, opts.auto,
new_2ndary is not None, iallocator is not None].count(True)
if cnt != 1:
raise errors.OpPrereqError("One and only one of the -p, -s, -a, -n and -i"
" options must be passed")
" options must be passed", errors.ECODE_INVAL)
elif opts.on_primary:
mode = constants.REPLACE_DISK_PRI
elif opts.on_secondary:
......@@ -766,7 +776,7 @@ def ReplaceDisks(opts, args):
mode = constants.REPLACE_DISK_AUTO
if disks:
raise errors.OpPrereqError("Cannot specify disks when using automatic"
" mode")
" mode", errors.ECODE_INVAL)
elif new_2ndary is not None or iallocator is not None:
# replace secondary
mode = constants.REPLACE_DISK_CHG
......@@ -1208,7 +1218,8 @@ def SetInstanceParams(opts, args):
pass
if disk_op == constants.DDM_ADD:
if 'size' not in disk_dict:
raise errors.OpPrereqError("Missing required parameter 'size'")
raise errors.OpPrereqError("Missing required parameter 'size'",
errors.ECODE_INVAL)
disk_dict['size'] = utils.ParseUnit(disk_dict['size'])
op = opcodes.OpSetInstanceParams(instance_name=args[0],
......
......@@ -114,7 +114,8 @@ def ConvertStorageType(user_storage_type):
try:
return _USER_STORAGE_TYPE[user_storage_type]
except KeyError:
raise errors.OpPrereqError("Unknown storage type: %s" % user_storage_type)
raise errors.OpPrereqError("Unknown storage type: %s" % user_storage_type,
errors.ECODE_INVAL)
@UsesRPC
......@@ -249,7 +250,7 @@ def EvacuateNode(opts, args):
cnt = [dst_node, iallocator].count(None)
if cnt != 1:
raise errors.OpPrereqError("One and only one of the -n and -I"
" options must be passed")
" options must be passed", errors.ECODE_INVAL)
selected_fields = ["name", "sinst_list"]
src_node = args[0]
......@@ -270,7 +271,7 @@ def EvacuateNode(opts, args):
if src_node == dst_node:
raise errors.OpPrereqError("Evacuate node needs different source and"
" target nodes (node %s given twice)" %
src_node)
src_node, errors.ECODE_INVAL)
txt_msg = "to node %s" % dst_node
else:
txt_msg = "using iallocator %s" % iallocator
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment