예제 #1
0
def test_nova():
    LOG.tc_func_start()
    ProjVar.set_var(SOURCE_OPENRC=True)
    cli.openstack('server list')
    cli.openstack('server list', auth_info=None)
    ProjVar.set_var(SOURCE_OPENRC=None)
    LOG.tc_func_end()
예제 #2
0
def verify_user(user_name,
                password,
                is_admin=True,
                expect_fail=False,
                keystone=None):
    scenario = ' and expect failure' if expect_fail else ''
    LOG.info('Run {} OpenStack command with {} role {}'.format(
        keystone, 'admin' if is_admin else 'member', scenario))

    dict_name = '{}_platform'.format(
        user_name) if keystone == 'platform' else user_name
    auth_info = Tenant.get(dict_name)
    auth_info = copy.deepcopy(auth_info)
    auth_info['password'] = password
    if is_admin:
        command = 'endpoint list'
        code, output = cli.openstack(command,
                                     fail_ok=expect_fail,
                                     auth_info=auth_info)
    else:
        command = 'user show {}'.format(user_name)
        code, output = cli.openstack(command,
                                     fail_ok=expect_fail,
                                     auth_info=auth_info)

    message = 'command:{}\nauth_info:{}\noutput:{}'.format(
        command, auth_info, output)

    if expect_fail:
        assert 1 == code, "OpenStack command ran successfully while rejection is " \
                          "expected: {}".format(message)
예제 #3
0
def test_create_snapshot_using_boot_from_image_vm():
    """
    This test creates a snapshot from a VM that is booted from image using
    nova image-create.  Nova image-create will create a glance image that can
    be used to boot a VM.

    Assumptions:
    * There are so images available on the system

    Test Steps:
    1.  Boot a vm from image
    2.  Run nova image-create <vm-id> <name> to save a snapshot of a vm in the
        form of a glance image
    3.  Run glance image-download --file <snapshot-img-filename>
        <snapshot-img-uuid> to download the snapshot image
    4.  Delete the downloaded image
    5.  Boot a VM using the snapshot that was created

    Teardown:
    1.  Delete VMs
    2.  Delete snapshots in the form a glance image
    """

    con_ssh = ControllerClient.get_active_controller()

    LOG.tc_step("Boot a VM from image")
    vm_id = vm_helper.boot_vm(source="image", cleanup='function')[1]
    assert vm_id, "Failed to boot VM"
    vm_name = vm_helper.get_vm_name_from_id(vm_id)
    snapshot_name = vm_name + "_snapshot"

    # nova image-create generates a glance image
    LOG.tc_step("Create a snapshot based on that VM")
    image_id = vm_helper.create_image_from_vm(vm_id, cleanup='function')[1]

    image_filename = '{}/images/temp'.format(HostLinuxUser.get_home())
    LOG.tc_step("Download the image snapshot")
    glance_cmd = "image save --file {} {}".format(image_filename, image_id)
    # Throw exception if glance cmd rejected
    cli.openstack(glance_cmd, ssh_client=con_ssh, fail_ok=False)

    # Downloading should be good enough for validation.  If the file is
    # zero-size, download will report failure.
    LOG.tc_step("Delete the downloaded image")
    con_ssh.exec_cmd("rm {}".format(image_filename), fail_ok=False)

    # Second form of validation is to boot a VM from the snapshot
    LOG.tc_step("Boot a VM from snapshot")
    snapshot_vm = "from_" + snapshot_name
    vm_helper.boot_vm(name=snapshot_vm,
                      source="image",
                      source_id=image_id,
                      cleanup='function',
                      fail_ok=False)
예제 #4
0
def test_clis():
    print(CliAuth.get_var('HTTPS'))
    cli.system('host-list')
    cli.system('host-show controller-0')
    cli.openstack('server list')
    cli.openstack('stack list')
    ceilometer_helper.get_alarms()
    keystone_helper.get_endpoints()
    cli.openstack('router list')
    cli.openstack('volume list')
    cli.openstack('image list')
