Пример #1
0
def get_client_from_cli_profile(client_class, **kwargs):
    """Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.

    This method will fill automatically the following client parameters:
    - credentials/credential
    - subscription_id
    - base_url

    Parameters provided in kwargs will override CLI parameters and be passed directly to the client.

    :Example:

    .. code:: python

        from azure.common.client_factory import get_client_from_cli_profile
        from azure.mgmt.compute import ComputeManagementClient
        client = get_client_from_cli_profile(ComputeManagementClient)

    .. versionadded:: 1.1.6

    :param client_class: A SDK client class
    :return: An instantiated client
    :raises: ImportError if azure-cli-core package is not available
    """
    cloud = get_cli_active_cloud()
    parameters = {}
    no_credential_sentinel = object()
    kwarg_cred = kwargs.pop('credentials', no_credential_sentinel)
    if kwarg_cred is no_credential_sentinel:
        kwarg_cred = kwargs.pop('credential', no_credential_sentinel)

    if kwarg_cred is no_credential_sentinel or 'subscription_id' not in kwargs:
        resource, _ = _client_resource(client_class, cloud)
        credentials, subscription_id, tenant_id = get_azure_cli_credentials(
            resource=resource,
            with_tenant=True,
        )
        # Provide both syntax of cred, we have an "inspect" filter later
        credential_to_pass = credentials if kwarg_cred is no_credential_sentinel else kwarg_cred
        parameters.update({
            'credentials': credential_to_pass,
            'credential': credential_to_pass,
            'subscription_id': kwargs.get('subscription_id', subscription_id)
        })

    args = get_arg_spec(client_class.__init__).args
    if 'adla_job_dns_suffix' in args and 'adla_job_dns_suffix' not in kwargs:  # Datalake
        # Let it raise here with AttributeError at worst, this would mean this cloud does not define
        # ADL endpoint and no manual suffix was given
        parameters['adla_job_dns_suffix'] = cloud.suffixes.azure_datalake_analytics_catalog_and_job_endpoint
    elif 'base_url' in args and 'base_url' not in kwargs:
        _, base_url = _client_resource(client_class, cloud)
        if base_url:
            parameters['base_url'] = base_url
        else:
            parameters['base_url'] = cloud.endpoints.resource_manager
    if 'tenant_id' in args and 'tenant_id' not in kwargs:
        parameters['tenant_id'] = tenant_id
    parameters.update(kwargs)
    return _instantiate_client(client_class, **parameters)
Пример #2
0
    def wrap(func):  # pylint: disable=missing-docstring
        if isinstance(func, property):
            raise RuntimeError('Override must go after @property decorator')

        args = get_arg_spec(func)[0]  # pylint: disable=deprecated-method
        if not args:
            raise RuntimeError(
                'Can only use the override decorator on member functions')

        if check:

            @functools.wraps(func)
            def wrapped_fn(self, *args, **kwargs):  # pylint: disable=missing-docstring
                try:
                    getattr(super(self.__class__, self), func.__name__)
                except AttributeError:
                    raise RuntimeError(
                        'Function {} does not override a superclass method'.
                        format(func))

                return func(self, *args, **kwargs)
        else:
            wrapped_fn = func

        return wrapped_fn
Пример #3
0
def is_track2(client_class):
    """ IS this client a autorestv3/track2 one?.
    Could be refined later if necessary.
    """
    from inspect import getfullargspec as get_arg_spec
    args = get_arg_spec(client_class.__init__).args
    return "credential" in args
Пример #4
0
    def wrap(func):  # pylint: disable=missing-docstring
        if isinstance(func, property):
            raise RuntimeError('Protected must go after @property decorator')

        args = get_arg_spec(func)[0]  # pylint: disable=deprecated-method
        if not args:
            raise RuntimeError(
                'Can only use the protected decorator on member functions')

        # We can only perform checks if the interpreter is capable of giving
        # us the stack i.e. currentframe() produces a valid object
        if check and currentframe() is not None:

            @functools.wraps(func)
            def wrapped_fn(self, *args, **kwargs):  # pylint: disable=missing-docstring
                try:
                    calling_class = stack()[1][0].f_locals['self']
                    assert self is calling_class
                except (KeyError, AssertionError):
                    raise RuntimeError(
                        'Cannot access protected function {} from outside'
                        ' class hierarchy'.format(func.__name__))

                return func(self, *args, **kwargs)
        else:
            wrapped_fn = func

        return wrapped_fn
