Ejemplo n.º 1
0
def set_host_enabled(self, arg_dict):
    """Sets this host's ability to accept new instances.

    It will otherwise continue to operate normally.
    """
    enabled = arg_dict.get("enabled")
    if enabled is None:
        raise pluginlib.PluginError(
            "Missing 'enabled' argument to set_host_enabled")

    host_uuid = arg_dict['host_uuid']
    if enabled == "true":
        result = _run_command(["xe", "host-enable", "uuid=%s" % host_uuid])
    elif enabled == "false":
        result = _run_command(["xe", "host-disable", "uuid=%s" % host_uuid])
    else:
        raise pluginlib.PluginError("Illegal enabled status: %s" % enabled)
    # Should be empty string
    if result:
        raise pluginlib.PluginError(result)
    # Return the current enabled status
    cmd = ["xe", "host-param-get", "uuid=%s" % host_uuid, "param-name=enabled"]
    host_enabled = _run_command(cmd)
    if host_enabled == "true":
        status = "enabled"
    else:
        status = "disabled"
    return {"status": status}
Ejemplo n.º 2
0
def network_config(session, args):
    """network config functions"""
    cmd = pluginlib.exists(args, 'cmd')
    if not isinstance(cmd, basestring):
        msg = "invalid command '%s'" % str(cmd)
        raise pluginlib.PluginError(msg)
        return
    if cmd not in ALLOWED_NETWORK_CMDS:
        msg = "Dom0 execution of '%s' is not permitted" % cmd
        raise pluginlib.PluginError(msg)
        return
    cmd_args = pluginlib.exists(args, 'args')
    return ALLOWED_NETWORK_CMDS[cmd](cmd_args)
Ejemplo n.º 3
0
def iptables_config(session, args):
    # command should be either save or restore
    logging.debug("iptables_config:enter")
    logging.debug("iptables_config: args=%s", args)
    cmd_args = pluginlib.exists(args, 'cmd_args')
    logging.debug("iptables_config: cmd_args=%s", cmd_args)
    process_input = pluginlib.optional(args, 'process_input')
    logging.debug("iptables_config: process_input=%s", process_input)
    cmd = json.loads(cmd_args)
    cmd = map(str, cmd)

    # either execute iptable-save or iptables-restore
    # command must be only one of these two
    # process_input must be used only with iptables-restore
    if len(cmd) > 0 and cmd[0] in ('iptables-save',
                                   'iptables-restore',
                                   'ip6tables-save',
                                   'ip6tables-restore'):
        result = _run_command(cmd, process_input)
        ret_str = json.dumps(dict(out=result, err=''))
        logging.debug("iptables_config:exit")
        return ret_str
    # else don't do anything and return an error
    else:
        raise pluginlib.PluginError("Invalid iptables command")
Ejemplo n.º 4
0
def make_partition(session, dev, partition_start, partition_end):
    dev_path = utils.make_dev_path(dev)

    if partition_end != "-":
        raise pluginlib.PluginError("Can only create unbounded partitions")

    utils.run_command(['sfdisk', '-uS', dev_path],
                      '%s,;\n' % (partition_start))
Ejemplo n.º 5
0
def _power_action(action, arg_dict):
    # Host must be disabled first
    host_uuid = arg_dict['host_uuid']
    result = _run_command(["xe", "host-disable", "uuid=%s" % host_uuid])
    if result:
        raise pluginlib.PluginError(result)
    # All running VMs must be shutdown
    result = _run_command(["xe", "vm-shutdown", "--multiple",
                          "resident-on=%s" % host_uuid])
    if result:
        raise pluginlib.PluginError(result)
    cmds = {"reboot": "host-reboot",
            "startup": "host-power-on",
            "shutdown": "host-shutdown"}
    result = _run_command(["xe", cmds[action], "uuid=%s" % host_uuid])
    # Should be empty string
    if result:
        raise pluginlib.PluginError(result)
    return {"power_action": action}