예제 #5
0
def delete_bundle(bundle_id, con_ssh=None, auth_info=None, fail_ok=False):
    """
    Delete murano bundle
    Args:
        bundle_id: Bundle id to delete
        con_ssh (SSHClient):
        auth_info (dict)
        fail_ok (bool): whether return False or raise exception when some
            services fail to reach enabled-active state

    Returns:
        code, msg: return code and msg

        """

    if bundle_id is None:
        raise ValueError("Murano bundle id has to be specified.")

    LOG.info("Deleting Murano bundle {}".format(bundle_id))
    code, output = cli.openstack('bundle delete',
                                 bundle_id,
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)

    if code > 0:
        return 1, output

    table_ = table_parser.table(output)
    pkg_id = table_parser.get_value_two_col_table(table_, 'id')
    return 0, pkg_id
예제 #6
0
def import_package(pkg, con_ssh=None, auth_info=None, fail_ok=False):
    """
    Import Murano package
    Args:
        pkg: package name to import (full path)
        con_ssh (SSHClient):
        auth_info (dict)
        fail_ok (bool): whether return False or raise exception when some
            services fail to reach enabled-active state

    Returns:
        code, msg: return code and msg

        """

    if pkg is None:
        raise ValueError("Package name has to be specified.")

    LOG.info("Importing Murano package {}".format(pkg))
    code, output = cli.openstack('package import --exists-action u',
                                 pkg,
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)

    if code > 0:
        return 1, output

    table_ = table_parser.table(output)
    pkg_id = table_parser.get_values(table_, 'ID')
    return 0, pkg_id
예제 #7
0
def get_flavor_values(flavor,
                      fields,
                      strict=True,
                      con_ssh=None,
                      auth_info=Tenant.get('admin')):
    """
    Get flavor values for given fields via openstack flavor show
    Args:
        flavor (str):
        fields (str|list|tuple):
        strict (bool): strict search for field name or not
        con_ssh:
        auth_info:

    Returns (list):

    """
    table_ = table_parser.table(
        cli.openstack('flavor show',
                      flavor,
                      ssh_client=con_ssh,
                      auth_info=auth_info)[1])
    return table_parser.get_multi_values_two_col_table(
        table_,
        fields,
        merge_lines=True,
        evaluate=True,
        strict=strict,
        dict_fields=('properties', ))
예제 #8
0
def get_flavors(name=None,
                memory=None,
                disk=None,
                ephemeral=None,
                swap=None,
                vcpu=None,
                rxtx=None,
                is_public=None,
                flv_id=None,
                long=False,
                con_ssh=None,
                auth_info=None,
                strict=True,
                field='id'):
    """
    Get a flavor id with given criteria. If no criteria given, a random flavor will be returned.

    Args:
        name (str): name of a flavor
        memory (int): memory size in MB
        disk (int): size of the disk in GB
        ephemeral (int): size of ephemeral disk in GB
        swap (int): size of swap disk in GB
        vcpu (int): number of vcpus
        rxtx (str):
        is_public (bool):
        flv_id (str)
        long (bool)
        con_ssh (SSHClient):
        auth_info (dict):
        strict (bool): whether or not to perform strict search on provided values
        field (str|list|tuple)

    Returns (list):

    """

    args = '--long' if long else ''
    table_ = table_parser.table(
        cli.openstack('flavor list',
                      args,
                      ssh_client=con_ssh,
                      auth_info=auth_info)[1])

    req_dict = {
        'Name': name,
        'RAM': memory,
        'Disk': disk,
        'Ephemeral': ephemeral,
        'Swap': '' if str(swap) == '0' else swap,
        'VCPUs': vcpu,
        'RXTX Factor': rxtx,
        'Is Public': is_public,
        'ID': flv_id,
    }
    final_dict = {k: str(v) for k, v in req_dict.items() if v is not None}
    return table_parser.get_multi_values(table_,
                                         field,
                                         strict=strict,
                                         **final_dict)
