Beispiel #1
0
    def get_client(cls, org, username, password):
        """Returns a client for a particular user.

        The user is identified by the specified username-password combo in a
        given organization.

        :param str org:  name of the organization, which the user belongs to.
        :param str username: username of the user.
        :param str password: password of the user.

        :return: a client.

        :rtype: pyvcloud.vcd.client.Client

        :raises: Exception: if the basic configuration is missing.
        """
        if cls._config is None:
            raise Exception('Missing base configuration.')

        client = Client(
            cls._config['vcd']['host'],
            api_version=cls._config['vcd']['api_version'],
            verify_ssl_certs=cls._config['connection']['verify'],
            log_file=cls._config['logging']['default_client_log_filename'],
            log_requests=cls._config['logging']['log_requests'],
            log_headers=cls._config['logging']['log_headers'],
            log_bodies=cls._config['logging']['log_bodies'])

        client.set_credentials(BasicLoginCredentials(username, org, password))

        return client
Beispiel #2
0
def init_environment(config_filepath=BASE_CONFIG_FILEPATH):
    """Set up module variables according to config dict.

    :param str config_filepath:
    """
    global AMQP_USERNAME, AMQP_PASSWORD, CLIENT, ORG_HREF, VDC_HREF, \
        CATALOG_NAME, TEARDOWN_INSTALLATION, TEARDOWN_CLUSTERS, \
        TEST_ALL_TEMPLATES

    config = testutils.yaml_to_dict(config_filepath)
    CLIENT = Client(config['vcd']['host'],
                    api_version=config['vcd']['api_version'],
                    verify_ssl_certs=config['vcd']['verify'])
    credentials = BasicLoginCredentials(config['vcd']['username'],
                                        utils.SYSTEM_ORG_NAME,
                                        config['vcd']['password'])
    CLIENT.set_credentials(credentials)

    org = utils.get_org(CLIENT, org_name=config['broker']['org'])
    vdc = utils.get_vdc(CLIENT, config['broker']['vdc'], org=org)
    ORG_HREF = org.href
    VDC_HREF = vdc.href
    CATALOG_NAME = config['broker']['catalog']
    AMQP_USERNAME = config['amqp']['username']
    AMQP_PASSWORD = config['amqp']['password']

    test_config = config.get('test')
    if test_config is not None:
        TEARDOWN_INSTALLATION = test_config.get('teardown_installation', True)
        TEARDOWN_CLUSTERS = test_config.get('teardown_clusters', True)
        TEST_ALL_TEMPLATES = test_config.get('test_all_templates', False)
