コード例 #1
0
def logout(stub_config):
    """
    Delete session with vCenter.
    """
    if stub_config:
        session_svc = Session(stub_config)
        session_svc.delete()
コード例 #2
0
ファイル: service_manager.py プロジェクト: kedr275/jk-2
class ServiceManager(object):
    """
    Manages all the services on a management node.
    """
    def __init__(self, node_id, platform_service_controller):
        self.platform_service_controller = platform_service_controller
        self.node_id = node_id
        self.instance_name = None

        self.vapi_url = None
        self.vim_url = None
        self.session = None
        self.session_id = None
        self.stub_config = None
        self.si = None
        self.content = None
        self.vim_uuid = None

    def connect(self):
        assert self.node_id is not None
        assert self.platform_service_controller is not None

        self.instance_name = self.platform_service_controller.lookupservicehelper.get_mgmt_node_instance_name(self.node_id)

        # discover the service endpoints from the lookup service on infrastructure node
        self.vapi_url = self.platform_service_controller.lookupservicehelper.find_vapi_url(self.node_id)
        assert self.vapi_url is not None
        self.vim_url = self.platform_service_controller.lookupservicehelper.find_vim_url(self.node_id)
        assert self.vim_url is not None

        # login to vAPI endpoint
        logger.info('Connecting to vapi url: {0}'.format(self.vapi_url))
        connector = connect.get_connector('https', 'json', url=self.vapi_url)
        self.stub_config = StubConfigurationFactory.new_std_configuration(connector)
        connector.set_security_context(self.platform_service_controller.sec_ctx)
        self.stub_config = StubConfigurationFactory.new_std_configuration(connector)
        self.session = Session(self.stub_config)
        self.session_id = self.session.create()
        # update the connection with session id
        session_sec_ctx = create_session_security_context(self.session_id)
        connector.set_security_context(session_sec_ctx)

        # pyvmomi
        # extract the host from the vim url
        vim_host = get_url_host(self.vim_url)
        assert vim_host is not None

        self.si = SmartConnect(host=vim_host,
                               user=self.platform_service_controller.ssousername,
                               pwd=self.platform_service_controller.ssopassword)
        assert self.si is not None

        # retrieve the service content
        self.content = self.si.RetrieveContent()
        assert self.content is not None
        self.vim_uuid = self.content.about.instanceUuid

    def disconnect(self):
        logger.info('disconnecting the session: {0}'.format(self.session_id))
        self.session.delete()
        Disconnect(self.si)