예제 #9
0
def create_keypair(name,
                   public_key=None,
                   private_key=None,
                   fail_ok=False,
                   con_ssh=None,
                   auth_info=Tenant.get('admin')):
    """
    Create a new keypair
    Args:
        name (str): keypair name to create
        public_key (str|None): existing public key file path to use
        private_key (str|None): file path to save private key
        fail_ok (bool)
        con_ssh (SSHClient):
        auth_info (dict):

    Returns (tuple):

    """
    args_dict = {'--public-key': public_key, '--private-key': private_key}
    args = '{} "{}"'.format(common.parse_args(args_dict), name)
    LOG.info("Creating keypair with args: {}".format(args))

    code, out = cli.openstack('keypair create',
                              args,
                              ssh_client=con_ssh,
                              fail_ok=fail_ok,
                              auth_info=auth_info)
    if code > 0:
        return 1, out

    LOG.info("Keypair {} created successfully".format(name))
    return 0, name
예제 #10
0
def get_aggregate_values(aggregate,
                         fields,
                         con_ssh=None,
                         auth_info=Tenant.get('admin'),
                         fail_ok=False):
    """
    Get values of a nova aggregate for given fields
    Args:
        aggregate (str):
        fields (str|list|tuple):
        con_ssh:
        auth_info (dict):
        fail_ok (bool)

    Returns (list):

    """
    code, out = cli.openstack('aggregate show',
                              aggregate,
                              ssh_client=con_ssh,
                              auth_info=auth_info,
                              fail_ok=fail_ok)
    if code > 0:
        return []

    table_ = table_parser.table(out)
    return table_parser.get_multi_values_two_col_table(
        table_, fields, evaluate=True, dict_fields=('properties', ))
예제 #11
0
def get_aggregates(field='name',
                   name=None,
                   avail_zone=None,
                   con_ssh=None,
                   auth_info=Tenant.get('admin')):
    """
    Get a list of aggregates

    Args:
        field (str|list|tuple): id or name
        name (str|list): filter out the aggregates with given name if specified
        avail_zone (str): filter out the aggregates with given availability zone if specified
        con_ssh (SSHClient):
        auth_info (dict):

    Returns (list):

    """
    kwargs = {}
    if avail_zone:
        kwargs['Availability Zone'] = avail_zone
    if name:
        kwargs['Name'] = name

    aggregates_tab = table_parser.table(
        cli.openstack('aggregate list',
                      ssh_client=con_ssh,
                      auth_info=auth_info)[1])
    return table_parser.get_multi_values(aggregates_tab, field, **kwargs)
예제 #12
0
def get_image_values(image,
                     fields,
                     auth_info=Tenant.get('admin'),
                     con_ssh=None,
                     fail_ok=False):
    """
    Get glance image values from openstack image show
    Args:
        image:
        fields:
        auth_info:
        con_ssh:
        fail_ok

    Returns (list):

    """
    if isinstance(fields, str):
        fields = (fields, )
    code, output = cli.openstack('image show',
                                 image,
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)
    if code > 0:
        return [None] * len(fields)

    table_ = table_parser.table(output)
    values = table_parser.get_multi_values_two_col_table(
        table_,
        fields,
        merge_lines=True,
        evaluate=True,
        dict_fields='properties')
    return values
예제 #13
0
def get_stacks(name=None, field='id', con_ssh=None, auth_info=None, all_=True):
    """
    Get the stacks list based on name if given for a given tenant.

    Args:
        con_ssh (SSHClient): If None, active controller ssh will be used.
        auth_info (dict): Tenant dict. If None, primary tenant will be used.
        all_ (bool): whether to display all stacks for admin user
        name (str): Given name for the heat stack
        field (str|list|tuple)

    Returns (list): list of heat stacks.

    """
    args = ''
    if auth_info is not None:
        if auth_info['user'] == 'admin' and all_:
            args = '--a'
    table_ = table_parser.table(
        cli.openstack('stack list',
                      positional_args=args,
                      ssh_client=con_ssh,
                      auth_info=auth_info)[1])

    kwargs = {'Stack Name': name} if name else {}
    return table_parser.get_multi_values(table_, field, **kwargs)
예제 #14
0
def get_roles(field='ID',
              con_ssh=None,
              auth_info=Tenant.get('admin'),
              **kwargs):
    table_ = table_parser.table(
        cli.openstack('role list', ssh_client=con_ssh, auth_info=auth_info)[1])
    return table_parser.get_multi_values(table_, field, **kwargs)
