from ganeti import ssconf
+class RPCFail(Exception):
+ """Class denoting RPC failure.
+
+ Its argument is the error message.
+
+ """
+
+def _Fail(msg, *args, **kwargs):
+ """Log an error and the raise an RPCFail exception.
+
+ This exception is then handled specially in the ganeti daemon and
+ turned into a 'failed' return type. As such, this function is a
+ useful shortcut for logging the error and returning it to the master
+ daemon.
+
+ @type msg: string
+ @param msg: the text of the exception
+ @raise RPCFail
+
+ """
+ if args:
+ msg = msg % args
+ if "exc" in kwargs and kwargs["exc"]:
+ logging.exception(msg)
+ else:
+ logging.error(msg)
+ raise RPCFail(msg)
+
+
def _GetConfig():
"""Simple wrapper to return a SimpleStore.
for consumption here or from the node daemon.
@rtype: tuple
- @return: (master_netdev, master_ip, master_name) if we have a good
- configuration, otherwise (None, None, None)
+ @return: True, (master_netdev, master_ip, master_name) in case of success
+ @raise RPCFail: in case of errors
"""
try:
master_ip = cfg.GetMasterIP()
master_node = cfg.GetMasterNode()
except errors.ConfigurationError, err:
- logging.exception("Cluster configuration incomplete")
- return (None, None, None)
- return (master_netdev, master_ip, master_node)
+ _Fail("Cluster configuration incomplete", exc=True)
+ return True, (master_netdev, master_ip, master_node)
def StartMaster(start_daemons):
@rtype: None
"""
- ok = True
- master_netdev, master_ip, _ = GetMasterInfo()
- if not master_netdev:
- return False
+ # GetMasterInfo will raise an exception if not able to return data
+ master_netdev, master_ip, _ = GetMasterInfo()[1]
+ payload = []
if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
if utils.OwnIpAddress(master_ip):
# we already have the ip:
- logging.debug("Already started")
+ logging.debug("Master IP already configured, doing nothing")
else:
- logging.error("Someone else has the master ip, not activating")
- ok = False
+ msg = "Someone else has the master ip, not activating"
+ logging.error(msg)
+ payload.append(msg)
else:
result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
"dev", master_netdev, "label",
"%s:0" % master_netdev])
if result.failed:
- logging.error("Can't activate master IP: %s", result.output)
- ok = False
+ msg = "Can't activate master IP: %s" % result.output
+ logging.error(msg)
+ payload.append(msg)
result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
"-s", master_ip, master_ip])
for daemon in 'ganeti-masterd', 'ganeti-rapi':
result = utils.RunCmd([daemon])
if result.failed:
- logging.error("Can't start daemon %s: %s", daemon, result.output)
- ok = False
- return ok
+ msg = "Can't start daemon %s: %s" % (daemon, result.output)
+ logging.error(msg)
+ payload.append(msg)
+
+ return not payload, "; ".join(payload)
def StopMaster(stop_daemons):
@rtype: None
"""
- master_netdev, master_ip, _ = GetMasterInfo()
- if not master_netdev:
- return False
+ # TODO: log and report back to the caller the error failures; we
+ # need to decide in which case we fail the RPC for this
+
+ # GetMasterInfo will raise an exception if not able to return data
+ master_netdev, master_ip, _ = GetMasterInfo()[1]
result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
"dev", master_netdev])
for daemon in constants.RAPI_PID, constants.MASTERD_PID:
utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
- return True
+ return True, None
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
mkdir=True)
except errors.OpExecError, err:
- msg = "Error while processing user ssh files"
- logging.exception(msg)
- return (False, "%s: %s" % (msg, err))
+ _Fail("Error while processing user ssh files: %s", err, exc=True)
for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
utils.WriteFile(name, data=content, mode=0600)
try:
priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
- except errors.OpExecError:
- logging.exception("Error while processing ssh files")
- return
- f = open(pub_key, 'r')
- try:
- utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
- finally:
- f.close()
+ f = open(pub_key, 'r')
+ try:
+ utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
+ finally:
+ f.close()
- utils.RemoveFile(priv_key)
- utils.RemoveFile(pub_key)
+ utils.RemoveFile(priv_key)
+ utils.RemoveFile(pub_key)
+ except errors.OpExecError:
+ logging.exception("Error while processing ssh files")
- # Return a reassuring string to the caller, and quit
- raise errors.QuitGanetiException(False, 'Shutdown scheduled')
+ # Raise a custom exception (handled in ganeti-noded)
+ raise errors.QuitGanetiException(True, 'Shutdown scheduled')
def GetNodeInfo(vgname, hypervisor_type):
finally:
f.close()
- return outputarray
+ return True, outputarray
def VerifyNode(what, cluster_name):
what[constants.NV_INSTANCELIST])
if constants.NV_VGLIST in what:
- result[constants.NV_VGLIST] = ListVolumeGroups()
+ result[constants.NV_VGLIST] = utils.ListVolumeGroups()
if constants.NV_VERSION in what:
result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
used_minors = str(err)
result[constants.NV_DRBDLIST] = used_minors
- return result
+ return True, result
def GetVolumeList(vg_name):
"--separator=%s" % sep,
"-olv_name,lv_size,lv_attr", vg_name])
if result.failed:
- logging.error("Failed to list logical volumes, lvs output: %s",
- result.output)
- return result.output
+ _Fail("Failed to list logical volumes, lvs output: %s", result.output)
valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
for line in result.stdout.splitlines():
size of the volume
"""
- return utils.ListVolumeGroups()
+ return True, utils.ListVolumeGroups()
def NodeVolumes():
"--separator=|",
"--options=lv_name,lv_size,devices,vg_name"])
if result.failed:
- logging.error("Failed to list logical volumes, lvs output: %s",
- result.output)
- return []
+ _Fail("Failed to list logical volumes, lvs output: %s",
+ result.output)
def parse_dev(dev):
if '(' in dev:
'vg': line[3].strip(),
}
- return [map_line(line.split('|')) for line in result.stdout.splitlines()
- if line.count('|') >= 3]
+ return True, [map_line(line.split('|'))
+ for line in result.stdout.splitlines()
+ if line.count('|') >= 3]
def BridgesExist(bridges_list):
@return: C{True} if all of them exist, C{False} otherwise
"""
+ missing = []
for bridge in bridges_list:
if not utils.BridgeExists(bridge):
- return False
+ missing.append(bridge)
- return True
+ if missing:
+ return False, "Missing bridges %s" % (", ".join(missing),)
+
+ return True, None
def GetInstanceList(hypervisor_list):
names = hypervisor.GetHypervisor(hname).ListInstances()
results.extend(names)
except errors.HypervisorError, err:
- logging.exception("Error enumerating instances for hypevisor %s", hname)
- raise
+ _Fail("Error enumerating instances (hypervisor %s): %s",
+ hname, err, exc=True)
return results
output['state'] = iinfo[4]
output['time'] = iinfo[5]
- return output
+ return True, output
def GetInstanceMigratable(instance):
# invocations of the different hypervisors
for key in 'memory', 'vcpus':
if value[key] != output[name][key]:
- raise errors.HypervisorError("Instance %s is running twice"
- " with different parameters" % name)
+ _Fail("Instance %s is running twice"
+ " with different parameters", name)
output[name] = value
- return output
+ return True, output
def InstanceOsAdd(instance, reinstall):
hyper = hypervisor.GetHypervisor(instance.hypervisor)
hyper.StartInstance(instance, block_devices)
except errors.BlockDeviceError, err:
- logging.exception("Failed to start instance")
- return (False, "Block device error: %s" % str(err))
+ _Fail("Block device error: %s", err, exc=True)
except errors.HypervisorError, err:
- logging.exception("Failed to start instance")
_RemoveBlockDevLinks(instance.name, instance.disks)
- return (False, "Hypervisor error: %s" % str(err))
+ _Fail("Hypervisor error: %s", err, exc=True)
return (True, "Instance started successfully")
try:
hyper.StopInstance(instance)
except errors.HypervisorError, err:
- msg = "Failed to stop instance %s: %s" % (instance.name, err)
- logging.error(msg)
- return (False, msg)
+ _Fail("Failed to stop instance %s: %s", instance.name, err)
# test every 10secs for 2min
try:
hyper.StopInstance(instance, force=True)
except errors.HypervisorError, err:
- msg = "Failed to force stop instance %s: %s" % (instance.name, err)
- logging.error(msg)
- return (False, msg)
+ _Fail("Failed to force stop instance %s: %s", instance.name, err)
time.sleep(1)
if instance.name in GetInstanceList([hv_name]):
- msg = ("Could not shutdown instance %s even by destroy" %
- instance.name)
- logging.error(msg)
- return (False, msg)
+ _Fail("Could not shutdown instance %s even by destroy", instance.name)
_RemoveBlockDevLinks(instance.name, instance.disks)
running_instances = GetInstanceList([instance.hypervisor])
if instance.name not in running_instances:
- msg = "Cannot reboot instance %s that is not running" % instance.name
- logging.error(msg)
- return (False, msg)
+ _Fail("Cannot reboot instance %s that is not running", instance.name)
hyper = hypervisor.GetHypervisor(instance.hypervisor)
if reboot_type == constants.INSTANCE_REBOOT_SOFT:
try:
hyper.RebootInstance(instance)
except errors.HypervisorError, err:
- msg = "Failed to soft reboot instance %s: %s" % (instance.name, err)
- logging.error(msg)
- return (False, msg)
+ _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
elif reboot_type == constants.INSTANCE_REBOOT_HARD:
try:
stop_result = InstanceShutdown(instance)
return stop_result
return StartInstance(instance)
except errors.HypervisorError, err:
- msg = "Failed to hard reboot instance %s: %s" % (instance.name, err)
- logging.error(msg)
- return (False, msg)
+ _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
else:
- return (False, "Invalid reboot_type received: %s" % (reboot_type,))
+ _Fail("Invalid reboot_type received: %s", reboot_type)
return (True, "Reboot successful")
try:
info = hyper.MigrationInfo(instance)
except errors.HypervisorError, err:
- msg = "Failed to fetch migration information"
- logging.exception(msg)
- return (False, '%s: %s' % (msg, err))
+ _Fail("Failed to fetch migration information: %s", err, exc=True)
return (True, info)
try:
hyper.AcceptInstance(instance, info, target)
except errors.HypervisorError, err:
- msg = "Failed to accept instance"
- logging.exception(msg)
- return (False, '%s: %s' % (msg, err))
+ _Fail("Failed to accept instance: %s", err, exc=True)
return (True, "Accept successfull")
try:
hyper.FinalizeMigration(instance, info, success)
except errors.HypervisorError, err:
- msg = "Failed to finalize migration"
- logging.exception(msg)
- return (False, '%s: %s' % (msg, err))
+ _Fail("Failed to finalize migration: %s", err, exc=True)
return (True, "Migration Finalized")
try:
hyper.MigrateInstance(instance.name, target, live)
except errors.HypervisorError, err:
- msg = "Failed to migrate instance"
- logging.exception(msg)
- return (False, "%s: %s" % (msg, err))
+ _Fail("Failed to migrate instance: %s", err, exc=True)
return (True, "Migration successfull")
try:
crdev = _RecursiveAssembleBD(child, owner, on_primary)
except errors.BlockDeviceError, err:
- errmsg = "Can't assemble device %s: %s" % (child, err)
- logging.error(errmsg)
- return False, errmsg
+ _Fail("Can't assemble device %s: %s", child, err)
if on_primary or disk.AssembleOnSecondary():
# we need the children open in case the device itself has to
# be assembled
try:
crdev.Open()
except errors.BlockDeviceError, err:
- errmsg = "Can't make child '%s' read-write: %s" % (child, err)
- logging.error(errmsg)
- return False, errmsg
+ _Fail("Can't make child '%s' read-write: %s", child, err)
clist.append(crdev)
try:
device = bdev.Create(disk.dev_type, disk.physical_id, clist, size)
except errors.BlockDeviceError, err:
- return False, "Can't create block device: %s" % str(err)
+ _Fail("Can't create block device: %s", err)
if on_primary or disk.AssembleOnSecondary():
try:
device.Assemble()
except errors.BlockDeviceError, err:
- errmsg = ("Can't assemble device after creation, very"
- " unusual event: %s" % str(err))
- logging.error(errmsg)
- return False, errmsg
+ _Fail("Can't assemble device after creation, unusual event: %s", err)
device.SetSyncSpeed(constants.SYNC_SPEED)
if on_primary or disk.OpenOnSecondary():
try:
device.Open(force=True)
except errors.BlockDeviceError, err:
- errmsg = ("Can't make device r/w after creation, very"
- " unusual event: %s" % str(err))
- logging.error(errmsg)
- return False, errmsg
+ _Fail("Can't make device r/w after creation, unusual event: %s", err)
DevCacheManager.UpdateCache(device.dev_path, owner,
on_primary, disk.iv_name)
"""
parent_bdev = _RecursiveFindBD(parent_cdev)
if parent_bdev is None:
- logging.error("Can't find parent device")
- return False
+ _Fail("Can't find parent device '%s' in add children", parent_cdev)
new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
if new_bdevs.count(None) > 0:
- logging.error("Can't find new device(s) to add: %s:%s",
- new_bdevs, new_cdevs)
- return False
+ _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
parent_bdev.AddChildren(new_bdevs)
- return True
+ return (True, None)
def BlockdevRemovechildren(parent_cdev, new_cdevs):
"""
parent_bdev = _RecursiveFindBD(parent_cdev)
if parent_bdev is None:
- logging.error("Can't find parent in remove children: %s", parent_cdev)
- return False
+ _Fail("Can't find parent device '%s' in remove children", parent_cdev)
devs = []
for disk in new_cdevs:
rpath = disk.StaticDevPath()
if rpath is None:
bd = _RecursiveFindBD(disk)
if bd is None:
- logging.error("Can't find dynamic device %s while removing children",
- disk)
- return False
+ _Fail("Can't find device %s while removing children", disk)
else:
devs.append(bd.dev_path)
else:
devs.append(rpath)
parent_bdev.RemoveChildren(devs)
- return True
+ return (True, None)
def BlockdevGetmirrorstatus(disks):
for dsk in disks:
rbd = _RecursiveFindBD(dsk)
if rbd is None:
- raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
+ _Fail("Can't find device %s", dsk)
stats.append(rbd.CombinedSyncStatus())
- return stats
+ return True, stats
def _RecursiveFindBD(disk):
try:
rbd = _RecursiveFindBD(disk)
except errors.BlockDeviceError, err:
- return (False, str(err))
+ _Fail("Failed to find device: %s", err, exc=True)
if rbd is None:
return (True, None)
return (True, (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus())
"""
if not os.path.isabs(file_name):
- err = "Filename passed to UploadFile is not absolute: '%s'" % file_name
- logging.error(err)
- return (False, err)
+ _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
allowed_files = set([
constants.CLUSTER_CONF_FILE,
allowed_files.update(hv_class.GetAncillaryFiles())
if file_name not in allowed_files:
- err = "Filename passed to UploadFile not in allowed upload targets: '%s'" \
- % file_name
- logging.error(err)
- return (False, err)
+ _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
+ file_name)
raw_data = _Decompress(data)
"""
ssconf.SimpleStore().WriteFiles(values)
+ return True, None
def _ErrnoOrStr(err):
result['NIC_%d_MAC' % idx] = nic.mac
if nic.ip:
result['NIC_%d_IP' % idx] = nic.ip
- result['NIC_%d_BRIDGE' % idx] = nic.bridge
+ result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
+ if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
+ result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
+ if nic.nicparams[constants.NIC_LINK]:
+ result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
if constants.HV_NIC_TYPE in instance.hvparams:
result['NIC_%d_FRONTEND_TYPE' % idx] = \
instance.hvparams[constants.HV_NIC_TYPE]
try:
r_dev.Grow(amount)
except errors.BlockDeviceError, err:
- return False, str(err)
+ _Fail("Failed to grow block device: %s", err, exc=True)
return True, None
r_dev = _RecursiveFindBD(disk)
if r_dev is not None:
# let's stay on the safe side and ask for the full size, for now
- return r_dev.Snapshot(disk.size)
+ return True, r_dev.Snapshot(disk.size)
else:
- return None
+ _Fail("Cannot find block device %s", disk)
else:
- raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
- " '%s' of type '%s'" %
- (disk.unique_id, disk.dev_type))
+ _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
+ disk.unique_id, disk.dev_type)
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
os.mkdir(constants.LOG_OS_DIR, 0750)
real_disk = _RecursiveFindBD(disk)
if real_disk is None:
- raise errors.BlockDeviceError("Block device '%s' is not set up" %
- str(disk))
+ _Fail("Block device '%s' is not set up", disk)
+
real_disk.Open()
export_env['EXPORT_DEVICE'] = real_disk.dev_path
result = utils.RunCmd(command, env=export_env)
if result.failed:
- logging.error("os snapshot export command '%s' returned error: %s"
- " output: %s", command, result.fail_reason, result.output)
- return False
+ _Fail("OS snapshot export command '%s' returned error: %s"
+ " output: %s", command, result.fail_reason, result.output)
- return True
+ return (True, None)
def FinalizeExport(instance, snap_disks):
shutil.rmtree(finaldestdir, True)
shutil.move(destdir, finaldestdir)
- return True
+ return True, None
def ExportInfo(dest):
if (not config.has_section(constants.INISECT_EXP) or
not config.has_section(constants.INISECT_INS)):
- return None
+ _Fail("Export info file doesn't have the required fields")
- return config
+ return True, config.Dumps()
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
logging.error("Disk import command '%s' returned error: %s"
" output: %s", command, result.fail_reason,
result.output)
- final_result.append(False)
- else:
- final_result.append(True)
- else:
- final_result.append(True)
+ final_result.append("error importing disk %d: %s, %s" %
+ (idx, result.fail_reason, result.output[-100]))
- return final_result
+ if final_result:
+ return False, "; ".join(final_result)
+ return True, None
def ListExports():
"""
if os.path.isdir(constants.EXPORT_DIR):
- return utils.ListVisibleFiles(constants.EXPORT_DIR)
+ return True, utils.ListVisibleFiles(constants.EXPORT_DIR)
else:
- return []
+ return False, "No exports directory"
def RemoveExport(export):
"""
target = os.path.join(constants.EXPORT_DIR, export)
- shutil.rmtree(target)
- # TODO: catch some of the relevant exceptions and provide a pretty
- # error message if rmtree fails.
+ try:
+ shutil.rmtree(target)
+ except EnvironmentError, err:
+ _Fail("Error while removing the export: %s", err, exc=True)
- return True
+ return True, None
def BlockdevRename(devlist):
@return: True if all renames succeeded, False otherwise
"""
+ msgs = []
result = True
for disk, unique_id in devlist:
dev = _RecursiveFindBD(disk)
if dev is None:
+ msgs.append("Can't find device %s in rename" % str(disk))
result = False
continue
try:
# cache? for now, we only lose lvm data when we rename, which
# is less critical than DRBD or MD
except errors.BlockDeviceError, err:
+ msgs.append("Can't rename device '%s' to '%s': %s" %
+ (dev, unique_id, err))
logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
result = False
- return result
+ return (result, "; ".join(msgs))
def _TransformFileStorageDir(file_storage_dir):
base_file_storage_dir = cfg.GetFileStorageDir()
if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
base_file_storage_dir):
- logging.error("file storage directory '%s' is not under base file"
- " storage directory '%s'",
- file_storage_dir, base_file_storage_dir)
- return None
+ _Fail("File storage directory '%s' is not under base file"
+ " storage directory '%s'", file_storage_dir, base_file_storage_dir)
return file_storage_dir
"""
file_storage_dir = _TransformFileStorageDir(file_storage_dir)
- result = True,
- if not file_storage_dir:
- result = False,
+ if os.path.exists(file_storage_dir):
+ if not os.path.isdir(file_storage_dir):
+ _Fail("Specified storage dir '%s' is not a directory",
+ file_storage_dir)
else:
- if os.path.exists(file_storage_dir):
- if not os.path.isdir(file_storage_dir):
- logging.error("'%s' is not a directory", file_storage_dir)
- result = False,
- else:
- try:
- os.makedirs(file_storage_dir, 0750)
- except OSError, err:
- logging.error("Cannot create file storage directory '%s': %s",
- file_storage_dir, err)
- result = False,
- return result
+ try:
+ os.makedirs(file_storage_dir, 0750)
+ except OSError, err:
+ _Fail("Cannot create file storage directory '%s': %s",
+ file_storage_dir, err, exc=True)
+ return True, None
def RemoveFileStorageDir(file_storage_dir):
"""
file_storage_dir = _TransformFileStorageDir(file_storage_dir)
- result = True,
- if not file_storage_dir:
- result = False,
- else:
- if os.path.exists(file_storage_dir):
- if not os.path.isdir(file_storage_dir):
- logging.error("'%s' is not a directory", file_storage_dir)
- result = False,
- # deletes dir only if empty, otherwise we want to return False
- try:
- os.rmdir(file_storage_dir)
- except OSError, err:
- logging.exception("Cannot remove file storage directory '%s'",
- file_storage_dir)
- result = False,
- return result
+ if os.path.exists(file_storage_dir):
+ if not os.path.isdir(file_storage_dir):
+ _Fail("Specified Storage directory '%s' is not a directory",
+ file_storage_dir)
+ # deletes dir only if empty, otherwise we want to return False
+ try:
+ os.rmdir(file_storage_dir)
+ except OSError, err:
+ _Fail("Cannot remove file storage directory '%s': %s",
+ file_storage_dir, err)
+
+ return True, None
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
"""
old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
- result = True,
- if not old_file_storage_dir or not new_file_storage_dir:
- result = False,
- else:
- if not os.path.exists(new_file_storage_dir):
- if os.path.isdir(old_file_storage_dir):
- try:
- os.rename(old_file_storage_dir, new_file_storage_dir)
- except OSError, err:
- logging.exception("Cannot rename '%s' to '%s'",
- old_file_storage_dir, new_file_storage_dir)
- result = False,
- else:
- logging.error("'%s' is not a directory", old_file_storage_dir)
- result = False,
+ if not os.path.exists(new_file_storage_dir):
+ if os.path.isdir(old_file_storage_dir):
+ try:
+ os.rename(old_file_storage_dir, new_file_storage_dir)
+ except OSError, err:
+ _Fail("Cannot rename '%s' to '%s': %s",
+ old_file_storage_dir, new_file_storage_dir, err)
else:
- if os.path.exists(old_file_storage_dir):
- logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
- old_file_storage_dir, new_file_storage_dir)
- result = False,
- return result
+ _Fail("Specified storage dir '%s' is not a directory",
+ old_file_storage_dir)
+ else:
+ if os.path.exists(old_file_storage_dir):
+ _Fail("Cannot rename '%s' to '%s': both locations exist",
+ old_file_storage_dir, new_file_storage_dir)
+ return True, None
def _IsJobQueueFile(file_name):
for cf in disks:
rd = _RecursiveFindBD(cf)
if rd is None:
- return (False, "Can't find device %s" % cf)
+ _Fail("Can't find device %s", cf)
bdevs.append(rd)
msg = []
try:
rd.DisconnectNet()
except errors.BlockDeviceError, err:
- logging.exception("Failed to go into standalone mode")
- return (False, "Can't change network configuration: %s" % str(err))
+ _Fail("Can't change network configuration to standalone mode: %s",
+ err, exc=True)
return (True, "All disks are now disconnected")
try:
_SymlinkBlockDev(instance_name, rd.dev_path, idx)
except EnvironmentError, err:
- return (False, "Can't create symlink: %s" % str(err))
+ _Fail("Can't create symlink: %s", err)
# reconnect disks, switch to new master configuration and if
# needed primary mode
for rd in bdevs:
try:
rd.AttachNet(multimaster)
except errors.BlockDeviceError, err:
- return (False, "Can't change network configuration: %s" % str(err))
+ _Fail("Can't change network configuration: %s", err)
# wait until the disks are connected; we need to retry the re-attach
# if the device becomes standalone, as this might happen if the one
# node disconnects and reconnects in a different mode before the
try:
rd.ReAttachNet(multimaster)
except errors.BlockDeviceError, err:
- return (False, "Can't change network configuration: %s" % str(err))
+ _Fail("Can't change network configuration: %s", err)
if all_connected:
break
time.sleep(sleep_time)
try:
rd.Open()
except errors.BlockDeviceError, err:
- return (False, "Can't change to primary mode: %s" % str(err))
+ _Fail("Can't change to primary mode: %s", err)
if multimaster:
msg = "multi-master and primary"
else:
elif phase == constants.HOOKS_PHASE_POST:
suffix = "post"
else:
- raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
+ _Fail("Unknown hooks phase '%s'", phase)
+
rr = []
subdir = "%s-%s.d" % (hpath, suffix)
dir_contents = utils.ListVisibleFiles(dir_name)
except OSError, err:
# FIXME: must log output in case of failures
- return rr
+ return True, rr
# we use the standard python sort order,
# so 00name is the recommended naming scheme
rrval = constants.HKR_SUCCESS
rr.append(("%s/%s" % (subdir, relname), rrval, output))
- return rr
+ return True, rr
class IAllocatorRunner(object):
@param idata: the allocator input data
@rtype: tuple
- @return: four element tuple of:
- - run status (one of the IARUN_ constants)
- - stdout
- - stderr
- - fail reason (as from L{utils.RunResult})
+ @return: two element tuple of:
+ - status
+ - either error message or stdout of allocator (for success)
"""
alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
os.path.isfile)
if alloc_script is None:
- return (constants.IARUN_NOTFOUND, None, None, None)
+ _Fail("iallocator module '%s' not found in the search path", name)
fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
try:
os.close(fd)
result = utils.RunCmd([alloc_script, fin_name])
if result.failed:
- return (constants.IARUN_FAILURE, result.stdout, result.stderr,
- result.fail_reason)
+ _Fail("iallocator module '%s' failed: %s, output '%s'",
+ name, result.fail_reason, result.output)
finally:
os.unlink(fin_name)
- return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
+ return True, result.stdout
class DevCacheManager(object):