コード例 #3
0
ファイル: connection_workflow.py プロジェクト: kedr275/jk-2
class ConnectionWorkflow(object):
    """
    Demonstrates vAPI connection and service initialization callflow
    Step 1: Connect to the SSO URL and retrieve the SAML token.
    Step 2: Connect to the vapi service endpoint.
    Step 3: Use the SAML token to login to vAPI service endpoint.
    Step 4: Create a vAPI session.
    Step 5: Delete the vAPI session.
    Note: Use the lookup service print services sample to retrieve the SSO and vAPI service URLs
    """

    def __init__(self):
        self.vapi_url = None
        self.sts_url = None
        self.sso_username = None
        self.sso_password = None
        self.session = None

    def options(self):
        self.argparser = argparse.ArgumentParser(description=self.__doc__)
        # setup the argument parser
        self.argparser.add_argument('-vapiurl', '--vapiurl', help='vAPI URL')
        self.argparser.add_argument('-stsurl', '--stsurl', help='SSO URL')
        self.argparser.add_argument('-ssousername', '--ssousername', help='SSO username')
        self.argparser.add_argument('-ssopassword', '--ssopassword', help='SSO user password')
        self.args = self.argparser.parse_args()   # parse all the sample arguments when they are all set

    def setup(self):
        self.vapi_url = self.args.vapiurl
        assert self.vapi_url is not None
        self.sts_url = self.args.stsurl
        assert self.sts_url is not None
        self.sso_username = self.args.ssousername
        assert self.sso_username is not None
        self.sso_password = self.args.ssopassword
        assert self.sso_password is not None

    def execute(self):
        logger.info('vapi_url: {0}'.format(self.vapi_url))
        # parse the URL and determine the scheme
        o = urlparse(self.vapi_url)
        assert o.scheme is not None
        if o.scheme.lower() != 'https':
            logger.error('VAPI URL must be a https URL')
            raise Exception('VAPI URL must be a https URL')

        logger.info('sts_url: {0}'.format(self.sts_url))
        logger.info('Initialize SsoAuthenticator and fetching SAML bearer token...')
        authenticator = sso.SsoAuthenticator(self.sts_url)
        bearer_token = authenticator.get_bearer_saml_assertion(self.sso_username, self.sso_password, delegatable=True)

        logger.info('Creating SAML Bearer Security Context...')
        sec_ctx = create_saml_bearer_security_context(bearer_token)

        logger.info('Connecting to VAPI provider and preparing stub configuration...')
        connector = connect.get_connector('https', 'json', url=self.vapi_url)
        self.stub_config = StubConfigurationFactory.new_std_configuration(connector)

        connector.set_security_context(sec_ctx)
        self.stub_config = StubConfigurationFactory.new_std_configuration(connector)
        self.session = Session(self.stub_config)

        logger.info('Login to VAPI endpoint and get the session_id...')
        self.session_id = self.session.create()

        logger.info('Update the VAPI connection with session_id...')
        session_sec_ctx = create_session_security_context(self.session_id)
        connector.set_security_context(session_sec_ctx)

    def cleanup(self):
        if self.session_id is not None:
            self.disconnect()
            logger.info('VAPI session disconnected successfully...')

    def disconnect(self):
        self.session.delete()
コード例 #4
0
class EmbeddedPscSsoWorkflow(object):
    """
    Demonstrates how to Login to vCenter vAPI service with
    embedded Platform Services Controller.
    """

    def __init__(self):
        self.server = None
        self.username = None
        self.password = None
        self.session = None
        self.session_id = None
        self.skip_verification = False
        self.category_svc = None
        self.category_id = None

    def setup(self):
        self.server, self.username, self.password, _, self.skip_verification = \
            parse_cli_args()

    def run(self):
        print('\n\n#### Example: Login to vCenter server with '
              'embedded Platform Services Controller')

        # Since the platform services controller is embedded, the sso server
        # is the same as the vCenter server.
        ssoUrl = 'https://{}/sts/STSService'.format(self.server)

        print('\nStep 1: Connect to the Single Sign-On URL and '
              'retrieve the SAML bearer token.')

        authenticator = sso.SsoAuthenticator(ssoUrl)
        context = None
        if self.skip_verification:
            context = get_unverified_context()
        bearer_token = authenticator.get_bearer_saml_assertion(
            self.username,
            self.password,
            delegatable=True,
            ssl_context=context)

        # Creating SAML Bearer Security Context
        sec_ctx = create_saml_bearer_security_context(bearer_token)

        print('\nStep 2. Login to vAPI services using the SAML bearer token.')

        # The URL for the stub requests are made against the /api HTTP endpoint
        # of the vCenter system.
        vapi_url = 'https://{}/api'.format(self.server)

        # Create an authenticated stub configuration object that can be used to
        # issue requests against vCenter.
        session = requests.Session()
        if self.skip_verification:
            session = create_unverified_session(session)
        connector = get_requests_connector(session=session, url=vapi_url)
        connector.set_security_context(sec_ctx)
        stub_config = StubConfigurationFactory.new_std_configuration(
            connector)
        self.session = Session(stub_config)

        # Login to VAPI endpoint and get the session_id
        self.session_id = self.session.create()

        # Update the VAPI connection with session_id
        session_sec_ctx = create_session_security_context(self.session_id)
        connector.set_security_context(session_sec_ctx)

        # Create and Delete TagCategory to Verify connection is successful
        print('\nStep 3: Creating and Deleting Tag Category...\n')
        self.category_svc = Category(stub_config)

        self.category_id = self.create_tag_category('TestTagCat', 'TestTagDesc',
                                                    CategoryModel.Cardinality.MULTIPLE)
        assert self.category_id is not None
        print('Tag category created; Id: {0}\n'.format(self.category_id))

        # Delete TagCategory
        self.category_svc.delete(self.category_id)

        self.session.delete()
        print('VAPI session disconnected successfully...')

    def create_tag_category(self, name, description, cardinality):
        """create a category. User who invokes this needs create category privilege."""
        create_spec = self.category_svc.CreateSpec()
        create_spec.name = name
        create_spec.description = description
        create_spec.cardinality = cardinality
        associableTypes = set()
        create_spec.associable_types = associableTypes
        return self.category_svc.create(create_spec)
