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
5# license information.
6#
7# Code generated by Microsoft (R) AutoRest Code Generator.
8# Changes may cause incorrect behavior and will be lost if the code is
9# regenerated.
10# --------------------------------------------------------------------------
11
12import uuid
13from msrest.pipeline import ClientRawResponse
14from msrest.polling import LROPoller, NoPolling
15from msrestazure.polling.arm_polling import ARMPolling
16
17from .. import models
18
19
20class UsageDetailsOperations(object):
21    """UsageDetailsOperations operations.
22
23    :param client: Client for service requests.
24    :param config: Configuration of service client.
25    :param serializer: An object model serializer.
26    :param deserializer: An object model deserializer.
27    :ivar api_version: Version of the API to be used with the client request. The current version is 2019-04-01-preview. Constant value: "2019-04-01-preview".
28    """
29
30    models = models
31
32    def __init__(self, client, config, serializer, deserializer):
33
34        self._client = client
35        self._serialize = serializer
36        self._deserialize = deserializer
37        self.api_version = "2019-04-01-preview"
38
39        self.config = config
40
41    def list(
42            self, scope, expand=None, filter=None, skiptoken=None, top=None, metric=None, custom_headers=None, raw=False, **operation_config):
43        """Lists the usage details for the defined scope. Usage details are
44        available via this API only for May 1, 2014 or later.
45
46        :param scope: The scope associated with usage details operations. This
47         includes '/subscriptions/{subscriptionId}/' for subscription scope,
48         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}'
49         for resourceGroup scope,
50         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for
51         Billing Account scope,
52         '/providers/Microsoft.Billing/departments/{departmentId}' for
53         Department scope,
54         '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}'
55         for EnrollmentAccount scope and
56         '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
57         for Management Group scope. For subscription, billing account,
58         department, enrollment account and management group, you can also add
59         billing period to the scope using
60         '/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. For
61         e.g. to specify billing period at department scope use
62         '/providers/Microsoft.Billing/departments/{departmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'
63        :type scope: str
64        :param expand: May be used to expand the properties/additionalInfo or
65         properties/meterDetails within a list of usage details. By default,
66         these fields are not included when listing usage details.
67        :type expand: str
68        :param filter: May be used to filter usageDetails by
69         properties/resourceGroup, properties/resourceName,
70         properties/resourceId, properties/chargeType, properties/reservationId
71         or tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'.
72         It does not currently support 'ne', 'or', or 'not'. Tag filter is a
73         key value pair string where key and value is separated by a colon (:).
74        :type filter: str
75        :param skiptoken: Skiptoken is only used if a previous operation
76         returned a partial result. If a previous response contains a nextLink
77         element, the value of the nextLink element will include a skiptoken
78         parameter that specifies a starting point to use for subsequent calls.
79        :type skiptoken: str
80        :param top: May be used to limit the number of results to the most
81         recent N usageDetails.
82        :type top: int
83        :param metric: Allows to select different type of cost/usage records.
84         Possible values include: 'ActualCostMetricType',
85         'AmortizedCostMetricType', 'UsageMetricType'
86        :type metric: str or ~azure.mgmt.consumption.models.Metrictype
87        :param dict custom_headers: headers that will be added to the request
88        :param bool raw: returns the direct response alongside the
89         deserialized response
90        :param operation_config: :ref:`Operation configuration
91         overrides<msrest:optionsforoperations>`.
92        :return: An iterator like instance of UsageDetail
93        :rtype:
94         ~azure.mgmt.consumption.models.UsageDetailPaged[~azure.mgmt.consumption.models.UsageDetail]
95        :raises:
96         :class:`ErrorResponseException<azure.mgmt.consumption.models.ErrorResponseException>`
97        """
98        def internal_paging(next_link=None, raw=False):
99
100            if not next_link:
101                # Construct URL
102                url = self.list.metadata['url']
103                path_format_arguments = {
104                    'scope': self._serialize.url("scope", scope, 'str', skip_quote=True)
105                }
106                url = self._client.format_url(url, **path_format_arguments)
107
108                # Construct parameters
109                query_parameters = {}
110                if expand is not None:
111                    query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
112                if filter is not None:
113                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
114                if skiptoken is not None:
115                    query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str')
116                if top is not None:
117                    query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1)
118                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
119                if metric is not None:
120                    query_parameters['metric'] = self._serialize.query("metric", metric, 'str')
121
122            else:
123                url = next_link
124                query_parameters = {}
125
126            # Construct headers
127            header_parameters = {}
128            header_parameters['Accept'] = 'application/json'
129            if self.config.generate_client_request_id:
130                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
131            if custom_headers:
132                header_parameters.update(custom_headers)
133            if self.config.accept_language is not None:
134                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
135
136            # Construct and send request
137            request = self._client.get(url, query_parameters, header_parameters)
138            response = self._client.send(request, stream=False, **operation_config)
139
140            if response.status_code not in [200]:
141                raise models.ErrorResponseException(self._deserialize, response)
142
143            return response
144
145        # Deserialize response
146        deserialized = models.UsageDetailPaged(internal_paging, self._deserialize.dependencies)
147
148        if raw:
149            header_dict = {}
150            client_raw_response = models.UsageDetailPaged(internal_paging, self._deserialize.dependencies, header_dict)
151            return client_raw_response
152
153        return deserialized
154    list.metadata = {'url': '/{scope}/providers/Microsoft.Consumption/usageDetails'}
155
156
157    def _download_initial(
158            self, scope, metric=None, custom_headers=None, raw=False, **operation_config):
159        # Construct URL
160        url = self.download.metadata['url']
161        path_format_arguments = {
162            'scope': self._serialize.url("scope", scope, 'str', skip_quote=True)
163        }
164        url = self._client.format_url(url, **path_format_arguments)
165
166        # Construct parameters
167        query_parameters = {}
168        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
169        if metric is not None:
170            query_parameters['metric'] = self._serialize.query("metric", metric, 'str')
171
172        # Construct headers
173        header_parameters = {}
174        header_parameters['Accept'] = 'application/json'
175        if self.config.generate_client_request_id:
176            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
177        if custom_headers:
178            header_parameters.update(custom_headers)
179        if self.config.accept_language is not None:
180            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
181
182        # Construct and send request
183        request = self._client.post(url, query_parameters, header_parameters)
184        response = self._client.send(request, stream=False, **operation_config)
185
186        if response.status_code not in [200, 202]:
187            raise models.ErrorResponseException(self._deserialize, response)
188
189        deserialized = None
190        header_dict = {}
191
192        if response.status_code == 200:
193            deserialized = self._deserialize('UsageDetailsDownloadResponse', response)
194            header_dict = {
195                'Location': 'str',
196                'Retry-After': 'str',
197                'Azure-AsyncOperation': 'str',
198            }
199
200        if raw:
201            client_raw_response = ClientRawResponse(deserialized, response)
202            client_raw_response.add_headers(header_dict)
203            return client_raw_response
204
205        return deserialized
206
207    def download(
208            self, scope, metric=None, custom_headers=None, raw=False, polling=True, **operation_config):
209        """Download usage details data.
210
211        :param scope: The scope associated with usage details operations. This
212         includes '/subscriptions/{subscriptionId}/' for subscription scope,
213         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}'
214         for resourceGroup scope,
215         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for
216         Billing Account scope,
217         '/providers/Microsoft.Billing/departments/{departmentId}' for
218         Department scope,
219         '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}'
220         for EnrollmentAccount scope and
221         '/providers/Microsoft.Management/managementGroups/{managementGroupId}'
222         for Management Group scope. For subscription, billing account,
223         department, enrollment account and management group, you can also add
224         billing period to the scope using
225         '/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'. For
226         e.g. to specify billing period at department scope use
227         '/providers/Microsoft.Billing/departments/{departmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'
228        :type scope: str
229        :param metric: Allows to select different type of cost/usage records.
230         Possible values include: 'ActualCostMetricType',
231         'AmortizedCostMetricType', 'UsageMetricType'
232        :type metric: str or ~azure.mgmt.consumption.models.Metrictype
233        :param dict custom_headers: headers that will be added to the request
234        :param bool raw: The poller return type is ClientRawResponse, the
235         direct response alongside the deserialized response
236        :param polling: True for ARMPolling, False for no polling, or a
237         polling object for personal polling strategy
238        :return: An instance of LROPoller that returns
239         UsageDetailsDownloadResponse or
240         ClientRawResponse<UsageDetailsDownloadResponse> if raw==True
241        :rtype:
242         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.consumption.models.UsageDetailsDownloadResponse]
243         or
244         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.consumption.models.UsageDetailsDownloadResponse]]
245        :raises:
246         :class:`ErrorResponseException<azure.mgmt.consumption.models.ErrorResponseException>`
247        """
248        raw_result = self._download_initial(
249            scope=scope,
250            metric=metric,
251            custom_headers=custom_headers,
252            raw=True,
253            **operation_config
254        )
255
256        def get_long_running_output(response):
257            header_dict = {
258                'Location': 'str',
259                'Retry-After': 'str',
260                'Azure-AsyncOperation': 'str',
261            }
262            deserialized = self._deserialize('UsageDetailsDownloadResponse', response)
263
264            if raw:
265                client_raw_response = ClientRawResponse(deserialized, response)
266                client_raw_response.add_headers(header_dict)
267                return client_raw_response
268
269            return deserialized
270
271        lro_delay = operation_config.get(
272            'long_running_operation_timeout',
273            self.config.long_running_operation_timeout)
274        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **operation_config)
275        elif polling is False: polling_method = NoPolling()
276        else: polling_method = polling
277        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
278    download.metadata = {'url': '/{scope}/providers/Microsoft.Consumption/usageDetails/download'}
279