예제 #15
0
def delete_package(package_id, con_ssh=None, auth_info=None, fail_ok=False):
    """
    Delete Murano package
    Args:
        package_id: package id to delete
        con_ssh (SSHClient):
        auth_info (dict)
        fail_ok (bool): whether return False or raise exception when some
            services fail to reach enabled-active state

    Returns:
        code, msg: return code and msg

        """

    if package_id is None:
        raise ValueError("Murano package name has to be specified.")

    LOG.info("Deleting Murano bundle {}".format(package_id))
    code, output = cli.openstack('package delete',
                                 package_id,
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)
    if code > 0:
        return 1, output

    return 0, "package {} deleted successfully".format(package_id)
예제 #16
0
def get_aggregated_measures(field='value', resource_type=None, metrics=None,
                            start=None, stop=None, overlap=None,
                            refresh=None, resource_ids=None, extra_query=None,
                            fail_ok=False, auth_info=Tenant.get('admin'),
                            con_ssh=None):
    """
    Get measurements via 'openstack metric measures aggregation'
    Args:
        field (str): header of a column
        resource_type (str|None):  used in --resource-type <resource_type>
        metrics (str|list|tuple|None): used in --metric <metric1> [metric2 ...]
        start (str|None): used in --start <start>
        stop (str|None): used in --stop <stop>
        refresh (bool): used in --refresh
        overlap (str|None): overlap percentage. used in
            --needed-overlap <overlap>
        resource_ids (str|list|tuple|None): used in --query "id=<resource_id1>[
            or id=<resource_id2> ...]"
        extra_query (str|None): used in --query <extra_query>
        fail_ok:
        auth_info:
        con_ssh:

    Returns (list): list of strings

    """
    LOG.info("Getting aggregated measurements...")
    args_dict = {
        'resource-type': resource_type,
        'metric': metrics,
        'start': start,
        'stop': stop,
        'needed-overlap': overlap,
        'refresh': refresh,
    }

    args = common.parse_args(args_dict, vals_sep=' ')
    query_str = ''
    if resource_ids:
        if isinstance(resource_ids, str):
            resource_ids = [resource_ids]
        resource_ids = ['id={}'.format(val) for val in resource_ids]
        query_str = ' or '.join(resource_ids)

    if extra_query:
        if resource_ids:
            query_str += ' and '
        query_str += '{}'.format(extra_query)

    if query_str:
        args += ' --query "{}"'.format(query_str)

    code, out = cli.openstack('metric measures aggregation', args,
                              ssh_client=con_ssh, fail_ok=fail_ok,
                              auth_info=auth_info)
    if code > 0:
        return 1, out

    table_ = table_parser.table(out)
    return 0, table_parser.get_values(table_, field)
예제 #17
0
def is_https_enabled(con_ssh=None, source_openrc=True, interface='public',
                     auth_info=Tenant.get('admin_platform')):
    """
    Check whether interface is https
    Args:
        con_ssh:
        source_openrc:
        interface: default is public
        auth_info:
    Returns True or False
    """
    if not con_ssh:
        con_name = auth_info.get('region') if (
                auth_info and ProjVar.get_var('IS_DC')) else None
        con_ssh = ControllerClient.get_active_controller(name=con_name)

    table_ = table_parser.table(
        cli.openstack('endpoint list', ssh_client=con_ssh, auth_info=auth_info,
                      source_openrc=source_openrc)[1])
    con_ssh.exec_cmd('unset OS_REGION_NAME')  # Workaround
    filters = {'Service Name': 'keystone', 'Service Type': 'identity',
               'Interface': interface}
    keystone_values = table_parser.get_values(table_=table_, target_header='URL',
                                              **filters)
    LOG.info('keystone {} URLs: {}'.format(interface, keystone_values))
    return all('https' in i for i in keystone_values)