Ejemplo n.º 6
0
def get_console_log(session, arg_dict):
    try:
        raw_dom_id = arg_dict['dom_id']
    except KeyError:
        raise dom0_pluginlib.PluginError("Missing dom_id")
    try:
        dom_id = int(raw_dom_id)
    except ValueError:
        raise dom0_pluginlib.PluginError("Invalid dom_id")

    logfile = open(CONSOLE_LOG_FILE_PATTERN % dom_id, 'rb')
    try:
        try:
            log_content = _last_bytes(logfile)
        except IOError, e:  # noqa
            msg = "Error reading console: %s" % e
            logging.debug(msg)
            raise dom0_pluginlib.PluginError(msg)
    finally:
        logfile.close()

    return base64.b64encode(zlib.compress(log_content))
Ejemplo n.º 7
0
def _mkfs(fs, path, label):
    """Format a file or block device

    :param fs: Filesystem type (only 'swap', 'ext3' supported)
    :param path: Path to file or block device to format
    :param label: Volume label to use
    """
    if fs == 'swap':
        args = ['mkswap']
    elif fs == 'ext3':
        args = ['mkfs', '-t', fs]
        # add -F to force no interactive execute on non-block device.
        args.extend(['-F'])
        if label:
            args.extend(['-L', label])
    else:
        raise pluginlib.PluginError("Partition type %s not supported" % fs)
    args.append(path)
    utils.run_command(args)
Ejemplo n.º 8
0
def make_partition(session, dev, partition_start, partition_end):
    # Since XS7.0 which has sfdisk V2.23, we observe sfdisk has a bug
    # that sfdisk will wrongly calculate cylinders when specify Sector
    # as unit (-uS). That bug will cause the partition operation failed.
    # And that's fixed in 2.26. So as a workaround, let's use the option
    # of '--force' for version <=2.25 and >=2.23. '--force' will ignore
    # the wrong cylinder value but works as expected.
    VER_FORCE_MIN = '2.23'
    VER_FORCE_MAX = '2.25'
    dev_path = utils.make_dev_path(dev)

    if partition_end != "-":
        raise pluginlib.PluginError("Can only create unbounded partitions")

    sfdisk_ver = _get_sfdisk_version()
    cmd_list = ['sfdisk', '-uS', dev_path]
    if sfdisk_ver:
        if StrictVersion(sfdisk_ver) >= StrictVersion(VER_FORCE_MIN) and \
           StrictVersion(sfdisk_ver) <= StrictVersion(VER_FORCE_MAX):
            cmd_list = ['sfdisk', '--force', '-uS', dev_path]

    utils.run_command(cmd_list, '%s,;\n' % (partition_start))
Ejemplo n.º 9
0
def _resume_compute(session, compute_ref, compute_uuid):
    """Resume compute node on slave host after pool join.

    This has to happen regardless of the success or failure of the join
    operation.
    """
    try:
        # session is valid if the join operation has failed
        session.xenapi.VM.start(compute_ref, False, True)
    except XenAPI.Failure:
        # if session is invalid, e.g. xapi has restarted, then the pool
        # join has been successful, wait for xapi to become alive again
        for c in range(0, DEFAULT_TRIES):
            try:
                _run_command(["xe", "vm-start", "uuid=%s" % compute_uuid])
                return
            except pluginlib.PluginError:
                logging.exception('Waited %d seconds for the slave to '
                                  'become available.' % (c * DEFAULT_SLEEP))
                time.sleep(DEFAULT_SLEEP)
        raise pluginlib.PluginError('Unrecoverable error: the host has '
                                    'not come back for more than %d seconds' %
                                    (DEFAULT_SLEEP * (DEFAULT_TRIES + 1)))
Ejemplo n.º 10
0
def _run_command(cmd, cmd_input=None):
    """Wrap utils.run_command to raise PluginError on failure"""
    try:
        return utils.run_command(cmd, cmd_input=cmd_input)
    except utils.SubprocessException, e:  # noqa
        raise pluginlib.PluginError(e.err)