Exemplo n.º 1
0
def list_vcenters(ctx):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.list_vcenters(), ctx)
    except Exception as e:
        stderr(e, ctx)
Exemplo n.º 2
0
Arquivo: vc.py Projeto: vmware/vca-cli
def list_vcenters(ctx):
    try:
        restore_session(ctx)
        platform = Platform(ctx.obj['client'])
        stdout(platform.list_vcenters(), ctx)
    except Exception as e:
        stderr(e, ctx)
Exemplo n.º 3
0
    def attach_vc(cls):
        """Attaches VC and NSX to vCD as per configuration file.

        If VC is already attached no further action is taken.

        :return: Nothing
        """
        cls._basic_check()
        platform = Platform(cls._sys_admin_client)
        vc_name = cls._config['vc']['vcenter_host_name']
        for record in platform.list_vcenters():
            if record.get('name').lower() == vc_name.lower():
                cls._logger.debug(vc_name + ' is already attached.')
                return
        # Untested code - see VCDA-603
        platform.attach_vcenter(
            vc_server_name=vc_name,
            vc_server_host=cls._config['vc']['vcenter_host_ip'],
            vc_admin_user=cls._config['vc']['vcenter_admin_username'],
            vc_admin_pwd=cls._config['vc']['vcenter_admin_password'],
            nsx_server_name=cls._config['nsx']['nsx_hostname'],
            nsx_host=cls._config['nsx']['nsx_host_ip'],
            nsx_admin_user=cls._config['nsx']['nsx_admin_username'],
            nsx_admin_pwd=cls._config['nsx']['nsx_admin_password'],
            is_enabled=True)
Exemplo n.º 4
0
 def test_0010_list_vc(self):
     """Platform.list_vcenters prints a list of virtual center servers."""
     logger = Environment.get_default_logger()
     platform = Platform(TestVC._client)
     vcenters = platform.list_vcenters()
     for vcenter in vcenters:
         logger.debug('vCenter found: %s' % vcenter.get('name'))
     self.assertTrue(len(vcenters) > 0)
Exemplo n.º 5
0
 def test_0010_list_vc(self):
     """Platform.list_vcenters prints a list of virtual center servers."""
     logger = Environment.get_default_logger()
     platform = Platform(TestVC._client)
     vcenters = platform.list_vcenters()
     for vcenter in vcenters:
         logger.debug('vCenter found: %s' % vcenter.get('name'))
     self.assertTrue(len(vcenters) > 0)
Exemplo n.º 6
0
    def attach_vc(cls):
        """Attaches VC and NSX to vCD as per configuration file.

        If VC is already attached no further action is taken.
        """
        cls._basic_check()
        platform = Platform(cls._sys_admin_client)
        vc_name = cls._config['vc']['vcenter_host_name']
        for record in platform.list_vcenters():
            if record.get('name').lower() == vc_name.lower():
                cls._logger.debug(vc_name + ' is already attached.')
                return
        platform.attach_vcenter(
            vc_server_name=vc_name,
            vc_server_host=cls._config['vc']['vcenter_host_ip'],
            vc_admin_user=cls._config['vc']['vcenter_admin_username'],
            vc_admin_pwd=cls._config['vc']['vcenter_admin_password'],
            nsx_server_name=cls._config['nsx']['nsx_hostname'],
            nsx_host=cls._config['nsx']['nsx_host_ip'],
            nsx_admin_user=cls._config['nsx']['nsx_admin_username'],
            nsx_admin_pwd=cls._config['nsx']['nsx_admin_password'],
            is_enabled=True)
Exemplo n.º 7
0
 def test_0001_list_vc(self):
     platform = Platform(self.client)
     vcenters = platform.list_vcenters()
     for vcenter in vcenters:
         self.logger.debug('vCenter found: %s' % vcenter.get('name'))
     assert len(vcenters) > 0