예제 #18
0
def get_events(event_type, limit=None, header='message_id', con_ssh=None,
               auth_info=None, **filters):
    """

    Args:
        event_type:
        limit
        header:
        con_ssh:
        auth_info:

    Returns:

    """
    args = ''
    if limit:
        args = '--limit {}'.format(limit)

    if event_type or filters:
        if event_type:
            filters['event_type'] = event_type

        extra_args = ['{}={}'.format(k, v) for k, v in filters.items()]
        args += ' --filter {}'.format(';'.join(extra_args))

    table_ = table_parser.table(cli.openstack('event list', args,
                                              ssh_client=con_ssh,
                                              auth_info=auth_info)[1])
    return table_parser.get_values(table_, header)
예제 #19
0
def get_alarms(header='alarm_id',
               name=None,
               strict=False,
               auth_info=Tenant.get('admin'),
               con_ssh=None):
    """

    Args:
        header
        name:
        strict:
        auth_info:
        con_ssh:

    Returns:

    """

    table_ = table_parser.table(cli.openstack('alarm list',
                                              ssh_client=con_ssh,
                                              auth_info=auth_info)[1],
                                combine_multiline_entry=True)
    if name is None:
        return table_parser.get_column(table_, header)

    return table_parser.get_values(table_, header, Name=name, strict=strict)
예제 #20
0
def get_metric_values(metric_id=None, metric_name=None, resource_id=None, fields='id', fail_ok=False,
                      auth_info=Tenant.get('admin'), con_ssh=None):
    """
    Get metric info via 'openstack metric show'
    Args:
        metric_id (str|None):
        metric_name (str|None): Only used if metric_id is not provided
        resource_id (str|None):  Only used if metric_id is not provided
        fields (str|list|tuple): field name
        fail_ok (bool):
        auth_info:
        con_ssh:

    Returns (list):

    """
    if metric_id is None and metric_name is None:
        raise ValueError("metric_id or metric_name has to be provided.")

    if metric_id:
        arg = metric_id
    else:
        if resource_id:
            arg = '--resource-id {} "{}"'.format(resource_id, metric_name)
        else:
            if not fail_ok:
                raise ValueError("resource_id needs to be provided when using metric_name")
            arg = '"{}"'.format(metric_name)

    code, output = cli.openstack('openstack metric show', arg, ssh_client=con_ssh, fail_ok=fail_ok, auth_info=auth_info)
    if code > 0:
        return output

    table_ = table_parser.table(output)
    return table_parser.get_multi_values_two_col_table(table_, fields)
예제 #21
0
def delete_env(env_id, con_ssh=None, auth_info=None, fail_ok=False):
    """
    Delete Murano Environment
    Args:
        env_id: Id of the env to create
        con_ssh (SSHClient):
        auth_info (dict)
        fail_ok (bool): whether return False or raise exception when some
            services fail to reach enabled-active 12state

    Returns:
        code, msg: return code and msg

        """

    if not env_id:
        raise ValueError("Murano env id has to be specified.")

    LOG.info("Deleting Murano Environment {}".format(env_id))
    code, output = cli.openstack('environment delete',
                                 env_id,
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)
    if code > 0:
        return 1, output

    return 0, "Env {} Deleted Successfully".format(env_id)
예제 #22
0
def deploy_env(env_id,
               session_id,
               con_ssh=None,
               auth_info=None,
               fail_ok=False):

    code, output = cli.openstack(
        'environment deploy --session-id {} {}'.format(session_id, env_id),
        ssh_client=con_ssh,
        fail_ok=fail_ok,
        auth_info=auth_info)

    if code == 1:
        return 1, output

    table_ = table_parser.table(output)
    deploy_id = table_parser.get_value_two_col_table(table_, 'id')
    if not deploy_id:
        msg = "Fail to get the deploy id; session-id {}; environment " \
              "id {}".format(session_id, env_id)
        if fail_ok:
            return 2, msg
        else:
            raise exceptions.MuranoError(msg)

    return 0, deploy_id