コード例 #5
0
class VsphereClient(ApiClient):
    """
    vSphere Client class that provides access to stubs for all services in the
    vSphere API
    """
    def __init__(self, session, server, username, password, bearer_token,
                 hok_token, private_key):
        """
        Initialize VsphereClient by creating a parent stub factory instance
        of all vSphere components.

        :type  session: :class:`requests.Session`
        :param session: Requests HTTP session instance. If not specified,
        then one is automatically created and used
        :type  server: :class:`str`
        :param server: vCenter host name or IP address
        :type  username: :class:`str`
        :param username: Name of the user
        :type  password: :class:`str`
        :param password: Password of the user
        :type  bearer_token: :class:`str`
        :param bearer_token: SAML Bearer Token
        :type  hok_token: :class:`str`
        :param hok_token: SAML Hok Token
        :type  private_key: :class:`str`
        :param private_key: Absolute file path of the private key of the user
        """
        if not session:
            self.session = session = requests.Session()
        host_url = "https://" + server + JSON_RPC_ENDPOINT

        if username is not None and password is not None and \
                not bearer_token and not hok_token:
            sec_ctx = create_user_password_security_context(username, password)
        elif bearer_token and not username and not hok_token:
            sec_ctx = create_saml_bearer_security_context(bearer_token)
        elif hok_token and private_key and not bearer_token and not username:
            sec_ctx = create_saml_security_context(hok_token, private_key)
        else:
            raise ValueError('Please provide exactly one of the following '
                             'authentication scheme: username/password, '
                             'bear_token or hok_token/private_key')

        session_svc = Session(
            StubConfigurationFactory.new_std_configuration(
                get_requests_connector(
                    session=session,
                    url=host_url,
                    provider_filter_chain=[
                        LegacySecurityContextFilter(security_context=sec_ctx)
                    ])))

        session_id = session_svc.create()
        sec_ctx = create_session_security_context(session_id)
        stub_config = StubConfigurationFactory.new_std_configuration(
            get_requests_connector(
                session=session,
                url=host_url,
                provider_filter_chain=[
                    LegacySecurityContextFilter(security_context=sec_ctx)
                ]))
        self.session_svc = Session(stub_config)
        stub_factory = StubFactory(stub_config)
        ApiClient.__init__(self, stub_factory)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.__del__()

    def __del__(self):
        try:
            self.session_svc.delete()
        except Exception:
            # Catch exceptions when terminating the vSphere session and go ahead
            # close the requests session.
            pass
        if hasattr(self, 'session'):
            self.session.close()