def _validate_vcd_and_vcs_config(
        vcd_dict,
        vcs,
        msg_update_callback=NullPrinter(),
        log_file=None,
        log_wire=False
):
    """Ensure that 'vcd' and vcs' section of config are correct.

    Checks that
        * 'vcd' and 'vcs' section of config have correct keys and value types.
        * vCD and all registered VCs in vCD are accessible.
        * api version specified for vcd is supported by CSE.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :param list vcs: 'vcs' section of config file as a list of dicts.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object.
    :param str log_file: log_file for pyvcloud wire log.
    :param bool log_wire: If pyvcloud requests should be logged.

    :raises KeyError: if @vcd_dict or a vc in @vcs has missing or
        extra properties.
    :raises TypeError: if the value type for a @vcd_dict or vc property
        is incorrect.
    :raises ValueError: if vCD has a VC that is not listed in the config file.
    """
    check_keys_and_value_types(vcd_dict, SAMPLE_VCD_CONFIG['vcd'],
                               location="config file 'vcd' section",
                               msg_update_callback=msg_update_callback)
    if not vcd_dict['verify']:
        msg_update_callback.general(
            'InsecureRequestWarning: Unverified HTTPS request is '
            'being made. Adding certificate verification is '
            'strongly advised.'
        )
        requests.packages.urllib3.disable_warnings()

    client = None
    try:
        _validate_vcd_url_scheme(vcd_dict['host'])
        client = Client(
            vcd_dict['host'],
            verify_ssl_certs=vcd_dict['verify'],
            log_file=log_file,
            log_requests=log_wire,
            log_headers=log_wire,
            log_bodies=log_wire
        )
        client.set_credentials(
            BasicLoginCredentials(
                vcd_dict['username'],
                SYSTEM_ORG_NAME,
                vcd_dict['password']
            )
        )
        msg_update_callback.general(
            "Connected to vCloud Director "
            f"({vcd_dict['host']}:{vcd_dict['port']})"
        )

        for index, vc in enumerate(vcs, 1):
            check_keys_and_value_types(
                vc,
                SAMPLE_VCS_CONFIG['vcs'][0],
                location=f"config file 'vcs' section, vc #{index}",
                msg_update_callback=msg_update_callback
            )

        # Check that all registered VCs in vCD are listed in config file
        platform = Platform(client)
        config_vc_names = [vc['name'] for vc in vcs]
        for platform_vc in platform.list_vcenters():
            platform_vc_name = platform_vc.get('name')
            if platform_vc_name not in config_vc_names:
                raise ValueError(
                    f"vCenter '{platform_vc_name}' registered in "
                    "vCD but not found in config file"
                )

        # Check that all VCs listed in config file are registered in vCD
        for vc in vcs:
            vcenter = platform.get_vcenter(vc['name'])
            if not (hasattr(vcenter, 'IsConnected') and vcenter.IsConnected):
                msg = f"vCenter Server '{vc['name']}' not available"
                msg_update_callback.info(msg)
                continue
            vsphere_url = urlparse(vcenter.Url.text)
            vsphere_url_port = vsphere_url.port
            if vsphere_url_port:
                v = VSphere(
                    vsphere_url.hostname,
                    vc['username'],
                    vc['password'],
                    vsphere_url.port
                )
            else:
                v = VSphere(
                    vsphere_url.hostname,
                    vc['username'],
                    vc['password']
                )
            v.connect()
            msg = f"Connected to vCenter Server '{vc['name']}' as " \
                f"'{vc['username']}' ({vsphere_url.hostname}"
            if vsphere_url_port:
                msg += f":{vsphere_url.port}"
            msg += ")"
            msg_update_callback.general(msg)
    finally:
        if client is not None:
            client.logout()
Exemplo n.º 9
0
 def test_0001_list_vc(self):
     platform = Platform(self.client)
     vcenters = platform.list_vcenters()
     for vcenter in vcenters:
         self.logger.debug('vCenter found: %s' % vcenter.get('name'))
     assert len(vcenters) > 0