def vcd_login(host, user, password, org):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("login called")
    client = Client(host,
                    api_version="27.0",
                    verify_ssl_certs=False,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        client.set_credentials(BasicLoginCredentials(user, org, password))
        x = client._session.headers['x-vcloud-authorization']
        logging.info(" =====  X VCloud ========\n  \n" + x + "\n \n")

        logged_in_org = client.get_org()
        org = Org(client, resource=logged_in_org)
        v = org.get_vdc('OVD2')
        vdc = VDC(client, href=v.get('href'))
        vapp = vdc.get_vapp('cento_vapp11_2')
        nconfig_section = vapp.NetworkConfigSection
        nconfig = nconfig_section.findall(
            "{http://www.vmware.com/vcloud/v1.5}NetworkConfig")
        for i in range(0, len(nconfig)):
            print(nconfig[i].get('networkName'))

        ##print(etree.tostring(nconfig[0], pretty_print=True))

        #pRes= catalog.isPresent(client,"c1")
        # res=catalog.create(client,"c44","c44",True)

        #logging.info(" is create ===== \n \n "+ str(res.created)+ "\n \n ")
        #logging.info("\n\n=====callling upload ova===\n")
        #catalog_item.upload_ova(client,"c44","/home/iso/tiny.ova",item_name="tiny3.ova")
        #logging.info("\n\n=====upload done ===\n ")
        #logging.info(" Delete  ===== \n \n "+ str(catalog.delete(client,"c3").deleted)+ "\n \n ")
        #logging.info(" Delete  ===== \n \n "+ str(catalog.delete(client,"c4").deleted)+ "\n \n ")

        #vappInfo=pyvcloudprovider_pb2.CreateVAppInfo()
        #vappInfo.name="vappacc2"
        #vappInfo.catalog_name="c1"
        #vappInfo.template_name="cento_tmpl1"
        #vapp.create(client,vappInfo)

        #delVappInfo=pyvcloudprovider_pb2.DeleteVAppInfo()
        #delVappInfo.name="vappacc2"

        #vapp.delete(client,delVappInfo)
        #ovaInfo=pyvcloudprovider_pb2.CatalogUploadOvaInfo()
        #ovaInfo.item_name="item1"
        #ovaInfo.catalog_name="testcata1"
        #ovaInfo.file_path="/Users/srinarayana/vmws/tiny.ova"

        # catalog_item.ova_check_resolved(client,ovaInfo)

        #vappInfo.template_name="cento_tmpl1"
        #vapp.create(client,vappInfo)
        return client
    except Exception as e:
        print('error occured', e)
Beispiel #4
0
def init_environment(config_filepath=BASE_CONFIG_FILEPATH):
    """Set up module variables according to config dict.

    :param str config_filepath:
    """
    global AMQP_USERNAME, AMQP_PASSWORD, CLIENT, ORG_HREF, VDC_HREF, \
        CATALOG_NAME, DEV_MODE

    config = testutils.yaml_to_dict(config_filepath)
    CLIENT = Client(config['vcd']['host'],
                    api_version=config['vcd']['api_version'],
                    verify_ssl_certs=config['vcd']['verify'])
    credentials = BasicLoginCredentials(config['vcd']['username'],
                                        utils.SYSTEM_ORG_NAME,
                                        config['vcd']['password'])
    CLIENT.set_credentials(credentials)

    org = utils.get_org(CLIENT, org_name=config['broker']['org'])
    vdc = utils.get_vdc(CLIENT, config['broker']['vdc'], org=org)
    ORG_HREF = org.href
    VDC_HREF = vdc.href
    CATALOG_NAME = config['broker']['catalog']
    AMQP_USERNAME = config['amqp']['username']
    AMQP_PASSWORD = config['amqp']['password']

    try:
        DEV_MODE = config['test']['developer_mode']
    except KeyError:
        pass
Beispiel #5
0
def init_environment(config_filepath=BASE_CONFIG_FILEPATH):
    """Set up module variables according to config dict.

    :param str config_filepath:
    """
    global AMQP_USERNAME, AMQP_PASSWORD, CLIENT, ORG_HREF, VDC_HREF, \
        CATALOG_NAME, TEARDOWN_INSTALLATION, TEARDOWN_CLUSTERS, \
        TEMPLATE_DEFINITIONS, TEST_ALL_TEMPLATES, SYS_ADMIN_LOGIN_CMD, \
        ORG_ADMIN_LOGIN_CMD, VAPP_AUTHOR_LOGIN_CMD, USER_LOGIN_CMD_MAP

    config = testutils.yaml_to_dict(config_filepath)

    rtm = RemoteTemplateManager(
        config['broker']['remote_template_cookbook_url'])
    template_cookbook = rtm.get_remote_template_cookbook()
    TEMPLATE_DEFINITIONS = template_cookbook['templates']
    rtm.download_all_template_scripts(force_overwrite=True)

    CLIENT = Client(config['vcd']['host'],
                    api_version=config['vcd']['api_version'],
                    verify_ssl_certs=config['vcd']['verify'])
    credentials = BasicLoginCredentials(config['vcd']['username'],
                                        SYSTEM_ORG_NAME,
                                        config['vcd']['password'])
    CLIENT.set_credentials(credentials)

    org = pyvcloud_utils.get_org(CLIENT, org_name=config['broker']['org'])
    vdc = pyvcloud_utils.get_vdc(CLIENT,
                                 vdc_name=config['broker']['vdc'],
                                 org=org)
    ORG_HREF = org.href
    VDC_HREF = vdc.href
    CATALOG_NAME = config['broker']['catalog']
    AMQP_USERNAME = config['amqp']['username']
    AMQP_PASSWORD = config['amqp']['password']

    SYS_ADMIN_LOGIN_CMD = f"login {config['vcd']['host']} system " \
                          f"{config['vcd']['username']} " \
                          f"-iwp {config['vcd']['password']} " \
                          f"-V {config['vcd']['api_version']}"
    ORG_ADMIN_LOGIN_CMD = f"login {config['vcd']['host']} " \
                          f"{config['broker']['org']}" \
                          f" {ORG_ADMIN_NAME} -iwp {ORG_ADMIN_PASSWORD} " \
                          f"-V {config['vcd']['api_version']}"
    VAPP_AUTHOR_LOGIN_CMD = f"login {config['vcd']['host']} " \
                            f"{config['broker']['org']} " \
                            f"{VAPP_AUTHOR_NAME} -iwp {VAPP_AUTHOR_PASSWORD}" \
                            f" -V {config['vcd']['api_version']}"

    USER_LOGIN_CMD_MAP = {
        'sys_admin': SYS_ADMIN_LOGIN_CMD,
        'org_admin': ORG_ADMIN_LOGIN_CMD,
        'vapp_author': VAPP_AUTHOR_LOGIN_CMD
    }

    test_config = config.get('test')
    if test_config is not None:
        TEARDOWN_INSTALLATION = test_config.get('teardown_installation', True)
        TEARDOWN_CLUSTERS = test_config.get('teardown_clusters', True)
        TEST_ALL_TEMPLATES = test_config.get('test_all_templates', False)
Beispiel #6
0
    def create_client_instance(self):
        host = self._common['host']
        version = self._common['api_version']
        verify = self._common['verify_certs']
        password = self._common['password']
        username = self._common['username']
        org = self._common['org']

        if not org:
            raise VcdError('missing required org for service_type vcd')

        if not verify:
            requests.packages.urllib3.disable_warnings()
        if self._debug:
            self.debug('Logging vcloud calls to /tmp/ansible_pyvcloud.log')
            client = Client(host,
                            verify_ssl_certs=verify,
                            api_version=version,
                            log_file='/tmp/ansible_pyvcloud.log',
                            log_requests=True,
                            log_bodies=True,
                            log_headers=True)
        else:
            client = Client(host, verify_ssl_certs=verify, api_version=version)
        try:
            client.set_credentials(
                BasicLoginCredentials(user=username,
                                      org=org,
                                      password=password))
        except VcdErrorResponseException as e:
            raise VcdError('Login to VCD failed', msg=e.vcd_error)
        return client
Beispiel #7
0
def vcdlogin(host, user, password, org):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("login called")
    client = Client(host,
                    api_version="27.0",
                    verify_ssl_certs=False,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        client.set_credentials(BasicLoginCredentials(user, org, password))
        x = client._session.headers['x-vcloud-authorization']
        logging.info(" =====  X VCloud ========\n  \n" + x + "\n \n")

        #pRes= catalog.isPresent(client,"c1")

        #res=catalog.create(client,"c3","c2UPD")

        #logging.info(" is create ===== \n \n "+ str(res.created)+ "\n \n ")
        logging.info("\n\n=====callling upload ova===\n")
        catalog.upload_media(client,
                             "c3",
                             "/home/iso/vcains13.ova",
                             item_name="vc installer 1.3")
        logging.info("\n\n=====upload done ===\n ")
        #logging.info(" Delete  ===== \n \n "+ str(catalog.delete(client,"c3").deleted)+ "\n \n ")
        #logging.info(" Delete  ===== \n \n "+ str(catalog.delete(client,"c4").deleted)+ "\n \n ")

        return client
    except Exception as e:
        print('error occured', e)
Beispiel #8
0
def get_all_host(host, org, user, password, vdc):

    #Linux guest hosts
    linux_os_list = ['CentOS 7 (64-bit)', 'Ubuntu Linux (64-bit)', 'CentOS 8 (64-bit)']

    #Windows guest hosts
    win_os_list = ['Microsoft Windows Server 2016 or later (64-bit)', 'Microsoft Windows Server 2019 (64-bit)']

    #Host list of all Vapps
    host_list = {}


    client = Client(host,
                verify_ssl_certs=True,#SSL 
                log_requests=False,
                log_headers=False,
                log_bodies=False)
    client.set_highest_supported_version()
    client.set_credentials(BasicLoginCredentials(user, org, password))

    org_resource = client.get_org()
    org = Org(client, resource=org_resource)

    vdc_resource = org.get_vdc(vdc)
    vdc = VDC(client, resource=vdc_resource)

    vapps = vdc.list_resources()

    win_list = []
    linux_list = []
    other_os_list = []
    hostvars = {}
    for vapp in vapps:
        if vapp["type"] == "application/vnd.vmware.vcloud.vApp+xml":
            currentHref = vdc.get_vapp_href(vapp["name"])
            currentVapp = VApp(client, href=currentHref)
            for vm in currentVapp.get_all_vms():
                vmName = vm.get('name')
                vmOs = VM(client, resource=vm)
                vOs = vmOs.get_operating_system_section()
                try:
                    vmIp = currentVapp.get_primary_ip(vmName)
                except:
                    pass
                if vmOs.is_powered_on():
                    if vOs.Description in win_os_list:
                        win_list.append(vmName)
                        hostvars.update({vmName:{'ansible_host':vmIp}})
                    elif vOs.Description in linux_os_list:
                        linux_list.append(vmName)
                        hostvars.update({vmName:{'ansible_host':vmIp}})
                    else:
                        other_os_list.append(vmName)
                        hostvars.update({vmName:{'ansible_host':vmIp}})
                    host_list.update({'windows':{'hosts':win_list}})
                    host_list.update({'linux':{'hosts':linux_list}})
                    host_list.update({'others':{'hosts':other_os_list}})
                    host_list.update({'_meta':{'hostvars':hostvars}})
    return host_list
def _validate_vcd_config(
        vcd_dict,
        msg_update_callback=NullPrinter(),
        log_file=None,
        log_wire=False
):
    """Ensure that 'vcd' section of config is correct.

    Checks that
        * 'vcd' section of config has correct keys and value types.
        * vCD is accessible.

    :param dict vcd_dict: 'vcd' section of config file as a dict.
    :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 has missing
    :raises TypeError: if the value type for a @vcd_dict is incorrect.
    """
    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']})"
        )
    finally:
        if client is not None:
            client.logout()
Beispiel #10
0
class VcdAnsibleModule(AnsibleModule):
    def __init__(self, *args, **kwargs):
        argument_spec = vcd_argument_spec()
        argument_spec.update(kwargs.get('argument_spec', dict()))
        kwargs['argument_spec'] = argument_spec

        super(VcdAnsibleModule, self).__init__(*args, **kwargs)
        self.login()

    def login(self):
        try:
            user = self.params.get('user')
            password = self.params.get('password')
            org = self.params.get('org')
            host = self.params.get('host')
            api_version = self.params.get('api_version')
            verify_ssl_certs = self.params.get('verify_ssl_certs')

            # giving more precedence to module level details
            user = user if user else os.environ['env_user']
            password = password if password else os.environ['env_password']
            host = host if host else os.environ['env_host']
            org = org if org else os.environ['env_org']
            api_version = api_version if api_version else os.environ[
                'env_api_version']
            verify_ssl_certs = verify_ssl_certs if verify_ssl_certs else os.environ[
                'env_verify_ssl_certs']
            verify_ssl_certs = False if verify_ssl_certs == "False" else True

            self.client = Client(host,
                                 api_version=api_version,
                                 verify_ssl_certs=verify_ssl_certs)

            self.client.set_credentials(
                BasicLoginCredentials(user, org, password))

        except Exception as error:
            error = 'Login failed for user {} to org {}'
            raise VCDLoginError(error.format(user, org))

    def execute_task(self, task):
        task_monitor = self.client.get_task_monitor()
        task_state = task_monitor.wait_for_status(task=task,
                                                  timeout=60,
                                                  poll_frequency=2,
                                                  fail_on_statuses=None,
                                                  expected_target_statuses=[
                                                      TaskStatus.SUCCESS,
                                                      TaskStatus.ABORTED,
                                                      TaskStatus.ERROR,
                                                      TaskStatus.CANCELED
                                                  ],
                                                  callback=None)

        task_status = task_state.get('status')
        if task_status != TaskStatus.SUCCESS.value:
            raise Exception(etree.tostring(task_state, pretty_print=True))

        return 1
Beispiel #11
0
def get_telemetry_instance_id(vcd_host: str,
                              vcd_username: str,
                              vcd_password: str,
                              verify_ssl: bool,
                              is_mqtt_exchange: bool,
                              logger_debug=NULL_LOGGER,
                              msg_update_callback=NullPrinter()):
    """Get CSE AMQP or MQTT extension id which is used as instance id.

    Any exception is logged as error. No exception is leaked out
    of this method and does not affect the server startup.

    :param str vcd_host:
    :param str vcd_username:
    :param str vcd_password:
    :param bool verify_ssl:
    :param bool is_mqtt_exchange:
    :param logging.logger logger_debug: logger instance to log any error
    in retrieving CSE extension id.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object.

    :return instance id to use for sending data to Vmware telemetry server

    :rtype str (unless no instance id found)
    """
    client = None
    try:
        client = Client(vcd_host, verify_ssl_certs=verify_ssl)
        client.set_credentials(
            BasicLoginCredentials(vcd_username, SYSTEM_ORG_NAME, vcd_password))
        if is_mqtt_exchange:
            # Get MQTT extension uuid
            mqtt_ext_manager = MQTTExtensionManager(client)
            ext_info = mqtt_ext_manager.get_extension_info(
                ext_name=CSE_SERVICE_NAME,
                ext_version=MQTT_EXTENSION_VERSION,
                ext_vendor=MQTT_EXTENSION_VENDOR)
            if not ext_info:
                logger_debug.debug("Failed to retrieve telemetry instance id")
                return None
            logger_debug.debug("Retrieved telemetry instance id")
            return mqtt_ext_manager.get_extension_uuid(
                ext_info[MQTTExtKey.EXT_URN_ID])
        else:
            # Get AMQP extension id
            ext = APIExtension(client)
            cse_info = ext.get_extension_info(CSE_SERVICE_NAME,
                                              namespace=CSE_SERVICE_NAMESPACE)
            logger_debug.debug("Retrieved telemetry instance id")
            return cse_info.get('id')
    except Exception as err:
        msg = f"Cannot retrieve telemetry instance id:{err}"
        msg_update_callback.general(msg)
        logger_debug.error(msg, exc_info=True)
    finally:
        if client is not None:
            client.logout()
Beispiel #12
0
def login(user, org, password):
    requests.packages.urllib3.disable_warnings()
    client = Client(host,
                    api_version='29.0',
                    verify_ssl_certs=False,
                    log_file='pyvcloud.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    client.set_credentials(BasicLoginCredentials(user, org, password))
    return client
def check_config(config_file_name, template='*'):
    click.secho('Validating CSE on vCD from file: %s' % config_file_name)
    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()

    v = VSphere(
        config['vcs']['host'],
        config['vcs']['username'],
        config['vcs']['password'],
        port=int(config['vcs']['port']))
    v.connect()
    click.echo('Connected to vCenter Server as %s '
               '(%s:%s): %s' % (config['vcs']['username'],
                                config['vcs']['host'], config['vcs']['port'],
                                bool_to_msg(True)))

    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.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)))
    click.secho('Validating \'%s\' service broker' % config['broker']['type'])
    if config['broker']['type'] == 'default':
        validate_broker_config_content(config, client, template)

    return config