예제 #23
0
def delete_stack(stack,
                 fail_ok=False,
                 check_first=False,
                 con_ssh=None,
                 auth_info=None):
    """
    Delete the given heat stack for a given tenant.

    Args:
        con_ssh (SSHClient): If None, active controller ssh will be used.
        fail_ok (bool):
        check_first (bool): whether or not to check the stack existence
            before attempt to delete
        auth_info (dict): Tenant dict. If None, primary tenant will be used.
        stack (str): Given name for the heat stack

    Returns (tuple): Status and msg of the heat deletion.

    """

    if not stack:
        raise ValueError("stack_name is not provided.")

    if check_first:
        if not get_stack_status(
                stack, con_ssh=con_ssh, auth_info=auth_info, fail_ok=True):
            msg = "Heat stack {} doesn't exist on the system. Do " \
                  "nothing.".format(stack)
            LOG.info(msg)
            return -1, msg

    LOG.info("Deleting Heat Stack %s", stack)
    exitcode, output = cli.openstack('stack delete -y',
                                     stack,
                                     ssh_client=con_ssh,
                                     fail_ok=fail_ok,
                                     auth_info=auth_info)
    if exitcode > 1:
        LOG.warning("Delete heat stack request rejected.")
        return 1, output

    if not _wait_for_heat_stack_deleted(stack_name=stack, auth_info=auth_info):
        stack_id = get_stack_values(stack=stack,
                                    fields='id',
                                    auth_info=auth_info,
                                    con_ssh=con_ssh)[0]
        get_stack_resources(stack=stack_id,
                            auth_info=auth_info,
                            con_ssh=con_ssh)

        msg = "heat stack {} is not removed after stack-delete.".format(stack)
        if fail_ok:
            LOG.warning(msg)
            return 2, msg
        raise exceptions.HeatError(msg)

    succ_msg = "Heat stack {} is successfully deleted.".format(stack)
    LOG.info(succ_msg)
    return 0, succ_msg
예제 #24
0
def get_role_assignments(field='Role', names=True, role=None, user=None,
                         project=None, user_domain=None, group=None,
                         group_domain=None, domain=None, project_domain=None,
                         inherited=None, effective_only=None,
                         con_ssh=None, auth_info=Tenant.get('admin')):
    """
    Get values from 'openstack role assignment list' table

    Args:
        field (str|list|tuple): role assignment table header to determine
            which values to return
        names (bool): whether to display role assignment with name
            (default is ID)
        role (str): an existing role from openstack role list
        project (str): tenant name. When unset, the primary tenant name
            will be used
        user (str): an existing user that belongs to given tenant
        domain (str): Include <domain> (name or ID)
        group (str): Include <group> (name or ID)
        group_domain (str): Domain the group belongs to (name or ID). This can
            be used in case collisions between group names exist.
        project_domain (str): Domain the project belongs to (name or ID). This
            can be used in case collisions between project names exist.
        user_domain (str): Domain the user belongs to (name or ID). This can
            be used in case collisions between user names exist.
        inherited (bool): Specifies if the role grant is inheritable to the
            sub projects
        effective_only (bool): Whether to show effective roles only
        con_ssh (SSHClient): active controller ssh session
        auth_info (dict): auth info to use to executing the add role cli

    Returns (list): list of values

    """
    optional_args = {
        'role': role,
        'user': user,
        'project': project,
        'domain': domain,
        'group': group,
        'group-domain': group_domain,
        'project-domain': project_domain,
        'user-domain': user_domain,
        'names': True if names else None,
        'effective': True if effective_only else None,
        'inherited': True if inherited else None
    }
    args = common.parse_args(optional_args)

    role_assignment_tab = table_parser.table(
        cli.openstack('role assignment list', args, ssh_client=con_ssh,
                      auth_info=auth_info)[1])

    if not role_assignment_tab['headers']:
        LOG.info("No role assignment is found with criteria: {}".format(args))
        return []

    return table_parser.get_multi_values(role_assignment_tab, field)
예제 #25
0
def get_cli_timestamps(vol_id):

    table_ = table_parser.table(cli.system('show')[1])
    sysinv_timestamp = table_parser.get_value_two_col_table(table_, 'created_at')

    table_ = table_parser.table(cli.openstack('volume show', vol_id, auth_info=Tenant.get('admin'))[1])
    openstack_timestamp = table_parser.get_value_two_col_table(table_, 'created_at')

    return  sysinv_timestamp, openstack_timestamp