Пример #5
0
def _instantiate_client(client_class, **kwargs):
    """Instantiate a client from kwargs, removing the subscription_id argument if unsupported.
    """
    args = get_arg_spec(client_class.__init__).args
    if 'subscription_id' not in args:
        del kwargs['subscription_id']
    return client_class(**kwargs)
Пример #6
0
def _is_autorest_v3(client_class):
    """Is this client a autorest v3/track2 one?

    Could be refined later if necessary.
    """
    args = get_arg_spec(client_class.__init__).args
    return "credential" in args
Пример #7
0
    def validate(self, value, breadcrumbs=()):
        """Validate a value to see if it is valid for this port

        :param value: the value to check
        :type value: typing.Any
        :param breadcrumbs: a tuple of the path to having reached this point in validation
        :type breadcrumbs: typing.Tuple[str]
        :return: None or tuple containing 0: error string 1: tuple of breadcrumb strings to where the validation failed
        :rtype: typing.Optional[ValidationError]
        """
        validation_error = None

        if value is UNSPECIFIED and self._required:
            validation_error = "required value was not provided for '{}'".format(self.name)
        elif value is not UNSPECIFIED and self._valid_type is not None and not isinstance(value, self._valid_type):
            validation_error = "value '{}' is not of the right type. Got '{}', expected '{}'".format(
                self.name, type(value), self._valid_type)

        if not validation_error and self._validator is not None:
            spec = get_arg_spec(self.validator)
            if len(spec[0]) == 1:
                warnings.warn(VALIDATOR_SIGNATURE_DEPRECATION_WARNING.format(self.validator.__name__))
                result = self.validator(value)
            else:
                result = self.validator(value, self)
            if result is not None:
                assert isinstance(result, str), "Validator returned non string type"
                validation_error = result

        if validation_error:
            breadcrumbs += (self.name,)
            return PortValidationError(validation_error, breadcrumbs_to_port(breadcrumbs))
Пример #8
0
def _instantiate_client(client_class, **kwargs):
    """Instantiate a client from kwargs, removing the subscription_id argument if unsupported.
    """
    args = get_arg_spec(client_class.__init__).args
    if 'subscription_id' not in args:
        del kwargs['subscription_id']
    elif sys.version_info < (3, 0) and isinstance(kwargs['subscription_id'], unicode):
        kwargs['subscription_id'] = kwargs['subscription_id'].encode('utf-8')
    return client_class(**kwargs)
Пример #9
0
def get_client_from_cli_profile(client_class, **kwargs):
    """Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.

    This method will fill automatically the following client parameters:
    - credentials
    - subscription_id
    - base_url

    Parameters provided in kwargs will override CLI parameters and be passed directly to the client.

    :Example:

    .. code:: python

        from azure.common.client_factory import get_client_from_cli_profile
        from azure.mgmt.compute import ComputeManagementClient
        client = get_client_from_cli_profile(ComputeManagementClient)

    .. versionadded:: 1.1.6

    :param client_class: A SDK client class
    :return: An instantiated client
    :raises: ImportError if azure-cli-core package is not available
    """
    is_graphrbac = client_class.__name__ == 'GraphRbacManagementClient'
    cloud = get_cli_active_cloud()
    parameters = {}
    if 'credentials' not in kwargs or 'subscription_id' not in kwargs:
        if is_graphrbac:
            resource = cloud.endpoints.active_directory_graph_resource_id
        else:
            resource = None
        credentials, subscription_id, tenant_id = get_azure_cli_credentials(
            resource=resource, with_tenant=True)
        parameters.update({
            'credentials':
            kwargs.get('credentials', credentials),
            'subscription_id':
            kwargs.get('subscription_id', subscription_id)
        })

    args = get_arg_spec(client_class.__init__).args
    if 'adla_job_dns_suffix' in args and 'adla_job_dns_suffix' not in kwargs:  # Datalake
        # Let it raise here with AttributeError at worst, this would mean this cloud does not define
        # ADL endpoint and no manual suffix was given
        parameters[
            'adla_job_dns_suffix'] = cloud.suffixes.azure_datalake_analytics_catalog_and_job_endpoint
    elif 'base_url' in args and 'base_url' not in kwargs:
        if is_graphrbac:
            parameters[
                'base_url'] = cloud.endpoints.active_directory_graph_resource_id
        else:
            parameters['base_url'] = cloud.endpoints.resource_manager
    if 'tenant_id' in args and 'tenant_id' not in kwargs:
        parameters['tenant_id'] = tenant_id
    parameters.update(kwargs)
    return _instantiate_client(client_class, **parameters)