def get_vsphere(config, vapp, vm_name, logger=None):
    """Get the VSphere object for a specific VM inside a VApp.

    :param dict config: CSE config as a dictionary
    :param pyvcloud.vcd.vapp.VApp vapp: VApp used to get the VM ID.
    :param str vm_name:
    :param logging.Logger logger: optional logger to log with.

    :return: VSphere object for a specific VM inside a VApp

    :rtype: vsphere_guest_run.vsphere.VSphere
    """
    global cache

    # get vm id from vm resource
    vm_id = vapp.get_vm(vm_name).get('id')
    if vm_id not in cache:
        client = Client(uri=config['vcd']['host'],
                        api_version=config['vcd']['api_version'],
                        verify_ssl_certs=config['vcd']['verify'],
                        log_headers=True,
                        log_bodies=True)
        credentials = BasicLoginCredentials(config['vcd']['username'],
                                            SYSTEM_ORG_NAME,
                                            config['vcd']['password'])
        client.set_credentials(credentials)

        # must recreate vapp, or cluster creation fails
        vapp = VApp(client, href=vapp.href)
        vm_resource = vapp.get_vm(vm_name)
        vm_sys = VM(client, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(client)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'port': vcenter_url.port
        }
        for vc in config['vcs']:
            if vc['name'] == vcenter_name:
                cache_item['username'] = vc['username']
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item

    if logger:
        logger.debug(f"VM ID: {vm_id}, Hostname: {cache[vm_id]['hostname']}")

    return VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                   cache[vm_id]['password'], cache[vm_id]['port'])
