Example #1
0
def configure_amqp_settings(ctx, client, config, amqp_install):
    if amqp_install == 'skip':
        click.secho('AMQP configuration: skipped')
        return
    amqp_service = AmqpService(client)
    current_settings = amqp_service.get_settings()
    click.secho('AMQP current settings:')
    stdout(to_dict(current_settings), ctx)
    amqp = config['amqp']
    amqp_config = {
        'AmqpExchange': amqp['exchange'],
        'AmqpHost': amqp['host'],
        'AmqpPort': amqp['port'],
        'AmqpPrefix': amqp['prefix'],
        'AmqpSslAcceptAll': amqp['ssl_accept_all'],
        'AmqpUseSSL': amqp['ssl'],
        'AmqpUsername': amqp['username'],
        'AmqpVHost': amqp['vhost']
    }
    click.secho('AMQP config file settings:')
    stdout(amqp_config, ctx)
    if amqp_install == 'prompt':
        if not click.confirm('Do you want to configure AMQP with the '
                             'config file settings?'):
            click.secho('AMQP not updated')
            return
    result = amqp_service.test_config(amqp_config, amqp['password'])
    click.secho('AMQP test settings, result: %s' % result['Valid'].text)

    if result['Valid'].text == 'true':
        amqp_service.set_config(amqp_config, amqp['password'])
        click.secho('Updated vCD AMQP configuration.')
    else:
        click.secho('Couldn\'t set vCD AMQP configuration.')
    def setUpClass(cls):
        """Runs once for this class, before all test methods.

        Tasks:
            - Initialize client, config, and other attributes.
            - Restore VCD AMQP settings to defaults.
            - Delete any pre-existing CSE entities.
        """
        cls._config = yaml_to_dict(BASE_CONFIG_FILEPATH)

        cls._client = Client(cls._config['vcd']['host'],
                             api_version=cls._config['vcd']['api_version'],
                             verify_ssl_certs=cls._config['vcd']['verify'])
        credentials = BasicLoginCredentials(cls._config['vcd']['username'],
                                            SYSTEM_ORG_NAME,
                                            cls._config['vcd']['password'])
        cls._client.set_credentials(credentials)
        assert cls._client is not None

        cls._org = get_org(cls._client, org_name=cls._config['broker']['org'])
        assert cls._org is not None

        cls._vdc = get_vdc(cls._client,
                           cls._config['broker']['vdc'],
                           org=cls._org)
        assert cls._vdc is not None

        cls._api_extension = APIExtension(cls._client)
        assert cls._api_extension is not None

        cls._amqp_service = AmqpService(cls._client)
        assert cls._amqp_service is not None

        cls._runner = CliRunner()
        assert cls._runner is not None

        cls._ssh_key_filepath = f"{Path.home() / '.ssh' / 'id_rsa.pub'}"

        configure_vcd_amqp(cls._client,
                           'vcdext',
                           cls._config['amqp']['host'],
                           cls._config['amqp']['port'],
                           'vcd',
                           cls._config['amqp']['ssl_accept_all'],
                           cls._config['amqp']['ssl'],
                           '/',
                           cls._config['amqp']['username'],
                           cls._config['amqp']['password'],
                           quiet=True)
        cls._default_amqp_settings = to_dict(cls._amqp_service.get_settings())
        assert cls._default_amqp_settings is not None

        cls._amqp_username = cls._config['amqp']['username']
        assert cls._amqp_username is not None

        cls._amqp_password = cls._config['amqp']['password']
        assert cls._amqp_password is not None

        CSEServerInstallationTest.delete_cse_entities()
Example #3
0
def info(ctx):
    try:
        client = ctx.obj['client']
        result = client.get_resource(
            client._session_endpoints[_WellKnownEndpoint.ADMIN])
        stdout(to_dict(result), ctx)
    except Exception as e:
        stderr(e, ctx)
Example #4
0
def info(ctx):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        result = client.get_resource(
            client._session_endpoints[_WellKnownEndpoint.ADMIN])
        stdout(to_dict(result), ctx)
    except Exception as e:
        stderr(e, ctx)