Exemplo n.º 10
0
def check_config(config_file_name, template=None):
    click.secho('Validating CSE on vCD from file: %s' % config_file_name)
    if sys.version_info.major >= 3 and sys.version_info.minor >= 6:
        python_valid = True
    else:
        python_valid = False
    click.echo('Python version >= 3.6 (installed: %s.%s.%s): %s' %
               (sys.version_info.major, sys.version_info.minor,
                sys.version_info.micro, bool_to_msg(python_valid)))
    if not python_valid:
        raise Exception('Python version not supported')
    config = get_config(config_file_name)
    validate_broker_config_elements(config['broker'])
    amqp = config['amqp']
    credentials = pika.PlainCredentials(amqp['username'], amqp['password'])
    parameters = pika.ConnectionParameters(amqp['host'],
                                           amqp['port'],
                                           '/',
                                           credentials,
                                           ssl=amqp['ssl'])
    connection = pika.BlockingConnection(parameters)
    click.echo('Connected to AMQP server (%s:%s): %s' %
               (amqp['host'], amqp['port'], bool_to_msg(connection.is_open)))
    connection.close()

    if not config['vcd']['verify']:
        click.secho(
            'InsecureRequestWarning: '
            'Unverified HTTPS request is being made. '
            'Adding certificate verification is strongly '
            'advised.',
            fg='yellow',
            err=True)
        requests.packages.urllib3.disable_warnings()
    client = Client(config['vcd']['host'],
                    api_version=config['vcd']['api_version'],
                    verify_ssl_certs=config['vcd']['verify'],
                    log_file='cse-check.log',
                    log_headers=True,
                    log_bodies=True)
    client.set_credentials(
        BasicLoginCredentials(config['vcd']['username'], 'System',
                              config['vcd']['password']))
    click.echo(
        'Connected to vCloud Director as system '
        'administrator (%s:%s): %s' %
        (config['vcd']['host'], config['vcd']['port'], bool_to_msg(True)))
    platform = Platform(client)
    for vc in platform.list_vcenters():
        found = False
        for config_vc in config['vcs']:
            if vc.get('name') == config_vc.get('name'):
                found = True
                break
        if not found:
            raise Exception('vCenter \'%s\' defined in vCloud Director '
                            'but not in CSE config file' % vc.get('name'))
            return None

    for vc in config['vcs']:
        vcenter = platform.get_vcenter(vc['name'])
        vsphere_url = urlparse(vcenter.Url.text)
        v = VSphere(vsphere_url.hostname, vcenter.Username.text,
                    vc['password'], vsphere_url.port)
        v.connect()
        click.echo('Connected to vCenter Server %s as %s '
                   '(%s:%s): %s' %
                   (vc['name'], vcenter.Username.text, vsphere_url.hostname,
                    vsphere_url.port, bool_to_msg(True)))

    if template is None:
        pass
    else:
        click.secho('Validating \'%s\' service broker' %
                    config['broker']['type'])
        if config['broker']['type'] == 'default':
            validate_broker_config_content(config, client, template)

    return config
Exemplo n.º 11
0
def validate_vcd_and_vcs_config(vcd_dict, vcs):
    """Ensures that 'vcd' and vcs' section of config are correct.

    Checks that 'vcd' and 'vcs' section of config have correct keys and value
    types. Also checks that vCD and all registered VCs in vCD are accessible.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :param list vcs: 'vcs' section of config file as a list of dicts.

    :raises KeyError: if @vcd_dict or a vc in @vcs has missing or
        extra properties.
    :raises: ValueError: if the value type for a @vcd_dict or vc property
        is incorrect, or if vCD has a VC that is not listed in the config file.
    """
    check_keys_and_value_types(vcd_dict,
                               SAMPLE_VCD_CONFIG['vcd'],
                               location="config file 'vcd' section")
    if not vcd_dict['verify']:
        click.secho(
            'InsecureRequestWarning: Unverified HTTPS request is '
            'being made. Adding certificate verification is '
            'strongly advised.',
            fg='yellow',
            err=True)
        requests.packages.urllib3.disable_warnings()

    client = None
    try:
        client = Client(vcd_dict['host'],
                        api_version=vcd_dict['api_version'],
                        verify_ssl_certs=vcd_dict['verify'])
        client.set_credentials(
            BasicLoginCredentials(vcd_dict['username'], SYSTEM_ORG_NAME,
                                  vcd_dict['password']))
        click.secho(
            f"Connected to vCloud Director "
            f"({vcd_dict['host']}:{vcd_dict['port']})",
            fg='green')

        for index, vc in enumerate(vcs, 1):
            check_keys_and_value_types(vc,
                                       SAMPLE_VCS_CONFIG['vcs'][0],
                                       location=f"config file 'vcs' section, "
                                       f"vc #{index}")

        # Check that all registered VCs in vCD are listed in config file
        platform = Platform(client)
        config_vc_names = [vc['name'] for vc in vcs]
        for platform_vc in platform.list_vcenters():
            platform_vc_name = platform_vc.get('name')
            if platform_vc_name not in config_vc_names:
                raise ValueError(f"vCenter '{platform_vc_name}' registered in "
                                 f"vCD but not found in config file")

        # Check that all VCs listed in config file are registered in vCD
        for vc in vcs:
            vcenter = platform.get_vcenter(vc['name'])
            vsphere_url = urlparse(vcenter.Url.text)
            v = VSphere(vsphere_url.hostname, vc['username'], vc['password'],
                        vsphere_url.port)
            v.connect()
            click.secho(
                f"Connected to vCenter Server '{vc['name']}' as "
                f"'{vc['username']}' ({vsphere_url.hostname}:"
                f"{vsphere_url.port})",
                fg='green')
    finally:
        if client is not None:
            client.logout()