def read_native_template_definition_from_catalog(
        config: ServerConfig,
        msg_update_callback=utils.NullPrinter()
):
    # NOTE: If `enable_tkg_plus` in the config file is set to false,
    # CSE server will skip loading the TKG+ template this will prevent
    # users from performing TKG+ related operations.
    msg = "Loading k8s template definition from catalog"
    logger.SERVER_LOGGER.info(msg)
    msg_update_callback.general_no_color(msg)

    client = None
    try:
        log_filename = None
        log_wire = \
            utils.str_to_bool(config.get_value_at('service.log_wire'))
        if log_wire:
            log_filename = logger.SERVER_DEBUG_WIRELOG_FILEPATH

        client = Client(
            uri=config.get_value_at('vcd.host'),
            api_version=config.get_value_at('service.default_api_version'),  # noqa: E501
            verify_ssl_certs=config.get_value_at('vcd.verify'),
            log_file=log_filename,
            log_requests=log_wire,
            log_headers=log_wire,
            log_bodies=log_wire
        )
        credentials = BasicLoginCredentials(
            config.get_value_at('vcd.username'),
            shared_constants.SYSTEM_ORG_NAME,
            config.get_value_at('vcd.password')
        )
        client.set_credentials(credentials)

        legacy_mode = config.get_value_at('service.legacy_mode')
        org_name = config.get_value_at('broker.org')
        catalog_name = config.get_value_at('broker.catalog')

        k8_templates = ltm.get_valid_k8s_local_template_definition(
            client=client, catalog_name=catalog_name, org_name=org_name,
            legacy_mode=legacy_mode,
            is_tkg_plus_enabled=server_utils.is_tkg_plus_enabled(config),
            logger_debug=logger.SERVER_LOGGER,
            msg_update_callback=msg_update_callback)

        return k8_templates
    finally:
        if client:
            client.logout()
def read_tkgm_template_definition_from_catalog(
        config: ServerConfig,
        msg_update_callback=utils.NullPrinter()
):
    msg = "Loading TKGm template definition from catalog"
    logger.SERVER_LOGGER.info(msg)
    msg_update_callback.general_no_color(msg)

    client = None
    try:
        log_filename = None
        log_wire = utils.str_to_bool(
            config.get_value_at('service.log_wire')
        )
        if log_wire:
            log_filename = logger.SERVER_DEBUG_WIRELOG_FILEPATH

        client = Client(
            uri=config.get_value_at('vcd.host'),
            api_version=config.get_value_at('service.default_api_version'),  # noqa: E501
            verify_ssl_certs=config.get_value_at('vcd.verify'),
            log_file=log_filename,
            log_requests=log_wire,
            log_headers=log_wire,
            log_bodies=log_wire
        )
        credentials = BasicLoginCredentials(
            config.get_value_at('vcd.username'),
            shared_constants.SYSTEM_ORG_NAME,
            config.get_value_at('vcd.password')
        )
        client.set_credentials(credentials)

        org_name = config.get_value_at('broker.org')
        catalog_name = config.get_value_at('broker.catalog')

        tkgm_templates = ttm.read_all_tkgm_template(
            client=client,
            org_name=org_name,
            catalog_name=catalog_name,
            logger=logger.SERVER_LOGGER,
            msg_update_callback=msg_update_callback
        )

        return tkgm_templates
    finally:
        if client:
            client.logout()