Пример #10
0
    def __init__(self, func):
        try:
            args = get_arg_spec(func)[0]
        except TypeError:
            raise TypeError("func is not a function, got {}".format(type(func)))
        if len(args) != 1:
            raise TypeError("Step must take one argument only: self")

        self._fn = func
Пример #11
0
    def validate(self, port_values=None, breadcrumbs=()):
        """
        Validate the namespace port itself and subsequently all the port_values it contains

        :param port_values: an arbitrarily nested dictionary of parsed port values
        :type port_values: dict
        :param breadcrumbs: a tuple of the path to having reached this point in validation
        :type breadcrumbs: typing.Tuple[str]
        :return: None or tuple containing 0: error string 1: tuple of breadcrumb strings to where the validation failed
        :rtype: typing.Optional[ValidationError]
        """
        breadcrumbs_local = breadcrumbs + (self.name,)

        if not port_values:
            port_values = {}

        if not isinstance(port_values, collections.Mapping):
            message = 'specified value is of type {} which is not sub class of `Mapping`'.format(type(port_values))
            return PortValidationError(message, breadcrumbs_to_port(breadcrumbs_local))

        # Turn the port values into a normal dictionary and create a shallow copy. The `validate_ports` method to which
        # the `port_values` will be passed, will pop the values corresponding to explicit ports. This is necessary for
        # the `validate_dynamic_ports` to correctly detect any implicit ports. However, the `validator` will expect the
        # entire original input namespace to be there. Since the latter has to be called after the ports have been
        # validated, we need to create a clone of the port values here.
        port_values = dict(port_values)
        port_values_clone = port_values.copy()

        # If the namespace is not required and there are no port_values specified, consider it valid
        if not port_values and not self.required:
            return

        # In all other cases, validate all input ports explicitly specified in this port namespace
        validation_error = self.validate_ports(port_values, breadcrumbs_local)
        if validation_error:
            return validation_error

        # If any port_values remain, validate against the dynamic properties of the namespace
        validation_error = self.validate_dynamic_ports(port_values, breadcrumbs)
        if validation_error:
            return validation_error

        # Validate the validator after the ports themselves, as it most likely will rely on the port values
        if self.validator is not None:
            spec = get_arg_spec(self.validator)
            if len(spec[0]) == 1:
                warnings.warn(VALIDATOR_SIGNATURE_DEPRECATION_WARNING.format(self.validator.__name__))
                message = self.validator(port_values_clone)
            else:
                message = self.validator(port_values_clone, self)
            if message is not None:
                assert isinstance(message, str), \
                    "Validator returned something other than None or str: '{}'".format(type(message))
                return PortValidationError(message, breadcrumbs_to_port(breadcrumbs_local))
Пример #12
0
def _instantiate_client(client_class, **kwargs):
    """Instantiate a client from kwargs, removing the subscription_id/tenant_id argument if unsupported.
    """
    args = get_arg_spec(client_class.__init__).args
    for key in ['subscription_id', 'tenant_id']:
        if key not in kwargs:
            continue
        if key not in args:
            del kwargs[key]
        elif sys.version_info < (3, 0) and isinstance(kwargs[key], unicode):
            kwargs[key] = kwargs[key].encode('utf-8')
    return client_class(**kwargs)
