Ejemplo n.º 1
0
def validate_load_for_delete(load):
    if not load:
        raise exception.InventoryException(_("Load not found"))

    valid_delete_states = [
        constants.IMPORTED_LOAD_STATE, constants.ERROR_LOAD_STATE,
        constants.DELETING_LOAD_STATE
    ]

    if load.state not in valid_delete_states:
        raise exception.InventoryException(
            _("Only a load in an imported or error state can be deleted"))
Ejemplo n.º 2
0
def get_local_controller_hostname():
    try:
        local_hostname = socket.gethostname()
    except Exception as e:
        raise exception.InventoryException(
            _("Failed to get the local hostname: %s") % str(e))
    return local_hostname
Ejemplo n.º 3
0
def get_mate_controller_hostname(hostname=None):
    if not hostname:
        try:
            hostname = socket.gethostname()
        except Exception as e:
            raise exception.InventoryException(
                _("Failed to get the local hostname: %s") % str(e))

    if hostname == k_host.CONTROLLER_0_HOSTNAME:
        mate_hostname = k_host.CONTROLLER_1_HOSTNAME
    elif hostname == k_host.CONTROLLER_1_HOSTNAME:
        mate_hostname = k_host.CONTROLLER_0_HOSTNAME
    else:
        raise exception.InventoryException(
            _("Unknown local hostname: %s)") % hostname)

    return mate_hostname
Ejemplo n.º 4
0
def get_imported_load(loads):
    imported_load = None
    for db_load in loads:
        if db_load.state == constants.IMPORTED_LOAD_STATE:
            imported_load = db_load

    if imported_load is None:
        raise exception.InventoryException(_("No imported load found"))

    return imported_load
Ejemplo n.º 5
0
def get_active_load(loads):
    active_load = None
    for db_load in loads:
        if db_load.state == constants.ACTIVE_LOAD_STATE:
            active_load = db_load

    if active_load is None:
        raise exception.InventoryException(_("No active load found"))

    return active_load
Ejemplo n.º 6
0
 def _get_primary_cgtsclient(self):
     # import the module in the function that uses it
     # as the cgtsclient is only installed on the controllers
     from cgtsclient.v1 import client as cgts_client
     # get region one name from platform.conf
     region1_name = get_region_name('region_1_name')
     if region1_name is None:
         region1_name = 'RegionOne'
     auth_ref = self._get_keystoneclient().auth_ref
     if auth_ref is None:
         raise exception.InventoryException(
             _("Unable to get auth ref from keystone client"))
     auth_token = auth_ref.service_catalog.get_token()
     endpoint = (auth_ref.service_catalog.
                 get_endpoints(service_type='platform',
                               endpoint_type='internal',
                               region_name=region1_name))
     endpoint = endpoint['platform'][0]
     version = 1
     return cgts_client.Client(version=version,
                               endpoint=endpoint['url'],
                               auth_url=self.auth_url,
                               token=auth_token['id'])
Ejemplo n.º 7
0
def validate_loads_for_import(loads):
    for db_load in loads:
        if db_load.state == constants.IMPORTED_LOAD_STATE:
            raise exception.InventoryException(_("Imported load exists."))
Ejemplo n.º 8
0
def execute(*cmd, **kwargs):
    """Helper method to execute command with optional retry.

    If you add a run_as_root=True command, don't forget to add the
    corresponding filter to etc/inventory/rootwrap.d !

    :param cmd:                Passed to subprocess.Popen.
    :param process_input:      Send to opened process.
    :param check_exit_code:    Single bool, int, or list of allowed exit
                               codes.  Defaults to [0].  Raise
                               exception.ProcessExecutionError unless
                               program exits with one of these code.
    :param delay_on_retry:     True | False. Defaults to True. If set to
                               True, wait a short amount of time
                               before retrying.
    :param attempts:           How many times to retry cmd.
    :param run_as_root:        True | False. Defaults to False. If set to True,
                               the command is run with rootwrap.

    :raises exception.InventoryException: on receiving unknown arguments
    :raises exception.ProcessExecutionError:

    :returns: a tuple, (stdout, stderr) from the spawned process, or None if
             the command fails.
    """
    process_input = kwargs.pop('process_input', None)
    check_exit_code = kwargs.pop('check_exit_code', [0])
    ignore_exit_code = False
    if isinstance(check_exit_code, bool):
        ignore_exit_code = not check_exit_code
        check_exit_code = [0]
    elif isinstance(check_exit_code, int):
        check_exit_code = [check_exit_code]
    delay_on_retry = kwargs.pop('delay_on_retry', True)
    attempts = kwargs.pop('attempts', 1)
    run_as_root = kwargs.pop('run_as_root', False)
    shell = kwargs.pop('shell', False)

    if len(kwargs):
        raise exception.InventoryException(
            _('Got unknown keyword args to utils.execute: %r') % kwargs)

    if run_as_root and os.geteuid() != 0:
        cmd = (['sudo', 'inventory-rootwrap', CONF.rootwrap_config] +
               list(cmd))

    cmd = map(str, cmd)

    while attempts > 0:
        attempts -= 1
        try:
            LOG.debug(_('Running cmd (subprocess): %s'), ' '.join(cmd))
            _PIPE = subprocess.PIPE  # pylint: disable=E1101

            if os.name == 'nt':
                preexec_fn = None
                close_fds = False
            else:
                preexec_fn = _subprocess_setup
                close_fds = True

            obj = subprocess.Popen(cmd,
                                   stdin=_PIPE,
                                   stdout=_PIPE,
                                   stderr=_PIPE,
                                   close_fds=close_fds,
                                   preexec_fn=preexec_fn,
                                   shell=shell)
            result = None
            if process_input is not None:
                result = obj.communicate(process_input)
            else:
                result = obj.communicate()
            obj.stdin.close()  # pylint: disable=E1101
            _returncode = obj.returncode  # pylint: disable=E1101
            LOG.debug(_('Result was %s') % _returncode)
            if not ignore_exit_code and _returncode not in check_exit_code:
                (stdout, stderr) = result
                raise exception.ProcessExecutionError(exit_code=_returncode,
                                                      stdout=stdout,
                                                      stderr=stderr,
                                                      cmd=' '.join(cmd))
            return result
        except exception.ProcessExecutionError:
            if not attempts:
                raise
            else:
                LOG.debug(_('%r failed. Retrying.'), cmd)
                if delay_on_retry:
                    greenthread.sleep(random.randint(20, 200) / 100.0)
        finally:
            # NOTE(termie): this appears to be necessary to let the subprocess
            #               call clean something up in between calls, without
            #               it two execute calls in a row hangs the second one
            greenthread.sleep(0)