Beispiel #17
0
def vcd_login(host, user, password, org):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("login called")
    client = Client(host,
                    api_version="27.0",
                    verify_ssl_certs=False,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        client.set_credentials(BasicLoginCredentials(user, org, password))

        return client
    except Exception as e:
        print('error occured', e)
Beispiel #18
0
class VcdAnsibleModule(AnsibleModule):
    def __init__(self, *args, **kwargs):
        argument_spec = vcd_argument_spec()
        argument_spec.update(kwargs.get('argument_spec', dict()))
        kwargs['argument_spec'] = argument_spec

        super(VcdAnsibleModule, self).__init__(*args, **kwargs)
        self.login()

    def login(self):
        try:
            user = self.params.get('user')
            password = self.params.get('password')
            org = self.params.get('org')
            host = self.params.get('host')
            api_version = self.params.get('api_version')
            verify_ssl_certs = self.params.get('verify_ssl_certs')
            self.client = Client(host,
                                 api_version=api_version,
                                 verify_ssl_certs=verify_ssl_certs)

            self.client.set_credentials(
                BasicLoginCredentials(user, org, password))

        except Exception as error:
            self.fail_json(
                msg='Login failed for user {} to org {}'.format(user, org))

    def execute_task(self, task):
        task_monitor = self.client.get_task_monitor()
        task_state = task_monitor.wait_for_status(task=task,
                                                  timeout=60,
                                                  poll_frequency=2,
                                                  fail_on_statuses=None,
                                                  expected_target_statuses=[
                                                      TaskStatus.SUCCESS,
                                                      TaskStatus.ABORTED,
                                                      TaskStatus.ERROR,
                                                      TaskStatus.CANCELED
                                                  ],
                                                  callback=None)

        task_status = task_state.get('status')
        if task_status != TaskStatus.SUCCESS.value:
            raise Exception(etree.tostring(task_state, pretty_print=True))

        return 1
def get_telemetry_instance_id(config_dict, logger_debug=NULL_LOGGER,
                              msg_update_callback=NullPrinter()):
    """Get CSE AMQP or MQTT extension id which is used as instance id.

    Any exception is logged as error. No exception is leaked out
    of this method and does not affect the server startup.

    :param dict config_dict: CSE configuration
    :param logging.logger logger_debug: logger instance to log any error
    in retrieving CSE extension id.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object.

    :return instance id to use for sending data to Vmware telemetry server

    :rtype str (unless no instance id found)
    """
    vcd = config_dict['vcd']
    try:
        client = Client(vcd['host'], api_version=vcd['api_version'],
                        verify_ssl_certs=vcd['verify'])
        client.set_credentials(BasicLoginCredentials(
            vcd['username'], SYSTEM_ORG_NAME, vcd['password']))
        if should_use_mqtt_protocol(config_dict):
            # Get MQTT extension uuid
            mqtt_ext_manager = MQTTExtensionManager(client)
            ext_info = mqtt_ext_manager.get_extension_info(
                ext_name=CSE_SERVICE_NAME,
                ext_version=MQTT_EXTENSION_VERSION,
                ext_vendor=MQTT_EXTENSION_VENDOR)
            if not ext_info:
                return None
            return mqtt_ext_manager.get_extension_uuid(
                ext_info[MQTTExtKey.EXT_URN_ID])
        else:
            # Get AMQP extension id
            ext = APIExtension(client)
            cse_info = ext.get_extension_info(CSE_SERVICE_NAME,
                                              namespace=CSE_SERVICE_NAMESPACE)
            logger_debug.info("Retrieved telemetry instance id")
            return cse_info.get('id')
    except Exception as err:
        msg = f"Cannot retrieve telemetry instance id:{err}"
        msg_update_callback.general(msg)
        logger_debug.error(msg)
    finally:
        if client is not None:
            client.logout()
def get_vsphere(config, vapp, vm_name):
    """Get the VSphere object for a specific VM inside a VApp.

    :param dict config: CSE config as a dictionary
    :param pyvcloud.vcd.vapp.VApp vapp:
    :param str vm_name:

    :return: VSphere object for a specific VM inside a VApp

    :rtype: vsphere_guest_run.vsphere.VSphere
    """
    global cache
    vm_resource = vapp.get_vm(vm_name)
    vm_id = vm_resource.get('id')
    if vm_id not in cache:
        client = Client(uri=config['vcd']['host'],
                        api_version=config['vcd']['api_version'],
                        verify_ssl_certs=config['vcd']['verify'],
                        log_headers=True,
                        log_bodies=True)
        credentials = BasicLoginCredentials(config['vcd']['username'],
                                            SYSTEM_ORG_NAME,
                                            config['vcd']['password'])
        client.set_credentials(credentials)

        vm_sys = VM(client, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(client)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'port': vcenter_url.port
        }
        for vc in config['vcs']:
            if vc['name'] == vcenter_name:
                cache_item['username'] = vc['username']
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item
    else:
        LOGGER.debug(f"vCenter retrieved from cache\nVM ID: {vm_id}"
                     f"\nHostname: {cache[vm_id]['hostname']}")

    return VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                   cache[vm_id]['password'], cache[vm_id]['port'])
Beispiel #21
0
    def connect(self):
        """ Method connect as normal user to vCloud director.

            Returns:
                The return vca object that letter can be used to connect to vCloud director as admin for VDC
        """

        try:
            self.logger.debug("Logging in to a vcd {} as user {}".format(self.org,
                                                                         self.user))
            client = Client(self.url, verify_ssl_certs=False)
            client.set_credentials(BasicLoginCredentials(self.user, self.org, self.password))
        except Exception:
            raise Exception("Can't connect to a vCloud director org: "
                            "{} as user: {}".format(self.org, self.user))

        return client