Example #5
0
def create(ctx, role_name, description, rights, org_name):
    try:
        client = ctx.obj['client']
        if org_name is not None:
            org_href = client.get_org_by_name(org_name).get('href')
        else:
            org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, org_href)
        role = org.create_role(role_name, description, rights)
        stdout(to_dict(role, exclude=['Link', 'RightReferences']), ctx)
    except Exception as e:
        stderr(e, ctx)
Example #6
0
def create(ctx, role_name, description, rights, org_name):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if org_name is not None:
            org_href = client.get_org_by_name(org_name).get('href')
        else:
            org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, href=org_href)
        role = org.create_role(role_name, description, rights)
        stdout(to_dict(role, exclude=['Link', 'RightReferences']), ctx)
    except Exception as e:
        stderr(e, ctx)
Example #7
0
def info(ctx, role_name, org_name):
    try:
        client = ctx.obj['client']
        if org_name is not None:
            org_href = client.get_org_by_name(org_name).get('href')
        else:
            org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, href=org_href)
        role_resource = org.get_role_resource(role_name)
        stdout(to_dict(role_resource, exclude=['Link', 'RightReferences']),
               ctx)
    except Exception as e:
        stderr(e, ctx)
def should_configure_amqp(client, amqp_config, amqp_install):
    """Decides if CSE installation should configure vCD AMQP settings.

    Returns False if config file AMQP settings are the same as vCD AMQP
    settings, or if the user declines configuration.

    :param pyvcloud.vcd.client.Client client:
    :param dict amqp_config: 'amqp' section of the config file
    :param str amqp_install: 'skip' skips vCD AMQP configuration,
        'config' configures vCD AMQP settings without prompting user,
        'prompt' asks user before configuring vCD AMQP settings.

    :return: boolean that signals whether we should configure AMQP settings.

    :rtype: bool
    """
    if amqp_install == 'skip':
        click.secho(f"Skipping AMQP configuration. vCD and config file may "
                    f"have different AMQP settings.", fg='yellow')
        return False

    current_settings = to_dict(AmqpService(client).get_settings())
    amqp = {
        'AmqpExchange': amqp_config['exchange'],
        'AmqpHost': amqp_config['host'],
        'AmqpPort': str(amqp_config['port']),
        'AmqpPrefix': amqp_config['prefix'],
        'AmqpSslAcceptAll': str(amqp_config['ssl_accept_all']).lower(),
        'AmqpUseSSL': str(amqp_config['ssl']).lower(),
        'AmqpUsername': amqp_config['username'],
        'AmqpVHost': amqp_config['vhost']
    }

    diff_settings = [k for k, v in current_settings.items() if amqp[k] != v]
    if diff_settings:
        click.secho('current vCD AMQP setting(s):', fg='blue')
        for setting in diff_settings:
            click.echo(f"{setting}: {current_settings[setting]}")
        click.secho('\nconfig file AMQP setting(s):', fg='blue')
        for setting in diff_settings:
            click.echo(f"{setting}: {amqp[setting]}")
        msg = '\nConfigure AMQP with the config file settings?'
        if amqp_install == 'prompt' and not click.confirm(msg):
            click.secho(f"Skipping AMQP configuration. vCD and config file "
                        f"may have different AMQP settings.", fg='yellow')
            return False
        return True

    click.secho("vCD and config file AMQP settings are the same. "
                "Skipping AMQP configuration", fg='green')
    return False
Example #9
0
def clone(ctx, original_role_name, new_role_name, org_name, description):
    try:
        restore_session(ctx)
        client = ctx.obj['client']
        if org_name is not None:
            org_href = client.get_org_by_name(org_name).get('href')
        else:
            org_href = ctx.obj['profiles'].get('org_href')
        org = Org(client, href=org_href)

        role_resource = org.get_role_resource(original_role_name)
        # get original role description
        if description is None:
            description = to_dict(role_resource)['Description']

        # get original role rights
        role = Role(client, resource=role_resource)
        raw_rights = role.list_rights()  # list of dicts: {'name': 'right'}
        rights = [right_dict['name'] for right_dict in raw_rights]

        role = org.create_role(new_role_name, description, rights)
        stdout(to_dict(role, exclude=['Link', 'RightReferences']), ctx)
    except Exception as e:
        stderr(e, ctx)
