1# coding=utf-8
2# --------------------------------------------------------------------------
3# Copyright (c) Microsoft Corporation. All rights reserved.
4# Licensed under the MIT License. See License.txt in the project root for license information.
5# Code generated by Microsoft (R) AutoRest Code Generator.
6# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7# --------------------------------------------------------------------------
8from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
9import warnings
10
11from azure.core.async_paging import AsyncItemPaged, AsyncList
12from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
13from azure.core.pipeline import PipelineResponse
14from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
15from azure.mgmt.core.exceptions import ARMErrorFormat
16
17from ... import models as _models
18
19T = TypeVar('T')
20ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
21
22class UsagesOperations:
23    """UsagesOperations async operations.
24
25    You should not instantiate this class directly. Instead, you should create a Client instance that
26    instantiates it for you and attaches it as an attribute.
27
28    :ivar models: Alias to model classes used in this operation group.
29    :type models: ~azure.mgmt.sql.models
30    :param client: Client for service requests.
31    :param config: Configuration of service client.
32    :param serializer: An object model serializer.
33    :param deserializer: An object model deserializer.
34    """
35
36    models = _models
37
38    def __init__(self, client, config, serializer, deserializer) -> None:
39        self._client = client
40        self._serialize = serializer
41        self._deserialize = deserializer
42        self._config = config
43
44    def list_by_instance_pool(
45        self,
46        resource_group_name: str,
47        instance_pool_name: str,
48        expand_children: Optional[bool] = None,
49        **kwargs: Any
50    ) -> AsyncIterable["_models.UsageListResult"]:
51        """Gets all instance pool usage metrics.
52
53        :param resource_group_name: The name of the resource group that contains the resource. You can
54         obtain this value from the Azure Resource Manager API or the portal.
55        :type resource_group_name: str
56        :param instance_pool_name: The name of the instance pool to be retrieved.
57        :type instance_pool_name: str
58        :param expand_children: Optional request parameter to include managed instance usages within
59         the instance pool.
60        :type expand_children: bool
61        :keyword callable cls: A custom type or function that will be passed the direct response
62        :return: An iterator like instance of either UsageListResult or the result of cls(response)
63        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.UsageListResult]
64        :raises: ~azure.core.exceptions.HttpResponseError
65        """
66        cls = kwargs.pop('cls', None)  # type: ClsType["_models.UsageListResult"]
67        error_map = {
68            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
69        }
70        error_map.update(kwargs.pop('error_map', {}))
71        api_version = "2021-02-01-preview"
72        accept = "application/json"
73
74        def prepare_request(next_link=None):
75            # Construct headers
76            header_parameters = {}  # type: Dict[str, Any]
77            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
78
79            if not next_link:
80                # Construct URL
81                url = self.list_by_instance_pool.metadata['url']  # type: ignore
82                path_format_arguments = {
83                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
84                    'instancePoolName': self._serialize.url("instance_pool_name", instance_pool_name, 'str'),
85                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
86                }
87                url = self._client.format_url(url, **path_format_arguments)
88                # Construct parameters
89                query_parameters = {}  # type: Dict[str, Any]
90                if expand_children is not None:
91                    query_parameters['expandChildren'] = self._serialize.query("expand_children", expand_children, 'bool')
92                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
93
94                request = self._client.get(url, query_parameters, header_parameters)
95            else:
96                url = next_link
97                query_parameters = {}  # type: Dict[str, Any]
98                request = self._client.get(url, query_parameters, header_parameters)
99            return request
100
101        async def extract_data(pipeline_response):
102            deserialized = self._deserialize('UsageListResult', pipeline_response)
103            list_of_elem = deserialized.value
104            if cls:
105                list_of_elem = cls(list_of_elem)
106            return deserialized.next_link or None, AsyncList(list_of_elem)
107
108        async def get_next(next_link=None):
109            request = prepare_request(next_link)
110
111            pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
112            response = pipeline_response.http_response
113
114            if response.status_code not in [200]:
115                map_error(status_code=response.status_code, response=response, error_map=error_map)
116                raise HttpResponseError(response=response, error_format=ARMErrorFormat)
117
118            return pipeline_response
119
120        return AsyncItemPaged(
121            get_next, extract_data
122        )
123    list_by_instance_pool.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/instancePools/{instancePoolName}/usages'}  # type: ignore
124