예제 #26
0
def get_package_list(header='ID',
                     pkgid=None,
                     name=None,
                     fqn=None,
                     author=None,
                     active=None,
                     is_public=None,
                     pkg_type=None,
                     version=None,
                     auth_info=Tenant.get('admin'),
                     con_ssh=None,
                     strict=True,
                     regex=None,
                     **kwargs):
    """

    Args:
        header:
        pkgid
        name:
        fqn:
        author:
        active:
        is_public:
        pkg_type:
        version:
        auth_info:
        con_ssh:
        strict:
        regex:
        **kwargs:

    Returns: list

    """

    table_ = table_parser.table(
        cli.openstack('package list', ssh_client=con_ssh,
                      auth_info=auth_info)[1])
    args_temp = {
        'ID': pkgid,
        'Name': name,
        'FQN': fqn,
        'Author': author,
        'Active': active,
        'Is Public': is_public,
        'Type': pkg_type,
        'Version': version
    }
    for key, value in args_temp.items():
        if value is not None:
            kwargs[key] = value
    return table_parser.get_values(table_,
                                   header,
                                   strict=strict,
                                   regex=regex,
                                   **kwargs)
예제 #27
0
def set_user(user, name=None, project=None, password=None, project_doamin=None,
             email=None, description=None,
             enable=None, fail_ok=False, auth_info=Tenant.get('admin'),
             con_ssh=None):
    LOG.info("Updating {}...".format(user))
    arg = ''
    optional_args = {
        'name': name,
        'project': project,
        'password': password,
        'project-domain': project_doamin,
        'email': email,
        'description': description,
    }
    for key, val in optional_args.items():
        if val is not None:
            arg += "--{} '{}' ".format(key, val)

    if enable is not None:
        arg += '--{} '.format('enable' if enable else 'disable')

    if not arg.strip():
        raise ValueError(
            "Please specify the param(s) and value(s) to change to")

    arg += user

    code, output = cli.openstack('user set', arg, ssh_client=con_ssh, timeout=120,
                                 fail_ok=fail_ok, auth_info=auth_info)

    if code > 0:
        return 1, output

    if name or project or password:
        tenant_dictname = user
        if auth_info and auth_info.get('platform'):
            tenant_dictname += '_platform'
        Tenant.update(tenant_dictname, username=name, password=password,
                      tenant=project)

    if password and user == 'admin':
        from consts.proj_vars import ProjVar
        if ProjVar.get_var('REGION') != 'RegionOne':
            LOG.info(
                "Run openstack_update_admin_password on secondary region "
                "after admin password change")
            if not con_ssh:
                con_ssh = ControllerClient.get_active_controller()
            with con_ssh.login_as_root(timeout=30) as con_ssh:
                con_ssh.exec_cmd(
                    "echo 'y' | openstack_update_admin_password '{}'".format(
                        password))

    msg = 'User {} updated successfully'.format(user)
    LOG.info(msg)
    return 0, output
예제 #28
0
def delete_flavors(flavors,
                   check_first=True,
                   fail_ok=False,
                   con_ssh=None,
                   auth_info=Tenant.get('admin')):
    """
    Delete given flavor(s)
    Args:
        flavors (list|str): id(s) of flavor(s) to delete
        check_first (bool)
        fail_ok (bool): whether to raise exception if any flavor fails to delete
        con_ssh (SSHClient):
        auth_info (dict):

    Returns (tuple):
        (-1, 'None of the flavor(s) exists. Do nothing.')
        (0, 'Flavor is successfully deleted')
        (1, <std_out>)
        (2, "Flavor <flavor_id> still exists on system after deleted.")

    """
    if isinstance(flavors, str):
        flavors = [flavors]

    if check_first:
        existing_favors = get_flavors(con_ssh=con_ssh, auth_info=auth_info)
        flavors = list(set(flavors) & set(existing_favors))
        if not flavors:
            msg = "None of the given flavors exist. Do nothing."
            LOG.info(msg)
            return -1, msg

    LOG.info("Flavor(s) to delete: {}".format(flavors))
    code, output = cli.openstack('flavor delete',
                                 ' '.join(flavors),
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)
    if code > 0:
        return 1, output

    existing_favors = get_flavors(con_ssh=con_ssh, auth_info=auth_info)
    flavors_still_exist = list(set(flavors) & set(existing_favors))
    if flavors_still_exist:
        err_msg = "Flavor(s) still exist after deletion: {}".format(
            flavors_still_exist)
        LOG.warning(err_msg)
        if fail_ok:
            return 2, err_msg
        else:
            raise exceptions.FlavorError(err_msg)

    success_msg = "Flavor(s) deleted successfully."
    LOG.info(success_msg)
    return 0, success_msg
