# 02110-1301, USA.
-"""Functions used by the node daemon"""
+"""Functions used by the node daemon
+
+@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
+ the L{UploadFile} function
+
+"""
import os
utils.RemoveFile(full_name)
+def _BuildUploadFileList():
+ """Build the list of allowed upload files.
+
+ This is abstracted so that it's built only once at module import time.
+
+ """
+ return frozenset([
+ constants.CLUSTER_CONF_FILE,
+ constants.ETC_HOSTS,
+ constants.SSH_KNOWN_HOSTS_FILE,
+ constants.VNC_PASSWORD_FILE,
+ ])
+
+
+_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
+
+
def JobQueuePurge():
"""Removes job queue files and archived jobs.
master_netdev = cfg.GetMasterNetdev()
master_ip = cfg.GetMasterIP()
master_node = cfg.GetMasterNode()
- except errors.ConfigurationError, err:
+ except errors.ConfigurationError:
logging.exception("Cluster configuration incomplete")
return (None, None, None)
return (master_netdev, master_ip, master_node)
-def StartMaster(start_daemons):
+def StartMaster(start_daemons, no_voting):
"""Activate local node as master node.
The function will always try activate the IP address of the master
@type start_daemons: boolean
@param start_daemons: whther to also start the master
daemons (ganeti-masterd and ganeti-rapi)
+ @type no_voting: boolean
+ @param no_voting: whether to start ganeti-masterd without a node vote
+ (if start_daemons is True), but still non-interactively
@rtype: None
"""
# and now start the master and rapi daemons
if start_daemons:
- for daemon in 'ganeti-masterd', 'ganeti-rapi':
- result = utils.RunCmd([daemon])
+ daemons_params = {
+ 'ganeti-masterd': [],
+ 'ganeti-rapi': [],
+ }
+ if no_voting:
+ daemons_params['ganeti-masterd'].append('--no-voting')
+ daemons_params['ganeti-masterd'].append('--yes-do-it')
+ for daemon in daemons_params:
+ cmd = [daemon]
+ cmd.extend(daemons_params[daemon])
+ result = utils.RunCmd(cmd)
if result.failed:
logging.error("Can't start daemon %s: %s", daemon, result.output)
ok = False
def GetNodeInfo(vgname, hypervisor_type):
- """Gives back a hash with different informations about the node.
+ """Gives back a hash with different information about the node.
@type vgname: C{string}
@param vgname: the name of the volume group to ask for disk space information
try:
names = hypervisor.GetHypervisor(hname).ListInstances()
results.extend(names)
- except errors.HypervisorError, err:
+ except errors.HypervisorError:
logging.exception("Error enumerating instances for hypevisor %s", hname)
raise
def GetInstanceInfo(instance, hname):
- """Gives back the informations about an instance as a dictionary.
+ """Gives back the information about an instance as a dictionary.
@type instance: string
@param instance: the instance name
def _GetVGInfo(vg_name):
- """Get informations about the volume group.
+ """Get information about the volume group.
@type vg_name: str
@param vg_name: the volume group which we query
# test every 10secs for 2min
time.sleep(1)
- for dummy in range(11):
+ for _ in range(11):
if instance.name not in GetInstanceList([hv_name]):
break
time.sleep(10)
instance OS, do not recreate the VM
- L{constants.INSTANCE_REBOOT_HARD}: tear down and
restart the VM (at the hypervisor level)
- - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
- is not accepted here, since that mode is handled
- differently
+ - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
+ not accepted here, since that mode is handled differently, in
+ cmdlib, and translates into full stop and start of the
+ instance (instead of a call_instance_reboot RPC)
@rtype: boolean
@return: the success of the operation
msg = "Failed to accept instance"
logging.exception(msg)
return (False, '%s: %s' % (msg, err))
- return (True, "Accept successfull")
+ return (True, "Accept successful")
def FinalizeMigration(instance, info, success):
msg = "Failed to migrate instance"
logging.exception(msg)
return (False, "%s: %s" % (msg, err))
- return (True, "Migration successfull")
+ return (True, "Migration successful")
def BlockdevCreate(disk, size, owner, on_primary, info):
# we need the children open in case the device itself has to
# be assembled
try:
+ # pylint: disable-msg=E1103
crdev.Open()
except errors.BlockDeviceError, err:
errmsg = "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)
+ device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
except errors.BlockDeviceError, err:
return False, "Can't create block device: %s" % str(err)
children.append(cdev)
if as_primary or disk.AssembleOnSecondary():
- r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children)
+ r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
r_dev.SetSyncSpeed(constants.SYNC_SPEED)
result = r_dev
if as_primary or disk.OpenOnSecondary():
try:
result = _RecursiveAssembleBD(disk, owner, as_primary)
if isinstance(result, bdev.BlockDev):
+ # pylint: disable-msg=E1103
result = result.dev_path
except errors.BlockDeviceError, err:
result = "Error while assembling disk: %s" % str(err)
def BlockdevShutdown(disk):
"""Shut down a block device.
- First, if the device is assembled (Attach() is successfull), then
+ First, if the device is assembled (Attach() is successful), then
the device is shutdown. Then the children of the device are
shutdown.
def _RecursiveFindBD(disk):
"""Check if a device is activated.
- If so, return informations about the real device.
+ If so, return information about the real device.
@type disk: L{objects.Disk}
@param disk: the disk object we need to find
for chdisk in disk.children:
children.append(_RecursiveFindBD(chdisk))
- return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
+ return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
def BlockdevFind(disk):
"""Check if a device is activated.
- If it is, return informations about the real device.
+ If it is, return information about the real device.
@type disk: L{objects.Disk}
@param disk: the disk to find
return (True, (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus())
+def BlockdevGetsize(disks):
+ """Computes the size of the given disks.
+
+ If a disk is not found, returns None instead.
+
+ @type disks: list of L{objects.Disk}
+ @param disks: the list of disk to compute the size for
+ @rtype: list
+ @return: list with elements None if the disk cannot be found,
+ otherwise the size
+
+ """
+ result = []
+ for cf in disks:
+ try:
+ rbd = _RecursiveFindBD(cf)
+ except errors.BlockDeviceError, err:
+ result.append(None)
+ continue
+ if rbd is None:
+ result.append(None)
+ else:
+ result.append(rbd.GetActualSize())
+ return result
+
+
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
"""Write a file to the filesystem.
file_name)
return False
- allowed_files = [
- constants.CLUSTER_CONF_FILE,
- constants.ETC_HOSTS,
- constants.SSH_KNOWN_HOSTS_FILE,
- constants.VNC_PASSWORD_FILE,
- ]
-
- if file_name not in allowed_files:
+ if file_name not in _ALLOWED_UPLOAD_FILES:
logging.error("Filename passed to UploadFile not in allowed"
" upload targets: '%s'", file_name)
return False
"""
if base_dir is None:
os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
- if os_dir is None:
- raise errors.InvalidOS(name, None, "OS dir not found in search path")
else:
- os_dir = os.path.sep.join([base_dir, name])
+ os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
+
+ if os_dir is None:
+ raise errors.InvalidOS(name, None, "OS dir not found in search path")
api_versions = _OSOndiskVersion(name, os_dir)
# the target command is built out of three individual commands,
# which are joined by pipes; we check each individual command for
# valid parameters
- expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
- export_script, logfile)
+ expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
+ inst_os.path, export_script, logfile)
comprcmd = "gzip"
# all commands have been checked, so we're safe to combine them
command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
- result = utils.RunCmd(command, env=export_env)
+ result = utils.RunCmd(["bash", "-c", command], env=export_env)
if result.failed:
logging.error("os snapshot export command '%s' returned error: %s"
# but we don't have the owner here - maybe parse from existing
# cache? for now, we only lose lvm data when we rename, which
# is less critical than DRBD or MD
- except errors.BlockDeviceError, err:
+ except errors.BlockDeviceError:
logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
result = False
return result
@param file_storage_dir: the directory we should cleanup
@rtype: tuple (success,)
@return: tuple of one element, C{success}, denoting
- whether the operation was successfull
+ whether the operation was successful
"""
file_storage_dir = _TransformFileStorageDir(file_storage_dir)
# deletes dir only if empty, otherwise we want to return False
try:
os.rmdir(file_storage_dir)
- except OSError, err:
+ except OSError:
logging.exception("Cannot remove file storage directory '%s'",
file_storage_dir)
result = False,
if os.path.isdir(old_file_storage_dir):
try:
os.rename(old_file_storage_dir, new_file_storage_dir)
- except OSError, err:
+ except OSError:
logging.exception("Cannot rename '%s' to '%s'",
old_file_storage_dir, new_file_storage_dir)
result = False,
if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
return (False, "The master daemon is running, will not demote")
try:
- utils.CreateBackup(constants.CLUSTER_CONF_FILE)
+ if os.path.isfile(constants.CLUSTER_CONF_FILE):
+ utils.CreateBackup(constants.CLUSTER_CONF_FILE)
except EnvironmentError, err:
if err.errno != errno.ENOENT:
return (False, "Error while backing up cluster file: %s" % str(err))
# standalone, even though this should not happen with the
# new staged way of changing disk configs
try:
- rd.ReAttachNet(multimaster)
+ rd.AttachNet(multimaster)
except errors.BlockDeviceError, err:
return (False, "Can't change network configuration: %s" % str(err))
if all_connected:
on the master side.
"""
- RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
-
def __init__(self, hooks_base_dir=None):
"""Constructor for hooks runner.
"""
if hooks_base_dir is None:
hooks_base_dir = constants.HOOKS_BASE_DIR
- self._BASE_DIR = hooks_base_dir
+ # yeah, _BASE_DIR is not valid for attributes, we use it like a
+ # constant
+ self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
@staticmethod
def ExecHook(script, env):
dir_name = "%s/%s" % (self._BASE_DIR, subdir)
try:
dir_contents = utils.ListVisibleFiles(dir_name)
- except OSError, err:
+ except OSError:
# FIXME: must log output in case of failures
return rr
for relname in dir_contents:
fname = os.path.join(dir_name, relname)
if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
- self.RE_MASK.match(relname) is not None):
+ constants.EXT_PLUGIN_MASK.match(relname) is not None):
rrval = constants.HKR_SKIP
output = ""
else:
fdata = "%s %s %s\n" % (str(owner), state, iv_name)
try:
utils.WriteFile(fpath, data=fdata)
- except EnvironmentError, err:
+ except EnvironmentError:
logging.exception("Can't update bdev cache for %s", dev_path)
@classmethod
fpath = cls._ConvertPath(dev_path)
try:
utils.RemoveFile(fpath)
- except EnvironmentError, err:
+ except EnvironmentError:
logging.exception("Can't update bdev cache for %s", dev_path)