Example #10
0
def diff_amqp_settings(amqp_service, amqp_config):
    """Gets a list of settings that differ between vCD and config file amqp.
    Returns an empty list if settings are the same.

    :param pyvcloud.vcd.amqp.AmqpService amqp_service:
    :param dict amqp_config: amqp section of config file.

    :return: list containing the keys that differ.

    :rtype: List[str]
    """
    cur_settings = to_dict(amqp_service.get_settings())
    amqp = {
        'AmqpExchange': amqp_config['exchange'],
        'AmqpHost': amqp_config['host'],
        'AmqpPort': str(amqp_config['port']),
        'AmqpPrefix': amqp_config['prefix'],
        'AmqpSslAcceptAll': str(amqp_config['ssl_accept_all']).lower(),
        'AmqpUseSSL': str(amqp_config['ssl']).lower(),
        'AmqpUsername': amqp_config['username'],
        'AmqpVHost': amqp_config['vhost']
    }
    return [k for k, v in cur_settings.items() if amqp[k] != v]
Example #11
0
def configure_amqp_settings(ctx, client, config, amqp_install):
    if amqp_install == 'skip':
        click.secho('AMQP configuration: skipped')
        return
    amqp_service = AmqpService(client)
    current_settings = amqp_service.get_settings()
    click.secho('AMQP current settings:')
    stdout(to_dict(current_settings), ctx)
    amqp = config['amqp']
    amqp_config = {
        'AmqpExchange': amqp['exchange'],
        'AmqpHost': amqp['host'],
        'AmqpPort': amqp['port'],
        'AmqpPrefix': amqp['prefix'],
        'AmqpSslAcceptAll': amqp['ssl_accept_all'],
        'AmqpUseSSL': amqp['ssl'],
        'AmqpUsername': amqp['username'],
        'AmqpVHost': amqp['vhost']
    }
    click.secho('AMQP config file settings:')
    stdout(amqp_config, ctx)
    if amqp_install == 'prompt':
        if not click.confirm('Do you want to configure AMQP with the '
                             'config file settings?'):
            click.secho('AMQP not updated')
            return
    result = amqp_service.test_config(amqp_config, amqp['password'])
    click.secho('AMQP test settings, result: %s' % result['Valid'].text)

    if result['Valid'].text == 'true':
        amqp_service.set_config(amqp_config, amqp['password'])
        click.secho('Updated vCD AMQP configuration.')
    else:
        click.secho('Couldn\'t set vCD AMQP configuration.')
    click.secho('Checking AMQP exchange \'%s\'' % amqp['exchange'])
    credentials = pika.PlainCredentials(amqp['username'], amqp['password'])
    parameters = pika.ConnectionParameters(amqp['host'],
                                           amqp['port'],
                                           amqp['vhost'],
                                           credentials,
                                           ssl=amqp['ssl'],
                                           connection_attempts=3,
                                           retry_delay=2,
                                           socket_timeout=5)
    connection = pika.BlockingConnection(parameters)
    click.echo('Connected to AMQP server (%s:%s): %s' %
               (amqp['host'], amqp['port'], bool_to_msg(connection.is_open)))
    channel = connection.channel()
    try:
        channel.exchange_declare(exchange=amqp['exchange'],
                                 exchange_type=EXCHANGE_TYPE,
                                 passive=True,
                                 durable=True,
                                 auto_delete=False)
        click.secho('Exchange \'%s\' found.' % amqp['exchange'])
    except Exception:
        click.secho('Exchange not found, creating exchange \'%s\'' %
                    amqp['exchange'])
        try:
            channel = connection.channel()
            channel.exchange_declare(exchange=amqp['exchange'],
                                     exchange_type=EXCHANGE_TYPE,
                                     durable=True,
                                     auto_delete=False)
            click.secho('Exchange \'%s\' created.' % amqp['exchange'])
        except Exception:
            LOGGER.error(traceback.format_exc())
            click.secho('Couldn\'t create exchange \'%s\'' % amqp['exchange'])
    connection.close()