class EmbeddedPscSsoWorkflow(object):
    """
    Demonstrates how to Login to vCenter vAPI service with
    embedded Platform Services Controller.
    """

    def __init__(self):
        self.server = None
        self.username = None
        self.password = None
        self.session = None
        self.session_id = None
        self.skip_verification = False

    def setup(self):
        self.server, self.username, self.password, _, self.skip_verification = \
            parse_cli_args()

    def run(self):
        print('\n\n#### Example: Login to vCenter server with '
              'embedded Platform Services Controller')

        # Since the platform services controller is embedded, the sso server
        # is the same as the vCenter server.
        ssoUrl = 'https://{}/sts/STSService'.format(self.server)

        print('\nStep 1: Connect to the Single Sign-On URL and '
              'retrieve the SAML bearer token.')

        authenticator = sso.SsoAuthenticator(ssoUrl)
        context = None
        if self.skip_verification:
            context = get_unverified_context()
        bearer_token = authenticator.get_bearer_saml_assertion(
            self.username,
            self.password,
            delegatable=True,
            ssl_context=context)

        # Creating SAML Bearer Security Context
        sec_ctx = create_saml_bearer_security_context(bearer_token)

        print('\nStep 2. Login to vAPI services using the SAML bearer token.')

        # The URL for the stub requests are made against the /api HTTP endpoint
        # of the vCenter system.
        vapi_url = 'https://{}/api'.format(self.server)

        # Create an authenticated stub configuration object that can be used to
        # issue requests against vCenter.
        session = requests.Session()
        if self.skip_verification:
            session = create_unverified_session(session)
        connector = get_requests_connector(session=session, url=vapi_url)
        connector.set_security_context(sec_ctx)
        stub_config = StubConfigurationFactory.new_std_configuration(
            connector)
        self.session = Session(stub_config)

        # Login to VAPI endpoint and get the session_id
        self.session_id = self.session.create()

        # Update the VAPI connection with session_id
        session_sec_ctx = create_session_security_context(self.session_id)
        connector.set_security_context(session_sec_ctx)

        print('\nStep 3: List available datacenters using the vAPI services')

        datacenter_svc = Datacenter(stub_config)
        pprint(datacenter_svc.list())

        self.session.delete()
        print('VAPI session disconnected successfully...')