예제 #29
0
def traffic_with_preset_configs(ixncfg, ixia_session=None):
    with ExitStack() as stack:
        if ixia_session is None:
            LOG.info("ixia_session not supplied, creating")
            from keywords import ixia_helper
            ixia_session = ixia_helper.IxiaSession()
            ixia_session.connect()
            stack.callback(ixia_session.disconnect)

        ixia_session.load_config(ixncfg)

        subnet_table = table_parser.table(
            cli.openstack('subnet list', auth_info=Tenant.get('admin'))[1])
        cidrs = list(
            map(ipaddress.ip_network,
                table_parser.get_column(subnet_table, 'Subnet')))
        for vport in ixia_session.getList(ixia_session.getRoot(), 'vport'):
            for interface in ixia_session.getList(vport, 'interface'):
                if ixia_session.testAttributes(interface, enabled='true'):
                    ipv4_interface = ixia_session.getList(interface, 'ipv4')[0]
                    gw = ipaddress.ip_address(
                        ixia_session.getAttribute(ipv4_interface, 'gateway'))
                    vlan_interface = ixia_session.getList(interface, 'vlan')[0]
                    for cidr in cidrs:
                        if gw in cidr:
                            net_id = table_parser.get_values(subnet_table,
                                                             'Network',
                                                             cidr=cidr)[0]
                            table = table_parser.table(
                                cli.openstack(
                                    'network show',
                                    net_id,
                                    auth_info=Tenant.get('admin'))[1])
                            seg_id = table_parser.get_value_two_col_table(
                                table, "provider:segmentation_id")
                            ixia_session.configure(vlan_interface,
                                                   vlanEnable=True,
                                                   vlanId=str(seg_id))
                            LOG.info(
                                "vport {} interface {} gw {} vlan updated to {}"
                                .format(vport, interface, gw, seg_id))
예제 #30
0
def create_env(name,
               mgmt_net_id=None,
               mgmt_subnet_id=None,
               con_ssh=None,
               auth_info=None,
               fail_ok=False):
    """
    Create Murano Environment
    Args:
        name: Name of the env to create
        mgmt_subnet_id (str): The ID of tenant1 management subnet
        mgmt_net_id (str): The ID of tenant1 management net
        con_ssh (SSHClient):
        auth_info (dict)
        fail_ok (bool): whether return False or raise exception when some
            services fail to reach enabled-active state

    Returns:
        code, msg: return code and msg

        """

    if name is None:
        raise ValueError("Murano environment name has to be specified.")

    LOG.info("Creating Murano Environment {}".format(name))

    args = ''
    if mgmt_subnet_id:
        args = " --join-subnet-id {}".format(mgmt_subnet_id)
    elif mgmt_net_id:
        args = " --join-net-id {}".format(mgmt_net_id)

    args = '{} {}'.format(args, name)
    code, output = cli.openstack("environment create",
                                 args,
                                 ssh_client=con_ssh,
                                 fail_ok=fail_ok,
                                 auth_info=auth_info)
    if code > 0:
        return 1, output

    table_ = table_parser.table(output)
    env_id = table_parser.get_values(table_, 'ID')
    if len(env_id) > 0:
        return 0, env_id[0]
    else:
        msg = "Fail to get the murano environment id"
        LOG.info(msg)
        if fail_ok:
            return 2, msg
        else:
            raise exceptions.MuranoError(msg)