Ejemplo n.º 1
0
    def __init__(self, next_provider=None, provider_config=None):
        """
        Initialize AuthorizationFilter

        :type  next_provider: :class:`vmware.vapi.core.ApiProvider`
        :param next_provider: API Provider to invoke the requests
        :type  provider_config:
            :class:`vmware.vapi.settings.config.ProviderConfig` or :class:`None`
        :param provider_config: Provider configuration object
        """
        handler_names = []
        self._metadata = None
        if provider_config:
            # Get the registered AuthN handlers from config file
            (handler_names, metadata_file) = \
                provider_config.get_authorization_handlers_and_file()
            self._metadata = get_metadata(metadata_file)

        from vmware.vapi.lib.load import dynamic_import
        self._authz_handlers = []
        for handler_name in handler_names:
            # Dynamically load the AuthZ handler
            handler_constructor = dynamic_import(handler_name)
            if handler_constructor is None:
                raise ImportError('Could not import %s' % handler_name)

            self._authz_handlers.append(handler_constructor())

        self._internal_server_error_def = make_std_error_def(
            'com.vmware.vapi.std.errors.internal_server_error')
        self._unauthorized_error_def = make_std_error_def(
            'com.vmware.vapi.std.errors.unauthorized')
        ApiProviderFilter.__init__(
            self, next_provider,
            [self._internal_server_error_def, self._unauthorized_error_def])
Ejemplo n.º 2
0
    def __init__(self,
                 http_provider,
                 post_processors,
                 rest_metadata_map=None,
                 is_vapi_rest=True):
        """
        Rest rpc client provider init

        :type  http_provider:
            :class:`vmware.vapi.protocol.client.rpc.provider.HTTPProvider`
        :param http_provider: rpc provider object
        :type  post_processors: :class:`list` of :class:`str`
        :param post_processors: List of post processor class names
        :type  rest_metadata_map: :class:`dict` of (:class:`str`, :class:`str`)
            and :class:`vmware.vapi.lib.rest.OperationRestMetadata`
        :param rest_metadata_map: Rest metadata for all operations
        :type  is_vapi_rest: :class:`bool`
        :param is_vapi_rest: Whether the Rest json message format is VAPI Rest
            or not
        """

        ApiProvider.__init__(self)
        self._http_provider = http_provider
        self._rest_metadata_map = rest_metadata_map or {}
        self._is_vapi_rest = is_vapi_rest

        # Load all the post processors
        self.post_processors = [dynamic_import(p)() for p in post_processors]
Ejemplo n.º 3
0
 def _resolve(self):
     """
     Resolves the struct or enum reference
     """
     tokens = self._type_name.split('.')
     target = dynamic_import(self._context_name)
     # Get the required reference by walking down the fully qualified name
     for token in tokens:
         target = getattr(target, token)
     self._resolved_type = target.get_binding_type()
Ejemplo n.º 4
0
    def __init__(self, stub_config):
        """
        Initialize StubFactoryBase

        :type  stub_config: :class:`vmware.vapi.bindings.stub.StubConfiguration`
        :param stub_config: Stub config instance
        """
        self._stub_config = stub_config
        for k, val in six.viewitems(self._attrs):
            if isinstance(val, six.string_types):
                # If the value in the _attr dict is a string, then import the
                # type and set it as the value in the same dict
                val = dynamic_import(val)
                self._attrs[k] = val
            # Set every key, value in _attrs dict as an instance variable
            setattr(self, k, val)
Ejemplo n.º 5
0
    def get_connector(self, protocol, *args, **kwargs):
        """
        Create protocol connector

        :type    protocol: :class:`str`
        :param   protocol: protocol name
        :type    args: :class:`tuple`
        :param   args: position parameters to protocol connector constructor
        :type    kwargs: :class:`dict`
        :param   kwargs: key parameters to protocol connector constructor
        :rtype:  :class:`vmware.vapi.protocol.client.connector.Connector`
        :return: Connector object
        """
        constructor = self.connectors.get(protocol)
        if constructor is not None:
            constructor = dynamic_import(constructor)
            if constructor:
                return constructor(*args, **kwargs)