def _validate_vcd_and_vcs_config(vcd_dict, vcs, msg_update_callback=None):
    """Ensure that 'vcd' and vcs' section of config are correct.

    Checks that 'vcd' and 'vcs' section of config have correct keys and value
    types. Also checks that vCD and all registered VCs in vCD are accessible.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :param list vcs: 'vcs' section of config file as a list of dicts.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object
        that writes messages onto console.

    :raises KeyError: if @vcd_dict or a vc in @vcs has missing or
        extra properties.
    :raises TypeError: if the value type for a @vcd_dict or vc property
        is incorrect.
    :raises ValueError: if vCD has a VC that is not listed in the config file.
    """
    check_keys_and_value_types(vcd_dict,
                               SAMPLE_VCD_CONFIG['vcd'],
                               location="config file 'vcd' section",
                               msg_update_callback=msg_update_callback)
    if not vcd_dict['verify']:
        if msg_update_callback:
            msg_update_callback.general(
                'InsecureRequestWarning: Unverified HTTPS request is '
                'being made. Adding certificate verification is '
                'strongly advised.')
        requests.packages.urllib3.disable_warnings()

    client = None
    try:
        # TODO() we get an error during client initialization if the specified
        # logfile points to the directory which doesn't exist. This issue
        # should be fixed in pyvcloud, where the logging setup creates
        # directories used in the log filepath if they do not exist yet.
        setup_log_file_directory()
        client = Client(vcd_dict['host'],
                        api_version=vcd_dict['api_version'],
                        verify_ssl_certs=vcd_dict['verify'],
                        log_file=SERVER_DEBUG_WIRELOG_FILEPATH,
                        log_requests=True,
                        log_headers=True,
                        log_bodies=True)
        client.set_credentials(
            BasicLoginCredentials(vcd_dict['username'], SYSTEM_ORG_NAME,
                                  vcd_dict['password']))
        if msg_update_callback:
            msg_update_callback.general(
                "Connected to vCloud Director "
                f"({vcd_dict['host']}:{vcd_dict['port']})")

        for index, vc in enumerate(vcs, 1):
            check_keys_and_value_types(
                vc,
                SAMPLE_VCS_CONFIG['vcs'][0],
                location=f"config file 'vcs' section, vc #{index}",
                msg_update_callback=msg_update_callback)

        # Check that all registered VCs in vCD are listed in config file
        platform = Platform(client)
        config_vc_names = [vc['name'] for vc in vcs]
        for platform_vc in platform.list_vcenters():
            platform_vc_name = platform_vc.get('name')
            if platform_vc_name not in config_vc_names:
                raise ValueError(f"vCenter '{platform_vc_name}' registered in "
                                 f"vCD but not found in config file")

        # Check that all VCs listed in config file are registered in vCD
        for vc in vcs:
            vcenter = platform.get_vcenter(vc['name'])
            vsphere_url = urlparse(vcenter.Url.text)
            v = VSphere(vsphere_url.hostname, vc['username'], vc['password'],
                        vsphere_url.port)
            v.connect()
            if msg_update_callback:
                msg_update_callback.general(
                    f"Connected to vCenter Server '{vc['name']}' as "
                    f"'{vc['username']}' ({vsphere_url.hostname}:"
                    f"{vsphere_url.port})")
    finally:
        if client is not None:
            client.logout()