Пример #13
0
def _instantiate_client(client_class, **kwargs):
    """Instantiate a client from kwargs, filtering kwargs to match client signature.
    """
    args = get_arg_spec(client_class.__init__).args
    for key in ['subscription_id', 'tenant_id', 'base_url', 'credential', 'credentials']:
        if key not in kwargs:
            continue
        if key not in args:
            del kwargs[key]
        elif sys.version_info < (3, 0) and isinstance(kwargs[key], unicode):
            kwargs[key] = kwargs[key].encode('utf-8')
    return client_class(**kwargs)
Пример #14
0
def _instantiate_client(client_class, **kwargs):
    """Instantiate a client from kwargs, removing the subscription_id/tenant_id argument if unsupported.
    """
    args = get_arg_spec(client_class.__init__).args
    for key in ['subscription_id', 'tenant_id']:
        if key not in kwargs:
            continue
        if key not in args:
            del kwargs[key]
        elif sys.version_info < (3, 0) and isinstance(kwargs[key], unicode):
            kwargs[key] = kwargs[key].encode('utf-8')
    return client_class(**kwargs)
Пример #15
0
def get_client_from_cli_profile(client_class, **kwargs):
    """Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.

    This method will fill automatically the following client parameters:
    - credentials
    - subscription_id
    - base_url

    Parameters provided in kwargs will override CLI parameters and be passed directly to the client.

    :Example:

    .. code:: python

        from azure.common.client_factory import get_client_from_cli_profile
        from azure.mgmt.compute import ComputeManagementClient
        client = get_client_from_cli_profile(ComputeManagementClient)

    .. versionadded:: 1.1.6

    :param client_class: A SDK client class
    :return: An instantiated client
    :raises: ImportError if azure-cli-core package is not available
    """
    cloud = get_cli_active_cloud()
    parameters = {}
    if 'credentials' not in kwargs or 'subscription_id' not in kwargs:
        resource, _ = _client_resource(client_class, cloud)
        credentials, subscription_id, tenant_id = get_azure_cli_credentials(resource=resource,
                                                                            with_tenant=True)
        parameters.update({
            'credentials': kwargs.get('credentials', credentials),
            'subscription_id': kwargs.get('subscription_id', subscription_id)
        })

    args = get_arg_spec(client_class.__init__).args
    if 'adla_job_dns_suffix' in args and 'adla_job_dns_suffix' not in kwargs:  # Datalake
        # Let it raise here with AttributeError at worst, this would mean this cloud does not define
        # ADL endpoint and no manual suffix was given
        parameters['adla_job_dns_suffix'] = cloud.suffixes.azure_datalake_analytics_catalog_and_job_endpoint
    elif 'base_url' in args and 'base_url' not in kwargs:
        _, base_url = _client_resource(client_class, cloud)
        if base_url:
            parameters['base_url'] = base_url
        else:
            parameters['base_url'] = cloud.endpoints.resource_manager
    if 'tenant_id' in args and 'tenant_id' not in kwargs:
        parameters['tenant_id'] = tenant_id
    parameters.update(kwargs)
    return _instantiate_client(client_class, **parameters)
Пример #16
0
def execute_samples(module_globals, key_env_variable):
    """Execute samples based on a dict <name, function>
    """
    try:
        subscription_key = key_env_variable
    except KeyError:
        raise SubscriptionKeyError(
            "You need to either set the {} env variable.".format(key_env_variable))

    for func in list(module_globals.values()):
        if not isinstance(func, types.FunctionType):
            continue
        args = get_arg_spec(func).args
        if 'subscription_key' in args:
            start_sample(func, subscription_key)