Ejemplo n.º 6
0
    def get_rpc_provider(self, rpc_provider_name, *args, **kwargs):
        """
        Create rpc provider

        :type  rpc_provider_name:
        :param rpc_provider_name:
        :type    args: :class:`tuple`
        :param   args: position parameters to rpc provider constructor
        :type    kwargs: :class:`dict`
        :param   kwargs: key parameters to rpc provider constructor
        :rtype:  :class:`vmware.vapi.protocol.client.rpc.provider.RpcProvider`
        :return: Rpc provider object
        """
        constructor = self.rpc_providers.get(rpc_provider_name)
        if constructor is not None:
            constructor = dynamic_import(constructor)
            if constructor:
                return constructor(*args, **kwargs)
Ejemplo n.º 7
0
    def get_handler(self, protocol_name, *args, **kwargs):
        """
        Create protocol handler

        :type    protocol: :class:`str`
        :param   protocol: protocol name
        :type    args: :class:`tuple`
        :param   args: position parameters to protocol handler constructor
        :type    kwargs: :class:`dict`
        :param   kwargs: key parameters to protocol handler constructor
        :rtype:  :class:`vmware.vapi.protocol.server.api_handler.ApiHandler`
        :return: Api handler object
        """
        constructor = self.handlers.get(protocol_name)
        if constructor is not None:
            constructor = dynamic_import(constructor)
            if constructor:
                return constructor(*args, **kwargs)
Ejemplo n.º 8
0
def setup_provider_chain(provider_cfg, singleton):
    """
    Setup the API Provider chain

    In the properties file, users would specify the order of ApiProviders
    For ex: InterposerProvider, ApiAggregator. In this case all incoming
    requests would first go to InterposerProvider and then forwarded to
    ApiAggregator after processing.

    This function initializes all these providers in the reverse order
    and passes the reference of n+1th provider to nth provider.

    :type  provider_cfg: :class:`vmware.vapi.settings.config.ProviderConfig`
    :param provider_cfg: Provider Configuration
    :type singleton: :class:`bool`
    :param singleton: Specify whether to create new instances of Providers or
                      use existing ones
    :rtype: :class:`list` of :class:`vmware.vapi.core.ApiProvider`
    :return: List of API Providers
    """
    # This import cannot be at the top as we need to wait for logger to get
    # initialized with right handlers
    from vmware.vapi.lib.load import dynamic_import
    singleton_providers = {
        'ApiAggregator':
        'vmware.vapi.provider.aggregator.get_provider',
        'LocalProvider':
        'vmware.vapi.provider.local.get_provider',
        'InterposerProvider':
        'vmware.vapi.provider.interposer.get_provider',
        'AuthenticationFilter':
        'vmware.vapi.security.authentication_filter.get_provider',
        'AuthorizationFilter':
        'vmware.vapi.security.authorization_filter.get_provider',
    }

    providers = {
        'ApiAggregator':
        'vmware.vapi.provider.aggregator.AggregatorProvider',
        'LocalProvider':
        'vmware.vapi.provider.local.LocalProvider',
        'InterposerProvider':
        'vmware.vapi.provider.interposer.InterposerProvider',
        'AuthenticationFilter':
        'vmware.vapi.security.authentication_filter.AuthenticationFilter',
        'AuthorizationFilter':
        'vmware.vapi.security.authorization_filter.AuthorizationFilter',
    }

    provider_types = provider_cfg.get_providers()
    provider_map = singleton_providers if singleton else providers
    filter_kwargs = {} if singleton else {'provider_config': provider_cfg}

    providers = []
    for i, provider_type in enumerate(reversed(provider_types)):
        provider_name = provider_map.get(provider_type)
        if provider_name:
            provider_constructor = dynamic_import(provider_name)
            if provider_constructor is None:
                raise ImportError('Could not import %s' % provider_name)
            if i == 0:
                # TODO: Add validation to make sure that the last provider
                # can support registration of services
                provider = provider_constructor()
                provider.register_by_properties(provider_cfg)
            else:
                provider = provider_constructor(**filter_kwargs)
                provider.next_provider = providers[i - 1]
            providers.append(provider)
        else:
            logger.error('Could not load provider')
            return []
    return providers[::-1]