def vcd_login(host, user, password, org):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("login called")
    client = Client(
        host,
        api_version="27.0",
        verify_ssl_certs=False,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        client.set_credentials(BasicLoginCredentials(user, org, password))

        return client
    except Exception as e:
        print('error occured', e)
class VcdAnsibleModule(AnsibleModule):
    def __init__(self, *args, **kwargs):
        argument_spec = vcd_argument_spec()
        argument_spec.update(kwargs.get('argument_spec', dict()))
        kwargs['argument_spec'] = argument_spec

        super(VcdAnsibleModule, self).__init__(*args, **kwargs)
        self.login()

    def login(self):
        try:
            user = self.params.get('user')
            password = self.params.get('password')
            org = self.params.get('org')
            host = self.params.get('host')
            api_version = self.params.get('api_version')
            verify_ssl_certs = self.params.get('verify_ssl_certs')
            self.client = Client(host,
                                 api_version=api_version,
                                 verify_ssl_certs=verify_ssl_certs)

            self.client.set_credentials(BasicLoginCredentials(user, org, password))

        except Exception as error:
            error = 'Login failed for user {} to org {}'
            raise VCDLoginError(error.format(user, org))

    def execute_task(self, task):
        task_monitor = self.client.get_task_monitor()
        task_state = task_monitor.wait_for_status(
            task=task,
            timeout=60,
            poll_frequency=2,
            fail_on_statuses=None,
            expected_target_statuses=[
                TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR,
                TaskStatus.CANCELED
            ],
            callback=None)

        task_status = task_state.get('status')
        if task_status != TaskStatus.SUCCESS.value:
            raise Exception(etree.tostring(task_state, pretty_print=True))

        return 1
Beispiel #24
0
def vcdlogin(host, user, password, org):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("login called")
    client = Client(host,
                    api_version="27.0",
                    verify_ssl_certs=False,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        client.set_credentials(BasicLoginCredentials(user, org, password))
        x = client._session.headers['x-vcloud-authorization']
        logging.info("X VCloud " + x)
        #       catalog.create(client,"c2","c2desc")
        return client
    except Exception as e:
        print('error occured', e)
def get_sys_admin_client():
    server_config = get_server_runtime_config()
    if not server_config['vcd']['verify']:
        LOGGER.warning("InsecureRequestWarning: Unverified HTTPS "
                       "request is being made. Adding certificate "
                       "verification is strongly advised.")
        requests.packages.urllib3.disable_warnings()
    client = Client(uri=server_config['vcd']['host'],
                    api_version=server_config['vcd']['api_version'],
                    verify_ssl_certs=server_config['vcd']['verify'],
                    log_file=SERVER_DEBUG_WIRELOG_FILEPATH,
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    credentials = BasicLoginCredentials(server_config['vcd']['username'],
                                        SYSTEM_ORG_NAME,
                                        server_config['vcd']['password'])
    client.set_credentials(credentials)
    return client
Beispiel #26
0
def get_telemetry_instance_id(vcd,
                              logger_instance=None,
                              msg_update_callback=None):
    """Get CSE extension id which is used as instance id.

    Any exception is logged as error. No exception is leaked out
    of this method and does not affect the server startup.

    :param dict vcd: 'vcd' section of config file as a dict.
    :param logging.logger logger_instance: logger instance to log any error
    in retrieving CSE extension id.
    :param utils.ConsoleMessagePrinter msg_update_callback: Callback object
    that writes messages onto console.

    :return instance id to use for sending data to Vmware telemetry server

    :rtype str

    :raises Exception: if any exception happens while retrieving CSE
    extension id
    """
    try:
        client = Client(vcd['host'],
                        api_version=vcd['api_version'],
                        verify_ssl_certs=vcd['verify'])
        client.set_credentials(
            BasicLoginCredentials(vcd['username'], SYSTEM_ORG_NAME,
                                  vcd['password']))
        ext = APIExtension(client)
        cse_info = ext.get_extension_info(CSE_SERVICE_NAME,
                                          namespace=CSE_SERVICE_NAMESPACE)
        if logger_instance:
            logger_instance.info("Retrieved telemetry instance id")
        return cse_info.get('id')
    except Exception as err:
        msg = f"Cannot retrieve telemetry instance id:{err}"
        if msg_update_callback:
            msg_update_callback.general(msg)
        if logger_instance:
            logger_instance.error(msg)
    finally:
        if client is not None:
            client.logout()
def uninstall_cse(ctx, config_file_name, template_name):
    click.secho('Uninstalling CSE from vCD from file: %s, template: %s' %
                (config_file_name, template_name))
    config = get_config(config_file_name)
    client = Client(
        config['vcd']['host'],
        api_version=config['vcd']['api_version'],
        verify_ssl_certs=config['vcd']['verify'],
        log_file='cse.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)))
    ctx.obj = {}
    ctx.obj['client'] = client
    if config['broker']['type'] == 'default':
        ctx.obj = {}
        ctx.obj['client'] = client
        orgs = client.get_org_list()
        for org in [o for o in orgs.Org if hasattr(orgs, 'Org')]:
            if org.get('name') == config['broker']['org']:
                org_href = org.get('href')
        org = Org(client, href=org_href)
        click.echo('Find org \'%s\': %s' % (org.get_name(), bool_to_msg(True)))
        vdc_resource = org.get_vdc(config['broker']['vdc'])
        click.echo('Find vdc \'%s\': %s' % (vdc_resource.get('name'),
                                            bool_to_msg(True)))
        vdc = VDC(client, resource=vdc_resource)
        assert vdc
        for template in config['broker']['templates']:
            if template_name == '*' or template['name'] == template_name:
                click.secho('Deleting template: %s (%s:%s)' %
                            (template['name'], config['broker']['catalog'],
                             template['catalog_item']))
                org.delete_catalog_item(config['broker']['catalog'],
                                        template['catalog_item'])
Beispiel #28
0
def login_as_system_admin():
    """Create and returns a new session with the service account for the proxy.

    Returns:
        pyvcloud.vcd.client.Client: Session as service account.
    """
    client = Client(conf('global.vcloud.hostname'),
                    api_version=conf('global.vcloud.api_version'),
                    verify_ssl_certs=conf('global.vcloud.ssl_verify', True),
                    log_file=conf("global.pyvcloud.log_file"),
                    log_requests=conf("global.pyvcloud.log_requests"),
                    log_headers=conf("global.pyvcloud.log_headers"),
                    log_bodies=conf("global.pyvcloud.log_bodies"))
    credentials = BasicLoginCredentials(conf('global.vcloud.username'),
                                        conf('global.vcloud.system_org'),
                                        conf('global.vcloud.password'))
    client.set_credentials(credentials)
    logger.info(
        f"Connected to vCD as system administrator: {conf('global.vcloud.hostname')}"
    )
    return client
def get_vsphere(config, vapp, vm_name):
    global cache
    vm_resource = vapp.get_vm(vm_name)
    vm_id = vm_resource.get('id')
    if vm_id not in cache:
        client_sysadmin = Client(uri=config['vcd']['host'],
                                 api_version=config['vcd']['api_version'],
                                 verify_ssl_certs=config['vcd']['verify'],
                                 log_headers=True,
                                 log_bodies=True)
        client_sysadmin.set_credentials(
            BasicLoginCredentials(config['vcd']['username'], 'System',
                                  config['vcd']['password']))

        vapp_sys = VApp(client_sysadmin, href=vapp.href)
        vm_resource = vapp_sys.get_vm(vm_name)
        vm_sys = VM(client_sysadmin, resource=vm_resource)
        vcenter_name = vm_sys.get_vc()
        platform = Platform(client_sysadmin)
        vcenter = platform.get_vcenter(vcenter_name)
        vcenter_url = urlparse(vcenter.Url.text)
        cache_item = {
            'hostname': vcenter_url.hostname,
            'username': vcenter.Username.text,
            'port': vcenter_url.port
        }
        for vc in config['vcs']:
            if vc['name'] == vcenter_name:
                cache_item['password'] = vc['password']
                break
        cache[vm_id] = cache_item
    else:
        LOGGER.debug('vCenter retrieved from cache: %s / %s' %
                     (vm_id, cache[vm_id]['hostname']))

    v = VSphere(cache[vm_id]['hostname'], cache[vm_id]['username'],
                cache[vm_id]['password'], cache[vm_id]['port'])

    return v
def login(session_id=None):
    log_requests = True if config['log'] == True else False
    log_headers = True if config['log'] == True else False
    log_bodies = True if config['log'] == True else False

    client = Client(config['host'],
                    api_version=config['api_version'],
                    verify_ssl_certs=config['verify_ssl_certs'],
                    log_file=config['log_file'],
                    log_requests=log_requests,
                    log_headers=log_headers,
                    log_bodies=log_bodies)

    if not config['verify_ssl_certs']:
        requests.packages.urllib3.disable_warnings()

    try:
        if session_id is not None:
            client.rehydrate_from_token(session_id)
        else:
            client.set_credentials(
                BasicLoginCredentials(config['username'], config['org'],
                                      config['password']))

        logged_in_org = client.get_org()
        org = Org(client, resource=logged_in_org)
        org_url = "https://%s/cloud/org/%s" % (config['host'], logged_in_org)
        the_vdc = org.get_vdc(config['vdc'])

        # Set contextual data:
        ctx.client = client
        ctx.vdc = VDC(client, href=the_vdc.get('href'))
        ctx.token = client._session.headers['x-vcloud-authorization']
    except Exception as e:
        if config['debug'] == True:
            print("Exception: {}\n".format(e))
        return False
    return True
def vcd_login(context, lc):
    logging.info("__INIT__vcd_login [%s]", lc)
    login_path = ""
    client = Client(
        lc.ip,
        api_version="27.0",
        verify_ssl_certs=not lc.allow_insecure_flag,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        if lc.use_vcd_cli_profile:
            login_path = "rehydrate_from_token"
            profiles = Profiles.load()
            token = profiles.get('token')
            client.rehydrate_from_token(token)

        else:
            login_path = "set_credentials"
            client.set_credentials(
                BasicLoginCredentials(lc.username, lc.org, lc.password))

        vref = VCDClientRef()
        vref.set_ref(client)
        logging.debug('LOGIN VIA :[{0}] ARG :[{1}]'.format(
            login_path, str(lc)))

        return client
    except Exception as e:
        traceback.print_exc()
        error_message = 'ERROR IN LOGIN .. Exception [{0}] LOGIN VIA :[{1}] ARG :[{2}]'.format(
            str(e), login_path, str(lc))
        error_message = error_message.replace('\n', ' ')
        context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
        context.set_details(error_message)
        raise
Beispiel #32
0
def vcd_login(context, lc):
    logging.info("__INIT__vcd_login [%s]", lc)
    login_path = ""
    client = Client(lc.ip,
                    api_version="27.0",
                    verify_ssl_certs=not lc.allow_insecure_flag,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        if lc.use_vcd_cli_profile:
            login_path = "rehydrate_from_token"
            profiles = Profiles.load()
            token = profiles.get('token')
            client.rehydrate_from_token(token)

        else:
            login_path = "set_credentials"
            client.set_credentials(
                BasicLoginCredentials(lc.username, lc.org, lc.password))

        vref = VCDClientRef()
        vref.set_ref(client)
        logging.debug('LOGIN VIA :[{0}] ARG :[{1}]'.format(
            login_path, str(lc)))

        return client
    except Exception as e:
        traceback.print_exc()
        error_message = 'ERROR IN LOGIN .. Exception [{0}] LOGIN VIA :[{1}] ARG :[{2}]'.format(
            str(e), login_path, str(lc))
        error_message = error_message.replace('\n', ' ')
        context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
        context.set_details(error_message)
        raise
Beispiel #33
0
def Authenticate(parameters):
    """
  Authenenticate with vCloud Director
  """
    try:
        print("INFO: Authenticating With vCloud Director")

        client = Client(parameters['VCD_HOST'],
                        api_version=parameters['VCD_API_VERSION'],
                        verify_ssl_certs=parameters['VCD_SSL_VERIFY'],
                        log_file='pyvcloud.log',
                        log_requests=True,
                        log_headers=True,
                        log_bodies=True)
        client.set_credentials(
            BasicLoginCredentials(parameters['VCD_USER'],
                                  parameters['VCD_ORG'],
                                  parameters['VCD_PASSWORD']))
        return client

    except Exception as e:
        print("ERROR: Failed To Authenticate With vCloud Director")
        print(e)
        exit(1)
def vcd_login(host, user, password, org):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("login called")
    client = Client(
        host,
        api_version="27.0",
        verify_ssl_certs=False,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        client.set_credentials(BasicLoginCredentials(user, org, password))
        x = client._session.headers['x-vcloud-authorization']
        logging.info(" =====  X VCloud ========\n  \n" + x + "\n \n")

        logged_in_org = client.get_org()
        org = Org(client, resource=logged_in_org)
        v = org.get_vdc('OVD2')
        vdc = VDC(client, href=v.get('href'))
        vapp = vdc.get_vapp('cento_vapp11_2')
        nconfig_section = vapp.NetworkConfigSection
        nconfig = nconfig_section.findall(
            "{http://www.vmware.com/vcloud/v1.5}NetworkConfig")
        for i in range(0, len(nconfig)):
            print(nconfig[i].get('networkName'))

        ##print(etree.tostring(nconfig[0], pretty_print=True))

        #pRes= catalog.isPresent(client,"c1")
        # res=catalog.create(client,"c44","c44",True)

        #logging.info(" is create ===== \n \n "+ str(res.created)+ "\n \n ")
        #logging.info("\n\n=====callling upload ova===\n")
        #catalog_item.upload_ova(client,"c44","/home/iso/tiny.ova",item_name="tiny3.ova")
        #logging.info("\n\n=====upload done ===\n ")
        #logging.info(" Delete  ===== \n \n "+ str(catalog.delete(client,"c3").deleted)+ "\n \n ")
        #logging.info(" Delete  ===== \n \n "+ str(catalog.delete(client,"c4").deleted)+ "\n \n ")

        #vappInfo=pyvcloudprovider_pb2.CreateVAppInfo()
        #vappInfo.name="vappacc2"
        #vappInfo.catalog_name="c1"
        #vappInfo.template_name="cento_tmpl1"
        #vapp.create(client,vappInfo)

        #delVappInfo=pyvcloudprovider_pb2.DeleteVAppInfo()
        #delVappInfo.name="vappacc2"

        #vapp.delete(client,delVappInfo)
        #ovaInfo=pyvcloudprovider_pb2.CatalogUploadOvaInfo()
        #ovaInfo.item_name="item1"
        #ovaInfo.catalog_name="testcata1"
        #ovaInfo.file_path="/Users/srinarayana/vmws/tiny.ova"

        # catalog_item.ova_check_resolved(client,ovaInfo)

        #vappInfo.template_name="cento_tmpl1"
        #vapp.create(client,vappInfo)
        return client
    except Exception as e:
        print('error occured', e)
Beispiel #35
0
def login(ctx, user, host, password, api_version, org, verify_ssl_certs,
          disable_warnings, vdc, session_id, use_browser_session):
    """Login to vCloud Director

\b
    Login to a vCloud Director service.
\b
    Examples
        vcd login mysp.com org1 usr1
            Login to host 'mysp.com'.
\b
        vcd login test.mysp.com org1 usr1 -i -w
            Login to a host with self-signed SSL certificate.
\b
        vcd login mysp.com org1 usr1 --use-browser-session
            Login using active session from browser.
\b
        vcd login session list chrome
            List active session ids from browser.
\b
        vcd login mysp.com org1 usr1 \\
            --session-id ee968665bf3412d581bbc6192508eec4
            Login using active session id.
\b
    Environment Variables
        VCD_PASSWORD
            If this environment variable is set, the command will use its value
            as the password to login and will not ask for one. The --password
            option has precedence over the environment variable.

    """

    if not verify_ssl_certs:
        if disable_warnings:
            pass
        else:
            click.secho(
                'InsecureRequestWarning: '
                'Unverified HTTPS request is being made. '
                'Adding certificate verification is strongly '
                'advised.',
                fg='yellow',
                err=True)
        requests.packages.urllib3.disable_warnings()
    if host == 'session' and org == 'list':
        sessions = []
        if user == 'chrome':
            cookies = browsercookie.chrome()
            for c in cookies:
                if c.name == 'vcloud_session_id':
                    sessions.append({'host': c.domain, 'session_id': c.value})
        stdout(sessions, ctx)
        return

    client = Client(
        host,
        api_version=api_version,
        verify_ssl_certs=verify_ssl_certs,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        if api_version is None:
            api_version = client.set_highest_supported_version()

        if session_id is not None or use_browser_session:
            if use_browser_session:
                browser_session_id = None
                cookies = browsercookie.chrome()
                for c in cookies:
                    if c.name == 'vcloud_session_id' and \
                       c.domain == host:
                        browser_session_id = c.value
                        break
                if browser_session_id is None:
                    raise Exception('Session not found in browser.')
                session_id = browser_session_id
            client.rehydrate_from_token(session_id)
        else:
            if password is None:
                password = click.prompt('Password', hide_input=True, type=str)
            client.set_credentials(BasicLoginCredentials(user, org, password))
        wkep = {}
        for endpoint in _WellKnownEndpoint:
            if endpoint in client._session_endpoints:
                wkep[endpoint.name] = client._session_endpoints[endpoint]
        profiles = Profiles.load()
        logged_in_org = client.get_org()
        org_href = logged_in_org.get('href')
        vdc_href = ''
        in_use_vdc = ''
        if vdc is None:
            for v in get_links(logged_in_org, media_type=EntityType.VDC.value):
                in_use_vdc = v.name
                vdc_href = v.href
                break
        else:
            for v in get_links(logged_in_org, media_type=EntityType.VDC.value):
                if vdc == v.name:
                    in_use_vdc = v.name
                    vdc_href = v.href
                    break
            if len(in_use_vdc) == 0:
                raise Exception('VDC not found')
        profiles.update(
            host,
            org,
            user,
            client._session.headers['x-vcloud-authorization'],
            api_version,
            wkep,
            verify_ssl_certs,
            disable_warnings,
            vdc=in_use_vdc,
            org_href=org_href,
            vdc_href=vdc_href,
            log_request=True,
            log_header=True,
            log_body=True,
            vapp='',
            vapp_href='')
        alt_text = '%s logged in, org: \'%s\', vdc: \'%s\'' % \
                   (user, org, in_use_vdc)
        stdout({
            'user': user,
            'org': org,
            'vdc': in_use_vdc,
            'logged_in': True
        }, ctx, alt_text)
    except Exception as e:
        try:
            profiles = Profiles.load()
            profiles.set('token', '')
        except Exception:
            pass
        stderr(e, ctx)
Beispiel #36
0
    sys.exit(1)
vcd_host = sys.argv[1]
org = sys.argv[2]
user = sys.argv[3]
password = sys.argv[4]

# Disable warnings from self-signed certificates.
requests.packages.urllib3.disable_warnings()

# Login. SSL certificate verification is turned off to allow self-signed
# certificates.  You should only do this in trusted environments.
print("Logging in: host={0}, org={1}, user={2}".format(vcd_host, org, user))
client = Client(vcd_host,
                api_version='29.0',
                verify_ssl_certs=False,
                log_file='pyvcloud.log',
                log_requests=True,
                log_headers=True,
                log_bodies=True)
client.set_credentials(BasicLoginCredentials(user, org, password))

print("Fetching vCD installation info...")
results = client.get_resource(
    client._session_endpoints[_WellKnownEndpoint.ADMIN])
for k, v in results.items():
    print("Key: {0} Value: {1}".format(k, v))

# Log out.
print("Logging out")
client.logout()
#!/usr/bin/env python3

import os
from pyvcloud.vcd.client import BasicLoginCredentials
from pyvcloud.vcd.client import Client
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.org import Org
from pyvcloud.vcd.vdc import VDC
import requests

requests.packages.urllib3.disable_warnings()

client = Client('bos1-vcd-sp-static-202-34.eng.vmware.com',
                verify_ssl_certs=False)
client.set_highest_supported_version()
client.set_credentials(BasicLoginCredentials('usr1', 'org1', 'ca$hc0w'))

org = Org(client, resource=client.get_org())
vdc = VDC(client, resource=org.get_vdc('vdc1'))

for resource in vdc.list_resources():
    print('%s%s' % (resource['name'].ljust(40),
                    resource['type']))

client.logout()
Beispiel #38
0
    config_dict = yaml.safe_load(config_file)
    cfg = namedtuple('ConfigObject', config_dict.keys())(**config_dict)

# Disable warnings from self-signed certificates.
requests.packages.urllib3.disable_warnings()

# Login. SSL certificate verification is turned off to allow self-signed
# certificates.  You should only do this in trusted environments.
print("Logging in...")
client = Client(cfg.vcd_host, verify_ssl_certs=False,
                log_file='pyvcloud.log',
                log_requests=True,
                log_headers=True,
                log_bodies=True)
client.set_highest_supported_version()
client.set_credentials(BasicLoginCredentials(cfg.vcd_admin_user,
                       "System", cfg.vcd_admin_password))

# Ensure the org exists.
print("Fetching org...")
try:
    # This call gets a record that we can turn into an Org class.
    org_record = client.get_org_by_name(cfg.org)
    org = Org(client, href=org_record.get('href'))
    print("Org already exists: {0}".format(org.get_name()))
except Exception:
    print("Org does not exist, creating: {0}".format(cfg.org))
    sys_admin_resource = client.get_admin()
    system = System(client, admin_resource=sys_admin_resource)
    admin_org_resource = system.create_org(cfg.org, "Test Org", True)
    org_record = client.get_org_by_name(cfg.org)
    org = Org(client, href=org_record.get('href'))