class ExternalPscSsoWorkflow(object):
    """
    Demonstrates how to Login to vCenter vAPI service with
    external Platform Services Controller.
    """
    def __init__(self):
        self.lswsdl = None
        self.lsurl = None
        self.mgmtinstancename = None
        self.username = None
        self.password = None
        self.session = None
        self.session_id = None
        self.args = None
        self.argparser = None
        self.mgmtinstancename = None
        self.skip_verification = False
        self.category_svc = None
        self.category_id = None

    def options(self):
        self.argparser = argparse.ArgumentParser(description=self.__doc__)
        # setup the argument parser
        self.argparser.add_argument('-w',
                                    '--lswsdl',
                                    help='Path to the Lookup Service WSDL. '
                                    'By default, lookupservice.wsdl in '
                                    '../wsdl will be used if the parameter'
                                    ' is absent')
        self.argparser.add_argument('-s', '--lsurl', help='Lookup service URL')
        self.argparser.add_argument('-m',
                                    '--mgmtinstancename',
                                    help='Instance name of the vCenter Server '
                                    'management node. '
                                    'When only one node is registered, '
                                    'it is selected by default; otherwise,'
                                    ' omit the parameter to get a list of '
                                    'available nodes.')
        self.argparser.add_argument('-u', '--username', help='SSO user name')
        self.argparser.add_argument('-p',
                                    '--password',
                                    help='SSO user password')
        self.argparser.add_argument('-v',
                                    '--skipverification',
                                    action='store_true',
                                    help='Do not verify server certificate')
        self.args = self.argparser.parse_args()

    def setup(self):
        if self.args.lswsdl:
            self.lswsdl = os.path.abspath(self.args.lswsdl)
        else:
            self.lswsdl = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), 'wsdl',
                'lookupservice.wsdl')
        assert self.lswsdl is not None
        print('lswsdl: {0}'.format(self.lswsdl))

        self.lsurl = self.args.lsurl
        assert self.lsurl is not None
        print('lsurl: {0}'.format(self.lsurl))

        self.username = self.args.username
        assert self.username is not None

        self.password = self.args.password
        assert self.password is not None

        self.mgmtinstancename = self.args.mgmtinstancename
        self.skip_verification = self.args.skipverification

    def run(self):
        print('\n\n#### Example: Login to vCenter server with '
              'external Platform Services Controller')

        print('\nStep 1: Connect to the lookup service on the '
              'Platform Services Controller node: {0}'.format(self.lsurl))

        # Convert wsdl path to url
        self.lswsdl = parse.urljoin('file:', request.pathname2url(self.lswsdl))
        lookupservicehelper = LookupServiceHelper(
            wsdl_url=self.lswsdl,
            soap_url=self.lsurl,
            skip_verification=self.skip_verification)
        lookupservicehelper.connect()

        if self.mgmtinstancename is None:
            self.mgmtinstancename, self.mgmtnodeid = lookupservicehelper.get_default_mgmt_node(
            )
        elif self.mgmtnodeid is None:
            self.mgmtnodeid = lookupservicehelper.get_mgmt_node_id(
                self.mgmtinstancename)
        assert self.mgmtnodeid is not None

        print('\nStep 2: Discover the Single Sign-On service URL'
              ' from lookup service.')
        sso_url = lookupservicehelper.find_sso_url()
        print('Sso URL: {0}'.format(sso_url))

        print('\nStep 3: Connect to the Single Sign-On URL and '
              'retrieve the SAML bearer token.')
        authenticator = sso.SsoAuthenticator(sso_url)
        context = None
        if self.skip_verification:
            context = get_unverified_context()
        bearer_token = authenticator.get_bearer_saml_assertion(
            self.username,
            self.password,
            delegatable=True,
            ssl_context=context)

        # Creating SAML Bearer Security Context
        sec_ctx = create_saml_bearer_security_context(bearer_token)

        print('\nStep 4. Discover the vAPI service URL from lookup service.')
        vapi_url = lookupservicehelper.find_vapi_url(self.mgmtnodeid)
        print('vAPI URL: {0}'.format(vapi_url))

        print('\nStep 5. Login to vAPI service using the SAML bearer token.')

        # Create an authenticated stub configuration object that can be used to
        # issue requests against vCenter.
        session = requests.Session()
        if self.skip_verification:
            session = create_unverified_session(session)
        connector = get_requests_connector(session=session, url=vapi_url)
        connector.set_security_context(sec_ctx)
        stub_config = StubConfigurationFactory.new_std_configuration(connector)
        self.session = Session(stub_config)

        # Login to VAPI endpoint and get the session_id
        self.session_id = self.session.create()

        # Update the VAPI connection with session_id
        session_sec_ctx = create_session_security_context(self.session_id)
        connector.set_security_context(session_sec_ctx)

        # Create and Delete TagCategory to Verify connection is successful
        print('\nStep 6: Creating and Deleting Tag Category...\n')
        self.category_svc = Category(stub_config)

        self.category_id = self.create_tag_category(
            'TestTagCat', 'TestTagDesc', CategoryModel.Cardinality.MULTIPLE)
        assert self.category_id is not None
        print('Tag category created; Id: {0}\n'.format(self.category_id))

        # Delete TagCategory
        self.category_svc.delete(self.category_id)

        self.session.delete()
        print('VAPI session disconnected successfully...')

    def create_tag_category(self, name, description, cardinality):
        """create a category. User who invokes this needs create category privilege."""
        create_spec = self.category_svc.CreateSpec()
        create_spec.name = name
        create_spec.description = description
        create_spec.cardinality = cardinality
        associableTypes = set()
        create_spec.associable_types = associableTypes
        return self.category_svc.create(create_spec)

        self.session.delete()
        print('VAPI session disconnected successfully...')