Ejemplo n.º 9
0
def create_servers(spec, singleton=False):
    """
    Create RPC servers

    :type  spec: :class:`str`
    :param spec: Provider configuration
    :type  singleton: :class:`bool`
    :kwarg singleton: Specify whether to create new instances of Providers or
                      use existing ones
    :rtype: :class:`list` of
        :class:`vmware.vapi.server.server_interface.ServerInterface`
    :return: list of servers
    """
    server_providers = {
        'twisted': 'vmware.vapi.server.twisted_server.get_server',
        'stdio': 'vmware.vapi.server.stdio_server.get_server',
        'wsgi': 'vmware.vapi.server.wsgi_server.get_server',
    }

    provider_cfg, providers = _create_provider_int(spec, singleton)
    provider = providers[0]

    try:
        protocol_configs = provider_cfg.get_provider_protocols()
    except configparser.NoOptionError:
        raise Exception('No protocol configurations specified')

    # These import cannot be at the top as we need to wait for logger to get
    # initialized with right handlers
    from vmware.vapi.lib.load import dynamic_import
    from vmware.vapi.protocol.server.msg.handler_factory import (
        ProtocolHandlerFactory)
    from vmware.vapi.protocol.server.transport.async_server_adapter_factory \
        import AsyncServerAdapterFactory
    servers = {}
    msg_handlers = {}
    protocol_handlers = {}
    is_wsgi = False
    for protocol_config in protocol_configs:
        url = provider_cfg.get_provider_url(protocol_config)
        logger.info('url: %s', url)

        transport_protocol = get_url_scheme(url)
        logger.info('transport protocol: %s', transport_protocol)

        # Get request handler
        msg_handler_factory = ProtocolHandlerFactory()

        # Add all pre processors
        # TODO Add these as default values in provider config instead of
        # hardcoding here
        pre_processors = ['vmware.vapi.security.sso.JSONSSOVerifier']

        msg_protocol = provider_cfg.get_provider_message_format(
            protocol_config)
        msg_handler = msg_handler_factory.get_handler(msg_protocol, provider,
                                                      pre_processors)
        msg_handlers[(msg_protocol, provider)] = msg_handler

        # Get server constructor
        rpc_server = provider_cfg.get_provider_server(protocol_config)
        logger.info('rpc server: %s', rpc_server)

        # Get async server to msg handler adapter
        adapter_factory = AsyncServerAdapterFactory()
        if rpc_server in ['wsgi', 'stdio']:
            protocol_handler = msg_handler
        else:
            protocol_handler = adapter_factory.get_adapter(
                transport_protocol, msg_handler)

        # Extract ssl arguments
        ssl_args = provider_cfg.get_provider_ssl_args(protocol_config)

        # Register handler
        server = servers.get(rpc_server)
        if not server:
            server_name = server_providers.get(rpc_server)
            if server_name is not None:
                server_constructor = dynamic_import(server_name)
            if server_constructor is None:
                raise Exception('Could not find RPC constructor')

            server = server_constructor()
            if rpc_server == 'wsgi':
                server.provider_config = provider_cfg
            servers[rpc_server] = server
        server.register_handler(url, msg_protocol, protocol_handler, ssl_args)

        # Get tasks configuration
        if provider_cfg.are_tasks_enabled():
            thread_count = provider_cfg.get_provider_task_threads()
            from vmware.vapi.lib.thread_pool import get_threadpool
            thread_pool = get_threadpool(thread_count)

            task_manager = provider_cfg.get_provider_task_manager()
            task_manager_constructor = dynamic_import(task_manager)
            from vmware.vapi.task.task_manager_impl import get_task_manager
            task_manager_instance = get_task_manager(task_manager_constructor)

            priv_validator = provider_cfg.get_provider_privilege_validator()
            if priv_validator is not None:
                priv_validator_constructor = dynamic_import(priv_validator)
                from vmware.vapi.security.privilege import (
                    get_privilege_validator)
                privilege_validator_instance = get_privilege_validator(
                    priv_validator_constructor)

    return list(servers.values())
Ejemplo n.º 10
0
 def test_load_failure_attr(self):
     di = dynamic_import('vmware.vapi.lib.load.dynamic_importx')
     self.assertEqual(di, None)
Ejemplo n.º 11
0
 def test_load_success(self):
     di = dynamic_import('vmware.vapi.lib.load.dynamic_import')
     self.assertEqual(di.__name__, 'dynamic_import')
     self.assertEqual(di.__module__, 'vmware.vapi.lib.load')