Пример #17
0
    args = parser.parse_args()

    callocr = True
    # Output dir
    if args.outputdir:
        RESULTS_FOLDER = args.outputdir

    if not os.path.exists(RESULTS_FOLDER):
        os.makedirs(RESULTS_FOLDER)

    # Check for available OCR engine functions
    ocrengines = []
    for func in list(globals().values()):
        if not isinstance(func, types.FunctionType):
            continue
        arguments = get_arg_spec(func).args
        if 'filename' in arguments:
            ocrengines.append(func)

    if len(ocrengines) == 0:
        print("No OCR Engine found. bye.")
        exit

    # Process a single image
    if args.document:
        if not os.path.exists(args.document):
            print("Image path doesn't exist.")
            exit
        else:
            process_one_image(args.document, ocrengines, callocr, args.verbose)
    else:
Пример #18
0
def get_client_from_cli_profile(client_class, **kwargs):
    """Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.

    *Disclaimer*: This is NOT the recommended approach to authenticate with CLI login, this method is deprecated.
    use https://pypi.org/project/azure-identity/ and AzureCliCredential instead. See example code below:

    .. code:: python

        from azure.identity import AzureCliCredential
        from azure.mgmt.compute import ComputeManagementClient
        client = ComputeManagementClient(AzureCliCredential(), subscription_id)

    This method is not working for azure-cli-core>=2.21.0 (released in March 2021).

    For compatible azure-cli-core (< 2.20.0), This method will automatically fill the following client parameters:
    - credentials/credential
    - subscription_id
    - base_url

    Parameters provided in kwargs will override CLI parameters and be passed directly to the client.

    :Example:

    .. code:: python

        from azure.common.client_factory import get_client_from_cli_profile
        from azure.mgmt.compute import ComputeManagementClient
        client = get_client_from_cli_profile(ComputeManagementClient)

    .. versionadded:: 1.1.6

    .. deprecated:: 1.1.28

    .. seealso:: https://aka.ms/azsdk/python/identity/migration

    :param client_class: A SDK client class
    :return: An instantiated client
    :raises: ImportError if azure-cli-core package is not available
    """
    warnings.warn(
        "get_client_from_cli_profile is deprecated, please use azure-identity and AzureCliCredential instead. "
        + "See also https://aka.ms/azsdk/python/identity/migration.",
        DeprecationWarning)

    cloud = get_cli_active_cloud()
    parameters = {}
    no_credential_sentinel = object()
    kwarg_cred = kwargs.pop('credentials', no_credential_sentinel)
    if kwarg_cred is no_credential_sentinel:
        kwarg_cred = kwargs.pop('credential', no_credential_sentinel)

    if kwarg_cred is no_credential_sentinel or 'subscription_id' not in kwargs:
        resource, _ = _client_resource(client_class, cloud)
        credentials, subscription_id, tenant_id = get_azure_cli_credentials(
            resource=resource,
            with_tenant=True,
        )
        # Provide both syntax of cred, we have an "inspect" filter later
        credential_to_pass = credentials if kwarg_cred is no_credential_sentinel else kwarg_cred
        parameters.update({
            'credentials':
            credential_to_pass,
            'credential':
            credential_to_pass,
            'subscription_id':
            kwargs.get('subscription_id', subscription_id)
        })

    args = get_arg_spec(client_class.__init__).args
    if 'adla_job_dns_suffix' in args and 'adla_job_dns_suffix' not in kwargs:  # Datalake
        # Let it raise here with AttributeError at worst, this would mean this cloud does not define
        # ADL endpoint and no manual suffix was given
        parameters[
            'adla_job_dns_suffix'] = cloud.suffixes.azure_datalake_analytics_catalog_and_job_endpoint
    elif 'base_url' in args and 'base_url' not in kwargs:
        _, base_url = _client_resource(client_class, cloud)
        if base_url:
            parameters['base_url'] = base_url
        else:
            parameters['base_url'] = cloud.endpoints.resource_manager
    if 'tenant_id' in args and 'tenant_id' not in kwargs:
        parameters['tenant_id'] = tenant_id
    parameters.update(kwargs)
    return _instantiate_client(client_class, **parameters)