コード例 #8
0
class VapiConnectionWorkflow(object):
    """
    Demonstrates vAPI connection and service initialization callflow using the username and password
    Step 1: Retrieve the vAPI service endpoint URL from lookup service.
    Step 2: Connect to the vAPI service endpoint.
    Step 3: Use the username/password to login to the vAPI service endpoint.
    Step 4: Create a vAPI session.
    Step 5: Validate some of the vAPI services.
    Step 6: Delete the vAPI session.
    """

    def __init__(self):
        self.lswsdlurl = None
        self.lssoapurl = None
        self.mgmtinstancename = None  # Optional: used when there are more than one mgmt node
        self.ssousername = None
        self.ssopassword = None

        self.mgmtnodeid = None
        self.vapiurl = None
        self.session = None
        self.session_id = None
        self.stub_config = None

    def options(self):
        self.argparser = argparse.ArgumentParser(description=self.__doc__)
        # setup the argument parser
        self.argparser.add_argument('-lswsdlurl', '--lswsdlurl', help='Lookup service WSDL URL')
        self.argparser.add_argument('-lssoapurl', '--lssoapurl', help='Lookup service SOAP URL')
        self.argparser.add_argument('-mgmtinstancename', '--mgmtinstancename',
                                    help='Instance name of the vCenter Server management node. ' + \
                                    'When only one node is registered, it is selected by default; ' + \
                                    'otherwise, omit the parameter to get a list of available nodes.')
        self.argparser.add_argument('-ssousername', '--ssousername', help='SSO user name')
        self.argparser.add_argument('-ssopassword', '--ssopassword', help='SSO user password')
        self.args = self.argparser.parse_args()   # parse all the sample arguments when they are all set

    def setup(self):
        if self.args.lswsdlurl is None:
            self.lswsdlurl = SampleConfig.get_ls_wsdl_url()  # look for lookup service WSDL in the sample config
        else:
            self.lswsdlurl = self.args.lswsdlurl
        assert self.lswsdlurl is not None
        logger.info('lswsdlurl: {0}'.format(self.lswsdlurl))

        if self.args.lssoapurl is None:
            self.lssoapurl = SampleConfig.get_ls_soap_url()  # look for lookup service SOAP URL in the sample config
        else:
            self.lssoapurl = self.args.lssoapurl
        assert self.lssoapurl is not None
        logger.info('lssoapurl: {0}'.format(self.lssoapurl))

        if self.args.ssousername is None:
            self.ssousername = SampleConfig.get_sso_username()  # look for sso user name in the sample config
        else:
            self.ssousername = self.args.ssousername
        assert self.ssousername is not None

        if self.args.ssopassword is None:
            self.ssopassword = SampleConfig.get_sso_password()  # look for sso password in the sample config
        else:
            self.ssopassword = self.args.ssopassword
        assert self.ssopassword is not None

        if self.mgmtinstancename is None:
            self.mgmtinstancename = self.args.mgmtinstancename

    def execute(self):
        logger.info('Connecting to lookup service url: {0}'.format(self.lssoapurl))
        lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, soap_url=self.lssoapurl)
        lookupservicehelper.connect()

        if self.mgmtinstancename is None:
            self.mgmtinstancename, self.mgmtnodeid = lookupservicehelper.get_default_mgmt_node()
        elif self.mgmtnodeid is None:
            self.mgmtnodeid = lookupservicehelper.get_mgmt_node_id(self.mgmtinstancename)
        assert self.mgmtnodeid is not None

        self.vapiurl = lookupservicehelper.find_vapi_url(self.mgmtnodeid)
        logger.info('vapi_url: {0}'.format(self.vapiurl))

        logger.info('Connecting to VAPI endpoint and preparing stub configuration...')
        connector = connect.get_connector('https', 'json', url=self.vapiurl)
        self.stub_config = StubConfigurationFactory.new_std_configuration(connector)

        sec_ctx = create_user_password_security_context(self.ssousername, self.ssopassword)
        connector.set_security_context(sec_ctx)
        self.stub_config = StubConfigurationFactory.new_std_configuration(connector)
        self.session = Session(self.stub_config)

        logger.info('Login to VAPI endpoint and get the session_id...')
        self.session_id = self.session.create()

        logger.info('Update the VAPI connection with session_id...')
        session_sec_ctx = create_session_security_context(self.session_id)
        connector.set_security_context(session_sec_ctx)

        # make sure you can access some of the VAPI services
        tag_svc = Tag(self.stub_config)
        logger.info('List all the existing tags user has access to...')
        tags = tag_svc.list()
        if len(tags) > 0:
            for tag in tags:
                logger.info('Found Tag: {0}'.format(tag))
        else:
            logger.info('No Tag Found...')

    def cleanup(self):
        if self.session_id is not None:
            self.disconnect()
            logger.info('VAPI session disconnected successfully...')

    def disconnect(self):
        self.session.delete()