diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json index 8041e01d515b..ea2ecce20f4b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json +++ b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.4.5", + "commit": "6054f1d9f96a4f5189dace33facf9144d468e705", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.8.4", - "@autorest/modelerfour@4.19.2" + "@autorest/python@6.2.1", + "@autorest/modelerfour@4.24.3" ], - "commit": "74efe54fbc55c91a1d9213afbb2723747acfddf9", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/cost-management/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.8.4 --use=@autorest/modelerfour@4.19.2 --version=3.4.5", + "autorest_command": "autorest specification/cost-management/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/cost-management/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py index 0e26ee2701fe..8968aa76c748 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/__init__.py @@ -10,10 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['CostManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "CostManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py index 0cd20f8ef97a..dabc5c4d4905 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_configuration.py @@ -6,60 +6,65 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +import sys +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class CostManagementClientConfiguration(Configuration): +class CostManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for CostManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential, # type: "TokenCredential" - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: + super(CostManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-10-01") # type: Literal["2022-10-01"] + if credential is None: raise ValueError("Parameter 'credential' must not be None.") - super(CostManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential - self.api_version = "2019-11-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-costmanagement/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-costmanagement/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py index 521cb5222a88..4ba98e38ed43 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_cost_management_client.py @@ -6,36 +6,45 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from ._configuration import CostManagementClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + AlertsOperations, + BenefitRecommendationsOperations, + BenefitUtilizationSummariesOperations, + DimensionsOperations, + ExportsOperations, + ForecastOperations, + GenerateCostDetailsReportOperations, + GenerateDetailedCostReportOperationResultsOperations, + GenerateDetailedCostReportOperationStatusOperations, + GenerateDetailedCostReportOperations, + GenerateReservationDetailsReportOperations, + Operations, + PriceSheetOperations, + QueryOperations, + ScheduledActionsOperations, + ViewsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import CostManagementClientConfiguration -from .operations import SettingsOperations -from .operations import ViewsOperations -from .operations import AlertsOperations -from .operations import ForecastOperations -from .operations import DimensionsOperations -from .operations import QueryOperations -from .operations import GenerateReservationDetailsReportOperations -from .operations import Operations -from .operations import ExportsOperations -from . import models -class CostManagementClient(object): - """CostManagementClient. +class CostManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """CostManagement management client provides access to CostManagement resources for Azure + Enterprise Subscriptions. - :ivar settings: SettingsOperations operations - :vartype settings: azure.mgmt.costmanagement.operations.SettingsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.costmanagement.operations.Operations :ivar views: ViewsOperations operations :vartype views: azure.mgmt.costmanagement.operations.ViewsOperations :ivar alerts: AlertsOperations operations @@ -46,68 +55,111 @@ class CostManagementClient(object): :vartype dimensions: azure.mgmt.costmanagement.operations.DimensionsOperations :ivar query: QueryOperations operations :vartype query: azure.mgmt.costmanagement.operations.QueryOperations - :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations operations - :vartype generate_reservation_details_report: azure.mgmt.costmanagement.operations.GenerateReservationDetailsReportOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.costmanagement.operations.Operations + :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations + operations + :vartype generate_reservation_details_report: + azure.mgmt.costmanagement.operations.GenerateReservationDetailsReportOperations :ivar exports: ExportsOperations operations :vartype exports: azure.mgmt.costmanagement.operations.ExportsOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar generate_cost_details_report: GenerateCostDetailsReportOperations operations + :vartype generate_cost_details_report: + azure.mgmt.costmanagement.operations.GenerateCostDetailsReportOperations + :ivar generate_detailed_cost_report: GenerateDetailedCostReportOperations operations + :vartype generate_detailed_cost_report: + azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperations + :ivar generate_detailed_cost_report_operation_results: + GenerateDetailedCostReportOperationResultsOperations operations + :vartype generate_detailed_cost_report_operation_results: + azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperationResultsOperations + :ivar generate_detailed_cost_report_operation_status: + GenerateDetailedCostReportOperationStatusOperations operations + :vartype generate_detailed_cost_report_operation_status: + azure.mgmt.costmanagement.operations.GenerateDetailedCostReportOperationStatusOperations + :ivar price_sheet: PriceSheetOperations operations + :vartype price_sheet: azure.mgmt.costmanagement.operations.PriceSheetOperations + :ivar scheduled_actions: ScheduledActionsOperations operations + :vartype scheduled_actions: azure.mgmt.costmanagement.operations.ScheduledActionsOperations + :ivar benefit_recommendations: BenefitRecommendationsOperations operations + :vartype benefit_recommendations: + azure.mgmt.costmanagement.operations.BenefitRecommendationsOperations + :ivar benefit_utilization_summaries: BenefitUtilizationSummariesOperations operations + :vartype benefit_utilization_summaries: + azure.mgmt.costmanagement.operations.BenefitUtilizationSummariesOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( - self, - credential, # type: "TokenCredential" - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = CostManagementClientConfiguration(credential, **kwargs) + self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any + ) -> None: + self._config = CostManagementClientConfiguration(credential=credential, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.settings = SettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.views = ViewsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.alerts = AlertsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.forecast = ForecastOperations( - self._client, self._config, self._serialize, self._deserialize) - self.dimensions = DimensionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.query = QueryOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) + self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.exports = ExportsOperations( - self._client, self._config, self._serialize, self._deserialize) - - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + self._client, self._config, self._serialize, self._deserialize + ) + self.exports = ExportsOperations(self._client, self._config, self._serialize, self._deserialize) + self.generate_cost_details_report = GenerateCostDetailsReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report = GenerateDetailedCostReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_results = GenerateDetailedCostReportOperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_status = GenerateDetailedCostReportOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.scheduled_actions = ScheduledActionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_recommendations = BenefitRecommendationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - http_request.url = self._client.format_url(http_request.url) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json deleted file mode 100644 index 1e323f28f6ac..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "chosen_version": "2019-11-01", - "total_api_version_list": ["2019-11-01"], - "client": { - "name": "CostManagementClient", - "filename": "_cost_management_client", - "description": "CostManagementClient.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, - "azure_arm": true, - "has_lro_operations": true, - "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"CostManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"CostManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - } - }, - "constant": { - }, - "call": "credential", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=None, # type: Optional[str]", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: Optional[str] = None,", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "settings": "SettingsOperations", - "views": "ViewsOperations", - "alerts": "AlertsOperations", - "forecast": "ForecastOperations", - "dimensions": "DimensionsOperations", - "query": "QueryOperations", - "generate_reservation_details_report": "GenerateReservationDetailsReportOperations", - "operations": "Operations", - "exports": "ExportsOperations" - } -} \ No newline at end of file diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py new file mode 100644 index 000000000000..9aad73fc743e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py index cac9f5d10f8b..e5754a47ce68 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "3.0.0" +VERSION = "1.0.0b1" diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py index 7dec206f98a6..b7a880c83975 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/__init__.py @@ -7,4 +7,17 @@ # -------------------------------------------------------------------------- from ._cost_management_client import CostManagementClient -__all__ = ['CostManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "CostManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py index 22c0705a007a..585b86de08bd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_configuration.py @@ -6,56 +6,62 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class CostManagementClientConfiguration(Configuration): +class CostManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for CostManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + super(CostManagementClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop("api_version", "2022-10-01") # type: Literal["2022-10-01"] + if credential is None: raise ValueError("Parameter 'credential' must not be None.") - super(CostManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential - self.api_version = "2019-11-01" - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-costmanagement/{}'.format(VERSION)) + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-costmanagement/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py index ab4f0f5bdab7..0b26c3c423d1 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_cost_management_client.py @@ -6,34 +6,45 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import CostManagementClientConfiguration +from .operations import ( + AlertsOperations, + BenefitRecommendationsOperations, + BenefitUtilizationSummariesOperations, + DimensionsOperations, + ExportsOperations, + ForecastOperations, + GenerateCostDetailsReportOperations, + GenerateDetailedCostReportOperationResultsOperations, + GenerateDetailedCostReportOperationStatusOperations, + GenerateDetailedCostReportOperations, + GenerateReservationDetailsReportOperations, + Operations, + PriceSheetOperations, + QueryOperations, + ScheduledActionsOperations, + ViewsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import CostManagementClientConfiguration -from .operations import SettingsOperations -from .operations import ViewsOperations -from .operations import AlertsOperations -from .operations import ForecastOperations -from .operations import DimensionsOperations -from .operations import QueryOperations -from .operations import GenerateReservationDetailsReportOperations -from .operations import Operations -from .operations import ExportsOperations -from .. import models - -class CostManagementClient(object): - """CostManagementClient. +class CostManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """CostManagement management client provides access to CostManagement resources for Azure + Enterprise Subscriptions. - :ivar settings: SettingsOperations operations - :vartype settings: azure.mgmt.costmanagement.aio.operations.SettingsOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.costmanagement.aio.operations.Operations :ivar views: ViewsOperations operations :vartype views: azure.mgmt.costmanagement.aio.operations.ViewsOperations :ivar alerts: AlertsOperations operations @@ -44,66 +55,111 @@ class CostManagementClient(object): :vartype dimensions: azure.mgmt.costmanagement.aio.operations.DimensionsOperations :ivar query: QueryOperations operations :vartype query: azure.mgmt.costmanagement.aio.operations.QueryOperations - :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations operations - :vartype generate_reservation_details_report: azure.mgmt.costmanagement.aio.operations.GenerateReservationDetailsReportOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.costmanagement.aio.operations.Operations + :ivar generate_reservation_details_report: GenerateReservationDetailsReportOperations + operations + :vartype generate_reservation_details_report: + azure.mgmt.costmanagement.aio.operations.GenerateReservationDetailsReportOperations :ivar exports: ExportsOperations operations :vartype exports: azure.mgmt.costmanagement.aio.operations.ExportsOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar generate_cost_details_report: GenerateCostDetailsReportOperations operations + :vartype generate_cost_details_report: + azure.mgmt.costmanagement.aio.operations.GenerateCostDetailsReportOperations + :ivar generate_detailed_cost_report: GenerateDetailedCostReportOperations operations + :vartype generate_detailed_cost_report: + azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperations + :ivar generate_detailed_cost_report_operation_results: + GenerateDetailedCostReportOperationResultsOperations operations + :vartype generate_detailed_cost_report_operation_results: + azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperationResultsOperations + :ivar generate_detailed_cost_report_operation_status: + GenerateDetailedCostReportOperationStatusOperations operations + :vartype generate_detailed_cost_report_operation_status: + azure.mgmt.costmanagement.aio.operations.GenerateDetailedCostReportOperationStatusOperations + :ivar price_sheet: PriceSheetOperations operations + :vartype price_sheet: azure.mgmt.costmanagement.aio.operations.PriceSheetOperations + :ivar scheduled_actions: ScheduledActionsOperations operations + :vartype scheduled_actions: azure.mgmt.costmanagement.aio.operations.ScheduledActionsOperations + :ivar benefit_recommendations: BenefitRecommendationsOperations operations + :vartype benefit_recommendations: + azure.mgmt.costmanagement.aio.operations.BenefitRecommendationsOperations + :ivar benefit_utilization_summaries: BenefitUtilizationSummariesOperations operations + :vartype benefit_utilization_summaries: + azure.mgmt.costmanagement.aio.operations.BenefitUtilizationSummariesOperations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( - self, - credential: "AsyncTokenCredential", - base_url: Optional[str] = None, - **kwargs: Any + self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = CostManagementClientConfiguration(credential, **kwargs) + self._config = CostManagementClientConfiguration(credential=credential, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - - self.settings = SettingsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.views = ViewsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.alerts = AlertsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.forecast = ForecastOperations( - self._client, self._config, self._serialize, self._deserialize) - self.dimensions = DimensionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.query = QueryOperations( - self._client, self._config, self._serialize, self._deserialize) + self._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.views = ViewsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.forecast = ForecastOperations(self._client, self._config, self._serialize, self._deserialize) + self.dimensions = DimensionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.query = QueryOperations(self._client, self._config, self._serialize, self._deserialize) self.generate_reservation_details_report = GenerateReservationDetailsReportOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.exports = ExportsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.exports = ExportsOperations(self._client, self._config, self._serialize, self._deserialize) + self.generate_cost_details_report = GenerateCostDetailsReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report = GenerateDetailedCostReportOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_results = GenerateDetailedCostReportOperationResultsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.generate_detailed_cost_report_operation_status = GenerateDetailedCostReportOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.price_sheet = PriceSheetOperations(self._client, self._config, self._serialize, self._deserialize) + self.scheduled_actions = ScheduledActionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_recommendations = BenefitRecommendationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self._client, self._config, self._serialize, self._deserialize + ) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - http_request.url = self._client.format_url(http_request.url) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py index c70a4cb564cb..2d305a7dc351 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/__init__.py @@ -6,24 +6,48 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._settings_operations import SettingsOperations +from ._operations import Operations from ._views_operations import ViewsOperations from ._alerts_operations import AlertsOperations from ._forecast_operations import ForecastOperations from ._dimensions_operations import DimensionsOperations from ._query_operations import QueryOperations from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations -from ._operations import Operations from ._exports_operations import ExportsOperations +from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations +from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations +from ._generate_detailed_cost_report_operation_results_operations import ( + GenerateDetailedCostReportOperationResultsOperations, +) +from ._generate_detailed_cost_report_operation_status_operations import ( + GenerateDetailedCostReportOperationStatusOperations, +) +from ._price_sheet_operations import PriceSheetOperations +from ._scheduled_actions_operations import ScheduledActionsOperations +from ._benefit_recommendations_operations import BenefitRecommendationsOperations +from ._benefit_utilization_summaries_operations import BenefitUtilizationSummariesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'SettingsOperations', - 'ViewsOperations', - 'AlertsOperations', - 'ForecastOperations', - 'DimensionsOperations', - 'QueryOperations', - 'GenerateReservationDetailsReportOperations', - 'Operations', - 'ExportsOperations', + "Operations", + "ViewsOperations", + "AlertsOperations", + "ForecastOperations", + "DimensionsOperations", + "QueryOperations", + "GenerateReservationDetailsReportOperations", + "ExportsOperations", + "GenerateCostDetailsReportOperations", + "GenerateDetailedCostReportOperations", + "GenerateDetailedCostReportOperationResultsOperations", + "GenerateDetailedCostReportOperationStatusOperations", + "PriceSheetOperations", + "ScheduledActionsOperations", + "BenefitRecommendationsOperations", + "BenefitUtilizationSummariesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py index 216d5ebc7b21..c24ac2826010 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,46 +6,62 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._alerts_operations import ( + build_dismiss_request, + build_get_request, + build_list_external_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AlertsOperations: - """AlertsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AlertsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`alerts` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def list( - self, - scope: str, - **kwargs: Any - ) -> "_models.AlertsResult": + @distributed_trace_async + async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: """Lists the alerts for scope defined. :param scope: The scope associated with alerts operations. This includes @@ -62,59 +79,61 @@ async def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] + + request = build_list_request( + scope=scope, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts'} # type: ignore - async def get( - self, - scope: str, - alert_id: str, - **kwargs: Any - ) -> "_models.Alert": + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: """Gets the alert for the scope by alert ID. :param scope: The scope associated with alerts operations. This includes @@ -132,63 +151,72 @@ async def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @overload async def dismiss( self, scope: str, alert_id: str, - parameters: "_models.DismissAlertPayload", + parameters: _models.DismissAlertPayload, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Alert": + ) -> _models.Alert: """Dismisses the specified alert. :param scope: The scope associated with alerts operations. This includes @@ -206,120 +234,219 @@ async def dismiss( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str - :param parameters: Parameters supplied to the Dismiss Alert operation. + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def dismiss( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def dismiss( + self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO], **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.dismiss.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'DismissAlertPayload') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "DismissAlertPayload") + + request = build_dismiss_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.dismiss.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - dismiss.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + dismiss.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @distributed_trace_async async def list_external( self, - external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, **kwargs: Any - ) -> "_models.AlertsResult": + ) -> _models.AlertsResult: """Lists the Alerts for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list_external.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] + + request = build_list_external_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + template_url=self.list_external.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_external.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts'} # type: ignore + + list_external.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py new file mode 100644 index 000000000000..95dfa1cd9532 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py @@ -0,0 +1,173 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._benefit_recommendations_operations import build_list_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class BenefitRecommendationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`benefit_recommendations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + billing_scope: str, + filter: Optional[str] = None, + orderby: Optional[str] = None, + expand: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.BenefitRecommendationModel"]: + """List of recommendations for purchasing savings plan. + + :param billing_scope: The scope associated with benefit recommendation operations. This + includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, + /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for enterprise agreement + scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type billing_scope: str + :param filter: Can be used to filter benefitRecommendations by: properties/scope with allowed + values ['Single', 'Shared'] and default value 'Shared'; and properties/lookBackPeriod with + allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and default value 'Last60Days'; + properties/term with allowed values ['P1Y', 'P3Y'] and default value 'P3Y'; + properties/subscriptionId; properties/resourceGroup. Default value is None. + :type filter: str + :param orderby: May be used to order the recommendations by: properties/armSkuName. For the + savings plan, the results are in order by default. There is no need to use this clause. Default + value is None. + :type orderby: str + :param expand: May be used to expand the properties by: properties/usage, + properties/allRecommendationDetails. Default value is None. + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitRecommendationModel or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitRecommendationModel] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitRecommendationsListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + billing_scope=billing_scope, + filter=filter, + orderby=orderby, + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitRecommendationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py new file mode 100644 index 000000000000..e38164f1b6da --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py @@ -0,0 +1,471 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._benefit_utilization_summaries_operations import ( + build_list_by_billing_account_id_request, + build_list_by_billing_profile_id_request, + build_list_by_savings_plan_id_request, + build_list_by_savings_plan_order_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class BenefitUtilizationSummariesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`benefit_utilization_summaries` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_billing_account_id( + self, + billing_account_id: str, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.BenefitUtilizationSummary"]: + """Lists savings plan utilization summaries for the enterprise agreement scope. Supported at grain + values: 'Daily' and 'Monthly'. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and + properties/usageDate. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_billing_account_id_request( + billing_account_id=billing_account_id, + grain_parameter=grain_parameter, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_account_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore + + @distributed_trace + def list_by_billing_profile_id( + self, + billing_account_id: str, + billing_profile_id: str, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterable["_models.BenefitUtilizationSummary"]: + """Lists savings plan utilization summaries for billing profile. Supported at grain values: + 'Daily' and 'Monthly'. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and + properties/usageDate. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_billing_profile_id_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + grain_parameter=grain_parameter, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_profile_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore + + @distributed_trace + def list_by_savings_plan_order( + self, + savings_plan_order_id: str, + filter: Optional[str] = None, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + **kwargs: Any + ) -> AsyncIterable["_models.BenefitUtilizationSummary"]: + """Lists the savings plan utilization summaries for daily or monthly grain. + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param filter: Supports filtering by properties/usageDate. Default value is None. + :type filter: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_savings_plan_order_request( + savings_plan_order_id=savings_plan_order_id, + filter=filter, + grain_parameter=grain_parameter, + api_version=api_version, + template_url=self.list_by_savings_plan_order.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_savings_plan_order.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore + + @distributed_trace + def list_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + filter: Optional[str] = None, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + **kwargs: Any + ) -> AsyncIterable["_models.BenefitUtilizationSummary"]: + """Lists the savings plan utilization summaries for daily or monthly grain. + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param filter: Supports filtering by properties/usageDate. Default value is None. + :type filter: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_savings_plan_id_request( + savings_plan_order_id=savings_plan_order_id, + savings_plan_id=savings_plan_id, + filter=filter, + grain_parameter=grain_parameter, + api_version=api_version, + template_url=self.list_by_savings_plan_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_savings_plan_id.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py index 090f2e992e2d..eff1333cb7cd 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,58 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._dimensions_operations import build_by_external_cloud_provider_type_request, build_list_request -T = TypeVar('T') +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DimensionsOperations: - """DimensionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class DimensionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`dimensions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( self, scope: str, @@ -49,7 +66,7 @@ def list( skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.DimensionsListResult"]: + ) -> AsyncIterable["_models.Dimension"]: """Lists the dimensions by the defined scope. :param scope: The scope associated with dimension operations. This includes @@ -67,66 +84,81 @@ def list( 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -135,99 +167,119 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/dimensions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/dimensions"} # type: ignore + + @distributed_trace def by_external_cloud_provider_type( self, - external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, filter: Optional[str] = None, expand: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.DimensionsListResult"]: + ) -> AsyncIterable["_models.Dimension"]: """Lists the dimensions by the external cloud provider type. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -236,17 +288,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py index 2f3497eee08b..d8ef0ca18c5b 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,49 +6,67 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._exports_operations import ( + build_create_or_update_request, + build_delete_request, + build_execute_request, + build_get_execution_history_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ExportsOperations: - """ExportsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ExportsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`exports` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def list( - self, - scope: str, - **kwargs: Any - ) -> "_models.ExportListResult": + @distributed_trace_async + async def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult: """The operation to list all exports at the given scope. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -62,62 +81,69 @@ async def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last run of each export. Default + value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportListResult, or the result of cls(response) + :return: ExportListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportListResult] + + request = build_list_request( + scope=scope, + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportListResult', pipeline_response) + deserialized = self._deserialize("ExportListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports'} # type: ignore - async def get( - self, - scope: str, - export_name: str, - **kwargs: Any - ) -> "_models.Export": + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports"} # type: ignore + + @distributed_trace_async + async def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.Export: """The operation to get the export for the defined scope by export name. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -132,68 +158,82 @@ async def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last 10 runs of the export. + Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Export] + + request = build_get_request( + scope=scope, + export_name=export_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @overload async def create_or_update( self, scope: str, export_name: str, - parameters: "_models.Export", + parameters: _models.Export, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Export": + ) -> _models.Export: """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -208,76 +248,167 @@ async def create_or_update( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str - :param parameters: Parameters supplied to the CreateOrUpdate Export operation. + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.Export + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, scope: str, export_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, scope: str, export_name: str, parameters: Union[_models.Export, IO], **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Export or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Export') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Export] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Export") + + request = build_create_or_update_request( + scope=scope, + export_name=export_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore - async def delete( - self, - scope: str, - export_name: str, - **kwargs: Any + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @distributed_trace_async + async def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any ) -> None: """The operation to delete a export. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -292,62 +423,65 @@ async def delete( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore - async def execute( - self, - scope: str, - export_name: str, - **kwargs: Any + @distributed_trace_async + async def execute( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any ) -> None: - """The operation to execute a export. + """The operation to run an export. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -362,62 +496,65 @@ async def execute( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.execute.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.execute.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - execute.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run'} # type: ignore + execute.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run"} # type: ignore + @distributed_trace_async async def get_execution_history( - self, - scope: str, - export_name: str, - **kwargs: Any - ) -> "_models.ExportExecutionListResult": - """The operation to get the execution history of an export for the defined scope by export name. + self, scope: str, export_name: str, **kwargs: Any + ) -> _models.ExportExecutionListResult: + """The operation to get the run history of an export for the defined scope and export name. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -432,52 +569,58 @@ async def get_execution_history( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportExecutionListResult, or the result of cls(response) + :return: ExportExecutionListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportExecutionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_execution_history.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportExecutionListResult] + + request = build_get_execution_history_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.get_execution_history.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportExecutionListResult', pipeline_response) + deserialized = self._deserialize("ExportExecutionListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_execution_history.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory'} # type: ignore + + get_execution_history.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py index 8524f06621a5..a84cbc9bac29 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,48 +6,65 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._forecast_operations import build_external_cloud_provider_usage_request, build_usage_request -T = TypeVar('T') +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ForecastOperations: - """ForecastOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ForecastOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`forecast` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload async def usage( self, scope: str, - parameters: "_models.ForecastDefinition", + parameters: _models.ForecastDefinition, filter: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> Optional["_models.QueryResult"]: + ) -> Optional[_models.ForecastResult]: """Lists the forecast charges for scope defined. :param scope: The scope associated with forecast operations. This includes @@ -64,140 +82,338 @@ async def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def usage( + self, + scope: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def usage( + self, scope: str, parameters: Union[_models.ForecastDefinition, IO], filter: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ForecastResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_usage_request( + scope=scope, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/forecast'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/forecast"} # type: ignore + + @overload async def external_cloud_provider_usage( self, - external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: "_models.ForecastDefinition", + parameters: _models.ForecastDefinition, filter: Optional[str] = None, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.QueryResult": + ) -> _models.ForecastResult: """Lists the forecast charges for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: Union[_models.ForecastDefinition, IO], + filter: Optional[str] = None, + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.external_cloud_provider_usage.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ForecastResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_external_cloud_provider_usage_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.external_cloud_provider_usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - external_cloud_provider_usage.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast'} # type: ignore + + external_cloud_provider_usage.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py new file mode 100644 index 000000000000..b494d94e6028 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py @@ -0,0 +1,425 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._generate_cost_details_report_operations import ( + build_create_operation_request, + build_get_operation_results_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateCostDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_cost_details_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CostDetailsOperationResults]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateCostDetailsReportRequestDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateCostDetailsReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + @overload + async def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateCostDetailsReportRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CostDetailsOperationResults] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + async def _get_operation_results_initial( + self, scope: str, operation_id: str, **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CostDetailsOperationResults]] + + request = build_get_operation_results_request( + scope=scope, + operation_id=operation_id, + api_version=api_version, + template_url=self._get_operation_results_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _get_operation_results_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore + + @distributed_trace_async + async def begin_get_operation_results( + self, scope: str, operation_id: str, **kwargs: Any + ) -> AsyncLROPoller[_models.CostDetailsOperationResults]: + """Get the result of the specified operation. This link is provided in the CostDetails creation + request response Location header. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param operation_id: The target operation Id. Required. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either CostDetailsOperationResults or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CostDetailsOperationResults] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._get_operation_results_initial( # type: ignore + scope=scope, + operation_id=operation_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_get_operation_results.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py new file mode 100644 index 000000000000..9337dc341ee7 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_results_operations.py @@ -0,0 +1,181 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._generate_detailed_cost_report_operation_results_operations import build_get_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateDetailedCostReportOperationResultsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_results` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _get_initial( + self, operation_id: str, scope: str, **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self._get_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _get_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} # type: ignore + + @distributed_trace_async + async def begin_get( + self, operation_id: str, scope: str, **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Gets the result of the specified operation. The link with this operationId is provided as a + response header of the initial request. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._get_initial( # type: ignore + operation_id=operation_id, + scope=scope, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py new file mode 100644 index 000000000000..3bf99479ad16 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operation_status_operations.py @@ -0,0 +1,120 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._generate_detailed_cost_report_operation_status_operations import build_get_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateDetailedCostReportOperationStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_status` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get( + self, operation_id: str, scope: str, **kwargs: Any + ) -> _models.GenerateDetailedCostReportOperationStatuses: + """Get the status of the specified operation. This link is provided in the + GenerateDetailedCostReport creation request response header. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GenerateDetailedCostReportOperationStatuses or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationStatuses] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py new file mode 100644 index 000000000000..1ea51c38d877 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_detailed_cost_report_operations.py @@ -0,0 +1,287 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._generate_detailed_cost_report_operations import build_create_operation_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class GenerateDetailedCostReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_detailed_cost_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateDetailedCostReportDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateDetailedCostReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-Consumption-AsyncOperation") + ) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore + + @overload + async def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateDetailedCostReportDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(only enterprise + customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(only enterprise + customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(only enterprise + customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either + GenerateDetailedCostReportOperationResult or the result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._create_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py index 04654269eb88..20874b3d0edf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,298 +6,328 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._generate_reservation_details_report_operations import ( + build_by_billing_account_id_request, + build_by_billing_profile_id_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GenerateReservationDetailsReportOperations: - """GenerateReservationDetailsReportOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class GenerateReservationDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`generate_reservation_details_report` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") async def _by_billing_account_id_initial( - self, - billing_account_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> Optional["_models.OperationStatus"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_account_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_account_id_request( + billing_account_id=billing_account_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_account_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _by_billing_account_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_account_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace_async async def begin_by_billing_account_id( - self, - billing_account_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.OperationStatus"]: + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously based on - enrollment id. + enrollment id. The Reservation usage details can be viewed only by certain enterprise roles. + For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. - :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). + :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). Required. :type billing_account_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._by_billing_account_id_initial( + raw_result = await self._by_billing_account_id_initial( # type: ignore billing_account_id=billing_account_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_account_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_account_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore async def _by_billing_profile_id_initial( - self, - billing_account_id: str, - billing_profile_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> Optional["_models.OperationStatus"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_profile_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_profile_id_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_profile_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _by_billing_profile_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_profile_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace_async async def begin_by_billing_profile_id( - self, - billing_account_id: str, - billing_profile_id: str, - start_date: str, - end_date: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.OperationStatus"]: + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> AsyncLROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously by billing - profile. + profile. The Reservation usage details can be viewed by only certain enterprise roles by + default. For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: Billing account ID. Required. :type billing_account_id: str - :param billing_profile_id: BillingProfile ID. + :param billing_profile_id: Billing profile ID. Required. :type billing_profile_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._by_billing_profile_id_initial( + raw_result = await self._by_billing_profile_id_initial( # type: ignore billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_profile_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_profile_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py index e9b536504b06..6134de06e246 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,116 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._operations import build_list_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.CostManagementOperation"]: """Lists all of the available cost management REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CostManagementOperation or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.CostManagementOperation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +124,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.CostManagement/operations"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_price_sheet_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_price_sheet_operations.py new file mode 100644 index 000000000000..a9689d030d9a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_price_sheet_operations.py @@ -0,0 +1,323 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._price_sheet_operations import build_download_by_billing_profile_request, build_download_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PriceSheetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`price_sheet` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def _download_initial( + self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any + ) -> Optional[_models.DownloadURL]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadURL]] + + request = build_download_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_name=invoice_name, + api_version=api_version, + template_url=self._download_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("DownloadURL", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) + response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _download_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore + + @distributed_trace_async + async def begin_download( + self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadURL]: + """Gets a URL to download the pricesheet for an invoice. The operation is supported for billing + accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param invoice_name: The ID that uniquely identifies an invoice. Required. + :type invoice_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadURL or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.DownloadURL] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadURL] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._download_initial( # type: ignore + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_name=invoice_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DownloadURL", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore + + async def _download_by_billing_profile_initial( + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Optional[_models.DownloadURL]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadURL]] + + request = build_download_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self._download_by_billing_profile_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("DownloadURL", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) + response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _download_by_billing_profile_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore + + @distributed_trace_async + async def begin_download_by_billing_profile( + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadURL]: + """Gets a URL to download the current month's pricesheet for a billing profile. The operation is + supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft + Customer Agreement.Due to Azure product growth, the Azure price sheet download experience in + this preview version will be updated from a single csv file to a Zip file containing multiple + csv files, each with max 200k records. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadURL or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.DownloadURL] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadURL] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = await self._download_by_billing_profile_initial( # type: ignore + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DownloadURL", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py index 7a973c90e3c8..da801dee2c07 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,47 +6,59 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._query_operations import build_usage_by_external_cloud_provider_type_request, build_usage_request -T = TypeVar('T') +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class QueryOperations: - """QueryOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class QueryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`query` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload async def usage( - self, - scope: str, - parameters: "_models.QueryDefinition", - **kwargs: Any - ) -> Optional["_models.QueryResult"]: + self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: """Query the usage data for scope defined. :param scope: The scope associated with query and export operations. This includes @@ -63,127 +76,299 @@ async def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def usage( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def usage( + self, scope: str, parameters: Union[_models.QueryDefinition, IO], **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.QueryResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/query'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/query"} # type: ignore + + @overload async def usage_by_external_cloud_provider_type( self, - external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], external_cloud_provider_id: str, - parameters: "_models.QueryDefinition", + parameters: _models.QueryDefinition, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.QueryResult": + ) -> _models.QueryResult: """Query the usage data for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: Union[_models.QueryDefinition, IO], + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage_by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage_by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage_by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query'} # type: ignore + + usage_by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py new file mode 100644 index 000000000000..f46cbd55ddb5 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py @@ -0,0 +1,1243 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._scheduled_actions_operations import ( + build_check_name_availability_by_scope_request, + build_check_name_availability_request, + build_create_or_update_by_scope_request, + build_create_or_update_request, + build_delete_by_scope_request, + build_delete_request, + build_get_by_scope_request, + build_get_request, + build_list_by_scope_request, + build_list_request, + build_run_by_scope_request, + build_run_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class ScheduledActionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`scheduled_actions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.ScheduledAction"]: + """List all private scheduled actions. + + :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator + is 'eq'. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ScheduledAction or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledActionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ScheduledActionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions"} # type: ignore + + @distributed_trace + def list_by_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.ScheduledAction"]: + """List all shared scheduled actions within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator + is 'eq'. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ScheduledAction or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledActionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ScheduledActionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions"} # type: ignore + + @overload + async def create_or_update( + self, + name: str, + scheduled_action: _models.ScheduledAction, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, name: str, scheduled_action: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, name: str, scheduled_action: Union[_models.ScheduledAction, IO], **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Is either a model type or a + IO type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(scheduled_action, (IO, bytes)): + _content = scheduled_action + else: + _json = self._serialize.body(scheduled_action, "ScheduledAction") + + request = build_create_or_update_request( + name=name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace_async + async def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: + """Get the private scheduled action by name. + + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + request = build_get_request( + name=name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace_async + async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + name=name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @overload + async def create_or_update_by_scope( + self, + scope: str, + name: str, + scheduled_action: _models.ScheduledAction, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_scope( + self, scope: str, name: str, scheduled_action: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_scope( + self, scope: str, name: str, scheduled_action: Union[_models.ScheduledAction, IO], **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Is either a model type or a + IO type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(scheduled_action, (IO, bytes)): + _content = scheduled_action + else: + _json = self._serialize.body(scheduled_action, "ScheduledAction") + + request = build_create_or_update_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace_async + async def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.ScheduledAction: + """Get the shared scheduled action from the given scope by name. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + request = build_get_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace_async + async def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, name: str, **kwargs: Any + ) -> None: + """Delete a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.delete_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace_async + async def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Processes a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_run_request( + name=name, + api_version=api_version, + template_url=self.run.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + run.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} # type: ignore + + @distributed_trace_async + async def run_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, name: str, **kwargs: Any + ) -> None: + """Runs a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_run_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.run_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + run_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} # type: ignore + + @overload + async def check_name_availability( + self, + check_name_availability_request: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action. + + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action. + + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action. + + :param check_name_availability_request: Scheduled action to be created or updated. Is either a + model type or a IO type. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(check_name_availability_request, (IO, bytes)): + _content = check_name_availability_request + else: + _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") + + request = build_check_name_availability_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_name_availability.metadata = {"url": "/providers/Microsoft.CostManagement/checkNameAvailability"} # type: ignore + + @overload + async def check_name_availability_by_scope( + self, + scope: str, + check_name_availability_request: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability_by_scope( + self, scope: str, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability_by_scope( + self, + scope: str, + check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param check_name_availability_request: Scheduled action to be created or updated. Is either a + model type or a IO type. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(check_name_availability_request, (IO, bytes)): + _content = check_name_availability_request + else: + _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") + + request = build_check_name_availability_by_scope_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_name_availability_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_name_availability_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/checkNameAvailability"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py deleted file mode 100644 index 2a0f8f9e272e..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py +++ /dev/null @@ -1,273 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest -from azure.mgmt.core.exceptions import ARMErrorFormat - -from ... import models as _models - -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - -class SettingsOperations: - """SettingsOperations async operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - """ - - models = _models - - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.SettingsListResult"]: - """Lists all of the settings that have been customized. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SettingsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.SettingsListResult] - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SettingsListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) - return request - - async def extract_data(pipeline_response): - deserialized = self._deserialize('SettingsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/settings'} # type: ignore - - async def get( - self, - setting_name: str, - **kwargs: Any - ) -> "_models.Setting": - """Retrieves the current value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - async def create_or_update( - self, - setting_name: str, - parameters: "_models.Setting", - **kwargs: Any - ) -> "_models.Setting": - """Sets a new value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :param parameters: Body supplied to the CreateOrUpdate setting operation. - :type parameters: ~azure.mgmt.costmanagement.models.Setting - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Setting') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - async def delete( - self, - setting_name: str, - **kwargs: Any - ) -> None: - """Remove the current value for a specific setting and reverts back to the default value, if - applicable. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py index a82f547d6103..783b77477239 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._views_operations import ( + build_create_or_update_by_scope_request, + build_create_or_update_request, + build_delete_by_scope_request, + build_delete_request, + build_get_by_scope_request, + build_get_request, + build_list_by_scope_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ViewsOperations: - """ViewsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ViewsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`views` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ViewListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.View"]: """Lists all views by tenant and object. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,26 +132,24 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/views'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - def list_by_scope( - self, - scope: str, - **kwargs: Any - ) -> AsyncIterable["_models.ViewListResult"]: + list.metadata = {"url": "/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace + def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncIterable["_models.View"]: """Lists all views at the given scope. :param scope: The scope associated with view operations. This includes @@ -127,46 +168,62 @@ def list_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -175,200 +232,259 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - view_name: str, - **kwargs: Any - ) -> "_models.View": + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace_async + async def get(self, view_name: str, **kwargs: Any) -> _models.View: """Gets the view by view name. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + request = build_get_request( + view_name=view_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload async def create_or_update( - self, - view_name: str, - parameters: "_models.View", - **kwargs: Any - ) -> "_models.View": + self, view_name: str, parameters: _models.View, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update( + self, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update( + self, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_request( + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - async def delete( - self, - view_name: str, - **kwargs: Any - ) -> None: + create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace_async + async def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """The operation to delete a view. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + view_name=view_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore - async def get_by_scope( - self, - scope: str, - view_name: str, - **kwargs: Any - ) -> "_models.View": + @distributed_trace_async + async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View: """Gets the view for the defined scope by view name. :param scope: The scope associated with view operations. This includes @@ -387,63 +503,72 @@ async def get_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + request = build_get_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload async def create_or_update_by_scope( self, scope: str, view_name: str, - parameters: "_models.View", + parameters: _models.View, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.View": + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -464,72 +589,165 @@ async def create_or_update_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - async def delete_by_scope( - self, - scope: str, - view_name: str, - **kwargs: Any + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace_async + async def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, view_name: str, **kwargs: Any ) -> None: """The operation to delete a view. @@ -549,49 +767,54 @@ async def delete_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.delete_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py index c55fa14a8390..aade15c2f223 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/__init__.py @@ -6,245 +6,326 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import Alert - from ._models_py3 import AlertPropertiesDefinition - from ._models_py3 import AlertPropertiesDetails - from ._models_py3 import AlertsResult - from ._models_py3 import CacheItem - from ._models_py3 import CommonExportProperties - from ._models_py3 import Dimension - from ._models_py3 import DimensionsListResult - from ._models_py3 import DismissAlertPayload - from ._models_py3 import ErrorDetails - from ._models_py3 import ErrorResponse - from ._models_py3 import Export - from ._models_py3 import ExportDefinition - from ._models_py3 import ExportDeliveryDestination - from ._models_py3 import ExportDeliveryInfo - from ._models_py3 import ExportExecution - from ._models_py3 import ExportExecutionListResult - from ._models_py3 import ExportListResult - from ._models_py3 import ExportProperties - from ._models_py3 import ExportRecurrencePeriod - from ._models_py3 import ExportSchedule - from ._models_py3 import ForecastDefinition - from ._models_py3 import KpiProperties - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationListResult - from ._models_py3 import OperationStatus - from ._models_py3 import PivotProperties - from ._models_py3 import ProxyResource - from ._models_py3 import ProxySettingResource - from ._models_py3 import QueryAggregation - from ._models_py3 import QueryColumn - from ._models_py3 import QueryComparisonExpression - from ._models_py3 import QueryDataset - from ._models_py3 import QueryDatasetAutoGenerated - from ._models_py3 import QueryDatasetConfiguration - from ._models_py3 import QueryDefinition - from ._models_py3 import QueryFilter - from ._models_py3 import QueryFilterAutoGenerated - from ._models_py3 import QueryGrouping - from ._models_py3 import QueryResult - from ._models_py3 import QueryTimePeriod - from ._models_py3 import ReportConfigAggregation - from ._models_py3 import ReportConfigComparisonExpression - from ._models_py3 import ReportConfigDataset - from ._models_py3 import ReportConfigDatasetConfiguration - from ._models_py3 import ReportConfigFilter - from ._models_py3 import ReportConfigGrouping - from ._models_py3 import ReportConfigSorting - from ._models_py3 import ReportConfigTimePeriod - from ._models_py3 import Resource - from ._models_py3 import Setting - from ._models_py3 import SettingsListResult - from ._models_py3 import Status - from ._models_py3 import View - from ._models_py3 import ViewListResult -except (SyntaxError, ImportError): - from ._models import Alert # type: ignore - from ._models import AlertPropertiesDefinition # type: ignore - from ._models import AlertPropertiesDetails # type: ignore - from ._models import AlertsResult # type: ignore - from ._models import CacheItem # type: ignore - from ._models import CommonExportProperties # type: ignore - from ._models import Dimension # type: ignore - from ._models import DimensionsListResult # type: ignore - from ._models import DismissAlertPayload # type: ignore - from ._models import ErrorDetails # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import Export # type: ignore - from ._models import ExportDefinition # type: ignore - from ._models import ExportDeliveryDestination # type: ignore - from ._models import ExportDeliveryInfo # type: ignore - from ._models import ExportExecution # type: ignore - from ._models import ExportExecutionListResult # type: ignore - from ._models import ExportListResult # type: ignore - from ._models import ExportProperties # type: ignore - from ._models import ExportRecurrencePeriod # type: ignore - from ._models import ExportSchedule # type: ignore - from ._models import ForecastDefinition # type: ignore - from ._models import KpiProperties # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationListResult # type: ignore - from ._models import OperationStatus # type: ignore - from ._models import PivotProperties # type: ignore - from ._models import ProxyResource # type: ignore - from ._models import ProxySettingResource # type: ignore - from ._models import QueryAggregation # type: ignore - from ._models import QueryColumn # type: ignore - from ._models import QueryComparisonExpression # type: ignore - from ._models import QueryDataset # type: ignore - from ._models import QueryDatasetAutoGenerated # type: ignore - from ._models import QueryDatasetConfiguration # type: ignore - from ._models import QueryDefinition # type: ignore - from ._models import QueryFilter # type: ignore - from ._models import QueryFilterAutoGenerated # type: ignore - from ._models import QueryGrouping # type: ignore - from ._models import QueryResult # type: ignore - from ._models import QueryTimePeriod # type: ignore - from ._models import ReportConfigAggregation # type: ignore - from ._models import ReportConfigComparisonExpression # type: ignore - from ._models import ReportConfigDataset # type: ignore - from ._models import ReportConfigDatasetConfiguration # type: ignore - from ._models import ReportConfigFilter # type: ignore - from ._models import ReportConfigGrouping # type: ignore - from ._models import ReportConfigSorting # type: ignore - from ._models import ReportConfigTimePeriod # type: ignore - from ._models import Resource # type: ignore - from ._models import Setting # type: ignore - from ._models import SettingsListResult # type: ignore - from ._models import Status # type: ignore - from ._models import View # type: ignore - from ._models import ViewListResult # type: ignore +from ._models_py3 import Alert +from ._models_py3 import AlertPropertiesDefinition +from ._models_py3 import AlertPropertiesDetails +from ._models_py3 import AlertsResult +from ._models_py3 import AllSavingsBenefitDetails +from ._models_py3 import AllSavingsList +from ._models_py3 import BenefitRecommendationModel +from ._models_py3 import BenefitRecommendationProperties +from ._models_py3 import BenefitRecommendationsListResult +from ._models_py3 import BenefitResource +from ._models_py3 import BenefitUtilizationSummariesListResult +from ._models_py3 import BenefitUtilizationSummary +from ._models_py3 import BenefitUtilizationSummaryProperties +from ._models_py3 import BlobInfo +from ._models_py3 import CheckNameAvailabilityRequest +from ._models_py3 import CheckNameAvailabilityResponse +from ._models_py3 import CommonExportProperties +from ._models_py3 import CostDetailsOperationResults +from ._models_py3 import CostDetailsTimePeriod +from ._models_py3 import CostManagementOperation +from ._models_py3 import CostManagementProxyResource +from ._models_py3 import CostManagementResource +from ._models_py3 import Dimension +from ._models_py3 import DimensionsListResult +from ._models_py3 import DismissAlertPayload +from ._models_py3 import DownloadURL +from ._models_py3 import ErrorDetails +from ._models_py3 import ErrorResponse +from ._models_py3 import Export +from ._models_py3 import ExportDataset +from ._models_py3 import ExportDatasetConfiguration +from ._models_py3 import ExportDefinition +from ._models_py3 import ExportDeliveryDestination +from ._models_py3 import ExportDeliveryInfo +from ._models_py3 import ExportExecutionListResult +from ._models_py3 import ExportListResult +from ._models_py3 import ExportProperties +from ._models_py3 import ExportRecurrencePeriod +from ._models_py3 import ExportRun +from ._models_py3 import ExportSchedule +from ._models_py3 import ExportTimePeriod +from ._models_py3 import FileDestination +from ._models_py3 import ForecastAggregation +from ._models_py3 import ForecastColumn +from ._models_py3 import ForecastComparisonExpression +from ._models_py3 import ForecastDataset +from ._models_py3 import ForecastDatasetConfiguration +from ._models_py3 import ForecastDefinition +from ._models_py3 import ForecastFilter +from ._models_py3 import ForecastResult +from ._models_py3 import ForecastTimePeriod +from ._models_py3 import GenerateCostDetailsReportErrorResponse +from ._models_py3 import GenerateCostDetailsReportRequestDefinition +from ._models_py3 import GenerateDetailedCostReportDefinition +from ._models_py3 import GenerateDetailedCostReportErrorResponse +from ._models_py3 import GenerateDetailedCostReportOperationResult +from ._models_py3 import GenerateDetailedCostReportOperationStatuses +from ._models_py3 import GenerateDetailedCostReportTimePeriod +from ._models_py3 import IncludedQuantityUtilizationSummary +from ._models_py3 import IncludedQuantityUtilizationSummaryProperties +from ._models_py3 import KpiProperties +from ._models_py3 import NotificationProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import OperationStatus +from ._models_py3 import PivotProperties +from ._models_py3 import ProxyResource +from ._models_py3 import QueryAggregation +from ._models_py3 import QueryColumn +from ._models_py3 import QueryComparisonExpression +from ._models_py3 import QueryDataset +from ._models_py3 import QueryDatasetConfiguration +from ._models_py3 import QueryDefinition +from ._models_py3 import QueryFilter +from ._models_py3 import QueryGrouping +from ._models_py3 import QueryResult +from ._models_py3 import QueryTimePeriod +from ._models_py3 import RecommendationUsageDetails +from ._models_py3 import ReportConfigAggregation +from ._models_py3 import ReportConfigComparisonExpression +from ._models_py3 import ReportConfigDataset +from ._models_py3 import ReportConfigDatasetConfiguration +from ._models_py3 import ReportConfigFilter +from ._models_py3 import ReportConfigGrouping +from ._models_py3 import ReportConfigSorting +from ._models_py3 import ReportConfigTimePeriod +from ._models_py3 import Resource +from ._models_py3 import SavingsPlanUtilizationSummary +from ._models_py3 import SavingsPlanUtilizationSummaryProperties +from ._models_py3 import ScheduleProperties +from ._models_py3 import ScheduledAction +from ._models_py3 import ScheduledActionListResult +from ._models_py3 import ScheduledActionProxyResource +from ._models_py3 import SharedScopeBenefitRecommendationProperties +from ._models_py3 import SingleScopeBenefitRecommendationProperties +from ._models_py3 import Status +from ._models_py3 import SystemData +from ._models_py3 import View +from ._models_py3 import ViewListResult -from ._cost_management_client_enums import ( - AccumulatedType, - AlertCategory, - AlertCriteria, - AlertOperator, - AlertSource, - AlertStatus, - AlertTimeGrainType, - AlertType, - ChartType, - ExecutionStatus, - ExecutionType, - ExportType, - ExternalCloudProviderType, - ForecastTimeframeType, - ForecastType, - FormatType, - FunctionType, - GranularityType, - KpiType, - MetricType, - OperationStatusType, - OperatorType, - PivotType, - QueryColumnType, - RecurrenceType, - ReportConfigColumnType, - ReportConfigSortingDirection, - ReportGranularityType, - ReportTimeframeType, - ReportType, - SettingsPropertiesStartOn, - StatusType, - TimeframeType, -) +from ._cost_management_client_enums import AccumulatedType +from ._cost_management_client_enums import ActionType +from ._cost_management_client_enums import AlertCategory +from ._cost_management_client_enums import AlertCriteria +from ._cost_management_client_enums import AlertOperator +from ._cost_management_client_enums import AlertSource +from ._cost_management_client_enums import AlertStatus +from ._cost_management_client_enums import AlertTimeGrainType +from ._cost_management_client_enums import AlertType +from ._cost_management_client_enums import BenefitKind +from ._cost_management_client_enums import ChartType +from ._cost_management_client_enums import CheckNameAvailabilityReason +from ._cost_management_client_enums import CostDetailsDataFormat +from ._cost_management_client_enums import CostDetailsMetricType +from ._cost_management_client_enums import CostDetailsStatusType +from ._cost_management_client_enums import CreatedByType +from ._cost_management_client_enums import DaysOfWeek +from ._cost_management_client_enums import ExecutionStatus +from ._cost_management_client_enums import ExecutionType +from ._cost_management_client_enums import ExportType +from ._cost_management_client_enums import ExternalCloudProviderType +from ._cost_management_client_enums import FileFormat +from ._cost_management_client_enums import ForecastOperatorType +from ._cost_management_client_enums import ForecastTimeframe +from ._cost_management_client_enums import ForecastType +from ._cost_management_client_enums import FormatType +from ._cost_management_client_enums import FunctionName +from ._cost_management_client_enums import FunctionType +from ._cost_management_client_enums import GenerateDetailedCostReportMetricType +from ._cost_management_client_enums import Grain +from ._cost_management_client_enums import GrainParameter +from ._cost_management_client_enums import GranularityType +from ._cost_management_client_enums import KpiType +from ._cost_management_client_enums import LookBackPeriod +from ._cost_management_client_enums import MetricType +from ._cost_management_client_enums import OperationStatusType +from ._cost_management_client_enums import OperatorType +from ._cost_management_client_enums import Origin +from ._cost_management_client_enums import PivotType +from ._cost_management_client_enums import QueryColumnType +from ._cost_management_client_enums import QueryOperatorType +from ._cost_management_client_enums import RecurrenceType +from ._cost_management_client_enums import ReportConfigColumnType +from ._cost_management_client_enums import ReportConfigSortingType +from ._cost_management_client_enums import ReportGranularityType +from ._cost_management_client_enums import ReportOperationStatusType +from ._cost_management_client_enums import ReportTimeframeType +from ._cost_management_client_enums import ReportType +from ._cost_management_client_enums import ReservationReportSchema +from ._cost_management_client_enums import ScheduleFrequency +from ._cost_management_client_enums import ScheduledActionKind +from ._cost_management_client_enums import ScheduledActionStatus +from ._cost_management_client_enums import Scope +from ._cost_management_client_enums import StatusType +from ._cost_management_client_enums import Term +from ._cost_management_client_enums import TimeframeType +from ._cost_management_client_enums import WeeksOfMonth +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'Alert', - 'AlertPropertiesDefinition', - 'AlertPropertiesDetails', - 'AlertsResult', - 'CacheItem', - 'CommonExportProperties', - 'Dimension', - 'DimensionsListResult', - 'DismissAlertPayload', - 'ErrorDetails', - 'ErrorResponse', - 'Export', - 'ExportDefinition', - 'ExportDeliveryDestination', - 'ExportDeliveryInfo', - 'ExportExecution', - 'ExportExecutionListResult', - 'ExportListResult', - 'ExportProperties', - 'ExportRecurrencePeriod', - 'ExportSchedule', - 'ForecastDefinition', - 'KpiProperties', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'OperationStatus', - 'PivotProperties', - 'ProxyResource', - 'ProxySettingResource', - 'QueryAggregation', - 'QueryColumn', - 'QueryComparisonExpression', - 'QueryDataset', - 'QueryDatasetAutoGenerated', - 'QueryDatasetConfiguration', - 'QueryDefinition', - 'QueryFilter', - 'QueryFilterAutoGenerated', - 'QueryGrouping', - 'QueryResult', - 'QueryTimePeriod', - 'ReportConfigAggregation', - 'ReportConfigComparisonExpression', - 'ReportConfigDataset', - 'ReportConfigDatasetConfiguration', - 'ReportConfigFilter', - 'ReportConfigGrouping', - 'ReportConfigSorting', - 'ReportConfigTimePeriod', - 'Resource', - 'Setting', - 'SettingsListResult', - 'Status', - 'View', - 'ViewListResult', - 'AccumulatedType', - 'AlertCategory', - 'AlertCriteria', - 'AlertOperator', - 'AlertSource', - 'AlertStatus', - 'AlertTimeGrainType', - 'AlertType', - 'ChartType', - 'ExecutionStatus', - 'ExecutionType', - 'ExportType', - 'ExternalCloudProviderType', - 'ForecastTimeframeType', - 'ForecastType', - 'FormatType', - 'FunctionType', - 'GranularityType', - 'KpiType', - 'MetricType', - 'OperationStatusType', - 'OperatorType', - 'PivotType', - 'QueryColumnType', - 'RecurrenceType', - 'ReportConfigColumnType', - 'ReportConfigSortingDirection', - 'ReportGranularityType', - 'ReportTimeframeType', - 'ReportType', - 'SettingsPropertiesStartOn', - 'StatusType', - 'TimeframeType', + "Alert", + "AlertPropertiesDefinition", + "AlertPropertiesDetails", + "AlertsResult", + "AllSavingsBenefitDetails", + "AllSavingsList", + "BenefitRecommendationModel", + "BenefitRecommendationProperties", + "BenefitRecommendationsListResult", + "BenefitResource", + "BenefitUtilizationSummariesListResult", + "BenefitUtilizationSummary", + "BenefitUtilizationSummaryProperties", + "BlobInfo", + "CheckNameAvailabilityRequest", + "CheckNameAvailabilityResponse", + "CommonExportProperties", + "CostDetailsOperationResults", + "CostDetailsTimePeriod", + "CostManagementOperation", + "CostManagementProxyResource", + "CostManagementResource", + "Dimension", + "DimensionsListResult", + "DismissAlertPayload", + "DownloadURL", + "ErrorDetails", + "ErrorResponse", + "Export", + "ExportDataset", + "ExportDatasetConfiguration", + "ExportDefinition", + "ExportDeliveryDestination", + "ExportDeliveryInfo", + "ExportExecutionListResult", + "ExportListResult", + "ExportProperties", + "ExportRecurrencePeriod", + "ExportRun", + "ExportSchedule", + "ExportTimePeriod", + "FileDestination", + "ForecastAggregation", + "ForecastColumn", + "ForecastComparisonExpression", + "ForecastDataset", + "ForecastDatasetConfiguration", + "ForecastDefinition", + "ForecastFilter", + "ForecastResult", + "ForecastTimePeriod", + "GenerateCostDetailsReportErrorResponse", + "GenerateCostDetailsReportRequestDefinition", + "GenerateDetailedCostReportDefinition", + "GenerateDetailedCostReportErrorResponse", + "GenerateDetailedCostReportOperationResult", + "GenerateDetailedCostReportOperationStatuses", + "GenerateDetailedCostReportTimePeriod", + "IncludedQuantityUtilizationSummary", + "IncludedQuantityUtilizationSummaryProperties", + "KpiProperties", + "NotificationProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "OperationStatus", + "PivotProperties", + "ProxyResource", + "QueryAggregation", + "QueryColumn", + "QueryComparisonExpression", + "QueryDataset", + "QueryDatasetConfiguration", + "QueryDefinition", + "QueryFilter", + "QueryGrouping", + "QueryResult", + "QueryTimePeriod", + "RecommendationUsageDetails", + "ReportConfigAggregation", + "ReportConfigComparisonExpression", + "ReportConfigDataset", + "ReportConfigDatasetConfiguration", + "ReportConfigFilter", + "ReportConfigGrouping", + "ReportConfigSorting", + "ReportConfigTimePeriod", + "Resource", + "SavingsPlanUtilizationSummary", + "SavingsPlanUtilizationSummaryProperties", + "ScheduleProperties", + "ScheduledAction", + "ScheduledActionListResult", + "ScheduledActionProxyResource", + "SharedScopeBenefitRecommendationProperties", + "SingleScopeBenefitRecommendationProperties", + "Status", + "SystemData", + "View", + "ViewListResult", + "AccumulatedType", + "ActionType", + "AlertCategory", + "AlertCriteria", + "AlertOperator", + "AlertSource", + "AlertStatus", + "AlertTimeGrainType", + "AlertType", + "BenefitKind", + "ChartType", + "CheckNameAvailabilityReason", + "CostDetailsDataFormat", + "CostDetailsMetricType", + "CostDetailsStatusType", + "CreatedByType", + "DaysOfWeek", + "ExecutionStatus", + "ExecutionType", + "ExportType", + "ExternalCloudProviderType", + "FileFormat", + "ForecastOperatorType", + "ForecastTimeframe", + "ForecastType", + "FormatType", + "FunctionName", + "FunctionType", + "GenerateDetailedCostReportMetricType", + "Grain", + "GrainParameter", + "GranularityType", + "KpiType", + "LookBackPeriod", + "MetricType", + "OperationStatusType", + "OperatorType", + "Origin", + "PivotType", + "QueryColumnType", + "QueryOperatorType", + "RecurrenceType", + "ReportConfigColumnType", + "ReportConfigSortingType", + "ReportGranularityType", + "ReportOperationStatusType", + "ReportTimeframeType", + "ReportType", + "ReservationReportSchema", + "ScheduleFrequency", + "ScheduledActionKind", + "ScheduledActionStatus", + "Scope", + "StatusType", + "Term", + "TimeframeType", + "WeeksOfMonth", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py index eac0fd7748ff..0dbdb4a13835 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_cost_management_client_enums.py @@ -6,45 +6,34 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class AccumulatedType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Show costs accumulated over time. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AccumulatedType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Show costs accumulated over time.""" TRUE = "true" FALSE = "false" -class AlertCategory(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Alert category - """ + +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" + + INTERNAL = "Internal" + + +class AlertCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Alert category.""" COST = "Cost" USAGE = "Usage" BILLING = "Billing" SYSTEM = "System" -class AlertCriteria(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Criteria that triggered alert - """ + +class AlertCriteria(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Criteria that triggered alert.""" COST_THRESHOLD_EXCEEDED = "CostThresholdExceeded" USAGE_THRESHOLD_EXCEEDED = "UsageThresholdExceeded" @@ -61,9 +50,9 @@ class AlertCriteria(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): CROSS_CLOUD_COLLECTION_ERROR = "CrossCloudCollectionError" GENERAL_THRESHOLD_ERROR = "GeneralThresholdError" -class AlertOperator(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """operator used to compare currentSpend with amount - """ + +class AlertOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """operator used to compare currentSpend with amount.""" NONE = "None" EQUAL_TO = "EqualTo" @@ -72,16 +61,16 @@ class AlertOperator(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): LESS_THAN = "LessThan" LESS_THAN_OR_EQUAL_TO = "LessThanOrEqualTo" -class AlertSource(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Source of alert - """ + +class AlertSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Source of alert.""" PRESET = "Preset" USER = "User" -class AlertStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """alert status - """ + +class AlertStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """alert status.""" NONE = "None" ACTIVE = "Active" @@ -89,9 +78,9 @@ class AlertStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): RESOLVED = "Resolved" DISMISSED = "Dismissed" -class AlertTimeGrainType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Type of timegrain cadence - """ + +class AlertTimeGrainType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of timegrain cadence.""" NONE = "None" MONTHLY = "Monthly" @@ -101,9 +90,9 @@ class AlertTimeGrainType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): BILLING_QUARTER = "BillingQuarter" BILLING_ANNUAL = "BillingAnnual" -class AlertType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """type of alert - """ + +class AlertType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """type of alert.""" BUDGET = "Budget" INVOICE = "Invoice" @@ -113,9 +102,20 @@ class AlertType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): X_CLOUD = "xCloud" BUDGET_FORECAST = "BudgetForecast" -class ChartType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Chart type of the main view in Cost Analysis. Required. - """ + +class BenefitKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind/type of the benefit.""" + + #: Benefit is IncludedQuantity. + INCLUDED_QUANTITY = "IncludedQuantity" + #: Benefit is Reservation. + RESERVATION = "Reservation" + #: Benefit is SavingsPlan. + SAVINGS_PLAN = "SavingsPlan" + + +class ChartType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Chart type of the main view in Cost Analysis. Required.""" AREA = "Area" LINE = "Line" @@ -123,9 +123,64 @@ class ChartType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): GROUPED_COLUMN = "GroupedColumn" TABLE = "Table" -class ExecutionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the export execution. - """ + +class CheckNameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The reason why the given name is not available.""" + + INVALID = "Invalid" + ALREADY_EXISTS = "AlreadyExists" + + +class CostDetailsDataFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The data format of the report.""" + + #: Csv data format. + CSV_COST_DETAILS_DATA_FORMAT = "Csv" + + +class CostDetailsMetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the detailed report. By default ActualCost is provided.""" + + #: Actual cost data. + ACTUAL_COST_COST_DETAILS_METRIC_TYPE = "ActualCost" + #: Amortized cost data. + AMORTIZED_COST_COST_DETAILS_METRIC_TYPE = "AmortizedCost" + + +class CostDetailsStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the cost details operation.""" + + #: Operation is Completed. + COMPLETED_COST_DETAILS_STATUS_TYPE = "Completed" + #: Operation is Completed and no cost data found. + NO_DATA_FOUND_COST_DETAILS_STATUS_TYPE = "NoDataFound" + #: Operation Failed. + FAILED_COST_DETAILS_STATUS_TYPE = "Failed" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class DaysOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Days of Week.""" + + MONDAY = "Monday" + TUESDAY = "Tuesday" + WEDNESDAY = "Wednesday" + THURSDAY = "Thursday" + FRIDAY = "Friday" + SATURDAY = "Saturday" + SUNDAY = "Sunday" + + +class ExecutionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The last known status of the export run.""" QUEUED = "Queued" IN_PROGRESS = "InProgress" @@ -135,142 +190,225 @@ class ExecutionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): NEW_DATA_NOT_AVAILABLE = "NewDataNotAvailable" DATA_NOT_AVAILABLE = "DataNotAvailable" -class ExecutionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the export execution. - """ + +class ExecutionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the export run.""" ON_DEMAND = "OnDemand" SCHEDULED = "Scheduled" -class ExportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the query. - """ + +class ExportType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the query.""" USAGE = "Usage" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" -class ExternalCloudProviderType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ExternalCloudProviderType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ExternalCloudProviderType.""" EXTERNAL_SUBSCRIPTIONS = "externalSubscriptions" EXTERNAL_BILLING_ACCOUNTS = "externalBillingAccounts" -class ForecastTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The time frame for pulling data for the forecast. If custom, then a specific time period must - be provided. - """ - MONTH_TO_DATE = "MonthToDate" - BILLING_MONTH_TO_DATE = "BillingMonthToDate" - THE_LAST_MONTH = "TheLastMonth" - THE_LAST_BILLING_MONTH = "TheLastBillingMonth" - WEEK_TO_DATE = "WeekToDate" +class FileFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Destination of the view data. Currently only CSV format is supported.""" + + CSV = "Csv" + + +class ForecastOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" + + +class ForecastTimeframe(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The time frame for pulling data for the forecast.""" + CUSTOM = "Custom" -class ForecastType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the forecast. - """ + +class ForecastType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the forecast.""" USAGE = "Usage" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" -class FormatType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The format of the export being delivered. - """ + +class FormatType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The format of the export being delivered. Currently only 'Csv' is supported.""" CSV = "Csv" -class FunctionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The name of the aggregation function to use. - """ - AVG = "Avg" - MAX = "Max" - MIN = "Min" +class FunctionName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the column to aggregate.""" + + PRE_TAX_COST_USD = "PreTaxCostUSD" + COST = "Cost" + COST_USD = "CostUSD" + PRE_TAX_COST = "PreTaxCost" + + +class FunctionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the aggregation function to use.""" + SUM = "Sum" -class GranularityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The granularity of rows in the query. - """ +class GenerateDetailedCostReportMetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the detailed report. By default ActualCost is provided.""" + + ACTUAL_COST = "ActualCost" + AMORTIZED_COST = "AmortizedCost" + + +class Grain(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Grain which corresponds to value.""" + + #: Hourly grain corresponds to value per hour. + HOURLY = "Hourly" + #: Hourly grain corresponds to value per day. DAILY = "Daily" + #: Hourly grain corresponds to value per month. + MONTHLY = "Monthly" -class KpiType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """KPI type (Forecast, Budget). - """ + +class GrainParameter(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """GrainParameter.""" + + #: Hourly grain corresponds to value per hour. + HOURLY = "Hourly" + #: Hourly grain corresponds to value per day. + DAILY = "Daily" + #: Hourly grain corresponds to value per month. + MONTHLY = "Monthly" + + +class GranularityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The granularity of rows in the forecast.""" + + DAILY = "Daily" + + +class KpiType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """KPI type (Forecast, Budget).""" FORECAST = "Forecast" BUDGET = "Budget" -class MetricType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Metric to use when displaying costs. - """ + +class LookBackPeriod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The number of days used to look back.""" + + #: 7 days used to look back. + LAST7_DAYS = "Last7Days" + #: 30 days used to look back. + LAST30_DAYS = "Last30Days" + #: 60 days used to look back. + LAST60_DAYS = "Last60Days" + + +class MetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Metric to use when displaying costs.""" ACTUAL_COST = "ActualCost" AMORTIZED_COST = "AmortizedCost" AHUB = "AHUB" -class OperationStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the long running operation. - """ + +class OperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the long running operation.""" RUNNING = "Running" COMPLETED = "Completed" FAILED = "Failed" -class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The operator to use for comparison. - """ - IN_ENUM = "In" +class OperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" CONTAINS = "Contains" -class PivotType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Data type to show in view. + +class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit + logs UX. Default value is "user,system". """ + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" + + +class PivotType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Data type to show in view.""" + DIMENSION = "Dimension" TAG_KEY = "TagKey" -class QueryColumnType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the column in the export. - """ + +class QueryColumnType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the column in the export.""" TAG = "Tag" DIMENSION = "Dimension" -class RecurrenceType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The schedule recurrence. - """ + +class QueryOperatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operator to use for comparison.""" + + IN = "In" + + +class RecurrenceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The schedule recurrence.""" DAILY = "Daily" WEEKLY = "Weekly" MONTHLY = "Monthly" ANNUALLY = "Annually" -class ReportConfigColumnType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the column in the report. - """ + +class ReportConfigColumnType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the column in the report.""" TAG = "Tag" DIMENSION = "Dimension" -class ReportConfigSortingDirection(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Direction of sort. - """ + +class ReportConfigSortingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Direction of sort.""" ASCENDING = "Ascending" DESCENDING = "Descending" -class ReportGranularityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The granularity of rows in the report. - """ + +class ReportGranularityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The granularity of rows in the report.""" DAILY = "Daily" MONTHLY = "Monthly" -class ReportTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ReportOperationStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the long running operation.""" + + IN_PROGRESS = "InProgress" + COMPLETED = "Completed" + FAILED = "Failed" + QUEUED = "Queued" + NO_DATA_FOUND = "NoDataFound" + READY_TO_DOWNLOAD = "ReadyToDownload" + TIMED_OUT = "TimedOut" + + +class ReportTimeframeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The time frame for pulling data for the report. If custom, then a specific time period must be provided. """ @@ -280,7 +418,8 @@ class ReportTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): YEAR_TO_DATE = "YearToDate" CUSTOM = "Custom" -class ReportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ReportType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of the report. Usage represents actual usage, forecast represents forecasted data and UsageAndForecast represents both usage and forecasted data. Actual usage and forecasted data can be differentiated based on dates. @@ -288,24 +427,83 @@ class ReportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): USAGE = "Usage" -class SettingsPropertiesStartOn(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Indicates what scope Cost Management in the Azure portal should default to. Allowed values: - LastUsed. + +class ReservationReportSchema(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The CSV file from the reportUrl blob link consists of reservation usage data with the following + schema at daily granularity. """ - LAST_USED = "LastUsed" - SCOPE_PICKER = "ScopePicker" - SPECIFIC_SCOPE = "SpecificScope" + INSTANCE_FLEXIBILITY_GROUP = "InstanceFlexibilityGroup" + INSTANCE_FLEXIBILITY_RATIO = "InstanceFlexibilityRatio" + INSTANCE_ID = "InstanceId" + KIND = "Kind" + RESERVATION_ID = "ReservationId" + RESERVATION_ORDER_ID = "ReservationOrderId" + RESERVED_HOURS = "ReservedHours" + SKU_NAME = "SkuName" + TOTAL_RESERVED_QUANTITY = "TotalReservedQuantity" + USAGE_DATE = "UsageDate" + USED_HOURS = "UsedHours" -class StatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the schedule. Whether active or not. If inactive, the export's scheduled - execution is paused. - """ + +class ScheduledActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind of the scheduled action.""" + + #: Cost analysis data will be emailed. + EMAIL = "Email" + #: Cost anomaly information will be emailed. Available only on subscription scope at daily + #: frequency. If no anomaly is detected on the resource, an email won't be sent. + INSIGHT_ALERT = "InsightAlert" + + +class ScheduledActionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the scheduled action.""" + + #: Scheduled action is saved but will not be run. + DISABLED = "Disabled" + #: Scheduled action is saved and will be run. + ENABLED = "Enabled" + #: Scheduled action is expired. + EXPIRED = "Expired" + + +class ScheduleFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Frequency of the schedule.""" + + #: Cost analysis data will be emailed every day. + DAILY = "Daily" + #: Cost analysis data will be emailed every week. + WEEKLY = "Weekly" + #: Cost analysis data will be emailed every month. + MONTHLY = "Monthly" + + +class Scope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind of the recommendation scope.""" + + #: Single scope recommendation. + SINGLE = "Single" + #: Shared scope recommendation. + SHARED = "Shared" + + +class StatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the export's schedule. If 'Inactive', the export's schedule is paused.""" ACTIVE = "Active" INACTIVE = "Inactive" -class TimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Grain which corresponds to value.""" + + #: Benefit term is 1 year. + P1_Y = "P1Y" + #: Benefit term is 3 years. + P3_Y = "P3Y" + + +class TimeframeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The time frame for pulling data for the query. If custom, then a specific time period must be provided. """ @@ -316,3 +514,13 @@ class TimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): THE_LAST_BILLING_MONTH = "TheLastBillingMonth" WEEK_TO_DATE = "WeekToDate" CUSTOM = "Custom" + + +class WeeksOfMonth(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Weeks of month.""" + + FIRST = "First" + SECOND = "Second" + THIRD = "Third" + FOURTH = "Fourth" + LAST = "Last" diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py deleted file mode 100644 index ffd3292fd2df..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py +++ /dev/null @@ -1,2225 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class Resource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.tags = None - - -class Alert(Resource): - """An individual alert. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Alert, self).__init__(**kwargs) - self.definition = kwargs.get('definition', None) - self.description = kwargs.get('description', None) - self.source = kwargs.get('source', None) - self.details = kwargs.get('details', None) - self.cost_entity_id = kwargs.get('cost_entity_id', None) - self.status = kwargs.get('status', None) - self.creation_time = kwargs.get('creation_time', None) - self.close_time = kwargs.get('close_time', None) - self.modification_time = kwargs.get('modification_time', None) - self.status_modification_user_name = kwargs.get('status_modification_user_name', None) - self.status_modification_time = kwargs.get('status_modification_time', None) - - -class AlertPropertiesDefinition(msrest.serialization.Model): - """defines the type of alert. - - :param type: type of alert. Possible values include: "Budget", "Invoice", "Credit", "Quota", - "General", "xCloud", "BudgetForecast". - :type type: str or ~azure.mgmt.costmanagement.models.AlertType - :param category: Alert category. Possible values include: "Cost", "Usage", "Billing", "System". - :type category: str or ~azure.mgmt.costmanagement.models.AlertCategory - :param criteria: Criteria that triggered alert. Possible values include: - "CostThresholdExceeded", "UsageThresholdExceeded", "CreditThresholdApproaching", - "CreditThresholdReached", "QuotaThresholdApproaching", "QuotaThresholdReached", - "MultiCurrency", "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", - "InvoiceDueDateApproaching", "InvoiceDueDateReached", "CrossCloudNewDataAvailable", - "CrossCloudCollectionError", "GeneralThresholdError". - :type criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'criteria': {'key': 'criteria', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AlertPropertiesDefinition, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.category = kwargs.get('category', None) - self.criteria = kwargs.get('criteria', None) - - -class AlertPropertiesDetails(msrest.serialization.Model): - """Alert details. - - :param time_grain_type: Type of timegrain cadence. Possible values include: "None", "Monthly", - "Quarterly", "Annually", "BillingMonth", "BillingQuarter", "BillingAnnual". - :type time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType - :param period_start_date: datetime of periodStartDate. - :type period_start_date: str - :param triggered_by: notificationId that triggered this alert. - :type triggered_by: str - :param resource_group_filter: array of resourceGroups to filter by. - :type resource_group_filter: list[any] - :param resource_filter: array of resources to filter by. - :type resource_filter: list[any] - :param meter_filter: array of meters to filter by. - :type meter_filter: list[any] - :param tag_filter: tags to filter by. - :type tag_filter: any - :param threshold: notification threshold percentage as a decimal which activated this alert. - :type threshold: float - :param operator: operator used to compare currentSpend with amount. Possible values include: - "None", "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", "LessThanOrEqualTo". - :type operator: str or ~azure.mgmt.costmanagement.models.AlertOperator - :param amount: budget threshold amount. - :type amount: float - :param unit: unit of currency being used. - :type unit: str - :param current_spend: current spend. - :type current_spend: float - :param contact_emails: list of emails to contact. - :type contact_emails: list[str] - :param contact_groups: list of action groups to broadcast to. - :type contact_groups: list[str] - :param contact_roles: list of contact roles. - :type contact_roles: list[str] - :param overriding_alert: overriding alert. - :type overriding_alert: str - """ - - _attribute_map = { - 'time_grain_type': {'key': 'timeGrainType', 'type': 'str'}, - 'period_start_date': {'key': 'periodStartDate', 'type': 'str'}, - 'triggered_by': {'key': 'triggeredBy', 'type': 'str'}, - 'resource_group_filter': {'key': 'resourceGroupFilter', 'type': '[object]'}, - 'resource_filter': {'key': 'resourceFilter', 'type': '[object]'}, - 'meter_filter': {'key': 'meterFilter', 'type': '[object]'}, - 'tag_filter': {'key': 'tagFilter', 'type': 'object'}, - 'threshold': {'key': 'threshold', 'type': 'float'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'current_spend': {'key': 'currentSpend', 'type': 'float'}, - 'contact_emails': {'key': 'contactEmails', 'type': '[str]'}, - 'contact_groups': {'key': 'contactGroups', 'type': '[str]'}, - 'contact_roles': {'key': 'contactRoles', 'type': '[str]'}, - 'overriding_alert': {'key': 'overridingAlert', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AlertPropertiesDetails, self).__init__(**kwargs) - self.time_grain_type = kwargs.get('time_grain_type', None) - self.period_start_date = kwargs.get('period_start_date', None) - self.triggered_by = kwargs.get('triggered_by', None) - self.resource_group_filter = kwargs.get('resource_group_filter', None) - self.resource_filter = kwargs.get('resource_filter', None) - self.meter_filter = kwargs.get('meter_filter', None) - self.tag_filter = kwargs.get('tag_filter', None) - self.threshold = kwargs.get('threshold', None) - self.operator = kwargs.get('operator', None) - self.amount = kwargs.get('amount', None) - self.unit = kwargs.get('unit', None) - self.current_spend = kwargs.get('current_spend', None) - self.contact_emails = kwargs.get('contact_emails', None) - self.contact_groups = kwargs.get('contact_groups', None) - self.contact_roles = kwargs.get('contact_roles', None) - self.overriding_alert = kwargs.get('overriding_alert', None) - - -class AlertsResult(msrest.serialization.Model): - """Result of alerts. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of alerts. - :vartype value: list[~azure.mgmt.costmanagement.models.Alert] - :ivar next_link: URL to get the next set of alerts results if there are any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Alert]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AlertsResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class CacheItem(msrest.serialization.Model): - """CacheItem. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Resource ID used by Resource Manager to uniquely identify the scope. - :type id: str - :param name: Required. Display name for the scope. - :type name: str - :param channel: Required. Indicates the account type. Allowed values include: EA, PAYG, Modern, - Internal, Unknown. - :type channel: str - :param subchannel: Required. Indicates the type of modern account. Allowed values include: - Individual, Enterprise, Partner, Indirect, NotApplicable. - :type subchannel: str - :param parent: Resource ID of the parent scope. For instance, subscription's resource ID for a - resource group or a management group resource ID for a subscription. - :type parent: str - :param status: Indicates the status of the scope. Status only applies to subscriptions and - billing accounts. - :type status: str - """ - - _validation = { - 'id': {'required': True}, - 'name': {'required': True}, - 'channel': {'required': True}, - 'subchannel': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'channel': {'key': 'channel', 'type': 'str'}, - 'subchannel': {'key': 'subchannel', 'type': 'str'}, - 'parent': {'key': 'parent', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CacheItem, self).__init__(**kwargs) - self.id = kwargs['id'] - self.name = kwargs['name'] - self.channel = kwargs['channel'] - self.subchannel = kwargs['subchannel'] - self.parent = kwargs.get('parent', None) - self.status = kwargs.get('status', None) - - -class CommonExportProperties(msrest.serialization.Model): - """The common properties of the export. - - All required parameters must be populated in order to send to Azure. - - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - """ - - _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, - } - - _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, - } - - def __init__( - self, - **kwargs - ): - super(CommonExportProperties, self).__init__(**kwargs) - self.format = kwargs.get('format', None) - self.delivery_info = kwargs['delivery_info'] - self.definition = kwargs['definition'] - - -class Dimension(Resource): - """Dimension. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :ivar description: Dimension description. - :vartype description: str - :ivar filter_enabled: Filter enabled. - :vartype filter_enabled: bool - :ivar grouping_enabled: Grouping enabled. - :vartype grouping_enabled: bool - :param data: - :type data: list[str] - :ivar total: Total number of data for the dimension. - :vartype total: int - :ivar category: Dimension category. - :vartype category: str - :ivar usage_start: Usage start. - :vartype usage_start: ~datetime.datetime - :ivar usage_end: Usage end. - :vartype usage_end: ~datetime.datetime - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'description': {'readonly': True}, - 'filter_enabled': {'readonly': True}, - 'grouping_enabled': {'readonly': True}, - 'total': {'readonly': True}, - 'category': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'filter_enabled': {'key': 'properties.filterEnabled', 'type': 'bool'}, - 'grouping_enabled': {'key': 'properties.groupingEnabled', 'type': 'bool'}, - 'data': {'key': 'properties.data', 'type': '[str]'}, - 'total': {'key': 'properties.total', 'type': 'int'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'iso-8601'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'iso-8601'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Dimension, self).__init__(**kwargs) - self.description = None - self.filter_enabled = None - self.grouping_enabled = None - self.data = kwargs.get('data', None) - self.total = None - self.category = None - self.usage_start = None - self.usage_end = None - self.next_link = None - - -class DimensionsListResult(msrest.serialization.Model): - """Result of listing dimensions. It contains a list of available dimensions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of dimensions. - :vartype value: list[~azure.mgmt.costmanagement.models.Dimension] - """ - - _validation = { - 'value': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Dimension]'}, - } - - def __init__( - self, - **kwargs - ): - super(DimensionsListResult, self).__init__(**kwargs) - self.value = None - - -class DismissAlertPayload(msrest.serialization.Model): - """The request payload to update an alert. - - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _attribute_map = { - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DismissAlertPayload, self).__init__(**kwargs) - self.definition = kwargs.get('definition', None) - self.description = kwargs.get('description', None) - self.source = kwargs.get('source', None) - self.details = kwargs.get('details', None) - self.cost_entity_id = kwargs.get('cost_entity_id', None) - self.status = kwargs.get('status', None) - self.creation_time = kwargs.get('creation_time', None) - self.close_time = kwargs.get('close_time', None) - self.modification_time = kwargs.get('modification_time', None) - self.status_modification_user_name = kwargs.get('status_modification_user_name', None) - self.status_modification_time = kwargs.get('status_modification_time', None) - - -class ErrorDetails(msrest.serialization.Model): - """The details of the error. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetails, self).__init__(**kwargs) - self.code = None - self.message = None - - -class ErrorResponse(msrest.serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. - -Some Error responses: - - -* - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. - -* - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. - - :param error: The details of the error. - :type error: ~azure.mgmt.costmanagement.models.ErrorDetails - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ProxyResource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProxyResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.e_tag = kwargs.get('e_tag', None) - - -class Export(ProxyResource): - """A export resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'format': {'key': 'properties.format', 'type': 'str'}, - 'delivery_info': {'key': 'properties.deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'properties.definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'properties.schedule', 'type': 'ExportSchedule'}, - } - - def __init__( - self, - **kwargs - ): - super(Export, self).__init__(**kwargs) - self.format = kwargs.get('format', None) - self.delivery_info = kwargs.get('delivery_info', None) - self.definition = kwargs.get('definition', None) - self.schedule = kwargs.get('schedule', None) - - -class ExportDefinition(msrest.serialization.Model): - """The definition of a query. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", - "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param data_set: Has definition for data in this query. - :type data_set: ~azure.mgmt.costmanagement.models.QueryDatasetAutoGenerated - """ - - _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'data_set': {'key': 'dataSet', 'type': 'QueryDatasetAutoGenerated'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportDefinition, self).__init__(**kwargs) - self.type = kwargs['type'] - self.timeframe = kwargs['timeframe'] - self.time_period = kwargs.get('time_period', None) - self.data_set = kwargs.get('data_set', None) - - -class ExportDeliveryDestination(msrest.serialization.Model): - """The destination information for the delivery of the export. To allow access to a storage account, you must register the account's subscription with the Microsoft.CostManagementExports resource provider. This is required once per subscription. When creating an export in the Azure portal, it is done automatically, however API users need to register the subscription. For more information see https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services . - - All required parameters must be populated in order to send to Azure. - - :param resource_id: Required. The resource id of the storage account where exports will be - delivered. - :type resource_id: str - :param container: Required. The name of the container where exports will be uploaded. - :type container: str - :param root_folder_path: The name of the directory where exports will be uploaded. - :type root_folder_path: str - """ - - _validation = { - 'resource_id': {'required': True}, - 'container': {'required': True}, - } - - _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'container': {'key': 'container', 'type': 'str'}, - 'root_folder_path': {'key': 'rootFolderPath', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportDeliveryDestination, self).__init__(**kwargs) - self.resource_id = kwargs['resource_id'] - self.container = kwargs['container'] - self.root_folder_path = kwargs.get('root_folder_path', None) - - -class ExportDeliveryInfo(msrest.serialization.Model): - """The delivery information associated with a export. - - All required parameters must be populated in order to send to Azure. - - :param destination: Required. Has destination for the export being delivered. - :type destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination - """ - - _validation = { - 'destination': {'required': True}, - } - - _attribute_map = { - 'destination': {'key': 'destination', 'type': 'ExportDeliveryDestination'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportDeliveryInfo, self).__init__(**kwargs) - self.destination = kwargs['destination'] - - -class ExportExecution(Resource): - """A export execution. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param execution_type: The type of the export execution. Possible values include: "OnDemand", - "Scheduled". - :type execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType - :param status: The status of the export execution. Possible values include: "Queued", - "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", "DataNotAvailable". - :type status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus - :param submitted_by: The identifier for the entity that executed the export. For OnDemand - executions, it is the email id. For Scheduled executions, it is the constant value - System. - :type submitted_by: str - :param submitted_time: The time when export was queued to be executed. - :type submitted_time: ~datetime.datetime - :param processing_start_time: The time when export was picked up to be executed. - :type processing_start_time: ~datetime.datetime - :param processing_end_time: The time when export execution finished. - :type processing_end_time: ~datetime.datetime - :param file_name: The name of the file export got written to. - :type file_name: str - :param run_settings: The common properties of the export. - :type run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'execution_type': {'key': 'properties.executionType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'submitted_by': {'key': 'properties.submittedBy', 'type': 'str'}, - 'submitted_time': {'key': 'properties.submittedTime', 'type': 'iso-8601'}, - 'processing_start_time': {'key': 'properties.processingStartTime', 'type': 'iso-8601'}, - 'processing_end_time': {'key': 'properties.processingEndTime', 'type': 'iso-8601'}, - 'file_name': {'key': 'properties.fileName', 'type': 'str'}, - 'run_settings': {'key': 'properties.runSettings', 'type': 'CommonExportProperties'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportExecution, self).__init__(**kwargs) - self.execution_type = kwargs.get('execution_type', None) - self.status = kwargs.get('status', None) - self.submitted_by = kwargs.get('submitted_by', None) - self.submitted_time = kwargs.get('submitted_time', None) - self.processing_start_time = kwargs.get('processing_start_time', None) - self.processing_end_time = kwargs.get('processing_end_time', None) - self.file_name = kwargs.get('file_name', None) - self.run_settings = kwargs.get('run_settings', None) - - -class ExportExecutionListResult(msrest.serialization.Model): - """Result of listing exports execution history of a export by name. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of export executions. - :vartype value: list[~azure.mgmt.costmanagement.models.ExportExecution] - """ - - _validation = { - 'value': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ExportExecution]'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportExecutionListResult, self).__init__(**kwargs) - self.value = None - - -class ExportListResult(msrest.serialization.Model): - """Result of listing exports. It contains a list of available exports in the scope provided. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of exports. - :vartype value: list[~azure.mgmt.costmanagement.models.Export] - """ - - _validation = { - 'value': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Export]'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportListResult, self).__init__(**kwargs) - self.value = None - - -class ExportProperties(CommonExportProperties): - """The properties of the export. - - All required parameters must be populated in order to send to Azure. - - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule - """ - - _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, - } - - _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'schedule', 'type': 'ExportSchedule'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportProperties, self).__init__(**kwargs) - self.schedule = kwargs.get('schedule', None) - - -class ExportRecurrencePeriod(msrest.serialization.Model): - """The start and end date for recurrence schedule. - - All required parameters must be populated in order to send to Azure. - - :param from_property: Required. The start date of recurrence. - :type from_property: ~datetime.datetime - :param to: The end date of recurrence. - :type to: ~datetime.datetime - """ - - _validation = { - 'from_property': {'required': True}, - } - - _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportRecurrencePeriod, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.to = kwargs.get('to', None) - - -class ExportSchedule(msrest.serialization.Model): - """The schedule associated with a export. - - All required parameters must be populated in order to send to Azure. - - :param status: The status of the schedule. Whether active or not. If inactive, the export's - scheduled execution is paused. Possible values include: "Active", "Inactive". - :type status: str or ~azure.mgmt.costmanagement.models.StatusType - :param recurrence: Required. The schedule recurrence. Possible values include: "Daily", - "Weekly", "Monthly", "Annually". - :type recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType - :param recurrence_period: Has start and end date of the recurrence. The start date must be in - future. If present, the end date must be greater than start date. - :type recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod - """ - - _validation = { - 'recurrence': {'required': True}, - } - - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'recurrence': {'key': 'recurrence', 'type': 'str'}, - 'recurrence_period': {'key': 'recurrencePeriod', 'type': 'ExportRecurrencePeriod'}, - } - - def __init__( - self, - **kwargs - ): - super(ExportSchedule, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - self.recurrence = kwargs['recurrence'] - self.recurrence_period = kwargs.get('recurrence_period', None) - - -class ForecastDefinition(msrest.serialization.Model): - """The definition of a forecast. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of the forecast. Possible values include: "Usage", - "ActualCost", "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ForecastType - :param timeframe: Required. The time frame for pulling data for the forecast. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframeType - :param time_period: Has time period for pulling data for the forecast. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this forecast. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset - :param include_actual_cost: a boolean determining if actualCost will be included. - :type include_actual_cost: bool - :param include_fresh_partial_cost: a boolean determining if FreshPartialCost will be included. - :type include_fresh_partial_cost: bool - """ - - _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, - 'include_actual_cost': {'key': 'includeActualCost', 'type': 'bool'}, - 'include_fresh_partial_cost': {'key': 'includeFreshPartialCost', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(ForecastDefinition, self).__init__(**kwargs) - self.type = kwargs['type'] - self.timeframe = kwargs['timeframe'] - self.time_period = kwargs.get('time_period', None) - self.dataset = kwargs['dataset'] - self.include_actual_cost = kwargs.get('include_actual_cost', None) - self.include_fresh_partial_cost = kwargs.get('include_fresh_partial_cost', None) - - -class KpiProperties(msrest.serialization.Model): - """Each KPI must contain a 'type' and 'enabled' key. - - :param type: KPI type (Forecast, Budget). Possible values include: "Forecast", "Budget". - :type type: str or ~azure.mgmt.costmanagement.models.KpiType - :param id: ID of resource related to metric (budget). - :type id: str - :param enabled: show the KPI in the UI?. - :type enabled: bool - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'enabled': {'key': 'enabled', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(KpiProperties, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.id = kwargs.get('id', None) - self.enabled = kwargs.get('enabled', None) - - -class Operation(msrest.serialization.Model): - """A Cost management REST API operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :param display: The object that represents the operation. - :type display: ~azure.mgmt.costmanagement.models.OperationDisplay - """ - - _validation = { - 'name': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.display = kwargs.get('display', None) - - -class OperationDisplay(msrest.serialization.Model): - """The object that represents the operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: Service provider: Microsoft.CostManagement. - :vartype provider: str - :ivar resource: Resource on which the operation is performed: Dimensions, Query. - :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. - :vartype operation: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - - -class OperationListResult(msrest.serialization.Model): - """Result of listing cost management operations. It contains a list of operations and a URL link to get the next set of results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: List of cost management operations supported by the Microsoft.CostManagement - resource provider. - :vartype value: list[~azure.mgmt.costmanagement.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class OperationStatus(msrest.serialization.Model): - """The status of the long running operation. - - :param status: The status of the long running operation. - :type status: ~azure.mgmt.costmanagement.models.Status - :param report_url: The URL to download the generated report. - :type report_url: str - :param valid_until: The time at which report URL becomes invalid. - :type valid_until: ~datetime.datetime - """ - - _attribute_map = { - 'status': {'key': 'status', 'type': 'Status'}, - 'report_url': {'key': 'properties.reportUrl', 'type': 'str'}, - 'valid_until': {'key': 'properties.validUntil', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationStatus, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - self.report_url = kwargs.get('report_url', None) - self.valid_until = kwargs.get('valid_until', None) - - -class PivotProperties(msrest.serialization.Model): - """Each pivot must contain a 'type' and 'name'. - - :param type: Data type to show in view. Possible values include: "Dimension", "TagKey". - :type type: str or ~azure.mgmt.costmanagement.models.PivotType - :param name: Data field to show in view. - :type name: str - """ - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PivotProperties, self).__init__(**kwargs) - self.type = kwargs.get('type', None) - self.name = kwargs.get('name', None) - - -class ProxySettingResource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProxySettingResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.kind = None - self.type = None - - -class QueryAggregation(msrest.serialization.Model): - """The aggregation expression to be used in the query. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType - """ - - _validation = { - 'name': {'required': True}, - 'function': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryAggregation, self).__init__(**kwargs) - self.name = kwargs['name'] - self.function = kwargs['function'] - - -class QueryColumn(msrest.serialization.Model): - """QueryColumn. - - :param name: The name of column. - :type name: str - :param type: The type of column. - :type type: str - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryColumn, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.type = kwargs.get('type', None) - - -class QueryComparisonExpression(msrest.serialization.Model): - """The comparison expression to be used in the query. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", - "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] - """ - - _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryComparisonExpression, self).__init__(**kwargs) - self.name = kwargs['name'] - self.operator = kwargs['operator'] - self.values = kwargs['values'] - - -class QueryDataset(msrest.serialization.Model): - """The definition of data present in the query. - - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each - item in the dictionary is the alias for the aggregated column. Query can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group - by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST - documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilter - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilter'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDataset, self).__init__(**kwargs) - self.granularity = kwargs.get('granularity', None) - self.configuration = kwargs.get('configuration', None) - self.aggregation = kwargs.get('aggregation', None) - self.grouping = kwargs.get('grouping', None) - self.filter = kwargs.get('filter', None) - - -class QueryDatasetAutoGenerated(msrest.serialization.Model): - """The definition of data present in the query. - - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each - item in the dictionary is the alias for the aggregated column. Query can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group - by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST - documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilterAutoGenerated'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDatasetAutoGenerated, self).__init__(**kwargs) - self.granularity = kwargs.get('granularity', None) - self.configuration = kwargs.get('configuration', None) - self.aggregation = kwargs.get('aggregation', None) - self.grouping = kwargs.get('grouping', None) - self.filter = kwargs.get('filter', None) - - -class QueryDatasetConfiguration(msrest.serialization.Model): - """The configuration of dataset in the query. - - :param columns: Array of column names to be included in the query. Any valid query column name - is allowed. If not provided, then query includes all columns. - :type columns: list[str] - """ - - _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDatasetConfiguration, self).__init__(**kwargs) - self.columns = kwargs.get('columns', None) - - -class QueryDefinition(msrest.serialization.Model): - """The definition of a query. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", - "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this query. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset - """ - - _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryDefinition, self).__init__(**kwargs) - self.type = kwargs['type'] - self.timeframe = kwargs['timeframe'] - self.time_period = kwargs.get('time_period', None) - self.dataset = kwargs['dataset'] - - -class QueryFilter(msrest.serialization.Model): - """The filter expression to be used in the export. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilter]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryFilter, self).__init__(**kwargs) - self.and_property = kwargs.get('and_property', None) - self.or_property = kwargs.get('or_property', None) - self.dimensions = kwargs.get('dimensions', None) - self.tags = kwargs.get('tags', None) - - -class QueryFilterAutoGenerated(msrest.serialization.Model): - """The filter expression to be used in the export. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilterAutoGenerated]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilterAutoGenerated]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryFilterAutoGenerated, self).__init__(**kwargs) - self.and_property = kwargs.get('and_property', None) - self.or_property = kwargs.get('or_property', None) - self.dimensions = kwargs.get('dimensions', None) - self.tags = kwargs.get('tags', None) - - -class QueryGrouping(msrest.serialization.Model): - """The group by expression to be used in the query. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.QueryColumnType - :param name: Required. The name of the column to group. - :type name: str - """ - - _validation = { - 'type': {'required': True}, - 'name': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryGrouping, self).__init__(**kwargs) - self.type = kwargs['type'] - self.name = kwargs['name'] - - -class QueryResult(Resource): - """Result of query. It contains all columns listed under groupings and aggregation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :ivar location: Resource location. - :vartype location: str - :ivar sku: Resource SKU. - :vartype sku: str - :param next_link: The link (url) to the next page of results. - :type next_link: str - :param columns: Array of columns. - :type columns: list[~azure.mgmt.costmanagement.models.QueryColumn] - :param rows: Array of rows. - :type rows: list[list[any]] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'location': {'readonly': True}, - 'sku': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - 'columns': {'key': 'properties.columns', 'type': '[QueryColumn]'}, - 'rows': {'key': 'properties.rows', 'type': '[[object]]'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryResult, self).__init__(**kwargs) - self.e_tag = kwargs.get('e_tag', None) - self.location = None - self.sku = None - self.next_link = kwargs.get('next_link', None) - self.columns = kwargs.get('columns', None) - self.rows = kwargs.get('rows', None) - - -class QueryTimePeriod(msrest.serialization.Model): - """The start and end date for pulling data for the query. - - All required parameters must be populated in order to send to Azure. - - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime - """ - - _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, - } - - _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryTimePeriod, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.to = kwargs['to'] - - -class ReportConfigAggregation(msrest.serialization.Model): - """The aggregation expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType - """ - - _validation = { - 'name': {'required': True}, - 'function': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigAggregation, self).__init__(**kwargs) - self.name = kwargs['name'] - self.function = kwargs['function'] - - -class ReportConfigComparisonExpression(msrest.serialization.Model): - """The comparison expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", - "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] - """ - - _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigComparisonExpression, self).__init__(**kwargs) - self.name = kwargs['name'] - self.operator = kwargs['operator'] - self.values = kwargs['values'] - - -class ReportConfigDataset(msrest.serialization.Model): - """The definition of data present in the report. - - :param granularity: The granularity of rows in the report. Possible values include: "Daily", - "Monthly". - :type granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType - :param configuration: Has configuration information for the data in the report. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the report. The key of each - item in the dictionary is the alias for the aggregated column. Report can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] - :param grouping: Array of group by expression to use in the report. Report can have up to 2 - group by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] - :param sorting: Array of order by expression to use in the report. - :type sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] - :param filter: Has filter expression to use in the report. - :type filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'ReportConfigDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{ReportConfigAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[ReportConfigGrouping]'}, - 'sorting': {'key': 'sorting', 'type': '[ReportConfigSorting]'}, - 'filter': {'key': 'filter', 'type': 'ReportConfigFilter'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigDataset, self).__init__(**kwargs) - self.granularity = kwargs.get('granularity', None) - self.configuration = kwargs.get('configuration', None) - self.aggregation = kwargs.get('aggregation', None) - self.grouping = kwargs.get('grouping', None) - self.sorting = kwargs.get('sorting', None) - self.filter = kwargs.get('filter', None) - - -class ReportConfigDatasetConfiguration(msrest.serialization.Model): - """The configuration of dataset in the report. - - :param columns: Array of column names to be included in the report. Any valid report column - name is allowed. If not provided, then report includes all columns. - :type columns: list[str] - """ - - _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigDatasetConfiguration, self).__init__(**kwargs) - self.columns = kwargs.get('columns', None) - - -class ReportConfigFilter(msrest.serialization.Model): - """The filter expression to be used in the report. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_key: Has comparison expression for a tag key. - :type tag_key: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_value: Has comparison expression for a tag value. - :type tag_value: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[ReportConfigFilter]'}, - 'or_property': {'key': 'or', 'type': '[ReportConfigFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'ReportConfigComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'ReportConfigComparisonExpression'}, - 'tag_key': {'key': 'tagKey', 'type': 'ReportConfigComparisonExpression'}, - 'tag_value': {'key': 'tagValue', 'type': 'ReportConfigComparisonExpression'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigFilter, self).__init__(**kwargs) - self.and_property = kwargs.get('and_property', None) - self.or_property = kwargs.get('or_property', None) - self.dimensions = kwargs.get('dimensions', None) - self.tags = kwargs.get('tags', None) - self.tag_key = kwargs.get('tag_key', None) - self.tag_value = kwargs.get('tag_value', None) - - -class ReportConfigGrouping(msrest.serialization.Model): - """The group by expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType - :param name: Required. The name of the column to group. This version supports subscription - lowest possible grain. - :type name: str - """ - - _validation = { - 'type': {'required': True}, - 'name': {'required': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigGrouping, self).__init__(**kwargs) - self.type = kwargs['type'] - self.name = kwargs['name'] - - -class ReportConfigSorting(msrest.serialization.Model): - """The order by expression to be used in the report. - - All required parameters must be populated in order to send to Azure. - - :param direction: Direction of sort. Possible values include: "Ascending", "Descending". - :type direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingDirection - :param name: Required. The name of the column to sort. - :type name: str - """ - - _validation = { - 'name': {'required': True}, - } - - _attribute_map = { - 'direction': {'key': 'direction', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigSorting, self).__init__(**kwargs) - self.direction = kwargs.get('direction', None) - self.name = kwargs['name'] - - -class ReportConfigTimePeriod(msrest.serialization.Model): - """The start and end date for pulling data for the report. - - All required parameters must be populated in order to send to Azure. - - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime - """ - - _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, - } - - _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(ReportConfigTimePeriod, self).__init__(**kwargs) - self.from_property = kwargs['from_property'] - self.to = kwargs['to'] - - -class Setting(ProxySettingResource): - """State of the myscope setting. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. - :vartype type: str - :param scope: Sets the default scope the current user will see when they sign into Azure Cost - Management in the Azure portal. - :type scope: str - :param start_on: Indicates what scope Cost Management in the Azure portal should default to. - Allowed values: LastUsed. Possible values include: "LastUsed", "ScopePicker", "SpecificScope". - :type start_on: str or ~azure.mgmt.costmanagement.models.SettingsPropertiesStartOn - :param cache: Array of scopes with additional details used by Cost Management in the Azure - portal. - :type cache: list[~azure.mgmt.costmanagement.models.CacheItem] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'start_on': {'key': 'properties.startOn', 'type': 'str'}, - 'cache': {'key': 'properties.cache', 'type': '[CacheItem]'}, - } - - def __init__( - self, - **kwargs - ): - super(Setting, self).__init__(**kwargs) - self.scope = kwargs.get('scope', None) - self.start_on = kwargs.get('start_on', None) - self.cache = kwargs.get('cache', None) - - -class SettingsListResult(msrest.serialization.Model): - """Result of listing settings. It contains a list of available settings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of settings. - :vartype value: list[~azure.mgmt.costmanagement.models.Setting] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True, 'max_items': 10, 'min_items': 0}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Setting]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SettingsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class Status(msrest.serialization.Model): - """The status of the long running operation. - - :param status: The status of the long running operation. Possible values include: "Running", - "Completed", "Failed". - :type status: str or ~azure.mgmt.costmanagement.models.OperationStatusType - """ - - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Status, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - - -class View(ProxyResource): - """States and configurations of Cost Analysis. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param display_name: User input name of the view. Required. - :type display_name: str - :param scope: Cost Management scope to save the view on. This includes - 'subscriptions/{subscriptionId}' for subscription scope, - 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for - Department scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' - for EnrollmentAccount scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' - for BillingProfile scope, - 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' - for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' - for Management Group scope, - '/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for - ExternalBillingAccount scope, and - '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - ExternalSubscription scope. - :type scope: str - :ivar created_on: Date the user created this view. - :vartype created_on: ~datetime.datetime - :ivar modified_on: Date when the user last modified this view. - :vartype modified_on: ~datetime.datetime - :ivar date_range: Selected date range for viewing cost in. - :vartype date_range: str - :ivar currency: Selected currency. - :vartype currency: str - :param chart: Chart type of the main view in Cost Analysis. Required. Possible values include: - "Area", "Line", "StackedColumn", "GroupedColumn", "Table". - :type chart: str or ~azure.mgmt.costmanagement.models.ChartType - :param accumulated: Show costs accumulated over time. Possible values include: "true", "false". - :type accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType - :param metric: Metric to use when displaying costs. Possible values include: "ActualCost", - "AmortizedCost", "AHUB". - :type metric: str or ~azure.mgmt.costmanagement.models.MetricType - :param kpis: List of KPIs to show in Cost Analysis UI. - :type kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] - :param pivots: Configuration of 3 sub-views in the Cost Analysis UI. - :type pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] - :param type_properties_query_type: The type of the report. Usage represents actual usage, - forecast represents forecasted data and UsageAndForecast represents both usage and forecasted - data. Actual usage and forecasted data can be differentiated based on dates. Possible values - include: "Usage". - :type type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType - :param timeframe: The time frame for pulling data for the report. If custom, then a specific - time period must be provided. Possible values include: "WeekToDate", "MonthToDate", - "YearToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType - :param time_period: Has time period for pulling data for the report. - :type time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod - :param data_set: Has definition for data in this report config. - :type data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset - :ivar include_monetary_commitment: Include monetary commitment. - :vartype include_monetary_commitment: bool - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_on': {'readonly': True}, - 'modified_on': {'readonly': True}, - 'date_range': {'readonly': True}, - 'currency': {'readonly': True}, - 'include_monetary_commitment': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'modified_on': {'key': 'properties.modifiedOn', 'type': 'iso-8601'}, - 'date_range': {'key': 'properties.dateRange', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'chart': {'key': 'properties.chart', 'type': 'str'}, - 'accumulated': {'key': 'properties.accumulated', 'type': 'str'}, - 'metric': {'key': 'properties.metric', 'type': 'str'}, - 'kpis': {'key': 'properties.kpis', 'type': '[KpiProperties]'}, - 'pivots': {'key': 'properties.pivots', 'type': '[PivotProperties]'}, - 'type_properties_query_type': {'key': 'properties.query.type', 'type': 'str'}, - 'timeframe': {'key': 'properties.query.timeframe', 'type': 'str'}, - 'time_period': {'key': 'properties.query.timePeriod', 'type': 'ReportConfigTimePeriod'}, - 'data_set': {'key': 'properties.query.dataSet', 'type': 'ReportConfigDataset'}, - 'include_monetary_commitment': {'key': 'properties.query.includeMonetaryCommitment', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(View, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.scope = kwargs.get('scope', None) - self.created_on = None - self.modified_on = None - self.date_range = None - self.currency = None - self.chart = kwargs.get('chart', None) - self.accumulated = kwargs.get('accumulated', None) - self.metric = kwargs.get('metric', None) - self.kpis = kwargs.get('kpis', None) - self.pivots = kwargs.get('pivots', None) - self.type_properties_query_type = kwargs.get('type_properties_query_type', None) - self.timeframe = kwargs.get('timeframe', None) - self.time_period = kwargs.get('time_period', None) - self.data_set = kwargs.get('data_set', None) - self.include_monetary_commitment = None - - -class ViewListResult(msrest.serialization.Model): - """Result of listing views. It contains a list of available views. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of views. - :vartype value: list[~azure.mgmt.costmanagement.models.View] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[View]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ViewListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py index e3f7e70197dd..94017df1f517 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,15 +8,23 @@ # -------------------------------------------------------------------------- import datetime -from typing import Any, Dict, List, Optional, Union +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._cost_management_client_enums import * +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class Resource(msrest.serialization.Model): + +class CostManagementProxyResource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -26,36 +35,38 @@ class Resource(msrest.serialization.Model): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, *, e_tag: Optional[str] = None, **kwargs): + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None - self.tags = None + self.e_tag = e_tag -class Alert(Resource): +class Alert(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes """An individual alert. Variables are only populated by the server, and will be ignored when sending a request. @@ -66,67 +77,68 @@ class Alert(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str + :ivar definition: defines the type of alert. + :vartype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :ivar description: Alert description. + :vartype description: str + :ivar source: Source of alert. Known values are: "Preset" and "User". + :vartype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :ivar details: Alert details. + :vartype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :ivar cost_entity_id: related budget. + :vartype cost_entity_id: str + :ivar status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", and + "Dismissed". + :vartype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :ivar creation_time: dateTime in which alert was created. + :vartype creation_time: str + :ivar close_time: dateTime in which alert was closed. + :vartype close_time: str + :ivar modification_time: dateTime in which alert was last modified. + :vartype modification_time: str + :ivar status_modification_user_name: User who last modified the alert. + :vartype status_modification_user_name: str + :ivar status_modification_time: dateTime in which the alert status was last modified. + :vartype status_modification_time: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "definition": {"key": "properties.definition", "type": "AlertPropertiesDefinition"}, + "description": {"key": "properties.description", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, + "details": {"key": "properties.details", "type": "AlertPropertiesDetails"}, + "cost_entity_id": {"key": "properties.costEntityId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "creation_time": {"key": "properties.creationTime", "type": "str"}, + "close_time": {"key": "properties.closeTime", "type": "str"}, + "modification_time": {"key": "properties.modificationTime", "type": "str"}, + "status_modification_user_name": {"key": "properties.statusModificationUserName", "type": "str"}, + "status_modification_time": {"key": "properties.statusModificationTime", "type": "str"}, } def __init__( self, *, - definition: Optional["AlertPropertiesDefinition"] = None, + e_tag: Optional[str] = None, + definition: Optional["_models.AlertPropertiesDefinition"] = None, description: Optional[str] = None, - source: Optional[Union[str, "AlertSource"]] = None, - details: Optional["AlertPropertiesDetails"] = None, + source: Optional[Union[str, "_models.AlertSource"]] = None, + details: Optional["_models.AlertPropertiesDetails"] = None, cost_entity_id: Optional[str] = None, - status: Optional[Union[str, "AlertStatus"]] = None, + status: Optional[Union[str, "_models.AlertStatus"]] = None, creation_time: Optional[str] = None, close_time: Optional[str] = None, modification_time: Optional[str] = None, @@ -134,7 +146,35 @@ def __init__( status_modification_time: Optional[str] = None, **kwargs ): - super(Alert, self).__init__(**kwargs) + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword definition: defines the type of alert. + :paramtype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :keyword description: Alert description. + :paramtype description: str + :keyword source: Source of alert. Known values are: "Preset" and "User". + :paramtype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :keyword details: Alert details. + :paramtype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :keyword cost_entity_id: related budget. + :paramtype cost_entity_id: str + :keyword status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", + and "Dismissed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :keyword creation_time: dateTime in which alert was created. + :paramtype creation_time: str + :keyword close_time: dateTime in which alert was closed. + :paramtype close_time: str + :keyword modification_time: dateTime in which alert was last modified. + :paramtype modification_time: str + :keyword status_modification_user_name: User who last modified the alert. + :paramtype status_modification_user_name: str + :keyword status_modification_time: dateTime in which the alert status was last modified. + :paramtype status_modification_time: str + """ + super().__init__(e_tag=e_tag, **kwargs) self.definition = definition self.description = description self.source = source @@ -148,113 +188,145 @@ def __init__( self.status_modification_time = status_modification_time -class AlertPropertiesDefinition(msrest.serialization.Model): +class AlertPropertiesDefinition(_serialization.Model): """defines the type of alert. - :param type: type of alert. Possible values include: "Budget", "Invoice", "Credit", "Quota", - "General", "xCloud", "BudgetForecast". - :type type: str or ~azure.mgmt.costmanagement.models.AlertType - :param category: Alert category. Possible values include: "Cost", "Usage", "Billing", "System". - :type category: str or ~azure.mgmt.costmanagement.models.AlertCategory - :param criteria: Criteria that triggered alert. Possible values include: - "CostThresholdExceeded", "UsageThresholdExceeded", "CreditThresholdApproaching", - "CreditThresholdReached", "QuotaThresholdApproaching", "QuotaThresholdReached", - "MultiCurrency", "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", - "InvoiceDueDateApproaching", "InvoiceDueDateReached", "CrossCloudNewDataAvailable", - "CrossCloudCollectionError", "GeneralThresholdError". - :type criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria + :ivar type: type of alert. Known values are: "Budget", "Invoice", "Credit", "Quota", "General", + "xCloud", and "BudgetForecast". + :vartype type: str or ~azure.mgmt.costmanagement.models.AlertType + :ivar category: Alert category. Known values are: "Cost", "Usage", "Billing", and "System". + :vartype category: str or ~azure.mgmt.costmanagement.models.AlertCategory + :ivar criteria: Criteria that triggered alert. Known values are: "CostThresholdExceeded", + "UsageThresholdExceeded", "CreditThresholdApproaching", "CreditThresholdReached", + "QuotaThresholdApproaching", "QuotaThresholdReached", "MultiCurrency", + "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", "InvoiceDueDateApproaching", + "InvoiceDueDateReached", "CrossCloudNewDataAvailable", "CrossCloudCollectionError", and + "GeneralThresholdError". + :vartype criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'criteria': {'key': 'criteria', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "criteria": {"key": "criteria", "type": "str"}, } def __init__( self, *, - type: Optional[Union[str, "AlertType"]] = None, - category: Optional[Union[str, "AlertCategory"]] = None, - criteria: Optional[Union[str, "AlertCriteria"]] = None, + type: Optional[Union[str, "_models.AlertType"]] = None, + category: Optional[Union[str, "_models.AlertCategory"]] = None, + criteria: Optional[Union[str, "_models.AlertCriteria"]] = None, **kwargs ): - super(AlertPropertiesDefinition, self).__init__(**kwargs) + """ + :keyword type: type of alert. Known values are: "Budget", "Invoice", "Credit", "Quota", + "General", "xCloud", and "BudgetForecast". + :paramtype type: str or ~azure.mgmt.costmanagement.models.AlertType + :keyword category: Alert category. Known values are: "Cost", "Usage", "Billing", and "System". + :paramtype category: str or ~azure.mgmt.costmanagement.models.AlertCategory + :keyword criteria: Criteria that triggered alert. Known values are: "CostThresholdExceeded", + "UsageThresholdExceeded", "CreditThresholdApproaching", "CreditThresholdReached", + "QuotaThresholdApproaching", "QuotaThresholdReached", "MultiCurrency", + "ForecastCostThresholdExceeded", "ForecastUsageThresholdExceeded", "InvoiceDueDateApproaching", + "InvoiceDueDateReached", "CrossCloudNewDataAvailable", "CrossCloudCollectionError", and + "GeneralThresholdError". + :paramtype criteria: str or ~azure.mgmt.costmanagement.models.AlertCriteria + """ + super().__init__(**kwargs) self.type = type self.category = category self.criteria = criteria -class AlertPropertiesDetails(msrest.serialization.Model): +class AlertPropertiesDetails(_serialization.Model): # pylint: disable=too-many-instance-attributes """Alert details. - :param time_grain_type: Type of timegrain cadence. Possible values include: "None", "Monthly", - "Quarterly", "Annually", "BillingMonth", "BillingQuarter", "BillingAnnual". - :type time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType - :param period_start_date: datetime of periodStartDate. - :type period_start_date: str - :param triggered_by: notificationId that triggered this alert. - :type triggered_by: str - :param resource_group_filter: array of resourceGroups to filter by. - :type resource_group_filter: list[any] - :param resource_filter: array of resources to filter by. - :type resource_filter: list[any] - :param meter_filter: array of meters to filter by. - :type meter_filter: list[any] - :param tag_filter: tags to filter by. - :type tag_filter: any - :param threshold: notification threshold percentage as a decimal which activated this alert. - :type threshold: float - :param operator: operator used to compare currentSpend with amount. Possible values include: - "None", "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", "LessThanOrEqualTo". - :type operator: str or ~azure.mgmt.costmanagement.models.AlertOperator - :param amount: budget threshold amount. - :type amount: float - :param unit: unit of currency being used. - :type unit: str - :param current_spend: current spend. - :type current_spend: float - :param contact_emails: list of emails to contact. - :type contact_emails: list[str] - :param contact_groups: list of action groups to broadcast to. - :type contact_groups: list[str] - :param contact_roles: list of contact roles. - :type contact_roles: list[str] - :param overriding_alert: overriding alert. - :type overriding_alert: str - """ - - _attribute_map = { - 'time_grain_type': {'key': 'timeGrainType', 'type': 'str'}, - 'period_start_date': {'key': 'periodStartDate', 'type': 'str'}, - 'triggered_by': {'key': 'triggeredBy', 'type': 'str'}, - 'resource_group_filter': {'key': 'resourceGroupFilter', 'type': '[object]'}, - 'resource_filter': {'key': 'resourceFilter', 'type': '[object]'}, - 'meter_filter': {'key': 'meterFilter', 'type': '[object]'}, - 'tag_filter': {'key': 'tagFilter', 'type': 'object'}, - 'threshold': {'key': 'threshold', 'type': 'float'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'float'}, - 'unit': {'key': 'unit', 'type': 'str'}, - 'current_spend': {'key': 'currentSpend', 'type': 'float'}, - 'contact_emails': {'key': 'contactEmails', 'type': '[str]'}, - 'contact_groups': {'key': 'contactGroups', 'type': '[str]'}, - 'contact_roles': {'key': 'contactRoles', 'type': '[str]'}, - 'overriding_alert': {'key': 'overridingAlert', 'type': 'str'}, + :ivar time_grain_type: Type of timegrain cadence. Known values are: "None", "Monthly", + "Quarterly", "Annually", "BillingMonth", "BillingQuarter", and "BillingAnnual". + :vartype time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType + :ivar period_start_date: datetime of periodStartDate. + :vartype period_start_date: str + :ivar triggered_by: notificationId that triggered this alert. + :vartype triggered_by: str + :ivar resource_group_filter: array of resourceGroups to filter by. + :vartype resource_group_filter: list[any] + :ivar resource_filter: array of resources to filter by. + :vartype resource_filter: list[any] + :ivar meter_filter: array of meters to filter by. + :vartype meter_filter: list[any] + :ivar tag_filter: tags to filter by. + :vartype tag_filter: JSON + :ivar threshold: notification threshold percentage as a decimal which activated this alert. + :vartype threshold: float + :ivar operator: operator used to compare currentSpend with amount. Known values are: "None", + "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", and "LessThanOrEqualTo". + :vartype operator: str or ~azure.mgmt.costmanagement.models.AlertOperator + :ivar amount: budget threshold amount. + :vartype amount: float + :ivar unit: unit of currency being used. + :vartype unit: str + :ivar current_spend: current spend. + :vartype current_spend: float + :ivar contact_emails: list of emails to contact. + :vartype contact_emails: list[str] + :ivar contact_groups: list of action groups to broadcast to. + :vartype contact_groups: list[str] + :ivar contact_roles: list of contact roles. + :vartype contact_roles: list[str] + :ivar overriding_alert: overriding alert. + :vartype overriding_alert: str + :ivar department_name: department name. + :vartype department_name: str + :ivar company_name: company name. + :vartype company_name: str + :ivar enrollment_number: enrollment number. + :vartype enrollment_number: str + :ivar enrollment_start_date: datetime of enrollmentStartDate. + :vartype enrollment_start_date: str + :ivar enrollment_end_date: datetime of enrollmentEndDate. + :vartype enrollment_end_date: str + :ivar invoicing_threshold: invoicing threshold. + :vartype invoicing_threshold: float + """ + + _attribute_map = { + "time_grain_type": {"key": "timeGrainType", "type": "str"}, + "period_start_date": {"key": "periodStartDate", "type": "str"}, + "triggered_by": {"key": "triggeredBy", "type": "str"}, + "resource_group_filter": {"key": "resourceGroupFilter", "type": "[object]"}, + "resource_filter": {"key": "resourceFilter", "type": "[object]"}, + "meter_filter": {"key": "meterFilter", "type": "[object]"}, + "tag_filter": {"key": "tagFilter", "type": "object"}, + "threshold": {"key": "threshold", "type": "float"}, + "operator": {"key": "operator", "type": "str"}, + "amount": {"key": "amount", "type": "float"}, + "unit": {"key": "unit", "type": "str"}, + "current_spend": {"key": "currentSpend", "type": "float"}, + "contact_emails": {"key": "contactEmails", "type": "[str]"}, + "contact_groups": {"key": "contactGroups", "type": "[str]"}, + "contact_roles": {"key": "contactRoles", "type": "[str]"}, + "overriding_alert": {"key": "overridingAlert", "type": "str"}, + "department_name": {"key": "departmentName", "type": "str"}, + "company_name": {"key": "companyName", "type": "str"}, + "enrollment_number": {"key": "enrollmentNumber", "type": "str"}, + "enrollment_start_date": {"key": "enrollmentStartDate", "type": "str"}, + "enrollment_end_date": {"key": "enrollmentEndDate", "type": "str"}, + "invoicing_threshold": {"key": "invoicingThreshold", "type": "float"}, } def __init__( self, *, - time_grain_type: Optional[Union[str, "AlertTimeGrainType"]] = None, + time_grain_type: Optional[Union[str, "_models.AlertTimeGrainType"]] = None, period_start_date: Optional[str] = None, triggered_by: Optional[str] = None, resource_group_filter: Optional[List[Any]] = None, resource_filter: Optional[List[Any]] = None, meter_filter: Optional[List[Any]] = None, - tag_filter: Optional[Any] = None, + tag_filter: Optional[JSON] = None, threshold: Optional[float] = None, - operator: Optional[Union[str, "AlertOperator"]] = None, + operator: Optional[Union[str, "_models.AlertOperator"]] = None, amount: Optional[float] = None, unit: Optional[str] = None, current_spend: Optional[float] = None, @@ -262,9 +334,63 @@ def __init__( contact_groups: Optional[List[str]] = None, contact_roles: Optional[List[str]] = None, overriding_alert: Optional[str] = None, + department_name: Optional[str] = None, + company_name: Optional[str] = None, + enrollment_number: Optional[str] = None, + enrollment_start_date: Optional[str] = None, + enrollment_end_date: Optional[str] = None, + invoicing_threshold: Optional[float] = None, **kwargs ): - super(AlertPropertiesDetails, self).__init__(**kwargs) + """ + :keyword time_grain_type: Type of timegrain cadence. Known values are: "None", "Monthly", + "Quarterly", "Annually", "BillingMonth", "BillingQuarter", and "BillingAnnual". + :paramtype time_grain_type: str or ~azure.mgmt.costmanagement.models.AlertTimeGrainType + :keyword period_start_date: datetime of periodStartDate. + :paramtype period_start_date: str + :keyword triggered_by: notificationId that triggered this alert. + :paramtype triggered_by: str + :keyword resource_group_filter: array of resourceGroups to filter by. + :paramtype resource_group_filter: list[any] + :keyword resource_filter: array of resources to filter by. + :paramtype resource_filter: list[any] + :keyword meter_filter: array of meters to filter by. + :paramtype meter_filter: list[any] + :keyword tag_filter: tags to filter by. + :paramtype tag_filter: JSON + :keyword threshold: notification threshold percentage as a decimal which activated this alert. + :paramtype threshold: float + :keyword operator: operator used to compare currentSpend with amount. Known values are: "None", + "EqualTo", "GreaterThan", "GreaterThanOrEqualTo", "LessThan", and "LessThanOrEqualTo". + :paramtype operator: str or ~azure.mgmt.costmanagement.models.AlertOperator + :keyword amount: budget threshold amount. + :paramtype amount: float + :keyword unit: unit of currency being used. + :paramtype unit: str + :keyword current_spend: current spend. + :paramtype current_spend: float + :keyword contact_emails: list of emails to contact. + :paramtype contact_emails: list[str] + :keyword contact_groups: list of action groups to broadcast to. + :paramtype contact_groups: list[str] + :keyword contact_roles: list of contact roles. + :paramtype contact_roles: list[str] + :keyword overriding_alert: overriding alert. + :paramtype overriding_alert: str + :keyword department_name: department name. + :paramtype department_name: str + :keyword company_name: company name. + :paramtype company_name: str + :keyword enrollment_number: enrollment number. + :paramtype enrollment_number: str + :keyword enrollment_start_date: datetime of enrollmentStartDate. + :paramtype enrollment_start_date: str + :keyword enrollment_end_date: datetime of enrollmentEndDate. + :paramtype enrollment_end_date: str + :keyword invoicing_threshold: invoicing threshold. + :paramtype invoicing_threshold: float + """ + super().__init__(**kwargs) self.time_grain_type = time_grain_type self.period_start_date = period_start_date self.triggered_by = triggered_by @@ -281,9 +407,15 @@ def __init__( self.contact_groups = contact_groups self.contact_roles = contact_roles self.overriding_alert = overriding_alert + self.department_name = department_name + self.company_name = company_name + self.enrollment_number = enrollment_number + self.enrollment_start_date = enrollment_start_date + self.enrollment_end_date = enrollment_end_date + self.invoicing_threshold = invoicing_threshold -class AlertsResult(msrest.serialization.Model): +class AlertsResult(_serialization.Model): """Result of alerts. Variables are only populated by the server, and will be ignored when sending a request. @@ -295,404 +427,2305 @@ class AlertsResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Alert]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Alert]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(AlertsResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class CacheItem(msrest.serialization.Model): - """CacheItem. +class AllSavingsBenefitDetails(_serialization.Model): + """Benefit recommendation details. - All required parameters must be populated in order to send to Azure. + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar overage_cost: The difference between total cost and benefit cost for the 'totalHours' in + the look-back period. + :vartype overage_cost: float + :ivar benefit_cost: The estimated cost with benefit for the 'totalHours' in the look-back + period. It's equal to (commitmentAmount * totalHours). + :vartype benefit_cost: float + :ivar total_cost: Total cost, which is sum of benefit cost and overage cost. + :vartype total_cost: float + :ivar savings_amount: The amount saved for the 'totalHours' in the look-back period, by + purchasing the recommended quantity of the benefit. + :vartype savings_amount: float + :ivar savings_percentage: The savings in percentage for the 'totalHours' in the look-back + period, by purchasing the recommended quantity of benefit. + :vartype savings_percentage: float + :ivar coverage_percentage: Estimated benefit coverage percentage for the 'totalHours' in the + look-back period, with this commitment. + :vartype coverage_percentage: float + :ivar commitment_amount: The commitment amount at the commitmentGranularity. + :vartype commitment_amount: float + :ivar average_utilization_percentage: Estimated average utilization percentage for the + 'totalHours' in the look-back period, with this commitment. + :vartype average_utilization_percentage: float + :ivar wastage_cost: Estimated unused portion of the 'benefitCost'. + :vartype wastage_cost: float + """ + + _validation = { + "overage_cost": {"readonly": True}, + "benefit_cost": {"readonly": True}, + "total_cost": {"readonly": True}, + "savings_amount": {"readonly": True}, + "savings_percentage": {"readonly": True}, + "coverage_percentage": {"readonly": True}, + "commitment_amount": {"readonly": True}, + "average_utilization_percentage": {"readonly": True}, + "wastage_cost": {"readonly": True}, + } + + _attribute_map = { + "overage_cost": {"key": "overageCost", "type": "float"}, + "benefit_cost": {"key": "benefitCost", "type": "float"}, + "total_cost": {"key": "totalCost", "type": "float"}, + "savings_amount": {"key": "savingsAmount", "type": "float"}, + "savings_percentage": {"key": "savingsPercentage", "type": "float"}, + "coverage_percentage": {"key": "coveragePercentage", "type": "float"}, + "commitment_amount": {"key": "commitmentAmount", "type": "float"}, + "average_utilization_percentage": {"key": "averageUtilizationPercentage", "type": "float"}, + "wastage_cost": {"key": "wastageCost", "type": "float"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.overage_cost = None + self.benefit_cost = None + self.total_cost = None + self.savings_amount = None + self.savings_percentage = None + self.coverage_percentage = None + self.commitment_amount = None + self.average_utilization_percentage = None + self.wastage_cost = None + + +class AllSavingsList(_serialization.Model): + """The list of all benefit recommendations with the recommendation details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of benefit recommendations with the recommendation details.. + :vartype value: list[~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails] + :ivar next_link: The link (URL) to the next page of results. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[AllSavingsBenefitDetails]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + + +class BenefitResource(Resource): + """The benefit resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Reservation or SavingsPlan. Known values are: "IncludedQuantity", "Reservation", + and "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + } + + def __init__(self, *, kind: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword kind: Reservation or SavingsPlan. Known values are: "IncludedQuantity", "Reservation", + and "SavingsPlan". + :paramtype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(**kwargs) + self.kind = kind - :param id: Required. Resource ID used by Resource Manager to uniquely identify the scope. - :type id: str - :param name: Required. Display name for the scope. - :type name: str - :param channel: Required. Indicates the account type. Allowed values include: EA, PAYG, Modern, - Internal, Unknown. - :type channel: str - :param subchannel: Required. Indicates the type of modern account. Allowed values include: - Individual, Enterprise, Partner, Indirect, NotApplicable. - :type subchannel: str - :param parent: Resource ID of the parent scope. For instance, subscription's resource ID for a - resource group or a management group resource ID for a subscription. - :type parent: str - :param status: Indicates the status of the scope. Status only applies to subscriptions and - billing accounts. - :type status: str + +class BenefitRecommendationModel(BenefitResource): + """benefit plan recommendation details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Reservation or SavingsPlan. Known values are: "IncludedQuantity", "Reservation", + and "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar properties: The properties of the benefit recommendations. + :vartype properties: ~azure.mgmt.costmanagement.models.BenefitRecommendationProperties """ _validation = { - 'id': {'required': True}, - 'name': {'required': True}, - 'channel': {'required': True}, - 'subchannel': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'channel': {'key': 'channel', 'type': 'str'}, - 'subchannel': {'key': 'subchannel', 'type': 'str'}, - 'parent': {'key': 'parent', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "properties": {"key": "properties", "type": "BenefitRecommendationProperties"}, } def __init__( self, *, - id: str, - name: str, - channel: str, - subchannel: str, - parent: Optional[str] = None, - status: Optional[str] = None, + kind: Optional[Union[str, "_models.BenefitKind"]] = None, + properties: Optional["_models.BenefitRecommendationProperties"] = None, **kwargs ): - super(CacheItem, self).__init__(**kwargs) - self.id = id - self.name = name - self.channel = channel - self.subchannel = subchannel - self.parent = parent - self.status = status + """ + :keyword kind: Reservation or SavingsPlan. Known values are: "IncludedQuantity", "Reservation", + and "SavingsPlan". + :paramtype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + :keyword properties: The properties of the benefit recommendations. + :paramtype properties: ~azure.mgmt.costmanagement.models.BenefitRecommendationProperties + """ + super().__init__(kind=kind, **kwargs) + self.properties = properties -class CommonExportProperties(msrest.serialization.Model): - """The common properties of the export. +class BenefitRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The properties of the benefit recommendations. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + SharedScopeBenefitRecommendationProperties, SingleScopeBenefitRecommendationProperties + + Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendations. + :vartype first_consumption_date: ~datetime.datetime + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendations. + :vartype last_consumption_date: ~datetime.datetime + :ivar look_back_period: The number of days of usage evaluated for computing the + recommendations. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :vartype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :ivar total_hours: The total hours for which the cost is covered. Its equal to number of + records in a property 'properties/usage/charges'. + :vartype total_hours: int + :ivar usage: On-demand charges between firstConsumptionDate and lastConsumptionDate that were + used for computing benefit recommendations. + :vartype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :ivar arm_sku_name: ARM SKU name. 'Compute_Savings_Plan' for SavingsPlan. + :vartype arm_sku_name: str + :ivar term: Term period of the benefit. For example, P1Y or P3Y. Known values are: "P1Y" and + "P3Y". + :vartype term: str or ~azure.mgmt.costmanagement.models.Term + :ivar commitment_granularity: Grain of the proposed commitment amount. Supported values: + 'Hourly'. Known values are: "Hourly", "Daily", and "Monthly". + :vartype commitment_granularity: str or ~azure.mgmt.costmanagement.models.Grain + :ivar currency_code: An ISO 4217 currency code identifier for the costs and savings amounts. + :vartype currency_code: str + :ivar cost_without_benefit: The current cost without benefit, corresponds to 'totalHours' in + the look-back period. + :vartype cost_without_benefit: float + :ivar recommendation_details: The details of the proposed recommendation. + :vartype recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails + :ivar all_recommendation_details: The list of all benefit recommendations with the + recommendation details. + :vartype all_recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsList + :ivar scope: Benefit scope. For example, Single or Shared. Required. Known values are: "Single" + and "Shared". + :vartype scope: str or ~azure.mgmt.costmanagement.models.Scope """ _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, + "first_consumption_date": {"readonly": True}, + "last_consumption_date": {"readonly": True}, + "total_hours": {"readonly": True}, + "arm_sku_name": {"readonly": True}, + "currency_code": {"readonly": True}, + "cost_without_benefit": {"readonly": True}, + "all_recommendation_details": {"readonly": True}, + "scope": {"required": True}, } _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, + "first_consumption_date": {"key": "firstConsumptionDate", "type": "iso-8601"}, + "last_consumption_date": {"key": "lastConsumptionDate", "type": "iso-8601"}, + "look_back_period": {"key": "lookBackPeriod", "type": "str"}, + "total_hours": {"key": "totalHours", "type": "int"}, + "usage": {"key": "usage", "type": "RecommendationUsageDetails"}, + "arm_sku_name": {"key": "armSkuName", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "commitment_granularity": {"key": "commitmentGranularity", "type": "str"}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "cost_without_benefit": {"key": "costWithoutBenefit", "type": "float"}, + "recommendation_details": {"key": "recommendationDetails", "type": "AllSavingsBenefitDetails"}, + "all_recommendation_details": {"key": "allRecommendationDetails", "type": "AllSavingsList"}, + "scope": {"key": "scope", "type": "str"}, + } + + _subtype_map = { + "scope": { + "Shared": "SharedScopeBenefitRecommendationProperties", + "Single": "SingleScopeBenefitRecommendationProperties", + } } def __init__( self, *, - delivery_info: "ExportDeliveryInfo", - definition: "ExportDefinition", - format: Optional[Union[str, "FormatType"]] = None, + look_back_period: Optional[Union[str, "_models.LookBackPeriod"]] = None, + usage: Optional["_models.RecommendationUsageDetails"] = None, + term: Optional[Union[str, "_models.Term"]] = None, + commitment_granularity: Optional[Union[str, "_models.Grain"]] = None, + recommendation_details: Optional["_models.AllSavingsBenefitDetails"] = None, **kwargs ): - super(CommonExportProperties, self).__init__(**kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition + """ + :keyword look_back_period: The number of days of usage evaluated for computing the + recommendations. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :paramtype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :keyword usage: On-demand charges between firstConsumptionDate and lastConsumptionDate that + were used for computing benefit recommendations. + :paramtype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :keyword term: Term period of the benefit. For example, P1Y or P3Y. Known values are: "P1Y" and + "P3Y". + :paramtype term: str or ~azure.mgmt.costmanagement.models.Term + :keyword commitment_granularity: Grain of the proposed commitment amount. Supported values: + 'Hourly'. Known values are: "Hourly", "Daily", and "Monthly". + :paramtype commitment_granularity: str or ~azure.mgmt.costmanagement.models.Grain + :keyword recommendation_details: The details of the proposed recommendation. + :paramtype recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails + """ + super().__init__(**kwargs) + self.first_consumption_date = None + self.last_consumption_date = None + self.look_back_period = look_back_period + self.total_hours = None + self.usage = usage + self.arm_sku_name = None + self.term = term + self.commitment_granularity = commitment_granularity + self.currency_code = None + self.cost_without_benefit = None + self.recommendation_details = recommendation_details + self.all_recommendation_details = None + self.scope = None # type: Optional[str] + + +class BenefitRecommendationsListResult(_serialization.Model): + """Result of listing benefit recommendations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of benefit recommendations. + :vartype value: list[~azure.mgmt.costmanagement.models.BenefitRecommendationModel] + :ivar next_link: The link (URL) to the next page of results. + :vartype next_link: str + """ + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[BenefitRecommendationModel]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None -class Dimension(Resource): - """Dimension. + +class BenefitUtilizationSummariesListResult(_serialization.Model): + """List of benefit utilization summaries. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Resource Id. + :ivar value: The list of benefit utilization summaries. + :vartype value: list[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :ivar next_link: The link (URL) to the next page of results. + :vartype next_link: str + """ + + _validation = { + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[BenefitUtilizationSummary]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class BenefitUtilizationSummary(Resource): + """Benefit utilization summary resource. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + IncludedQuantityUtilizationSummary, SavingsPlanUtilizationSummary + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: Resource name. + :ivar name: The name of the resource. :vartype name: str - :ivar type: Resource type. + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :ivar description: Dimension description. - :vartype description: str - :ivar filter_enabled: Filter enabled. - :vartype filter_enabled: bool - :ivar grouping_enabled: Grouping enabled. - :vartype grouping_enabled: bool - :param data: - :type data: list[str] - :ivar total: Total number of data for the dimension. - :vartype total: int - :ivar category: Dimension category. - :vartype category: str - :ivar usage_start: Usage start. - :vartype usage_start: ~datetime.datetime - :ivar usage_end: Usage end. - :vartype usage_end: ~datetime.datetime - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str + :ivar kind: Supported values: 'SavingsPlan'. Required. Known values are: "IncludedQuantity", + "Reservation", and "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'description': {'readonly': True}, - 'filter_enabled': {'readonly': True}, - 'grouping_enabled': {'readonly': True}, - 'total': {'readonly': True}, - 'category': {'readonly': True}, - 'usage_start': {'readonly': True}, - 'usage_end': {'readonly': True}, - 'next_link': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'filter_enabled': {'key': 'properties.filterEnabled', 'type': 'bool'}, - 'grouping_enabled': {'key': 'properties.groupingEnabled', 'type': 'bool'}, - 'data': {'key': 'properties.data', 'type': '[str]'}, - 'total': {'key': 'properties.total', 'type': 'int'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'usage_start': {'key': 'properties.usageStart', 'type': 'iso-8601'}, - 'usage_end': {'key': 'properties.usageEnd', 'type': 'iso-8601'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, } - def __init__( - self, - *, - data: Optional[List[str]] = None, - **kwargs - ): - super(Dimension, self).__init__(**kwargs) - self.description = None - self.filter_enabled = None - self.grouping_enabled = None - self.data = data - self.total = None - self.category = None - self.usage_start = None - self.usage_end = None - self.next_link = None + _subtype_map = { + "kind": { + "IncludedQuantity": "IncludedQuantityUtilizationSummary", + "SavingsPlan": "SavingsPlanUtilizationSummary", + } + } + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind = None # type: Optional[str] -class DimensionsListResult(msrest.serialization.Model): - """Result of listing dimensions. It contains a list of available dimensions. + +class BenefitUtilizationSummaryProperties(_serialization.Model): + """The properties of a benefit utilization summary. Variables are only populated by the server, and will be ignored when sending a request. - :ivar value: The list of dimensions. - :vartype value: list[~azure.mgmt.costmanagement.models.Dimension] + :ivar arm_sku_name: ARM SKU name. For example, 'Compute_Savings_Plan' for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of the benefit. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :vartype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar usage_date: Date corresponding to the utilization summary record. If the grain of data is + monthly, value for this field will be first day of the month. + :vartype usage_date: ~datetime.datetime """ _validation = { - 'value': {'readonly': True}, + "arm_sku_name": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_order_id": {"readonly": True}, + "usage_date": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Dimension]'}, + "arm_sku_name": {"key": "armSkuName", "type": "str"}, + "benefit_id": {"key": "benefitId", "type": "str"}, + "benefit_order_id": {"key": "benefitOrderId", "type": "str"}, + "benefit_type": {"key": "benefitType", "type": "str"}, + "usage_date": {"key": "usageDate", "type": "iso-8601"}, } - def __init__( - self, - **kwargs - ): - super(DimensionsListResult, self).__init__(**kwargs) - self.value = None + def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :paramtype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(**kwargs) + self.arm_sku_name = None + self.benefit_id = None + self.benefit_order_id = None + self.benefit_type = benefit_type + self.usage_date = None + + +class BlobInfo(_serialization.Model): + """The blob information generated by this operation. + + :ivar blob_link: Link to the blob to download file. + :vartype blob_link: str + :ivar byte_count: Bytes in the blob. + :vartype byte_count: int + """ + _attribute_map = { + "blob_link": {"key": "blobLink", "type": "str"}, + "byte_count": {"key": "byteCount", "type": "int"}, + } -class DismissAlertPayload(msrest.serialization.Model): - """The request payload to update an alert. + def __init__(self, *, blob_link: Optional[str] = None, byte_count: Optional[int] = None, **kwargs): + """ + :keyword blob_link: Link to the blob to download file. + :paramtype blob_link: str + :keyword byte_count: Bytes in the blob. + :paramtype byte_count: int + """ + super().__init__(**kwargs) + self.blob_link = blob_link + self.byte_count = byte_count + + +class CheckNameAvailabilityRequest(_serialization.Model): + """The check availability request body. + + :ivar name: The name of the resource for which availability needs to be checked. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword name: The name of the resource for which availability needs to be checked. + :paramtype name: str + :keyword type: The resource type. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type - :param definition: defines the type of alert. - :type definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition - :param description: Alert description. - :type description: str - :param source: Source of alert. Possible values include: "Preset", "User". - :type source: str or ~azure.mgmt.costmanagement.models.AlertSource - :param details: Alert details. - :type details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails - :param cost_entity_id: related budget. - :type cost_entity_id: str - :param status: alert status. Possible values include: "None", "Active", "Overridden", - "Resolved", "Dismissed". - :type status: str or ~azure.mgmt.costmanagement.models.AlertStatus - :param creation_time: dateTime in which alert was created. - :type creation_time: str - :param close_time: dateTime in which alert was closed. - :type close_time: str - :param modification_time: dateTime in which alert was last modified. - :type modification_time: str - :param status_modification_user_name: - :type status_modification_user_name: str - :param status_modification_time: dateTime in which the alert status was last modified. - :type status_modification_time: str - """ - - _attribute_map = { - 'definition': {'key': 'properties.definition', 'type': 'AlertPropertiesDefinition'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': 'AlertPropertiesDetails'}, - 'cost_entity_id': {'key': 'properties.costEntityId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'str'}, - 'close_time': {'key': 'properties.closeTime', 'type': 'str'}, - 'modification_time': {'key': 'properties.modificationTime', 'type': 'str'}, - 'status_modification_user_name': {'key': 'properties.statusModificationUserName', 'type': 'str'}, - 'status_modification_time': {'key': 'properties.statusModificationTime', 'type': 'str'}, + +class CheckNameAvailabilityResponse(_serialization.Model): + """The check availability result. + + :ivar name_available: Indicates if the resource name is available. + :vartype name_available: bool + :ivar reason: The reason why the given name is not available. Known values are: "Invalid" and + "AlreadyExists". + :vartype reason: str or ~azure.mgmt.costmanagement.models.CheckNameAvailabilityReason + :ivar message: Detailed reason why the given name is available. + :vartype message: str + """ + + _attribute_map = { + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( self, *, - definition: Optional["AlertPropertiesDefinition"] = None, - description: Optional[str] = None, - source: Optional[Union[str, "AlertSource"]] = None, - details: Optional["AlertPropertiesDetails"] = None, - cost_entity_id: Optional[str] = None, - status: Optional[Union[str, "AlertStatus"]] = None, - creation_time: Optional[str] = None, - close_time: Optional[str] = None, - modification_time: Optional[str] = None, - status_modification_user_name: Optional[str] = None, - status_modification_time: Optional[str] = None, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, + message: Optional[str] = None, **kwargs ): - super(DismissAlertPayload, self).__init__(**kwargs) - self.definition = definition - self.description = description - self.source = source - self.details = details - self.cost_entity_id = cost_entity_id - self.status = status - self.creation_time = creation_time - self.close_time = close_time - self.modification_time = modification_time - self.status_modification_user_name = status_modification_user_name - self.status_modification_time = status_modification_time - - -class ErrorDetails(msrest.serialization.Model): - """The details of the error. + """ + :keyword name_available: Indicates if the resource name is available. + :paramtype name_available: bool + :keyword reason: The reason why the given name is not available. Known values are: "Invalid" + and "AlreadyExists". + :paramtype reason: str or ~azure.mgmt.costmanagement.models.CheckNameAvailabilityReason + :keyword message: Detailed reason why the given name is available. + :paramtype message: str + """ + super().__init__(**kwargs) + self.name_available = name_available + self.reason = reason + self.message = message + + +class CommonExportProperties(_serialization.Model): + """The common properties of the export. Variables are only populated by the server, and will be ignored when sending a request. - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str + All required parameters must be populated in order to send to Azure. + + :ivar format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. Required. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. Required. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent run history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + Microsoft Customer Agreement commerce scopes. + :vartype partition_data: bool + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next run time. + :vartype next_run_time_estimate: ~datetime.datetime """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, + "delivery_info": {"required": True}, + "definition": {"required": True}, + "next_run_time_estimate": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "format": {"key": "format", "type": "str"}, + "delivery_info": {"key": "deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "definition", "type": "ExportDefinition"}, + "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "partitionData", "type": "bool"}, + "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, } def __init__( self, + *, + delivery_info: "_models.ExportDeliveryInfo", + definition: "_models.ExportDefinition", + format: Optional[Union[str, "_models.FormatType"]] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, **kwargs ): - super(ErrorDetails, self).__init__(**kwargs) - self.code = None - self.message = None + """ + :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. Required. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. Required. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent run history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for Microsoft Customer Agreement commerce scopes. + :paramtype partition_data: bool + """ + super().__init__(**kwargs) + self.format = format + self.delivery_info = delivery_info + self.definition = definition + self.run_history = run_history + self.partition_data = partition_data + self.next_run_time_estimate = None -class ErrorResponse(msrest.serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. +class CostDetailsOperationResults(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The result of the long running operation for cost details Api. + + :ivar id: The id of the long running operation. + :vartype id: str + :ivar name: The name of the long running operation. + :vartype name: str + :ivar type: The type of the long running operation. + :vartype type: str + :ivar status: The status of the cost details operation. Known values are: "Completed", + "NoDataFound", and "Failed". + :vartype status: str or ~azure.mgmt.costmanagement.models.CostDetailsStatusType + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :ivar manifest_version: The Manifest version. + :vartype manifest_version: str + :ivar data_format: The data format of the report. "Csv" + :vartype data_format: str or ~azure.mgmt.costmanagement.models.CostDetailsDataFormat + :ivar byte_count: The total number of bytes in all blobs. + :vartype byte_count: int + :ivar blob_count: The total number of blobs. + :vartype blob_count: int + :ivar compress_data: Is the data in compressed format. + :vartype compress_data: bool + :ivar blobs: List of blob information generated by this operation. + :vartype blobs: list[~azure.mgmt.costmanagement.models.BlobInfo] + :ivar request_scope: The request scope of the request. + :vartype request_scope: str + :ivar request_body: The request payload body provided in Cost Details call. + :vartype request_body: + ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "valid_till": {"key": "validTill", "type": "iso-8601"}, + "error": {"key": "error", "type": "ErrorDetails"}, + "manifest_version": {"key": "manifest.manifestVersion", "type": "str"}, + "data_format": {"key": "manifest.dataFormat", "type": "str"}, + "byte_count": {"key": "manifest.byteCount", "type": "int"}, + "blob_count": {"key": "manifest.blobCount", "type": "int"}, + "compress_data": {"key": "manifest.compressData", "type": "bool"}, + "blobs": {"key": "manifest.blobs", "type": "[BlobInfo]"}, + "request_scope": {"key": "manifest.requestContext.requestScope", "type": "str"}, + "request_body": { + "key": "manifest.requestContext.requestBody", + "type": "GenerateCostDetailsReportRequestDefinition", + }, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + type: Optional[str] = None, + status: Optional[Union[str, "_models.CostDetailsStatusType"]] = None, + valid_till: Optional[datetime.datetime] = None, + error: Optional["_models.ErrorDetails"] = None, + manifest_version: Optional[str] = None, + data_format: Optional[Union[str, "_models.CostDetailsDataFormat"]] = None, + byte_count: Optional[int] = None, + blob_count: Optional[int] = None, + compress_data: Optional[bool] = None, + blobs: Optional[List["_models.BlobInfo"]] = None, + request_scope: Optional[str] = None, + request_body: Optional["_models.GenerateCostDetailsReportRequestDefinition"] = None, + **kwargs + ): + """ + :keyword id: The id of the long running operation. + :paramtype id: str + :keyword name: The name of the long running operation. + :paramtype name: str + :keyword type: The type of the long running operation. + :paramtype type: str + :keyword status: The status of the cost details operation. Known values are: "Completed", + "NoDataFound", and "Failed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.CostDetailsStatusType + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :keyword manifest_version: The Manifest version. + :paramtype manifest_version: str + :keyword data_format: The data format of the report. "Csv" + :paramtype data_format: str or ~azure.mgmt.costmanagement.models.CostDetailsDataFormat + :keyword byte_count: The total number of bytes in all blobs. + :paramtype byte_count: int + :keyword blob_count: The total number of blobs. + :paramtype blob_count: int + :keyword compress_data: Is the data in compressed format. + :paramtype compress_data: bool + :keyword blobs: List of blob information generated by this operation. + :paramtype blobs: list[~azure.mgmt.costmanagement.models.BlobInfo] + :keyword request_scope: The request scope of the request. + :paramtype request_scope: str + :keyword request_body: The request payload body provided in Cost Details call. + :paramtype request_body: + ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + """ + super().__init__(**kwargs) + self.id = id + self.name = name + self.type = type + self.status = status + self.valid_till = valid_till + self.error = error + self.manifest_version = manifest_version + self.data_format = data_format + self.byte_count = byte_count + self.blob_count = blob_count + self.compress_data = compress_data + self.blobs = blobs + self.request_scope = request_scope + self.request_body = request_body + + +class CostDetailsTimePeriod(_serialization.Model): + """The start and end date for pulling data for the cost detailed report. API only allows data to be pulled for 1 month or less and no older than 13 months. + + All required parameters must be populated in order to send to Azure. + + :ivar start: The start date to pull data from. example format 2020-03-15. Required. + :vartype start: str + :ivar end: The end date to pull data to. example format 2020-03-15. Required. + :vartype end: str + """ + + _validation = { + "start": {"required": True}, + "end": {"required": True}, + } + + _attribute_map = { + "start": {"key": "start", "type": "str"}, + "end": {"key": "end", "type": "str"}, + } + + def __init__(self, *, start: str, end: str, **kwargs): + """ + :keyword start: The start date to pull data from. example format 2020-03-15. Required. + :paramtype start: str + :keyword end: The end date to pull data to. example format 2020-03-15. Required. + :paramtype end: str + """ + super().__init__(**kwargs) + self.start = start + self.end = end + + +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.costmanagement.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.costmanagement.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.costmanagement.models.ActionType + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.costmanagement.models.OperationDisplay + """ + super().__init__(**kwargs) + self.name = None + self.is_data_action = None + self.display = display + self.origin = None + self.action_type = None + + +class CostManagementOperation(Operation): + """A Cost management REST API operation. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar name: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + :vartype name: str + :ivar is_data_action: Whether the operation applies to data-plane. This is "true" for + data-plane operations and "false" for ARM/control-plane operations. + :vartype is_data_action: bool + :ivar display: Localized display information for this particular operation. + :vartype display: ~azure.mgmt.costmanagement.models.OperationDisplay + :ivar origin: The intended executor of the operation; as in Resource Based Access Control + (RBAC) and audit logs UX. Default value is "user,system". Known values are: "user", "system", + and "user,system". + :vartype origin: str or ~azure.mgmt.costmanagement.models.Origin + :ivar action_type: Enum. Indicates the action type. "Internal" refers to actions that are for + internal only APIs. "Internal" + :vartype action_type: str or ~azure.mgmt.costmanagement.models.ActionType + :ivar id: Operation id: {provider}/{resource}/{operation}. + :vartype id: str + """ + + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + "id": {"readonly": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "action_type": {"key": "actionType", "type": "str"}, + "id": {"key": "id", "type": "str"}, + } + + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): + """ + :keyword display: Localized display information for this particular operation. + :paramtype display: ~azure.mgmt.costmanagement.models.OperationDisplay + """ + super().__init__(display=display, **kwargs) + self.id = None + + +class CostManagementResource(_serialization.Model): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Location of the resource. + :vartype location: str + :ivar sku: SKU of the resource. + :vartype sku: str + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = None + self.sku = None + self.e_tag = None + self.tags = None + + +class Dimension(CostManagementResource): # pylint: disable=too-many-instance-attributes + """List of Dimension. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar location: Location of the resource. + :vartype location: str + :ivar sku: SKU of the resource. + :vartype sku: str + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar description: Dimension description. + :vartype description: str + :ivar filter_enabled: Filter enabled. + :vartype filter_enabled: bool + :ivar grouping_enabled: Grouping enabled. + :vartype grouping_enabled: bool + :ivar data: Dimension data. + :vartype data: list[str] + :ivar total: Total number of data for the dimension. + :vartype total: int + :ivar category: Dimension category. + :vartype category: str + :ivar usage_start: Usage start. + :vartype usage_start: ~datetime.datetime + :ivar usage_end: Usage end. + :vartype usage_end: ~datetime.datetime + :ivar next_link: The link (url) to the next page of results. + :vartype next_link: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, + "description": {"readonly": True}, + "filter_enabled": {"readonly": True}, + "grouping_enabled": {"readonly": True}, + "total": {"readonly": True}, + "category": {"readonly": True}, + "usage_start": {"readonly": True}, + "usage_end": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "description": {"key": "properties.description", "type": "str"}, + "filter_enabled": {"key": "properties.filterEnabled", "type": "bool"}, + "grouping_enabled": {"key": "properties.groupingEnabled", "type": "bool"}, + "data": {"key": "properties.data", "type": "[str]"}, + "total": {"key": "properties.total", "type": "int"}, + "category": {"key": "properties.category", "type": "str"}, + "usage_start": {"key": "properties.usageStart", "type": "iso-8601"}, + "usage_end": {"key": "properties.usageEnd", "type": "iso-8601"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + } + + def __init__(self, *, data: Optional[List[str]] = None, **kwargs): + """ + :keyword data: Dimension data. + :paramtype data: list[str] + """ + super().__init__(**kwargs) + self.description = None + self.filter_enabled = None + self.grouping_enabled = None + self.data = data + self.total = None + self.category = None + self.usage_start = None + self.usage_end = None + self.next_link = None + + +class DimensionsListResult(_serialization.Model): + """Result of listing dimensions. It contains a list of available dimensions. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of dimensions. + :vartype value: list[~azure.mgmt.costmanagement.models.Dimension] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Dimension]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + + +class DismissAlertPayload(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The request payload to update an alert. + + :ivar definition: defines the type of alert. + :vartype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :ivar description: Alert description. + :vartype description: str + :ivar source: Source of alert. Known values are: "Preset" and "User". + :vartype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :ivar details: Alert details. + :vartype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :ivar cost_entity_id: related budget. + :vartype cost_entity_id: str + :ivar status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", and + "Dismissed". + :vartype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :ivar creation_time: dateTime in which alert was created. + :vartype creation_time: str + :ivar close_time: dateTime in which alert was closed. + :vartype close_time: str + :ivar modification_time: dateTime in which alert was last modified. + :vartype modification_time: str + :ivar status_modification_user_name: User who last modified the alert. + :vartype status_modification_user_name: str + :ivar status_modification_time: dateTime in which the alert status was last modified. + :vartype status_modification_time: str + """ + + _attribute_map = { + "definition": {"key": "properties.definition", "type": "AlertPropertiesDefinition"}, + "description": {"key": "properties.description", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, + "details": {"key": "properties.details", "type": "AlertPropertiesDetails"}, + "cost_entity_id": {"key": "properties.costEntityId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "creation_time": {"key": "properties.creationTime", "type": "str"}, + "close_time": {"key": "properties.closeTime", "type": "str"}, + "modification_time": {"key": "properties.modificationTime", "type": "str"}, + "status_modification_user_name": {"key": "properties.statusModificationUserName", "type": "str"}, + "status_modification_time": {"key": "properties.statusModificationTime", "type": "str"}, + } + + def __init__( + self, + *, + definition: Optional["_models.AlertPropertiesDefinition"] = None, + description: Optional[str] = None, + source: Optional[Union[str, "_models.AlertSource"]] = None, + details: Optional["_models.AlertPropertiesDetails"] = None, + cost_entity_id: Optional[str] = None, + status: Optional[Union[str, "_models.AlertStatus"]] = None, + creation_time: Optional[str] = None, + close_time: Optional[str] = None, + modification_time: Optional[str] = None, + status_modification_user_name: Optional[str] = None, + status_modification_time: Optional[str] = None, + **kwargs + ): + """ + :keyword definition: defines the type of alert. + :paramtype definition: ~azure.mgmt.costmanagement.models.AlertPropertiesDefinition + :keyword description: Alert description. + :paramtype description: str + :keyword source: Source of alert. Known values are: "Preset" and "User". + :paramtype source: str or ~azure.mgmt.costmanagement.models.AlertSource + :keyword details: Alert details. + :paramtype details: ~azure.mgmt.costmanagement.models.AlertPropertiesDetails + :keyword cost_entity_id: related budget. + :paramtype cost_entity_id: str + :keyword status: alert status. Known values are: "None", "Active", "Overridden", "Resolved", + and "Dismissed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.AlertStatus + :keyword creation_time: dateTime in which alert was created. + :paramtype creation_time: str + :keyword close_time: dateTime in which alert was closed. + :paramtype close_time: str + :keyword modification_time: dateTime in which alert was last modified. + :paramtype modification_time: str + :keyword status_modification_user_name: User who last modified the alert. + :paramtype status_modification_user_name: str + :keyword status_modification_time: dateTime in which the alert status was last modified. + :paramtype status_modification_time: str + """ + super().__init__(**kwargs) + self.definition = definition + self.description = description + self.source = source + self.details = details + self.cost_entity_id = cost_entity_id + self.status = status + self.creation_time = creation_time + self.close_time = close_time + self.modification_time = modification_time + self.status_modification_user_name = status_modification_user_name + self.status_modification_time = status_modification_time + + +class DownloadURL(_serialization.Model): + """The URL to download the generated report. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar expiry_time: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype expiry_time: ~datetime.datetime + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime + :ivar download_url: The URL to download the generated report. + :vartype download_url: str + """ + + _validation = { + "expiry_time": {"readonly": True}, + } + + _attribute_map = { + "expiry_time": {"key": "expiryTime", "type": "iso-8601"}, + "valid_till": {"key": "validTill", "type": "iso-8601"}, + "download_url": {"key": "downloadUrl", "type": "str"}, + } + + def __init__(self, *, valid_till: Optional[datetime.datetime] = None, download_url: Optional[str] = None, **kwargs): + """ + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + :keyword download_url: The URL to download the generated report. + :paramtype download_url: str + """ + super().__init__(**kwargs) + self.expiry_time = None + self.valid_till = valid_till + self.download_url = download_url + + +class ErrorDetails(_serialization.Model): + """The details of the error. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: Error code. + :vartype code: str + :ivar message: Error message indicating why the operation failed. + :vartype message: str + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + + +class ErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. + + Some Error responses: + + + * + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. + + * + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetails"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(**kwargs) + self.error = error + + +class Export(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes + """An export resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str + :ivar format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent run history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + Microsoft Customer Agreement commerce scopes. + :vartype partition_data: bool + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next run time. + :vartype next_run_time_estimate: ~datetime.datetime + :ivar schedule: Has schedule information for the export. + :vartype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "next_run_time_estimate": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "format": {"key": "properties.format", "type": "str"}, + "delivery_info": {"key": "properties.deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "properties.definition", "type": "ExportDefinition"}, + "run_history": {"key": "properties.runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "properties.partitionData", "type": "bool"}, + "next_run_time_estimate": {"key": "properties.nextRunTimeEstimate", "type": "iso-8601"}, + "schedule": {"key": "properties.schedule", "type": "ExportSchedule"}, + } + + def __init__( + self, + *, + e_tag: Optional[str] = None, + format: Optional[Union[str, "_models.FormatType"]] = None, + delivery_info: Optional["_models.ExportDeliveryInfo"] = None, + definition: Optional["_models.ExportDefinition"] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, + schedule: Optional["_models.ExportSchedule"] = None, + **kwargs + ): + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent run history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for Microsoft Customer Agreement commerce scopes. + :paramtype partition_data: bool + :keyword schedule: Has schedule information for the export. + :paramtype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + """ + super().__init__(e_tag=e_tag, **kwargs) + self.format = format + self.delivery_info = delivery_info + self.definition = definition + self.run_history = run_history + self.partition_data = partition_data + self.next_run_time_estimate = None + self.schedule = schedule + + +class ExportDataset(_serialization.Model): + """The definition for data in the export. + + :ivar granularity: The granularity of rows in the export. Currently only 'Daily' is supported. + "Daily" + :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :ivar configuration: The export dataset configuration. + :vartype configuration: ~azure.mgmt.costmanagement.models.ExportDatasetConfiguration + """ + + _attribute_map = { + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "ExportDatasetConfiguration"}, + } + + def __init__( + self, + *, + granularity: Optional[Union[str, "_models.GranularityType"]] = None, + configuration: Optional["_models.ExportDatasetConfiguration"] = None, + **kwargs + ): + """ + :keyword granularity: The granularity of rows in the export. Currently only 'Daily' is + supported. "Daily" + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :keyword configuration: The export dataset configuration. + :paramtype configuration: ~azure.mgmt.costmanagement.models.ExportDatasetConfiguration + """ + super().__init__(**kwargs) + self.granularity = granularity + self.configuration = configuration + + +class ExportDatasetConfiguration(_serialization.Model): + """The export dataset configuration. Allows columns to be selected for the export. If not provided then the export will include all available columns. + + :ivar columns: Array of column names to be included in the export. If not provided then the + export will include all available columns. The available columns can vary by customer channel + (see examples). + :vartype columns: list[str] + """ + + _attribute_map = { + "columns": {"key": "columns", "type": "[str]"}, + } + + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the export. If not provided then the + export will include all available columns. The available columns can vary by customer channel + (see examples). + :paramtype columns: list[str] + """ + super().__init__(**kwargs) + self.columns = columns + + +class ExportDefinition(_serialization.Model): + """The definition of an export. + + All required parameters must be populated in order to send to Azure. + + :ivar type: The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is + applicable to exports that do not yet provide data for charges or amortization for service + reservations. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". + :vartype type: str or ~azure.mgmt.costmanagement.models.ExportType + :ivar timeframe: The time frame for pulling data for the export. If custom, then a specific + time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :ivar time_period: Has time period for pulling data for the export. + :vartype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod + :ivar data_set: The definition for data in the export. + :vartype data_set: ~azure.mgmt.costmanagement.models.ExportDataset + """ + + _validation = { + "type": {"required": True}, + "timeframe": {"required": True}, + } + + _attribute_map = { + "type": {"key": "type", "type": "str"}, + "timeframe": {"key": "timeframe", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "ExportTimePeriod"}, + "data_set": {"key": "dataSet", "type": "ExportDataset"}, + } + + def __init__( + self, + *, + type: Union[str, "_models.ExportType"], + timeframe: Union[str, "_models.TimeframeType"], + time_period: Optional["_models.ExportTimePeriod"] = None, + data_set: Optional["_models.ExportDataset"] = None, + **kwargs + ): + """ + :keyword type: The type of the export. Note that 'Usage' is equivalent to 'ActualCost' and is + applicable to exports that do not yet provide data for charges or amortization for service + reservations. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ExportType + :keyword timeframe: The time frame for pulling data for the export. If custom, then a specific + time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :keyword time_period: Has time period for pulling data for the export. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ExportTimePeriod + :keyword data_set: The definition for data in the export. + :paramtype data_set: ~azure.mgmt.costmanagement.models.ExportDataset + """ + super().__init__(**kwargs) + self.type = type + self.timeframe = timeframe + self.time_period = time_period + self.data_set = data_set + + +class ExportDeliveryDestination(_serialization.Model): + """This represents the blob storage account location where exports of costs will be delivered. There are two ways to configure the destination. The approach recommended for most customers is to specify the resourceId of the storage account. This requires a one-time registration of the account's subscription with the Microsoft.CostManagementExports resource provider in order to give Cost Management services access to the storage. When creating an export in the Azure portal this registration is performed automatically but API users may need to register the subscription explicitly (for more information see https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services ). Another way to configure the destination is available ONLY to Partners with a Microsoft Partner Agreement plan who are global admins of their billing account. These Partners, instead of specifying the resourceId of a storage account, can specify the storage account name along with a SAS token for the account. This allows exports of costs to a storage account in any tenant. The SAS token should be created for the blob service with Service/Container/Object resource types and with Read/Write/Delete/List/Add/Create permissions (for more information see https://docs.microsoft.com/en-us/azure/cost-management-billing/costs/export-cost-data-storage-account-sas-key ). + + All required parameters must be populated in order to send to Azure. + + :ivar resource_id: The resource id of the storage account where exports will be delivered. This + is not required if a sasToken and storageAccount are specified. + :vartype resource_id: str + :ivar container: The name of the container where exports will be uploaded. If the container + does not exist it will be created. Required. + :vartype container: str + :ivar root_folder_path: The name of the directory where exports will be uploaded. + :vartype root_folder_path: str + :ivar sas_token: A SAS token for the storage account. For a restricted set of Azure customers + this together with storageAccount can be specified instead of resourceId. Note: the value + returned by the API for this property will always be obfuscated. Returning this same obfuscated + value will not result in the SAS token being updated. To update this value a new SAS token must + be specified. + :vartype sas_token: str + :ivar storage_account: The storage account where exports will be uploaded. For a restricted set + of Azure customers this together with sasToken can be specified instead of resourceId. + :vartype storage_account: str + """ + + _validation = { + "container": {"required": True}, + } + + _attribute_map = { + "resource_id": {"key": "resourceId", "type": "str"}, + "container": {"key": "container", "type": "str"}, + "root_folder_path": {"key": "rootFolderPath", "type": "str"}, + "sas_token": {"key": "sasToken", "type": "str"}, + "storage_account": {"key": "storageAccount", "type": "str"}, + } + + def __init__( + self, + *, + container: str, + resource_id: Optional[str] = None, + root_folder_path: Optional[str] = None, + sas_token: Optional[str] = None, + storage_account: Optional[str] = None, + **kwargs + ): + """ + :keyword resource_id: The resource id of the storage account where exports will be delivered. + This is not required if a sasToken and storageAccount are specified. + :paramtype resource_id: str + :keyword container: The name of the container where exports will be uploaded. If the container + does not exist it will be created. Required. + :paramtype container: str + :keyword root_folder_path: The name of the directory where exports will be uploaded. + :paramtype root_folder_path: str + :keyword sas_token: A SAS token for the storage account. For a restricted set of Azure + customers this together with storageAccount can be specified instead of resourceId. Note: the + value returned by the API for this property will always be obfuscated. Returning this same + obfuscated value will not result in the SAS token being updated. To update this value a new SAS + token must be specified. + :paramtype sas_token: str + :keyword storage_account: The storage account where exports will be uploaded. For a restricted + set of Azure customers this together with sasToken can be specified instead of resourceId. + :paramtype storage_account: str + """ + super().__init__(**kwargs) + self.resource_id = resource_id + self.container = container + self.root_folder_path = root_folder_path + self.sas_token = sas_token + self.storage_account = storage_account + + +class ExportDeliveryInfo(_serialization.Model): + """The delivery information associated with a export. + + All required parameters must be populated in order to send to Azure. + + :ivar destination: Has destination for the export being delivered. Required. + :vartype destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination + """ + + _validation = { + "destination": {"required": True}, + } + + _attribute_map = { + "destination": {"key": "destination", "type": "ExportDeliveryDestination"}, + } + + def __init__(self, *, destination: "_models.ExportDeliveryDestination", **kwargs): + """ + :keyword destination: Has destination for the export being delivered. Required. + :paramtype destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination + """ + super().__init__(**kwargs) + self.destination = destination + + +class ExportExecutionListResult(_serialization.Model): + """Result of listing the run history of an export. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: A list of export runs. + :vartype value: list[~azure.mgmt.costmanagement.models.ExportRun] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ExportRun]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + + +class ExportListResult(_serialization.Model): + """Result of listing exports. It contains a list of available exports in the scope provided. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar value: The list of exports. + :vartype value: list[~azure.mgmt.costmanagement.models.Export] + """ + + _validation = { + "value": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[Export]"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + + +class ExportProperties(CommonExportProperties): + """The properties of the export. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :vartype format: str or ~azure.mgmt.costmanagement.models.FormatType + :ivar delivery_info: Has delivery information for the export. Required. + :vartype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :ivar definition: Has the definition for the export. Required. + :vartype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :ivar run_history: If requested, has the most recent run history for the export. + :vartype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :ivar partition_data: If set to true, exported data will be partitioned by size and placed in a + blob directory together with a manifest file. Note: this option is currently available only for + Microsoft Customer Agreement commerce scopes. + :vartype partition_data: bool + :ivar next_run_time_estimate: If the export has an active schedule, provides an estimate of the + next run time. + :vartype next_run_time_estimate: ~datetime.datetime + :ivar schedule: Has schedule information for the export. + :vartype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + """ + + _validation = { + "delivery_info": {"required": True}, + "definition": {"required": True}, + "next_run_time_estimate": {"readonly": True}, + } + + _attribute_map = { + "format": {"key": "format", "type": "str"}, + "delivery_info": {"key": "deliveryInfo", "type": "ExportDeliveryInfo"}, + "definition": {"key": "definition", "type": "ExportDefinition"}, + "run_history": {"key": "runHistory", "type": "ExportExecutionListResult"}, + "partition_data": {"key": "partitionData", "type": "bool"}, + "next_run_time_estimate": {"key": "nextRunTimeEstimate", "type": "iso-8601"}, + "schedule": {"key": "schedule", "type": "ExportSchedule"}, + } + + def __init__( + self, + *, + delivery_info: "_models.ExportDeliveryInfo", + definition: "_models.ExportDefinition", + format: Optional[Union[str, "_models.FormatType"]] = None, + run_history: Optional["_models.ExportExecutionListResult"] = None, + partition_data: Optional[bool] = None, + schedule: Optional["_models.ExportSchedule"] = None, + **kwargs + ): + """ + :keyword format: The format of the export being delivered. Currently only 'Csv' is supported. + "Csv" + :paramtype format: str or ~azure.mgmt.costmanagement.models.FormatType + :keyword delivery_info: Has delivery information for the export. Required. + :paramtype delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo + :keyword definition: Has the definition for the export. Required. + :paramtype definition: ~azure.mgmt.costmanagement.models.ExportDefinition + :keyword run_history: If requested, has the most recent run history for the export. + :paramtype run_history: ~azure.mgmt.costmanagement.models.ExportExecutionListResult + :keyword partition_data: If set to true, exported data will be partitioned by size and placed + in a blob directory together with a manifest file. Note: this option is currently available + only for Microsoft Customer Agreement commerce scopes. + :paramtype partition_data: bool + :keyword schedule: Has schedule information for the export. + :paramtype schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + """ + super().__init__( + format=format, + delivery_info=delivery_info, + definition=definition, + run_history=run_history, + partition_data=partition_data, + **kwargs + ) + self.schedule = schedule + + +class ExportRecurrencePeriod(_serialization.Model): + """The start and end date for recurrence schedule. + + All required parameters must be populated in order to send to Azure. + + :ivar from_property: The start date of recurrence. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date of recurrence. + :vartype to: ~datetime.datetime + """ + + _validation = { + "from_property": {"required": True}, + } + + _attribute_map = { + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: Optional[datetime.datetime] = None, **kwargs): + """ + :keyword from_property: The start date of recurrence. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date of recurrence. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) + self.from_property = from_property + self.to = to + + +class ExportRun(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes + """An export run. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Resource Id. + :vartype id: str + :ivar name: Resource name. + :vartype name: str + :ivar type: Resource type. + :vartype type: str + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :vartype e_tag: str + :ivar execution_type: The type of the export run. Known values are: "OnDemand" and "Scheduled". + :vartype execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType + :ivar status: The last known status of the export run. Known values are: "Queued", + "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", and "DataNotAvailable". + :vartype status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus + :ivar submitted_by: The identifier for the entity that triggered the export. For on-demand runs + it is the user email. For scheduled runs it is 'System'. + :vartype submitted_by: str + :ivar submitted_time: The time when export was queued to be run. + :vartype submitted_time: ~datetime.datetime + :ivar processing_start_time: The time when export was picked up to be run. + :vartype processing_start_time: ~datetime.datetime + :ivar processing_end_time: The time when the export run finished. + :vartype processing_end_time: ~datetime.datetime + :ivar file_name: The name of the exported file. + :vartype file_name: str + :ivar run_settings: The export settings that were in effect for this run. + :vartype run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties + :ivar error: The details of any error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "execution_type": {"key": "properties.executionType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "submitted_by": {"key": "properties.submittedBy", "type": "str"}, + "submitted_time": {"key": "properties.submittedTime", "type": "iso-8601"}, + "processing_start_time": {"key": "properties.processingStartTime", "type": "iso-8601"}, + "processing_end_time": {"key": "properties.processingEndTime", "type": "iso-8601"}, + "file_name": {"key": "properties.fileName", "type": "str"}, + "run_settings": {"key": "properties.runSettings", "type": "CommonExportProperties"}, + "error": {"key": "properties.error", "type": "ErrorDetails"}, + } + + def __init__( + self, + *, + e_tag: Optional[str] = None, + execution_type: Optional[Union[str, "_models.ExecutionType"]] = None, + status: Optional[Union[str, "_models.ExecutionStatus"]] = None, + submitted_by: Optional[str] = None, + submitted_time: Optional[datetime.datetime] = None, + processing_start_time: Optional[datetime.datetime] = None, + processing_end_time: Optional[datetime.datetime] = None, + file_name: Optional[str] = None, + run_settings: Optional["_models.CommonExportProperties"] = None, + error: Optional["_models.ErrorDetails"] = None, + **kwargs + ): + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword execution_type: The type of the export run. Known values are: "OnDemand" and + "Scheduled". + :paramtype execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType + :keyword status: The last known status of the export run. Known values are: "Queued", + "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", and "DataNotAvailable". + :paramtype status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus + :keyword submitted_by: The identifier for the entity that triggered the export. For on-demand + runs it is the user email. For scheduled runs it is 'System'. + :paramtype submitted_by: str + :keyword submitted_time: The time when export was queued to be run. + :paramtype submitted_time: ~datetime.datetime + :keyword processing_start_time: The time when export was picked up to be run. + :paramtype processing_start_time: ~datetime.datetime + :keyword processing_end_time: The time when the export run finished. + :paramtype processing_end_time: ~datetime.datetime + :keyword file_name: The name of the exported file. + :paramtype file_name: str + :keyword run_settings: The export settings that were in effect for this run. + :paramtype run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties + :keyword error: The details of any error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(e_tag=e_tag, **kwargs) + self.execution_type = execution_type + self.status = status + self.submitted_by = submitted_by + self.submitted_time = submitted_time + self.processing_start_time = processing_start_time + self.processing_end_time = processing_end_time + self.file_name = file_name + self.run_settings = run_settings + self.error = error + + +class ExportSchedule(_serialization.Model): + """The schedule associated with the export. + + :ivar status: The status of the export's schedule. If 'Inactive', the export's schedule is + paused. Known values are: "Active" and "Inactive". + :vartype status: str or ~azure.mgmt.costmanagement.models.StatusType + :ivar recurrence: The schedule recurrence. Known values are: "Daily", "Weekly", "Monthly", and + "Annually". + :vartype recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType + :ivar recurrence_period: Has start and end date of the recurrence. The start date must be in + future. If present, the end date must be greater than start date. + :vartype recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod + """ + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "recurrence": {"key": "recurrence", "type": "str"}, + "recurrence_period": {"key": "recurrencePeriod", "type": "ExportRecurrencePeriod"}, + } + + def __init__( + self, + *, + status: Optional[Union[str, "_models.StatusType"]] = None, + recurrence: Optional[Union[str, "_models.RecurrenceType"]] = None, + recurrence_period: Optional["_models.ExportRecurrencePeriod"] = None, + **kwargs + ): + """ + :keyword status: The status of the export's schedule. If 'Inactive', the export's schedule is + paused. Known values are: "Active" and "Inactive". + :paramtype status: str or ~azure.mgmt.costmanagement.models.StatusType + :keyword recurrence: The schedule recurrence. Known values are: "Daily", "Weekly", "Monthly", + and "Annually". + :paramtype recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType + :keyword recurrence_period: Has start and end date of the recurrence. The start date must be in + future. If present, the end date must be greater than start date. + :paramtype recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod + """ + super().__init__(**kwargs) + self.status = status + self.recurrence = recurrence + self.recurrence_period = recurrence_period + + +class ExportTimePeriod(_serialization.Model): + """The date range for data in the export. This should only be specified with timeFrame set to 'Custom'. The maximum date range is 3 months. + + All required parameters must be populated in order to send to Azure. + + :ivar from_property: The start date for export data. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date for export data. Required. + :vartype to: ~datetime.datetime + """ + + _validation = { + "from_property": {"required": True}, + "to": {"required": True}, + } + + _attribute_map = { + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, + } + + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date for export data. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date for export data. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) + self.from_property = from_property + self.to = to + + +class FileDestination(_serialization.Model): + """Destination of the view data. This is optional. Currently only CSV format is supported. + + :ivar file_formats: Destination of the view data. Currently only CSV format is supported. + :vartype file_formats: list[str or ~azure.mgmt.costmanagement.models.FileFormat] + """ + + _attribute_map = { + "file_formats": {"key": "fileFormats", "type": "[str]"}, + } + + def __init__(self, *, file_formats: Optional[List[Union[str, "_models.FileFormat"]]] = None, **kwargs): + """ + :keyword file_formats: Destination of the view data. Currently only CSV format is supported. + :paramtype file_formats: list[str or ~azure.mgmt.costmanagement.models.FileFormat] + """ + super().__init__(**kwargs) + self.file_formats = file_formats + + +class ForecastAggregation(_serialization.Model): + """The aggregation expression to be used in the forecast. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the column to aggregate. Required. Known values are: "PreTaxCostUSD", + "Cost", "CostUSD", and "PreTaxCost". + :vartype name: str or ~azure.mgmt.costmanagement.models.FunctionName + :ivar function: The name of the aggregation function to use. Required. "Sum" + :vartype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + + _validation = { + "name": {"required": True}, + "function": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "function": {"key": "function", "type": "str"}, + } + + def __init__( + self, *, name: Union[str, "_models.FunctionName"], function: Union[str, "_models.FunctionType"], **kwargs + ): + """ + :keyword name: The name of the column to aggregate. Required. Known values are: + "PreTaxCostUSD", "Cost", "CostUSD", and "PreTaxCost". + :paramtype name: str or ~azure.mgmt.costmanagement.models.FunctionName + :keyword function: The name of the aggregation function to use. Required. "Sum" + :paramtype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + super().__init__(**kwargs) + self.name = name + self.function = function + + +class ForecastColumn(_serialization.Model): + """Forecast column properties. + + :ivar name: The name of column. + :vartype name: str + :ivar type: The type of column. + :vartype type: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword name: The name of column. + :paramtype name: str + :keyword type: The type of column. + :paramtype type: str + """ + super().__init__(**kwargs) + self.name = name + self.type = type + + +class ForecastComparisonExpression(_serialization.Model): + """The comparison expression to be used in the forecast. + + All required parameters must be populated in order to send to Azure. + + :ivar name: The name of the column to use in comparison. Required. + :vartype name: str + :ivar operator: The operator to use for comparison. Required. "In" + :vartype operator: str or ~azure.mgmt.costmanagement.models.ForecastOperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] + """ + + _validation = { + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True, "min_items": 1}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__(self, *, name: str, operator: Union[str, "_models.ForecastOperatorType"], values: List[str], **kwargs): + """ + :keyword name: The name of the column to use in comparison. Required. + :paramtype name: str + :keyword operator: The operator to use for comparison. Required. "In" + :paramtype operator: str or ~azure.mgmt.costmanagement.models.ForecastOperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) + self.name = name + self.operator = operator + self.values = values + + +class ForecastDataset(_serialization.Model): + """The definition of data present in the forecast. + + All required parameters must be populated in order to send to Azure. + + :ivar granularity: The granularity of rows in the forecast. "Daily" + :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :ivar configuration: Has configuration information for the data in the export. The + configuration will be ignored if aggregation and grouping are provided. + :vartype configuration: ~azure.mgmt.costmanagement.models.ForecastDatasetConfiguration + :ivar aggregation: Dictionary of aggregation expression to use in the forecast. The key of each + item in the dictionary is the alias for the aggregated column. forecast can have up to 2 + aggregation clauses. Required. + :vartype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ForecastAggregation] + :ivar filter: Has filter expression to use in the forecast. + :vartype filter: ~azure.mgmt.costmanagement.models.ForecastFilter + """ + + _validation = { + "aggregation": {"required": True}, + } + + _attribute_map = { + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "ForecastDatasetConfiguration"}, + "aggregation": {"key": "aggregation", "type": "{ForecastAggregation}"}, + "filter": {"key": "filter", "type": "ForecastFilter"}, + } + + def __init__( + self, + *, + aggregation: Dict[str, "_models.ForecastAggregation"], + granularity: Optional[Union[str, "_models.GranularityType"]] = None, + configuration: Optional["_models.ForecastDatasetConfiguration"] = None, + filter: Optional["_models.ForecastFilter"] = None, # pylint: disable=redefined-builtin + **kwargs + ): + """ + :keyword granularity: The granularity of rows in the forecast. "Daily" + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :keyword configuration: Has configuration information for the data in the export. The + configuration will be ignored if aggregation and grouping are provided. + :paramtype configuration: ~azure.mgmt.costmanagement.models.ForecastDatasetConfiguration + :keyword aggregation: Dictionary of aggregation expression to use in the forecast. The key of + each item in the dictionary is the alias for the aggregated column. forecast can have up to 2 + aggregation clauses. Required. + :paramtype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ForecastAggregation] + :keyword filter: Has filter expression to use in the forecast. + :paramtype filter: ~azure.mgmt.costmanagement.models.ForecastFilter + """ + super().__init__(**kwargs) + self.granularity = granularity + self.configuration = configuration + self.aggregation = aggregation + self.filter = filter + + +class ForecastDatasetConfiguration(_serialization.Model): + """The configuration of dataset in the forecast. + + :ivar columns: Array of column names to be included in the forecast. Any valid forecast column + name is allowed. If not provided, then forecast includes all columns. + :vartype columns: list[str] + """ + + _attribute_map = { + "columns": {"key": "columns", "type": "[str]"}, + } -Some Error responses: + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the forecast. Any valid forecast + column name is allowed. If not provided, then forecast includes all columns. + :paramtype columns: list[str] + """ + super().__init__(**kwargs) + self.columns = columns -* - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. +class ForecastDefinition(_serialization.Model): + """The definition of a forecast. -* - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + All required parameters must be populated in order to send to Azure. - :param error: The details of the error. - :type error: ~azure.mgmt.costmanagement.models.ErrorDetails + :ivar type: The type of the forecast. Required. Known values are: "Usage", "ActualCost", and + "AmortizedCost". + :vartype type: str or ~azure.mgmt.costmanagement.models.ForecastType + :ivar timeframe: The time frame for pulling data for the forecast. If custom, then a specific + time period must be provided. Required. "Custom" + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframe + :ivar time_period: Has time period for pulling data for the forecast. + :vartype time_period: ~azure.mgmt.costmanagement.models.ForecastTimePeriod + :ivar dataset: Has definition for data in this forecast. Required. + :vartype dataset: ~azure.mgmt.costmanagement.models.ForecastDataset + :ivar include_actual_cost: A boolean determining if actualCost will be included. + :vartype include_actual_cost: bool + :ivar include_fresh_partial_cost: A boolean determining if FreshPartialCost will be included. + :vartype include_fresh_partial_cost: bool """ + _validation = { + "type": {"required": True}, + "timeframe": {"required": True}, + "dataset": {"required": True}, + } + _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, + "type": {"key": "type", "type": "str"}, + "timeframe": {"key": "timeframe", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "ForecastTimePeriod"}, + "dataset": {"key": "dataset", "type": "ForecastDataset"}, + "include_actual_cost": {"key": "includeActualCost", "type": "bool"}, + "include_fresh_partial_cost": {"key": "includeFreshPartialCost", "type": "bool"}, } def __init__( self, *, - error: Optional["ErrorDetails"] = None, + type: Union[str, "_models.ForecastType"], + timeframe: Union[str, "_models.ForecastTimeframe"], + dataset: "_models.ForecastDataset", + time_period: Optional["_models.ForecastTimePeriod"] = None, + include_actual_cost: Optional[bool] = None, + include_fresh_partial_cost: Optional[bool] = None, **kwargs ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = error - + """ + :keyword type: The type of the forecast. Required. Known values are: "Usage", "ActualCost", and + "AmortizedCost". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ForecastType + :keyword timeframe: The time frame for pulling data for the forecast. If custom, then a + specific time period must be provided. Required. "Custom" + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframe + :keyword time_period: Has time period for pulling data for the forecast. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ForecastTimePeriod + :keyword dataset: Has definition for data in this forecast. Required. + :paramtype dataset: ~azure.mgmt.costmanagement.models.ForecastDataset + :keyword include_actual_cost: A boolean determining if actualCost will be included. + :paramtype include_actual_cost: bool + :keyword include_fresh_partial_cost: A boolean determining if FreshPartialCost will be + included. + :paramtype include_fresh_partial_cost: bool + """ + super().__init__(**kwargs) + self.type = type + self.timeframe = timeframe + self.time_period = time_period + self.dataset = dataset + self.include_actual_cost = include_actual_cost + self.include_fresh_partial_cost = include_fresh_partial_cost -class ProxyResource(msrest.serialization.Model): - """The Resource model definition. - Variables are only populated by the server, and will be ignored when sending a request. +class ForecastFilter(_serialization.Model): + """The filter expression to be used in the export. - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + :vartype and_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :ivar or_property: The logical "OR" expression. Must have at least 2 items. + :vartype or_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :ivar dimensions: Has comparison expression for a dimension. + :vartype dimensions: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression + :ivar tags: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "and_property": {"min_items": 2}, + "or_property": {"min_items": 2}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, + "and_property": {"key": "and", "type": "[ForecastFilter]"}, + "or_property": {"key": "or", "type": "[ForecastFilter]"}, + "dimensions": {"key": "dimensions", "type": "ForecastComparisonExpression"}, + "tags": {"key": "tags", "type": "ForecastComparisonExpression"}, } def __init__( self, *, - e_tag: Optional[str] = None, + and_property: Optional[List["_models.ForecastFilter"]] = None, + or_property: Optional[List["_models.ForecastFilter"]] = None, + dimensions: Optional["_models.ForecastComparisonExpression"] = None, + tags: Optional["_models.ForecastComparisonExpression"] = None, **kwargs ): - super(ProxyResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.e_tag = e_tag + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :keyword or_property: The logical "OR" expression. Must have at least 2 items. + :paramtype or_property: list[~azure.mgmt.costmanagement.models.ForecastFilter] + :keyword dimensions: Has comparison expression for a dimension. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression + :keyword tags: Has comparison expression for a tag. + :paramtype tags: ~azure.mgmt.costmanagement.models.ForecastComparisonExpression + """ + super().__init__(**kwargs) + self.and_property = and_property + self.or_property = or_property + self.dimensions = dimensions + self.tags = tags -class Export(ProxyResource): - """A export resource. +class ForecastResult(CostManagementResource): + """Result of forecast. It contains all columns listed under groupings and aggregation. Variables are only populated by the server, and will be ignored when sending a request. @@ -702,882 +2735,1055 @@ class Export(ProxyResource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + :ivar location: Location of the resource. + :vartype location: str + :ivar sku: SKU of the resource. + :vartype sku: str + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar next_link: The link (url) to the next page of results. + :vartype next_link: str + :ivar columns: Array of columns. + :vartype columns: list[~azure.mgmt.costmanagement.models.ForecastColumn] + :ivar rows: Array of rows. + :vartype rows: list[list[any]] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'format': {'key': 'properties.format', 'type': 'str'}, - 'delivery_info': {'key': 'properties.deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'properties.definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'properties.schedule', 'type': 'ExportSchedule'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + "columns": {"key": "properties.columns", "type": "[ForecastColumn]"}, + "rows": {"key": "properties.rows", "type": "[[object]]"}, } def __init__( self, *, - e_tag: Optional[str] = None, - format: Optional[Union[str, "FormatType"]] = None, - delivery_info: Optional["ExportDeliveryInfo"] = None, - definition: Optional["ExportDefinition"] = None, - schedule: Optional["ExportSchedule"] = None, + next_link: Optional[str] = None, + columns: Optional[List["_models.ForecastColumn"]] = None, + rows: Optional[List[List[Any]]] = None, **kwargs ): - super(Export, self).__init__(e_tag=e_tag, **kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition - self.schedule = schedule + """ + :keyword next_link: The link (url) to the next page of results. + :paramtype next_link: str + :keyword columns: Array of columns. + :paramtype columns: list[~azure.mgmt.costmanagement.models.ForecastColumn] + :keyword rows: Array of rows. + :paramtype rows: list[list[any]] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.columns = columns + self.rows = rows -class ExportDefinition(msrest.serialization.Model): - """The definition of a query. +class ForecastTimePeriod(_serialization.Model): + """Has time period for pulling data for the forecast. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", - "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param data_set: Has definition for data in this query. - :type data_set: ~azure.mgmt.costmanagement.models.QueryDatasetAutoGenerated + :ivar from_property: The start date to pull data from. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date to pull data to. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'data_set': {'key': 'dataSet', 'type': 'QueryDatasetAutoGenerated'}, + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, } - def __init__( - self, - *, - type: Union[str, "ExportType"], - timeframe: Union[str, "TimeframeType"], - time_period: Optional["QueryTimePeriod"] = None, - data_set: Optional["QueryDatasetAutoGenerated"] = None, - **kwargs - ): - super(ExportDefinition, self).__init__(**kwargs) - self.type = type - self.timeframe = timeframe - self.time_period = time_period - self.data_set = data_set + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date to pull data from. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date to pull data to. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) + self.from_property = from_property + self.to = to -class ExportDeliveryDestination(msrest.serialization.Model): - """The destination information for the delivery of the export. To allow access to a storage account, you must register the account's subscription with the Microsoft.CostManagementExports resource provider. This is required once per subscription. When creating an export in the Azure portal, it is done automatically, however API users need to register the subscription. For more information see https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-supported-services . +class GenerateCostDetailsReportErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. - All required parameters must be populated in order to send to Azure. + Some Error responses: - :param resource_id: Required. The resource id of the storage account where exports will be - delivered. - :type resource_id: str - :param container: Required. The name of the container where exports will be uploaded. - :type container: str - :param root_folder_path: The name of the directory where exports will be uploaded. - :type root_folder_path: str - """ - _validation = { - 'resource_id': {'required': True}, - 'container': {'required': True}, - } + * + 400 Bad Request - Invalid Request Payload. Request payload provided is not in a json format or had an invalid member not accepted in the request payload. - _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'container': {'key': 'container', 'type': 'str'}, - 'root_folder_path': {'key': 'rootFolderPath', 'type': 'str'}, - } + * + 400 Bad Request - Invalid request payload: can only have either timePeriod or invoiceId or billingPeriod. API only allows data to be pulled for either timePeriod or invoiceId or billingPeriod. Customer should provide only one of these parameters. - def __init__( - self, - *, - resource_id: str, - container: str, - root_folder_path: Optional[str] = None, - **kwargs - ): - super(ExportDeliveryDestination, self).__init__(**kwargs) - self.resource_id = resource_id - self.container = container - self.root_folder_path = root_folder_path + * + 400 Bad Request - Start date must be after . API only allows data to be pulled no older than 13 months from now. + * + 400 Bad Request - The maximum allowed date range is 1 months. API only allows data to be pulled for 1 month or less. -class ExportDeliveryInfo(msrest.serialization.Model): - """The delivery information associated with a export. + * + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "retry-after" header. - All required parameters must be populated in order to send to Azure. + * + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. - :param destination: Required. Has destination for the export being delivered. - :type destination: ~azure.mgmt.costmanagement.models.ExportDeliveryDestination + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails """ - _validation = { - 'destination': {'required': True}, + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetails"}, } + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(**kwargs) + self.error = error + + +class GenerateCostDetailsReportRequestDefinition(_serialization.Model): + """The definition of a cost detailed report. + + :ivar metric: The type of the detailed report. By default ActualCost is provided. Known values + are: "ActualCost" and "AmortizedCost". + :vartype metric: str or ~azure.mgmt.costmanagement.models.CostDetailsMetricType + :ivar time_period: The specific date range of cost details requested for the report. This + parameter cannot be used alongside either the invoiceId or billingPeriod parameters. If a + timePeriod, invoiceId or billingPeriod parameter is not provided in the request body the API + will return the current month's cost. API only allows data to be pulled for 1 month or less and + no older than 13 months. If no timePeriod or billingPeriod or invoiceId is provided the API + defaults to the open month time period. + :vartype time_period: ~azure.mgmt.costmanagement.models.CostDetailsTimePeriod + :ivar billing_period: This parameter can be used only by Enterprise Agreement customers. Use + the YearMonth(e.g. 202008) format. This parameter cannot be used alongside either the invoiceId + or timePeriod parameters. If a timePeriod, invoiceId or billingPeriod parameter is not provided + in the request body the API will return the current month's cost. + :vartype billing_period: str + :ivar invoice_id: This parameter can only be used by Microsoft Customer Agreement customers. + Additionally, it can only be used at the Billing Profile or Customer scope. This parameter + cannot be used alongside either the billingPeriod or timePeriod parameters. If a timePeriod, + invoiceId or billingPeriod parameter is not provided in the request body the API will return + the current month's cost. + :vartype invoice_id: str + """ + _attribute_map = { - 'destination': {'key': 'destination', 'type': 'ExportDeliveryDestination'}, + "metric": {"key": "metric", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "CostDetailsTimePeriod"}, + "billing_period": {"key": "billingPeriod", "type": "str"}, + "invoice_id": {"key": "invoiceId", "type": "str"}, } def __init__( self, *, - destination: "ExportDeliveryDestination", + metric: Optional[Union[str, "_models.CostDetailsMetricType"]] = None, + time_period: Optional["_models.CostDetailsTimePeriod"] = None, + billing_period: Optional[str] = None, + invoice_id: Optional[str] = None, **kwargs ): - super(ExportDeliveryInfo, self).__init__(**kwargs) - self.destination = destination - - -class ExportExecution(Resource): - """A export execution. - - Variables are only populated by the server, and will be ignored when sending a request. + """ + :keyword metric: The type of the detailed report. By default ActualCost is provided. Known + values are: "ActualCost" and "AmortizedCost". + :paramtype metric: str or ~azure.mgmt.costmanagement.models.CostDetailsMetricType + :keyword time_period: The specific date range of cost details requested for the report. This + parameter cannot be used alongside either the invoiceId or billingPeriod parameters. If a + timePeriod, invoiceId or billingPeriod parameter is not provided in the request body the API + will return the current month's cost. API only allows data to be pulled for 1 month or less and + no older than 13 months. If no timePeriod or billingPeriod or invoiceId is provided the API + defaults to the open month time period. + :paramtype time_period: ~azure.mgmt.costmanagement.models.CostDetailsTimePeriod + :keyword billing_period: This parameter can be used only by Enterprise Agreement customers. Use + the YearMonth(e.g. 202008) format. This parameter cannot be used alongside either the invoiceId + or timePeriod parameters. If a timePeriod, invoiceId or billingPeriod parameter is not provided + in the request body the API will return the current month's cost. + :paramtype billing_period: str + :keyword invoice_id: This parameter can only be used by Microsoft Customer Agreement customers. + Additionally, it can only be used at the Billing Profile or Customer scope. This parameter + cannot be used alongside either the billingPeriod or timePeriod parameters. If a timePeriod, + invoiceId or billingPeriod parameter is not provided in the request body the API will return + the current month's cost. + :paramtype invoice_id: str + """ + super().__init__(**kwargs) + self.metric = metric + self.time_period = time_period + self.billing_period = billing_period + self.invoice_id = invoice_id + + +class GenerateDetailedCostReportDefinition(_serialization.Model): + """The definition of a cost detailed report. + + :ivar metric: The type of the detailed report. By default ActualCost is provided. Known values + are: "ActualCost" and "AmortizedCost". + :vartype metric: str or ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportMetricType + :ivar time_period: Has time period for pulling data for the cost detailed report. Can only have + one of either timePeriod or invoiceId or billingPeriod parameters. If none provided current + month cost is provided. + :vartype time_period: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportTimePeriod + :ivar billing_period: Billing period in YearMonth(e.g. 202008) format. Only for legacy + enterprise customers can use this. Can only have one of either timePeriod or invoiceId or + billingPeriod parameters. If none provided current month cost is provided. + :vartype billing_period: str + :ivar invoice_id: Invoice ID for Pay-as-you-go and Microsoft Customer Agreement scopes. Can + only have one of either timePeriod or invoiceId or billingPeriod parameters. If none provided + current month cost is provided. + :vartype invoice_id: str + :ivar customer_id: Customer ID for Microsoft Customer Agreement scopes (Invoice Id is also + required for this). + :vartype customer_id: str + """ - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param execution_type: The type of the export execution. Possible values include: "OnDemand", - "Scheduled". - :type execution_type: str or ~azure.mgmt.costmanagement.models.ExecutionType - :param status: The status of the export execution. Possible values include: "Queued", - "InProgress", "Completed", "Failed", "Timeout", "NewDataNotAvailable", "DataNotAvailable". - :type status: str or ~azure.mgmt.costmanagement.models.ExecutionStatus - :param submitted_by: The identifier for the entity that executed the export. For OnDemand - executions, it is the email id. For Scheduled executions, it is the constant value - System. - :type submitted_by: str - :param submitted_time: The time when export was queued to be executed. - :type submitted_time: ~datetime.datetime - :param processing_start_time: The time when export was picked up to be executed. - :type processing_start_time: ~datetime.datetime - :param processing_end_time: The time when export execution finished. - :type processing_end_time: ~datetime.datetime - :param file_name: The name of the file export got written to. - :type file_name: str - :param run_settings: The common properties of the export. - :type run_settings: ~azure.mgmt.costmanagement.models.CommonExportProperties - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'execution_type': {'key': 'properties.executionType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'submitted_by': {'key': 'properties.submittedBy', 'type': 'str'}, - 'submitted_time': {'key': 'properties.submittedTime', 'type': 'iso-8601'}, - 'processing_start_time': {'key': 'properties.processingStartTime', 'type': 'iso-8601'}, - 'processing_end_time': {'key': 'properties.processingEndTime', 'type': 'iso-8601'}, - 'file_name': {'key': 'properties.fileName', 'type': 'str'}, - 'run_settings': {'key': 'properties.runSettings', 'type': 'CommonExportProperties'}, + _attribute_map = { + "metric": {"key": "metric", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "GenerateDetailedCostReportTimePeriod"}, + "billing_period": {"key": "billingPeriod", "type": "str"}, + "invoice_id": {"key": "invoiceId", "type": "str"}, + "customer_id": {"key": "customerId", "type": "str"}, } def __init__( self, *, - execution_type: Optional[Union[str, "ExecutionType"]] = None, - status: Optional[Union[str, "ExecutionStatus"]] = None, - submitted_by: Optional[str] = None, - submitted_time: Optional[datetime.datetime] = None, - processing_start_time: Optional[datetime.datetime] = None, - processing_end_time: Optional[datetime.datetime] = None, - file_name: Optional[str] = None, - run_settings: Optional["CommonExportProperties"] = None, + metric: Optional[Union[str, "_models.GenerateDetailedCostReportMetricType"]] = None, + time_period: Optional["_models.GenerateDetailedCostReportTimePeriod"] = None, + billing_period: Optional[str] = None, + invoice_id: Optional[str] = None, + customer_id: Optional[str] = None, **kwargs ): - super(ExportExecution, self).__init__(**kwargs) - self.execution_type = execution_type - self.status = status - self.submitted_by = submitted_by - self.submitted_time = submitted_time - self.processing_start_time = processing_start_time - self.processing_end_time = processing_end_time - self.file_name = file_name - self.run_settings = run_settings + """ + :keyword metric: The type of the detailed report. By default ActualCost is provided. Known + values are: "ActualCost" and "AmortizedCost". + :paramtype metric: str or + ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportMetricType + :keyword time_period: Has time period for pulling data for the cost detailed report. Can only + have one of either timePeriod or invoiceId or billingPeriod parameters. If none provided + current month cost is provided. + :paramtype time_period: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportTimePeriod + :keyword billing_period: Billing period in YearMonth(e.g. 202008) format. Only for legacy + enterprise customers can use this. Can only have one of either timePeriod or invoiceId or + billingPeriod parameters. If none provided current month cost is provided. + :paramtype billing_period: str + :keyword invoice_id: Invoice ID for Pay-as-you-go and Microsoft Customer Agreement scopes. Can + only have one of either timePeriod or invoiceId or billingPeriod parameters. If none provided + current month cost is provided. + :paramtype invoice_id: str + :keyword customer_id: Customer ID for Microsoft Customer Agreement scopes (Invoice Id is also + required for this). + :paramtype customer_id: str + """ + super().__init__(**kwargs) + self.metric = metric + self.time_period = time_period + self.billing_period = billing_period + self.invoice_id = invoice_id + self.customer_id = customer_id -class ExportExecutionListResult(msrest.serialization.Model): - """Result of listing exports execution history of a export by name. +class GenerateDetailedCostReportErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. - Variables are only populated by the server, and will be ignored when sending a request. + Some Error responses: - :ivar value: The list of export executions. - :vartype value: list[~azure.mgmt.costmanagement.models.ExportExecution] - """ - _validation = { - 'value': {'readonly': True}, - } + * + 413 Request Entity Too Large - Request is throttled. The amount of data required to fulfill the request exceeds the maximum size permitted of 2Gb. Please utilize our Exports feature instead. + + * + 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. + + * + 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ExportExecution]'}, + "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__( - self, - **kwargs - ): - super(ExportExecutionListResult, self).__init__(**kwargs) - self.value = None + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + """ + super().__init__(**kwargs) + self.error = error -class ExportListResult(msrest.serialization.Model): - """Result of listing exports. It contains a list of available exports in the scope provided. +class GenerateDetailedCostReportOperationResult(_serialization.Model): + """The result of the long running operation for cost detailed report. Variables are only populated by the server, and will be ignored when sending a request. - :ivar value: The list of exports. - :vartype value: list[~azure.mgmt.costmanagement.models.Export] + :ivar id: The ARM resource id of the long running operation. + :vartype id: str + :ivar name: The name of the long running operation. + :vartype name: str + :ivar type: The type of the long running operation. + :vartype type: str + :ivar expiry_time: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype expiry_time: ~datetime.datetime + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime + :ivar download_url: The URL to download the generated report. + :vartype download_url: str """ _validation = { - 'value': {'readonly': True}, + "expiry_time": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Export]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "expiry_time": {"key": "properties.expiryTime", "type": "iso-8601"}, + "valid_till": {"key": "properties.validTill", "type": "iso-8601"}, + "download_url": {"key": "properties.downloadUrl", "type": "str"}, } def __init__( self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + type: Optional[str] = None, + valid_till: Optional[datetime.datetime] = None, + download_url: Optional[str] = None, **kwargs ): - super(ExportListResult, self).__init__(**kwargs) - self.value = None + """ + :keyword id: The ARM resource id of the long running operation. + :paramtype id: str + :keyword name: The name of the long running operation. + :paramtype name: str + :keyword type: The type of the long running operation. + :paramtype type: str + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + :keyword download_url: The URL to download the generated report. + :paramtype download_url: str + """ + super().__init__(**kwargs) + self.id = id + self.name = name + self.type = type + self.expiry_time = None + self.valid_till = valid_till + self.download_url = download_url -class ExportProperties(CommonExportProperties): - """The properties of the export. +class GenerateDetailedCostReportOperationStatuses(_serialization.Model): + """The status of the long running operation for cost detailed report. - All required parameters must be populated in order to send to Azure. + Variables are only populated by the server, and will be ignored when sending a request. - :param format: The format of the export being delivered. Possible values include: "Csv". - :type format: str or ~azure.mgmt.costmanagement.models.FormatType - :param delivery_info: Required. Has delivery information for the export. - :type delivery_info: ~azure.mgmt.costmanagement.models.ExportDeliveryInfo - :param definition: Required. Has definition for the export. - :type definition: ~azure.mgmt.costmanagement.models.ExportDefinition - :param schedule: Has schedule information for the export. - :type schedule: ~azure.mgmt.costmanagement.models.ExportSchedule + :ivar id: The ID of the long running operation. + :vartype id: str + :ivar name: The name of the long running operation. + :vartype name: str + :ivar status: The status of the long running operation. + :vartype status: ~azure.mgmt.costmanagement.models.Status + :ivar type: The type of the long running operation. + :vartype type: str + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :ivar expiry_time: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype expiry_time: ~datetime.datetime + :ivar valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :vartype valid_till: ~datetime.datetime + :ivar download_url: The URL to download the generated report. + :vartype download_url: str """ _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, + "expiry_time": {"readonly": True}, } _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, - 'schedule': {'key': 'schedule', 'type': 'ExportSchedule'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "status": {"key": "status", "type": "Status"}, + "type": {"key": "type", "type": "str"}, + "error": {"key": "error", "type": "ErrorDetails"}, + "expiry_time": {"key": "properties.expiryTime", "type": "iso-8601"}, + "valid_till": {"key": "properties.validTill", "type": "iso-8601"}, + "download_url": {"key": "properties.downloadUrl", "type": "str"}, } def __init__( self, *, - delivery_info: "ExportDeliveryInfo", - definition: "ExportDefinition", - format: Optional[Union[str, "FormatType"]] = None, - schedule: Optional["ExportSchedule"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + name: Optional[str] = None, + status: Optional["_models.Status"] = None, + type: Optional[str] = None, + error: Optional["_models.ErrorDetails"] = None, + valid_till: Optional[datetime.datetime] = None, + download_url: Optional[str] = None, **kwargs ): - super(ExportProperties, self).__init__(format=format, delivery_info=delivery_info, definition=definition, **kwargs) - self.schedule = schedule + """ + :keyword id: The ID of the long running operation. + :paramtype id: str + :keyword name: The name of the long running operation. + :paramtype name: str + :keyword status: The status of the long running operation. + :paramtype status: ~azure.mgmt.costmanagement.models.Status + :keyword type: The type of the long running operation. + :paramtype type: str + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.costmanagement.models.ErrorDetails + :keyword valid_till: The time at which report URL becomes invalid/expires in UTC e.g. + 2020-12-08T05:55:59.4394737Z. + :paramtype valid_till: ~datetime.datetime + :keyword download_url: The URL to download the generated report. + :paramtype download_url: str + """ + super().__init__(**kwargs) + self.id = id + self.name = name + self.status = status + self.type = type + self.error = error + self.expiry_time = None + self.valid_till = valid_till + self.download_url = download_url -class ExportRecurrencePeriod(msrest.serialization.Model): - """The start and end date for recurrence schedule. +class GenerateDetailedCostReportTimePeriod(_serialization.Model): + """The start and end date for pulling data for the cost detailed report. All required parameters must be populated in order to send to Azure. - :param from_property: Required. The start date of recurrence. - :type from_property: ~datetime.datetime - :param to: The end date of recurrence. - :type to: ~datetime.datetime + :ivar start: The start date to pull data from. example format 2020-03-15. Required. + :vartype start: str + :ivar end: The end date to pull data to. example format 2020-03-15. Required. + :vartype end: str """ _validation = { - 'from_property': {'required': True}, + "start": {"required": True}, + "end": {"required": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, + "start": {"key": "start", "type": "str"}, + "end": {"key": "end", "type": "str"}, } - def __init__( - self, - *, - from_property: datetime.datetime, - to: Optional[datetime.datetime] = None, - **kwargs - ): - super(ExportRecurrencePeriod, self).__init__(**kwargs) - self.from_property = from_property - self.to = to + def __init__(self, *, start: str, end: str, **kwargs): + """ + :keyword start: The start date to pull data from. example format 2020-03-15. Required. + :paramtype start: str + :keyword end: The end date to pull data to. example format 2020-03-15. Required. + :paramtype end: str + """ + super().__init__(**kwargs) + self.start = start + self.end = end -class ExportSchedule(msrest.serialization.Model): - """The schedule associated with a export. +class IncludedQuantityUtilizationSummary(BenefitUtilizationSummary): + """Included Quantity utilization summary resource. + + Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :param status: The status of the schedule. Whether active or not. If inactive, the export's - scheduled execution is paused. Possible values include: "Active", "Inactive". - :type status: str or ~azure.mgmt.costmanagement.models.StatusType - :param recurrence: Required. The schedule recurrence. Possible values include: "Daily", - "Weekly", "Monthly", "Annually". - :type recurrence: str or ~azure.mgmt.costmanagement.models.RecurrenceType - :param recurrence_period: Has start and end date of the recurrence. The start date must be in - future. If present, the end date must be greater than start date. - :type recurrence_period: ~azure.mgmt.costmanagement.models.ExportRecurrencePeriod + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Supported values: 'SavingsPlan'. Required. Known values are: "IncludedQuantity", + "Reservation", and "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar arm_sku_name: ARM SKU name. For example, 'Compute_Savings_Plan' for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of the benefit. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :vartype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar usage_date: Date corresponding to the utilization summary record. If the grain of data is + monthly, value for this field will be first day of the month. + :vartype usage_date: ~datetime.datetime + :ivar utilization_percentage: This is the utilized percentage for the benefit ID. + :vartype utilization_percentage: float """ _validation = { - 'recurrence': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True}, + "arm_sku_name": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_order_id": {"readonly": True}, + "usage_date": {"readonly": True}, + "utilization_percentage": {"readonly": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'recurrence': {'key': 'recurrence', 'type': 'str'}, - 'recurrence_period': {'key': 'recurrencePeriod', 'type': 'ExportRecurrencePeriod'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "arm_sku_name": {"key": "properties.armSkuName", "type": "str"}, + "benefit_id": {"key": "properties.benefitId", "type": "str"}, + "benefit_order_id": {"key": "properties.benefitOrderId", "type": "str"}, + "benefit_type": {"key": "properties.benefitType", "type": "str"}, + "usage_date": {"key": "properties.usageDate", "type": "iso-8601"}, + "utilization_percentage": {"key": "properties.utilizationPercentage", "type": "float"}, } - def __init__( - self, - *, - recurrence: Union[str, "RecurrenceType"], - status: Optional[Union[str, "StatusType"]] = None, - recurrence_period: Optional["ExportRecurrencePeriod"] = None, - **kwargs - ): - super(ExportSchedule, self).__init__(**kwargs) - self.status = status - self.recurrence = recurrence - self.recurrence_period = recurrence_period - - -class ForecastDefinition(msrest.serialization.Model): - """The definition of a forecast. + def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :paramtype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(**kwargs) + self.kind = "IncludedQuantity" # type: str + self.arm_sku_name = None + self.benefit_id = None + self.benefit_order_id = None + self.benefit_type = benefit_type + self.usage_date = None + self.utilization_percentage = None + + +class IncludedQuantityUtilizationSummaryProperties(BenefitUtilizationSummaryProperties): + """Included Quantity utilization summary properties. - All required parameters must be populated in order to send to Azure. + Variables are only populated by the server, and will be ignored when sending a request. - :param type: Required. The type of the forecast. Possible values include: "Usage", - "ActualCost", "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ForecastType - :param timeframe: Required. The time frame for pulling data for the forecast. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ForecastTimeframeType - :param time_period: Has time period for pulling data for the forecast. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this forecast. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset - :param include_actual_cost: a boolean determining if actualCost will be included. - :type include_actual_cost: bool - :param include_fresh_partial_cost: a boolean determining if FreshPartialCost will be included. - :type include_fresh_partial_cost: bool + :ivar arm_sku_name: ARM SKU name. For example, 'Compute_Savings_Plan' for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of the benefit. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :vartype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar usage_date: Date corresponding to the utilization summary record. If the grain of data is + monthly, value for this field will be first day of the month. + :vartype usage_date: ~datetime.datetime + :ivar utilization_percentage: This is the utilized percentage for the benefit ID. + :vartype utilization_percentage: float """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, + "arm_sku_name": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_order_id": {"readonly": True}, + "usage_date": {"readonly": True}, + "utilization_percentage": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, - 'include_actual_cost': {'key': 'includeActualCost', 'type': 'bool'}, - 'include_fresh_partial_cost': {'key': 'includeFreshPartialCost', 'type': 'bool'}, + "arm_sku_name": {"key": "armSkuName", "type": "str"}, + "benefit_id": {"key": "benefitId", "type": "str"}, + "benefit_order_id": {"key": "benefitOrderId", "type": "str"}, + "benefit_type": {"key": "benefitType", "type": "str"}, + "usage_date": {"key": "usageDate", "type": "iso-8601"}, + "utilization_percentage": {"key": "utilizationPercentage", "type": "float"}, } - def __init__( - self, - *, - type: Union[str, "ForecastType"], - timeframe: Union[str, "ForecastTimeframeType"], - dataset: "QueryDataset", - time_period: Optional["QueryTimePeriod"] = None, - include_actual_cost: Optional[bool] = None, - include_fresh_partial_cost: Optional[bool] = None, - **kwargs - ): - super(ForecastDefinition, self).__init__(**kwargs) - self.type = type - self.timeframe = timeframe - self.time_period = time_period - self.dataset = dataset - self.include_actual_cost = include_actual_cost - self.include_fresh_partial_cost = include_fresh_partial_cost + def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :paramtype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(benefit_type=benefit_type, **kwargs) + self.utilization_percentage = None -class KpiProperties(msrest.serialization.Model): +class KpiProperties(_serialization.Model): """Each KPI must contain a 'type' and 'enabled' key. - :param type: KPI type (Forecast, Budget). Possible values include: "Forecast", "Budget". - :type type: str or ~azure.mgmt.costmanagement.models.KpiType - :param id: ID of resource related to metric (budget). - :type id: str - :param enabled: show the KPI in the UI?. - :type enabled: bool + :ivar type: KPI type (Forecast, Budget). Known values are: "Forecast" and "Budget". + :vartype type: str or ~azure.mgmt.costmanagement.models.KpiType + :ivar id: ID of resource related to metric (budget). + :vartype id: str + :ivar enabled: show the KPI in the UI?. + :vartype enabled: bool """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'enabled': {'key': 'enabled', 'type': 'bool'}, + "type": {"key": "type", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "enabled": {"key": "enabled", "type": "bool"}, } def __init__( self, *, - type: Optional[Union[str, "KpiType"]] = None, - id: Optional[str] = None, + type: Optional[Union[str, "_models.KpiType"]] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin enabled: Optional[bool] = None, **kwargs ): - super(KpiProperties, self).__init__(**kwargs) + """ + :keyword type: KPI type (Forecast, Budget). Known values are: "Forecast" and "Budget". + :paramtype type: str or ~azure.mgmt.costmanagement.models.KpiType + :keyword id: ID of resource related to metric (budget). + :paramtype id: str + :keyword enabled: show the KPI in the UI?. + :paramtype enabled: bool + """ + super().__init__(**kwargs) self.type = type self.id = id self.enabled = enabled -class Operation(msrest.serialization.Model): - """A Cost management REST API operation. +class NotificationProperties(_serialization.Model): + """The properties of the scheduled action notification. - Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to Azure. - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :param display: The object that represents the operation. - :type display: ~azure.mgmt.costmanagement.models.OperationDisplay + :ivar to: Array of email addresses. Required. + :vartype to: list[str] + :ivar language: Locale of the email. + :vartype language: str + :ivar message: Optional message to be added in the email. Length is limited to 250 characters. + :vartype message: str + :ivar regional_format: Regional format used for formatting date/time and currency values in the + email. + :vartype regional_format: str + :ivar subject: Subject of the email. Length is limited to 70 characters. Required. + :vartype subject: str """ _validation = { - 'name': {'readonly': True}, + "to": {"required": True, "max_items": 20, "min_items": 1}, + "subject": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, + "to": {"key": "to", "type": "[str]"}, + "language": {"key": "language", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "regional_format": {"key": "regionalFormat", "type": "str"}, + "subject": {"key": "subject", "type": "str"}, } def __init__( self, *, - display: Optional["OperationDisplay"] = None, + to: List[str], + subject: str, + language: Optional[str] = None, + message: Optional[str] = None, + regional_format: Optional[str] = None, **kwargs ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.display = display + """ + :keyword to: Array of email addresses. Required. + :paramtype to: list[str] + :keyword language: Locale of the email. + :paramtype language: str + :keyword message: Optional message to be added in the email. Length is limited to 250 + characters. + :paramtype message: str + :keyword regional_format: Regional format used for formatting date/time and currency values in + the email. + :paramtype regional_format: str + :keyword subject: Subject of the email. Length is limited to 70 characters. Required. + :paramtype subject: str + """ + super().__init__(**kwargs) + self.to = to + self.language = language + self.message = message + self.regional_format = regional_format + self.subject = subject -class OperationDisplay(msrest.serialization.Model): - """The object that represents the operation. +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provider: Service provider: Microsoft.CostManagement. + :ivar provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". :vartype provider: str - :ivar resource: Resource on which the operation is performed: Dimensions, Query. + :ivar resource: The localized friendly name of the resource type related to this operation. + E.g. "Virtual Machines" or "Job Schedule Collections". :vartype resource: str - :ivar operation: Operation type: Read, write, delete, etc. + :ivar operation: The concise, localized friendly name for the operation; suitable for + dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". :vartype operation: str + :ivar description: The short, localized friendly description of the operation; suitable for + tool tips and detailed views. + :vartype description: str """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None + self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """Result of listing cost management operations. It contains a list of operations and a URL link to get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of cost management operations supported by the Microsoft.CostManagement resource provider. - :vartype value: list[~azure.mgmt.costmanagement.models.Operation] + :vartype value: list[~azure.mgmt.costmanagement.models.CostManagementOperation] :ivar next_link: URL to get the next set of operation list results if there are any. :vartype next_link: str """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CostManagementOperation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class OperationStatus(msrest.serialization.Model): +class OperationStatus(_serialization.Model): """The status of the long running operation. - :param status: The status of the long running operation. - :type status: ~azure.mgmt.costmanagement.models.Status - :param report_url: The URL to download the generated report. - :type report_url: str - :param valid_until: The time at which report URL becomes invalid. - :type valid_until: ~datetime.datetime + :ivar status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :vartype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :ivar report_url: The CSV file from the reportUrl blob link consists of reservation usage data + with the following schema at daily granularity. Known values are: "InstanceFlexibilityGroup", + "InstanceFlexibilityRatio", "InstanceId", "Kind", "ReservationId", "ReservationOrderId", + "ReservedHours", "SkuName", "TotalReservedQuantity", "UsageDate", and "UsedHours". + :vartype report_url: str or ~azure.mgmt.costmanagement.models.ReservationReportSchema + :ivar valid_until: The time at which report URL becomes invalid. + :vartype valid_until: ~datetime.datetime """ _attribute_map = { - 'status': {'key': 'status', 'type': 'Status'}, - 'report_url': {'key': 'properties.reportUrl', 'type': 'str'}, - 'valid_until': {'key': 'properties.validUntil', 'type': 'iso-8601'}, + "status": {"key": "status", "type": "str"}, + "report_url": {"key": "properties.reportUrl", "type": "str"}, + "valid_until": {"key": "properties.validUntil", "type": "iso-8601"}, } def __init__( self, *, - status: Optional["Status"] = None, - report_url: Optional[str] = None, + status: Optional[Union[str, "_models.OperationStatusType"]] = None, + report_url: Optional[Union[str, "_models.ReservationReportSchema"]] = None, valid_until: Optional[datetime.datetime] = None, **kwargs ): - super(OperationStatus, self).__init__(**kwargs) + """ + :keyword status: The status of the long running operation. Known values are: "Running", + "Completed", and "Failed". + :paramtype status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :keyword report_url: The CSV file from the reportUrl blob link consists of reservation usage + data with the following schema at daily granularity. Known values are: + "InstanceFlexibilityGroup", "InstanceFlexibilityRatio", "InstanceId", "Kind", "ReservationId", + "ReservationOrderId", "ReservedHours", "SkuName", "TotalReservedQuantity", "UsageDate", and + "UsedHours". + :paramtype report_url: str or ~azure.mgmt.costmanagement.models.ReservationReportSchema + :keyword valid_until: The time at which report URL becomes invalid. + :paramtype valid_until: ~datetime.datetime + """ + super().__init__(**kwargs) self.status = status self.report_url = report_url self.valid_until = valid_until -class PivotProperties(msrest.serialization.Model): +class PivotProperties(_serialization.Model): """Each pivot must contain a 'type' and 'name'. - :param type: Data type to show in view. Possible values include: "Dimension", "TagKey". - :type type: str or ~azure.mgmt.costmanagement.models.PivotType - :param name: Data field to show in view. - :type name: str + :ivar type: Data type to show in view. Known values are: "Dimension" and "TagKey". + :vartype type: str or ~azure.mgmt.costmanagement.models.PivotType + :ivar name: Data field to show in view. + :vartype name: str """ _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - type: Optional[Union[str, "PivotType"]] = None, - name: Optional[str] = None, - **kwargs - ): - super(PivotProperties, self).__init__(**kwargs) + def __init__(self, *, type: Optional[Union[str, "_models.PivotType"]] = None, name: Optional[str] = None, **kwargs): + """ + :keyword type: Data type to show in view. Known values are: "Dimension" and "TagKey". + :paramtype type: str or ~azure.mgmt.costmanagement.models.PivotType + :keyword name: Data field to show in view. + :paramtype name: str + """ + super().__init__(**kwargs) self.type = type self.name = name -class ProxySettingResource(msrest.serialization.Model): - """The Resource model definition. +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Resource Id. + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: Resource name. + :ivar name: The name of the resource. :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". :vartype type: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ProxySettingResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.kind = None - self.type = None + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) -class QueryAggregation(msrest.serialization.Model): +class QueryAggregation(_serialization.Model): """The aggregation expression to be used in the query. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType + :ivar name: The name of the column to aggregate. Required. + :vartype name: str + :ivar function: The name of the aggregation function to use. Required. "Sum" + :vartype function: str or ~azure.mgmt.costmanagement.models.FunctionType """ _validation = { - 'name': {'required': True}, - 'function': {'required': True}, + "name": {"required": True}, + "function": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "function": {"key": "function", "type": "str"}, } - def __init__( - self, - *, - name: str, - function: Union[str, "FunctionType"], - **kwargs - ): - super(QueryAggregation, self).__init__(**kwargs) + def __init__(self, *, name: str, function: Union[str, "_models.FunctionType"], **kwargs): + """ + :keyword name: The name of the column to aggregate. Required. + :paramtype name: str + :keyword function: The name of the aggregation function to use. Required. "Sum" + :paramtype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + super().__init__(**kwargs) self.name = name self.function = function -class QueryColumn(msrest.serialization.Model): - """QueryColumn. +class QueryColumn(_serialization.Model): + """QueryColumn properties. - :param name: The name of column. - :type name: str - :param type: The type of column. - :type type: str + :ivar name: The name of column. + :vartype name: str + :ivar type: The type of column. + :vartype type: str """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - type: Optional[str] = None, - **kwargs - ): - super(QueryColumn, self).__init__(**kwargs) + def __init__(self, *, name: Optional[str] = None, type: Optional[str] = None, **kwargs): + """ + :keyword name: The name of column. + :paramtype name: str + :keyword type: The type of column. + :paramtype type: str + """ + super().__init__(**kwargs) self.name = name self.type = type -class QueryComparisonExpression(msrest.serialization.Model): +class QueryComparisonExpression(_serialization.Model): """The comparison expression to be used in the query. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", - "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] + :ivar name: The name of the column to use in comparison. Required. + :vartype name: str + :ivar operator: The operator to use for comparison. Required. "In" + :vartype operator: str or ~azure.mgmt.costmanagement.models.QueryOperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] """ _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True, "min_items": 1}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, } - def __init__( - self, - *, - name: str, - operator: Union[str, "OperatorType"], - values: List[str], - **kwargs - ): - super(QueryComparisonExpression, self).__init__(**kwargs) + def __init__(self, *, name: str, operator: Union[str, "_models.QueryOperatorType"], values: List[str], **kwargs): + """ + :keyword name: The name of the column to use in comparison. Required. + :paramtype name: str + :keyword operator: The operator to use for comparison. Required. "In" + :paramtype operator: str or ~azure.mgmt.costmanagement.models.QueryOperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) self.name = name self.operator = operator self.values = values -class QueryDataset(msrest.serialization.Model): - """The definition of data present in the query. - - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The - configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each - item in the dictionary is the alias for the aggregated column. Query can have up to 2 - aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group - by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST - documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilter - """ - - _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, - } - - _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilter'}, - } - - def __init__( - self, - *, - granularity: Optional[Union[str, "GranularityType"]] = None, - configuration: Optional["QueryDatasetConfiguration"] = None, - aggregation: Optional[Dict[str, "QueryAggregation"]] = None, - grouping: Optional[List["QueryGrouping"]] = None, - filter: Optional["QueryFilter"] = None, - **kwargs - ): - super(QueryDataset, self).__init__(**kwargs) - self.granularity = granularity - self.configuration = configuration - self.aggregation = aggregation - self.grouping = grouping - self.filter = filter - - -class QueryDatasetAutoGenerated(msrest.serialization.Model): +class QueryDataset(_serialization.Model): """The definition of data present in the query. - :param granularity: The granularity of rows in the query. Possible values include: "Daily". - :type granularity: str or ~azure.mgmt.costmanagement.models.GranularityType - :param configuration: Has configuration information for the data in the export. The + :ivar granularity: The granularity of rows in the query. "Daily" + :vartype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :ivar configuration: Has configuration information for the data in the export. The configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the query. The key of each + :vartype configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration + :ivar aggregation: Dictionary of aggregation expression to use in the query. The key of each item in the dictionary is the alias for the aggregated column. Query can have up to 2 aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] - :param grouping: Array of group by expression to use in the query. Query can have up to 2 group + :vartype aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] + :ivar grouping: Array of group by expression to use in the query. Query can have up to 2 group by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] - :param filter: The filter expression to use in the query. Please reference our Query API REST + :vartype grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] + :ivar filter: The filter expression to use in the query. Please reference our Query API REST documentation for how to properly format the filter. - :type filter: ~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated + :vartype filter: ~azure.mgmt.costmanagement.models.QueryFilter """ _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, + "grouping": {"max_items": 2, "min_items": 0}, } _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'QueryDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{QueryAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[QueryGrouping]'}, - 'filter': {'key': 'filter', 'type': 'QueryFilterAutoGenerated'}, + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "QueryDatasetConfiguration"}, + "aggregation": {"key": "aggregation", "type": "{QueryAggregation}"}, + "grouping": {"key": "grouping", "type": "[QueryGrouping]"}, + "filter": {"key": "filter", "type": "QueryFilter"}, } def __init__( self, *, - granularity: Optional[Union[str, "GranularityType"]] = None, - configuration: Optional["QueryDatasetConfiguration"] = None, - aggregation: Optional[Dict[str, "QueryAggregation"]] = None, - grouping: Optional[List["QueryGrouping"]] = None, - filter: Optional["QueryFilterAutoGenerated"] = None, + granularity: Optional[Union[str, "_models.GranularityType"]] = None, + configuration: Optional["_models.QueryDatasetConfiguration"] = None, + aggregation: Optional[Dict[str, "_models.QueryAggregation"]] = None, + grouping: Optional[List["_models.QueryGrouping"]] = None, + filter: Optional["_models.QueryFilter"] = None, # pylint: disable=redefined-builtin **kwargs ): - super(QueryDatasetAutoGenerated, self).__init__(**kwargs) + """ + :keyword granularity: The granularity of rows in the query. "Daily" + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.GranularityType + :keyword configuration: Has configuration information for the data in the export. The + configuration will be ignored if aggregation and grouping are provided. + :paramtype configuration: ~azure.mgmt.costmanagement.models.QueryDatasetConfiguration + :keyword aggregation: Dictionary of aggregation expression to use in the query. The key of each + item in the dictionary is the alias for the aggregated column. Query can have up to 2 + aggregation clauses. + :paramtype aggregation: dict[str, ~azure.mgmt.costmanagement.models.QueryAggregation] + :keyword grouping: Array of group by expression to use in the query. Query can have up to 2 + group by clauses. + :paramtype grouping: list[~azure.mgmt.costmanagement.models.QueryGrouping] + :keyword filter: The filter expression to use in the query. Please reference our Query API REST + documentation for how to properly format the filter. + :paramtype filter: ~azure.mgmt.costmanagement.models.QueryFilter + """ + super().__init__(**kwargs) self.granularity = granularity self.configuration = configuration self.aggregation = aggregation @@ -1585,192 +3791,174 @@ def __init__( self.filter = filter -class QueryDatasetConfiguration(msrest.serialization.Model): +class QueryDatasetConfiguration(_serialization.Model): """The configuration of dataset in the query. - :param columns: Array of column names to be included in the query. Any valid query column name + :ivar columns: Array of column names to be included in the query. Any valid query column name is allowed. If not provided, then query includes all columns. - :type columns: list[str] + :vartype columns: list[str] """ _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, + "columns": {"key": "columns", "type": "[str]"}, } - def __init__( - self, - *, - columns: Optional[List[str]] = None, - **kwargs - ): - super(QueryDatasetConfiguration, self).__init__(**kwargs) + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the query. Any valid query column + name is allowed. If not provided, then query includes all columns. + :paramtype columns: list[str] + """ + super().__init__(**kwargs) self.columns = columns -class QueryDefinition(msrest.serialization.Model): +class QueryDefinition(_serialization.Model): """The definition of a query. All required parameters must be populated in order to send to Azure. - :param type: Required. The type of the query. Possible values include: "Usage", "ActualCost", + :ivar type: The type of the query. Required. Known values are: "Usage", "ActualCost", and "AmortizedCost". - :type type: str or ~azure.mgmt.costmanagement.models.ExportType - :param timeframe: Required. The time frame for pulling data for the query. If custom, then a - specific time period must be provided. Possible values include: "MonthToDate", - "BillingMonthToDate", "TheLastMonth", "TheLastBillingMonth", "WeekToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType - :param time_period: Has time period for pulling data for the query. - :type time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod - :param dataset: Required. Has definition for data in this query. - :type dataset: ~azure.mgmt.costmanagement.models.QueryDataset + :vartype type: str or ~azure.mgmt.costmanagement.models.ExportType + :ivar timeframe: The time frame for pulling data for the query. If custom, then a specific time + period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :ivar time_period: Has time period for pulling data for the query. + :vartype time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod + :ivar dataset: Has definition for data in this query. Required. + :vartype dataset: ~azure.mgmt.costmanagement.models.QueryDataset """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'required': True}, + "type": {"required": True}, + "timeframe": {"required": True}, + "dataset": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, + "type": {"key": "type", "type": "str"}, + "timeframe": {"key": "timeframe", "type": "str"}, + "time_period": {"key": "timePeriod", "type": "QueryTimePeriod"}, + "dataset": {"key": "dataset", "type": "QueryDataset"}, } def __init__( self, *, - type: Union[str, "ExportType"], - timeframe: Union[str, "TimeframeType"], - dataset: "QueryDataset", - time_period: Optional["QueryTimePeriod"] = None, + type: Union[str, "_models.ExportType"], + timeframe: Union[str, "_models.TimeframeType"], + dataset: "_models.QueryDataset", + time_period: Optional["_models.QueryTimePeriod"] = None, **kwargs ): - super(QueryDefinition, self).__init__(**kwargs) + """ + :keyword type: The type of the query. Required. Known values are: "Usage", "ActualCost", and + "AmortizedCost". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ExportType + :keyword timeframe: The time frame for pulling data for the query. If custom, then a specific + time period must be provided. Required. Known values are: "MonthToDate", "BillingMonthToDate", + "TheLastMonth", "TheLastBillingMonth", "WeekToDate", and "Custom". + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.TimeframeType + :keyword time_period: Has time period for pulling data for the query. + :paramtype time_period: ~azure.mgmt.costmanagement.models.QueryTimePeriod + :keyword dataset: Has definition for data in this query. Required. + :paramtype dataset: ~azure.mgmt.costmanagement.models.QueryDataset + """ + super().__init__(**kwargs) self.type = type self.timeframe = timeframe self.time_period = time_period self.dataset = dataset -class QueryFilter(msrest.serialization.Model): - """The filter expression to be used in the export. - - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - """ - - _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, - } - - _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilter]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, - } - - def __init__( - self, - *, - and_property: Optional[List["QueryFilter"]] = None, - or_property: Optional[List["QueryFilter"]] = None, - dimensions: Optional["QueryComparisonExpression"] = None, - tags: Optional["QueryComparisonExpression"] = None, - **kwargs - ): - super(QueryFilter, self).__init__(**kwargs) - self.and_property = and_property - self.or_property = or_property - self.dimensions = dimensions - self.tags = tags - - -class QueryFilterAutoGenerated(msrest.serialization.Model): +class QueryFilter(_serialization.Model): """The filter expression to be used in the export. - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.QueryFilterAutoGenerated] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + :vartype and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :ivar or_property: The logical "OR" expression. Must have at least 2 items. + :vartype or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :ivar dimensions: Has comparison expression for a dimension. + :vartype dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + :ivar tags: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression """ _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, + "and_property": {"min_items": 2}, + "or_property": {"min_items": 2}, } _attribute_map = { - 'and_property': {'key': 'and', 'type': '[QueryFilterAutoGenerated]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilterAutoGenerated]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, + "and_property": {"key": "and", "type": "[QueryFilter]"}, + "or_property": {"key": "or", "type": "[QueryFilter]"}, + "dimensions": {"key": "dimensions", "type": "QueryComparisonExpression"}, + "tags": {"key": "tags", "type": "QueryComparisonExpression"}, } def __init__( self, *, - and_property: Optional[List["QueryFilterAutoGenerated"]] = None, - or_property: Optional[List["QueryFilterAutoGenerated"]] = None, - dimensions: Optional["QueryComparisonExpression"] = None, - tags: Optional["QueryComparisonExpression"] = None, + and_property: Optional[List["_models.QueryFilter"]] = None, + or_property: Optional[List["_models.QueryFilter"]] = None, + dimensions: Optional["_models.QueryComparisonExpression"] = None, + tags: Optional["_models.QueryComparisonExpression"] = None, **kwargs ): - super(QueryFilterAutoGenerated, self).__init__(**kwargs) + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :keyword or_property: The logical "OR" expression. Must have at least 2 items. + :paramtype or_property: list[~azure.mgmt.costmanagement.models.QueryFilter] + :keyword dimensions: Has comparison expression for a dimension. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + :keyword tags: Has comparison expression for a tag. + :paramtype tags: ~azure.mgmt.costmanagement.models.QueryComparisonExpression + """ + super().__init__(**kwargs) self.and_property = and_property self.or_property = or_property self.dimensions = dimensions self.tags = tags -class QueryGrouping(msrest.serialization.Model): +class QueryGrouping(_serialization.Model): """The group by expression to be used in the query. All required parameters must be populated in order to send to Azure. - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.QueryColumnType - :param name: Required. The name of the column to group. - :type name: str + :ivar type: Has type of the column to group. Required. Known values are: "Tag" and "Dimension". + :vartype type: str or ~azure.mgmt.costmanagement.models.QueryColumnType + :ivar name: The name of the column to group. Required. + :vartype name: str """ _validation = { - 'type': {'required': True}, - 'name': {'required': True}, + "type": {"required": True}, + "name": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - type: Union[str, "QueryColumnType"], - name: str, - **kwargs - ): - super(QueryGrouping, self).__init__(**kwargs) + def __init__(self, *, type: Union[str, "_models.QueryColumnType"], name: str, **kwargs): + """ + :keyword type: Has type of the column to group. Required. Known values are: "Tag" and + "Dimension". + :paramtype type: str or ~azure.mgmt.costmanagement.models.QueryColumnType + :keyword name: The name of the column to group. Required. + :paramtype name: str + """ + super().__init__(**kwargs) self.type = type self.name = name -class QueryResult(Resource): +class QueryResult(CostManagementResource): """Result of query. It contains all columns listed under groupings and aggregation. Variables are only populated by the server, and will be ignored when sending a request. @@ -1781,217 +3969,274 @@ class QueryResult(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :ivar tags: A set of tags. Resource tags. - :vartype tags: dict[str, str] - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be - used to determine whether the user is updating the latest version or not. - :type e_tag: str - :ivar location: Resource location. + :ivar location: Location of the resource. :vartype location: str - :ivar sku: Resource SKU. + :ivar sku: SKU of the resource. :vartype sku: str - :param next_link: The link (url) to the next page of results. - :type next_link: str - :param columns: Array of columns. - :type columns: list[~azure.mgmt.costmanagement.models.QueryColumn] - :param rows: Array of rows. - :type rows: list[list[any]] + :ivar e_tag: ETag of the resource. + :vartype e_tag: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar next_link: The link (url) to the next page of results. + :vartype next_link: str + :ivar columns: Array of columns. + :vartype columns: list[~azure.mgmt.costmanagement.models.QueryColumn] + :ivar rows: Array of rows. + :vartype rows: list[list[any]] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': True}, - 'location': {'readonly': True}, - 'sku': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "sku": {"readonly": True}, + "e_tag": {"readonly": True}, + "tags": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'str'}, - 'next_link': {'key': 'properties.nextLink', 'type': 'str'}, - 'columns': {'key': 'properties.columns', 'type': '[QueryColumn]'}, - 'rows': {'key': 'properties.rows', 'type': '[[object]]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "next_link": {"key": "properties.nextLink", "type": "str"}, + "columns": {"key": "properties.columns", "type": "[QueryColumn]"}, + "rows": {"key": "properties.rows", "type": "[[object]]"}, } def __init__( self, *, - e_tag: Optional[str] = None, next_link: Optional[str] = None, - columns: Optional[List["QueryColumn"]] = None, + columns: Optional[List["_models.QueryColumn"]] = None, rows: Optional[List[List[Any]]] = None, **kwargs ): - super(QueryResult, self).__init__(**kwargs) - self.e_tag = e_tag - self.location = None - self.sku = None + """ + :keyword next_link: The link (url) to the next page of results. + :paramtype next_link: str + :keyword columns: Array of columns. + :paramtype columns: list[~azure.mgmt.costmanagement.models.QueryColumn] + :keyword rows: Array of rows. + :paramtype rows: list[list[any]] + """ + super().__init__(**kwargs) self.next_link = next_link self.columns = columns self.rows = rows -class QueryTimePeriod(msrest.serialization.Model): +class QueryTimePeriod(_serialization.Model): """The start and end date for pulling data for the query. All required parameters must be populated in order to send to Azure. - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime + :ivar from_property: The start date to pull data from. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date to pull data to. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, } - def __init__( - self, - *, - from_property: datetime.datetime, - to: datetime.datetime, - **kwargs - ): - super(QueryTimePeriod, self).__init__(**kwargs) + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date to pull data from. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date to pull data to. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) self.from_property = from_property self.to = to -class ReportConfigAggregation(msrest.serialization.Model): +class RecommendationUsageDetails(_serialization.Model): + """On-demand charges between firstConsumptionDate and lastConsumptionDate that were used for computing benefit recommendations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar usage_grain: The grain of the usage. Supported values: 'Hourly'. Known values are: + "Hourly", "Daily", and "Monthly". + :vartype usage_grain: str or ~azure.mgmt.costmanagement.models.Grain + :ivar charges: On-demand charges for each hour between firstConsumptionDate and + lastConsumptionDate that were used for computing benefit recommendations. + :vartype charges: list[float] + """ + + _validation = { + "charges": {"readonly": True}, + } + + _attribute_map = { + "usage_grain": {"key": "usageGrain", "type": "str"}, + "charges": {"key": "charges", "type": "[float]"}, + } + + def __init__(self, *, usage_grain: Optional[Union[str, "_models.Grain"]] = None, **kwargs): + """ + :keyword usage_grain: The grain of the usage. Supported values: 'Hourly'. Known values are: + "Hourly", "Daily", and "Monthly". + :paramtype usage_grain: str or ~azure.mgmt.costmanagement.models.Grain + """ + super().__init__(**kwargs) + self.usage_grain = usage_grain + self.charges = None + + +class ReportConfigAggregation(_serialization.Model): """The aggregation expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to aggregate. - :type name: str - :param function: Required. The name of the aggregation function to use. Possible values - include: "Avg", "Max", "Min", "Sum". - :type function: str or ~azure.mgmt.costmanagement.models.FunctionType + :ivar name: The name of the column to aggregate. Required. + :vartype name: str + :ivar function: The name of the aggregation function to use. Required. "Sum" + :vartype function: str or ~azure.mgmt.costmanagement.models.FunctionType """ _validation = { - 'name': {'required': True}, - 'function': {'required': True}, + "name": {"required": True}, + "function": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "function": {"key": "function", "type": "str"}, } - def __init__( - self, - *, - name: str, - function: Union[str, "FunctionType"], - **kwargs - ): - super(ReportConfigAggregation, self).__init__(**kwargs) + def __init__(self, *, name: str, function: Union[str, "_models.FunctionType"], **kwargs): + """ + :keyword name: The name of the column to aggregate. Required. + :paramtype name: str + :keyword function: The name of the aggregation function to use. Required. "Sum" + :paramtype function: str or ~azure.mgmt.costmanagement.models.FunctionType + """ + super().__init__(**kwargs) self.name = name self.function = function -class ReportConfigComparisonExpression(msrest.serialization.Model): +class ReportConfigComparisonExpression(_serialization.Model): """The comparison expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param name: Required. The name of the column to use in comparison. - :type name: str - :param operator: Required. The operator to use for comparison. Possible values include: "In", + :ivar name: The name of the column to use in comparison. Required. + :vartype name: str + :ivar operator: The operator to use for comparison. Required. Known values are: "In" and "Contains". - :type operator: str or ~azure.mgmt.costmanagement.models.OperatorType - :param values: Required. Array of values to use for comparison. - :type values: list[str] + :vartype operator: str or ~azure.mgmt.costmanagement.models.OperatorType + :ivar values: Array of values to use for comparison. Required. + :vartype values: list[str] """ _validation = { - 'name': {'required': True}, - 'operator': {'required': True}, - 'values': {'required': True, 'min_items': 1}, + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True, "min_items": 1}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'operator': {'key': 'operator', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, } - def __init__( - self, - *, - name: str, - operator: Union[str, "OperatorType"], - values: List[str], - **kwargs - ): - super(ReportConfigComparisonExpression, self).__init__(**kwargs) + def __init__(self, *, name: str, operator: Union[str, "_models.OperatorType"], values: List[str], **kwargs): + """ + :keyword name: The name of the column to use in comparison. Required. + :paramtype name: str + :keyword operator: The operator to use for comparison. Required. Known values are: "In" and + "Contains". + :paramtype operator: str or ~azure.mgmt.costmanagement.models.OperatorType + :keyword values: Array of values to use for comparison. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) self.name = name self.operator = operator self.values = values -class ReportConfigDataset(msrest.serialization.Model): +class ReportConfigDataset(_serialization.Model): """The definition of data present in the report. - :param granularity: The granularity of rows in the report. Possible values include: "Daily", + :ivar granularity: The granularity of rows in the report. Known values are: "Daily" and "Monthly". - :type granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType - :param configuration: Has configuration information for the data in the report. The + :vartype granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType + :ivar configuration: Has configuration information for the data in the report. The configuration will be ignored if aggregation and grouping are provided. - :type configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration - :param aggregation: Dictionary of aggregation expression to use in the report. The key of each + :vartype configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration + :ivar aggregation: Dictionary of aggregation expression to use in the report. The key of each item in the dictionary is the alias for the aggregated column. Report can have up to 2 aggregation clauses. - :type aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] - :param grouping: Array of group by expression to use in the report. Report can have up to 2 + :vartype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] + :ivar grouping: Array of group by expression to use in the report. Report can have up to 2 group by clauses. - :type grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] - :param sorting: Array of order by expression to use in the report. - :type sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] - :param filter: Has filter expression to use in the report. - :type filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter + :vartype grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] + :ivar sorting: Array of order by expression to use in the report. + :vartype sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] + :ivar filter: Has filter expression to use in the report. + :vartype filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter """ _validation = { - 'grouping': {'max_items': 2, 'min_items': 0}, + "grouping": {"max_items": 2, "min_items": 0}, } _attribute_map = { - 'granularity': {'key': 'granularity', 'type': 'str'}, - 'configuration': {'key': 'configuration', 'type': 'ReportConfigDatasetConfiguration'}, - 'aggregation': {'key': 'aggregation', 'type': '{ReportConfigAggregation}'}, - 'grouping': {'key': 'grouping', 'type': '[ReportConfigGrouping]'}, - 'sorting': {'key': 'sorting', 'type': '[ReportConfigSorting]'}, - 'filter': {'key': 'filter', 'type': 'ReportConfigFilter'}, + "granularity": {"key": "granularity", "type": "str"}, + "configuration": {"key": "configuration", "type": "ReportConfigDatasetConfiguration"}, + "aggregation": {"key": "aggregation", "type": "{ReportConfigAggregation}"}, + "grouping": {"key": "grouping", "type": "[ReportConfigGrouping]"}, + "sorting": {"key": "sorting", "type": "[ReportConfigSorting]"}, + "filter": {"key": "filter", "type": "ReportConfigFilter"}, } def __init__( self, *, - granularity: Optional[Union[str, "ReportGranularityType"]] = None, - configuration: Optional["ReportConfigDatasetConfiguration"] = None, - aggregation: Optional[Dict[str, "ReportConfigAggregation"]] = None, - grouping: Optional[List["ReportConfigGrouping"]] = None, - sorting: Optional[List["ReportConfigSorting"]] = None, - filter: Optional["ReportConfigFilter"] = None, + granularity: Optional[Union[str, "_models.ReportGranularityType"]] = None, + configuration: Optional["_models.ReportConfigDatasetConfiguration"] = None, + aggregation: Optional[Dict[str, "_models.ReportConfigAggregation"]] = None, + grouping: Optional[List["_models.ReportConfigGrouping"]] = None, + sorting: Optional[List["_models.ReportConfigSorting"]] = None, + filter: Optional["_models.ReportConfigFilter"] = None, # pylint: disable=redefined-builtin **kwargs ): - super(ReportConfigDataset, self).__init__(**kwargs) + """ + :keyword granularity: The granularity of rows in the report. Known values are: "Daily" and + "Monthly". + :paramtype granularity: str or ~azure.mgmt.costmanagement.models.ReportGranularityType + :keyword configuration: Has configuration information for the data in the report. The + configuration will be ignored if aggregation and grouping are provided. + :paramtype configuration: ~azure.mgmt.costmanagement.models.ReportConfigDatasetConfiguration + :keyword aggregation: Dictionary of aggregation expression to use in the report. The key of + each item in the dictionary is the alias for the aggregated column. Report can have up to 2 + aggregation clauses. + :paramtype aggregation: dict[str, ~azure.mgmt.costmanagement.models.ReportConfigAggregation] + :keyword grouping: Array of group by expression to use in the report. Report can have up to 2 + group by clauses. + :paramtype grouping: list[~azure.mgmt.costmanagement.models.ReportConfigGrouping] + :keyword sorting: Array of order by expression to use in the report. + :paramtype sorting: list[~azure.mgmt.costmanagement.models.ReportConfigSorting] + :keyword filter: Has filter expression to use in the report. + :paramtype filter: ~azure.mgmt.costmanagement.models.ReportConfigFilter + """ + super().__init__(**kwargs) self.granularity = granularity self.configuration = configuration self.aggregation = aggregation @@ -2000,287 +4245,985 @@ def __init__( self.filter = filter -class ReportConfigDatasetConfiguration(msrest.serialization.Model): +class ReportConfigDatasetConfiguration(_serialization.Model): """The configuration of dataset in the report. - :param columns: Array of column names to be included in the report. Any valid report column - name is allowed. If not provided, then report includes all columns. - :type columns: list[str] + :ivar columns: Array of column names to be included in the report. Any valid report column name + is allowed. If not provided, then report includes all columns. + :vartype columns: list[str] """ _attribute_map = { - 'columns': {'key': 'columns', 'type': '[str]'}, + "columns": {"key": "columns", "type": "[str]"}, } - def __init__( - self, - *, - columns: Optional[List[str]] = None, - **kwargs - ): - super(ReportConfigDatasetConfiguration, self).__init__(**kwargs) + def __init__(self, *, columns: Optional[List[str]] = None, **kwargs): + """ + :keyword columns: Array of column names to be included in the report. Any valid report column + name is allowed. If not provided, then report includes all columns. + :paramtype columns: list[str] + """ + super().__init__(**kwargs) self.columns = columns -class ReportConfigFilter(msrest.serialization.Model): +class ReportConfigFilter(_serialization.Model): """The filter expression to be used in the report. - :param and_property: The logical "AND" expression. Must have at least 2 items. - :type and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param or_property: The logical "OR" expression. Must have at least 2 items. - :type or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] - :param dimensions: Has comparison expression for a dimension. - :type dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tags: A set of tags. Has comparison expression for a tag. - :type tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_key: Has comparison expression for a tag key. - :type tag_key: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression - :param tag_value: Has comparison expression for a tag value. - :type tag_value: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + :ivar and_property: The logical "AND" expression. Must have at least 2 items. + :vartype and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :ivar or_property: The logical "OR" expression. Must have at least 2 items. + :vartype or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :ivar dimensions: Has comparison expression for a dimension. + :vartype dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + :ivar tags: Has comparison expression for a tag. + :vartype tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression """ _validation = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, + "and_property": {"min_items": 2}, + "or_property": {"min_items": 2}, } _attribute_map = { - 'and_property': {'key': 'and', 'type': '[ReportConfigFilter]'}, - 'or_property': {'key': 'or', 'type': '[ReportConfigFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'ReportConfigComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'ReportConfigComparisonExpression'}, - 'tag_key': {'key': 'tagKey', 'type': 'ReportConfigComparisonExpression'}, - 'tag_value': {'key': 'tagValue', 'type': 'ReportConfigComparisonExpression'}, + "and_property": {"key": "and", "type": "[ReportConfigFilter]"}, + "or_property": {"key": "or", "type": "[ReportConfigFilter]"}, + "dimensions": {"key": "dimensions", "type": "ReportConfigComparisonExpression"}, + "tags": {"key": "tags", "type": "ReportConfigComparisonExpression"}, } def __init__( self, *, - and_property: Optional[List["ReportConfigFilter"]] = None, - or_property: Optional[List["ReportConfigFilter"]] = None, - dimensions: Optional["ReportConfigComparisonExpression"] = None, - tags: Optional["ReportConfigComparisonExpression"] = None, - tag_key: Optional["ReportConfigComparisonExpression"] = None, - tag_value: Optional["ReportConfigComparisonExpression"] = None, + and_property: Optional[List["_models.ReportConfigFilter"]] = None, + or_property: Optional[List["_models.ReportConfigFilter"]] = None, + dimensions: Optional["_models.ReportConfigComparisonExpression"] = None, + tags: Optional["_models.ReportConfigComparisonExpression"] = None, **kwargs ): - super(ReportConfigFilter, self).__init__(**kwargs) + """ + :keyword and_property: The logical "AND" expression. Must have at least 2 items. + :paramtype and_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :keyword or_property: The logical "OR" expression. Must have at least 2 items. + :paramtype or_property: list[~azure.mgmt.costmanagement.models.ReportConfigFilter] + :keyword dimensions: Has comparison expression for a dimension. + :paramtype dimensions: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + :keyword tags: Has comparison expression for a tag. + :paramtype tags: ~azure.mgmt.costmanagement.models.ReportConfigComparisonExpression + """ + super().__init__(**kwargs) self.and_property = and_property self.or_property = or_property self.dimensions = dimensions self.tags = tags - self.tag_key = tag_key - self.tag_value = tag_value -class ReportConfigGrouping(msrest.serialization.Model): +class ReportConfigGrouping(_serialization.Model): """The group by expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param type: Required. Has type of the column to group. Possible values include: "Tag", - "Dimension". - :type type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType - :param name: Required. The name of the column to group. This version supports subscription - lowest possible grain. - :type name: str + :ivar type: Has type of the column to group. Required. Known values are: "Tag" and "Dimension". + :vartype type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType + :ivar name: The name of the column to group. This version supports subscription lowest possible + grain. Required. + :vartype name: str """ _validation = { - 'type': {'required': True}, - 'name': {'required': True}, + "type": {"required": True}, + "name": {"required": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - type: Union[str, "ReportConfigColumnType"], - name: str, - **kwargs - ): - super(ReportConfigGrouping, self).__init__(**kwargs) + def __init__(self, *, type: Union[str, "_models.ReportConfigColumnType"], name: str, **kwargs): + """ + :keyword type: Has type of the column to group. Required. Known values are: "Tag" and + "Dimension". + :paramtype type: str or ~azure.mgmt.costmanagement.models.ReportConfigColumnType + :keyword name: The name of the column to group. This version supports subscription lowest + possible grain. Required. + :paramtype name: str + """ + super().__init__(**kwargs) self.type = type self.name = name -class ReportConfigSorting(msrest.serialization.Model): +class ReportConfigSorting(_serialization.Model): """The order by expression to be used in the report. All required parameters must be populated in order to send to Azure. - :param direction: Direction of sort. Possible values include: "Ascending", "Descending". - :type direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingDirection - :param name: Required. The name of the column to sort. - :type name: str + :ivar direction: Direction of sort. Known values are: "Ascending" and "Descending". + :vartype direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingType + :ivar name: The name of the column to sort. Required. + :vartype name: str """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'direction': {'key': 'direction', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, + "direction": {"key": "direction", "type": "str"}, + "name": {"key": "name", "type": "str"}, } def __init__( - self, - *, - name: str, - direction: Optional[Union[str, "ReportConfigSortingDirection"]] = None, - **kwargs + self, *, name: str, direction: Optional[Union[str, "_models.ReportConfigSortingType"]] = None, **kwargs ): - super(ReportConfigSorting, self).__init__(**kwargs) + """ + :keyword direction: Direction of sort. Known values are: "Ascending" and "Descending". + :paramtype direction: str or ~azure.mgmt.costmanagement.models.ReportConfigSortingType + :keyword name: The name of the column to sort. Required. + :paramtype name: str + """ + super().__init__(**kwargs) self.direction = direction self.name = name -class ReportConfigTimePeriod(msrest.serialization.Model): +class ReportConfigTimePeriod(_serialization.Model): """The start and end date for pulling data for the report. All required parameters must be populated in order to send to Azure. - :param from_property: Required. The start date to pull data from. - :type from_property: ~datetime.datetime - :param to: Required. The end date to pull data to. - :type to: ~datetime.datetime + :ivar from_property: The start date to pull data from. Required. + :vartype from_property: ~datetime.datetime + :ivar to: The end date to pull data to. Required. + :vartype to: ~datetime.datetime """ _validation = { - 'from_property': {'required': True}, - 'to': {'required': True}, + "from_property": {"required": True}, + "to": {"required": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, + "from_property": {"key": "from", "type": "iso-8601"}, + "to": {"key": "to", "type": "iso-8601"}, } - def __init__( - self, - *, - from_property: datetime.datetime, - to: datetime.datetime, - **kwargs - ): - super(ReportConfigTimePeriod, self).__init__(**kwargs) + def __init__(self, *, from_property: datetime.datetime, to: datetime.datetime, **kwargs): + """ + :keyword from_property: The start date to pull data from. Required. + :paramtype from_property: ~datetime.datetime + :keyword to: The end date to pull data to. Required. + :paramtype to: ~datetime.datetime + """ + super().__init__(**kwargs) self.from_property = from_property self.to = to -class Setting(ProxySettingResource): - """State of the myscope setting. +class SavingsPlanUtilizationSummary(BenefitUtilizationSummary): # pylint: disable=too-many-instance-attributes + """Savings plan utilization summary resource. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Resource Id. + All required parameters must be populated in order to send to Azure. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str - :ivar name: Resource name. + :ivar name: The name of the resource. :vartype name: str - :ivar kind: Resource kind. - :vartype kind: str - :ivar type: Resource type. + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Supported values: 'SavingsPlan'. Required. Known values are: "IncludedQuantity", + "Reservation", and "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar arm_sku_name: ARM SKU name. For example, 'Compute_Savings_Plan' for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of the benefit. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :vartype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar usage_date: Date corresponding to the utilization summary record. If the grain of data is + monthly, value for this field will be first day of the month. + :vartype usage_date: ~datetime.datetime + :ivar avg_utilization_percentage: This is the average hourly utilization for each date range + that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > + 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per + benefit id for each day. For a single day, the avgUtilizationPercentage value will be equal to + the average of the set of values where the set contains 24 utilization percentage entries one + for each hour in a specific day. + :vartype avg_utilization_percentage: float + :ivar min_utilization_percentage: This is the minimum hourly utilization for each date range + that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > + 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per + benefit id for each day. For a single day, the minUtilizationPercentage value will be equal to + the smallest in the set of values where the set contains 24 utilization percentage entries one + for each hour in a specific day. If on the day 2022-10-18, the lowest utilization percentage + was 10% at hour 4, then the value for the minUtilizationPercentage in the response will be 10%. + :vartype min_utilization_percentage: float + :ivar max_utilization_percentage: This is the maximum hourly utilization for each date range + that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > + 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per + benefit id for each day. For a single day, the maxUtilizationPercentage value will be equal to + the largest in the set of values where the set contains 24 utilization percentage entries one + for each hour in a specific day. If on the day 2022-10-18, the largest utilization percentage + was 90% at hour 5, then the value for the maxUtilizationPercentage in the response will be 90%. + :vartype max_utilization_percentage: float + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True}, + "arm_sku_name": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_order_id": {"readonly": True}, + "usage_date": {"readonly": True}, + "avg_utilization_percentage": {"readonly": True}, + "min_utilization_percentage": {"readonly": True}, + "max_utilization_percentage": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "arm_sku_name": {"key": "properties.armSkuName", "type": "str"}, + "benefit_id": {"key": "properties.benefitId", "type": "str"}, + "benefit_order_id": {"key": "properties.benefitOrderId", "type": "str"}, + "benefit_type": {"key": "properties.benefitType", "type": "str"}, + "usage_date": {"key": "properties.usageDate", "type": "iso-8601"}, + "avg_utilization_percentage": {"key": "properties.avgUtilizationPercentage", "type": "float"}, + "min_utilization_percentage": {"key": "properties.minUtilizationPercentage", "type": "float"}, + "max_utilization_percentage": {"key": "properties.maxUtilizationPercentage", "type": "float"}, + } + + def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :paramtype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(**kwargs) + self.kind = "SavingsPlan" # type: str + self.arm_sku_name = None + self.benefit_id = None + self.benefit_order_id = None + self.benefit_type = benefit_type + self.usage_date = None + self.avg_utilization_percentage = None + self.min_utilization_percentage = None + self.max_utilization_percentage = None + + +class SavingsPlanUtilizationSummaryProperties(BenefitUtilizationSummaryProperties): + """Savings plan utilization summary properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar arm_sku_name: ARM SKU name. For example, 'Compute_Savings_Plan' for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of the benefit. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :vartype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + :ivar usage_date: Date corresponding to the utilization summary record. If the grain of data is + monthly, value for this field will be first day of the month. + :vartype usage_date: ~datetime.datetime + :ivar avg_utilization_percentage: This is the average hourly utilization for each date range + that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > + 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per + benefit id for each day. For a single day, the avgUtilizationPercentage value will be equal to + the average of the set of values where the set contains 24 utilization percentage entries one + for each hour in a specific day. + :vartype avg_utilization_percentage: float + :ivar min_utilization_percentage: This is the minimum hourly utilization for each date range + that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > + 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per + benefit id for each day. For a single day, the minUtilizationPercentage value will be equal to + the smallest in the set of values where the set contains 24 utilization percentage entries one + for each hour in a specific day. If on the day 2022-10-18, the lowest utilization percentage + was 10% at hour 4, then the value for the minUtilizationPercentage in the response will be 10%. + :vartype min_utilization_percentage: float + :ivar max_utilization_percentage: This is the maximum hourly utilization for each date range + that corresponds to given grain (Daily, Monthly). Suppose the API call is for usageDate > + 2022-10-01 and usageDate < 2022-10-31 at a daily granularity. There will be one record per + benefit id for each day. For a single day, the maxUtilizationPercentage value will be equal to + the largest in the set of values where the set contains 24 utilization percentage entries one + for each hour in a specific day. If on the day 2022-10-18, the largest utilization percentage + was 90% at hour 5, then the value for the maxUtilizationPercentage in the response will be 90%. + :vartype max_utilization_percentage: float + """ + + _validation = { + "arm_sku_name": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_order_id": {"readonly": True}, + "usage_date": {"readonly": True}, + "avg_utilization_percentage": {"readonly": True}, + "min_utilization_percentage": {"readonly": True}, + "max_utilization_percentage": {"readonly": True}, + } + + _attribute_map = { + "arm_sku_name": {"key": "armSkuName", "type": "str"}, + "benefit_id": {"key": "benefitId", "type": "str"}, + "benefit_order_id": {"key": "benefitOrderId", "type": "str"}, + "benefit_type": {"key": "benefitType", "type": "str"}, + "usage_date": {"key": "usageDate", "type": "iso-8601"}, + "avg_utilization_percentage": {"key": "avgUtilizationPercentage", "type": "float"}, + "min_utilization_percentage": {"key": "minUtilizationPercentage", "type": "float"}, + "max_utilization_percentage": {"key": "maxUtilizationPercentage", "type": "float"}, + } + + def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. Supported values: 'SavingsPlan'. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :paramtype benefit_type: str or ~azure.mgmt.costmanagement.models.BenefitKind + """ + super().__init__(benefit_type=benefit_type, **kwargs) + self.avg_utilization_percentage = None + self.min_utilization_percentage = None + self.max_utilization_percentage = None + + +class ScheduledActionProxyResource(ProxyResource): + """The Resource model definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar e_tag: Resource Etag. + :vartype e_tag: str + :ivar kind: Kind of the scheduled action. Known values are: "Email" and "InsightAlert". + :vartype kind: str or ~azure.mgmt.costmanagement.models.ScheduledActionKind + :ivar system_data: Kind of the scheduled action. + :vartype system_data: ~azure.mgmt.costmanagement.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "e_tag": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, *, kind: Optional[Union[str, "_models.ScheduledActionKind"]] = None, **kwargs): + """ + :keyword kind: Kind of the scheduled action. Known values are: "Email" and "InsightAlert". + :paramtype kind: str or ~azure.mgmt.costmanagement.models.ScheduledActionKind + """ + super().__init__(**kwargs) + self.e_tag = None + self.kind = kind + self.system_data = None + + +class ScheduledAction(ScheduledActionProxyResource): # pylint: disable=too-many-instance-attributes + """Scheduled action definition. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". :vartype type: str - :param scope: Sets the default scope the current user will see when they sign into Azure Cost - Management in the Azure portal. - :type scope: str - :param start_on: Indicates what scope Cost Management in the Azure portal should default to. - Allowed values: LastUsed. Possible values include: "LastUsed", "ScopePicker", "SpecificScope". - :type start_on: str or ~azure.mgmt.costmanagement.models.SettingsPropertiesStartOn - :param cache: Array of scopes with additional details used by Cost Management in the Azure - portal. - :type cache: list[~azure.mgmt.costmanagement.models.CacheItem] + :ivar e_tag: Resource Etag. + :vartype e_tag: str + :ivar kind: Kind of the scheduled action. Known values are: "Email" and "InsightAlert". + :vartype kind: str or ~azure.mgmt.costmanagement.models.ScheduledActionKind + :ivar system_data: Kind of the scheduled action. + :vartype system_data: ~azure.mgmt.costmanagement.models.SystemData + :ivar display_name: Scheduled action name. + :vartype display_name: str + :ivar file_destination: Destination format of the view data. This is optional. + :vartype file_destination: ~azure.mgmt.costmanagement.models.FileDestination + :ivar notification: Notification properties based on scheduled action kind. + :vartype notification: ~azure.mgmt.costmanagement.models.NotificationProperties + :ivar notification_email: Email address of the point of contact that should get the unsubscribe + requests and notification emails. + :vartype notification_email: str + :ivar schedule: Schedule of the scheduled action. + :vartype schedule: ~azure.mgmt.costmanagement.models.ScheduleProperties + :ivar scope: Cost Management scope like 'subscriptions/{subscriptionId}' for subscription + scope, 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup + scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account + scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + '/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + ExternalBillingAccount scope, and + '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + ExternalSubscription scope. + :vartype scope: str + :ivar status: Status of the scheduled action. Known values are: "Disabled", "Enabled", and + "Expired". + :vartype status: str or ~azure.mgmt.costmanagement.models.ScheduledActionStatus + :ivar view_id: Cost analysis viewId used for scheduled action. For example, + '/providers/Microsoft.CostManagement/views/swaggerExample'. + :vartype view_id: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'kind': {'readonly': True, 'max_length': 10, 'min_length': 0}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "e_tag": {"readonly": True}, + "system_data": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'start_on': {'key': 'properties.startOn', 'type': 'str'}, - 'cache': {'key': 'properties.cache', 'type': '[CacheItem]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "file_destination": {"key": "properties.fileDestination", "type": "FileDestination"}, + "notification": {"key": "properties.notification", "type": "NotificationProperties"}, + "notification_email": {"key": "properties.notificationEmail", "type": "str"}, + "schedule": {"key": "properties.schedule", "type": "ScheduleProperties"}, + "scope": {"key": "properties.scope", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "view_id": {"key": "properties.viewId", "type": "str"}, } def __init__( self, *, + kind: Optional[Union[str, "_models.ScheduledActionKind"]] = None, + display_name: Optional[str] = None, + file_destination: Optional["_models.FileDestination"] = None, + notification: Optional["_models.NotificationProperties"] = None, + notification_email: Optional[str] = None, + schedule: Optional["_models.ScheduleProperties"] = None, scope: Optional[str] = None, - start_on: Optional[Union[str, "SettingsPropertiesStartOn"]] = None, - cache: Optional[List["CacheItem"]] = None, + status: Optional[Union[str, "_models.ScheduledActionStatus"]] = None, + view_id: Optional[str] = None, **kwargs ): - super(Setting, self).__init__(**kwargs) + """ + :keyword kind: Kind of the scheduled action. Known values are: "Email" and "InsightAlert". + :paramtype kind: str or ~azure.mgmt.costmanagement.models.ScheduledActionKind + :keyword display_name: Scheduled action name. + :paramtype display_name: str + :keyword file_destination: Destination format of the view data. This is optional. + :paramtype file_destination: ~azure.mgmt.costmanagement.models.FileDestination + :keyword notification: Notification properties based on scheduled action kind. + :paramtype notification: ~azure.mgmt.costmanagement.models.NotificationProperties + :keyword notification_email: Email address of the point of contact that should get the + unsubscribe requests and notification emails. + :paramtype notification_email: str + :keyword schedule: Schedule of the scheduled action. + :paramtype schedule: ~azure.mgmt.costmanagement.models.ScheduleProperties + :keyword scope: Cost Management scope like 'subscriptions/{subscriptionId}' for subscription + scope, 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup + scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account + scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + '/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + ExternalBillingAccount scope, and + '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + ExternalSubscription scope. + :paramtype scope: str + :keyword status: Status of the scheduled action. Known values are: "Disabled", "Enabled", and + "Expired". + :paramtype status: str or ~azure.mgmt.costmanagement.models.ScheduledActionStatus + :keyword view_id: Cost analysis viewId used for scheduled action. For example, + '/providers/Microsoft.CostManagement/views/swaggerExample'. + :paramtype view_id: str + """ + super().__init__(kind=kind, **kwargs) + self.display_name = display_name + self.file_destination = file_destination + self.notification = notification + self.notification_email = notification_email + self.schedule = schedule self.scope = scope - self.start_on = start_on - self.cache = cache + self.status = status + self.view_id = view_id -class SettingsListResult(msrest.serialization.Model): - """Result of listing settings. It contains a list of available settings. +class ScheduledActionListResult(_serialization.Model): + """Scheduled actions list result. It contains a list of scheduled actions. Variables are only populated by the server, and will be ignored when sending a request. - :ivar value: The list of settings. - :vartype value: list[~azure.mgmt.costmanagement.models.Setting] + :ivar value: The list of scheduled actions. + :vartype value: list[~azure.mgmt.costmanagement.models.ScheduledAction] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { - 'value': {'readonly': True, 'max_items': 10, 'min_items': 0}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ScheduledAction]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class ScheduleProperties(_serialization.Model): + """The properties of the schedule. + + All required parameters must be populated in order to send to Azure. + + :ivar frequency: Frequency of the schedule. Required. Known values are: "Daily", "Weekly", and + "Monthly". + :vartype frequency: str or ~azure.mgmt.costmanagement.models.ScheduleFrequency + :ivar hour_of_day: UTC time at which cost analysis data will be emailed. + :vartype hour_of_day: int + :ivar days_of_week: Day names in english on which cost analysis data will be emailed. This + property is applicable when frequency is Weekly or Monthly. + :vartype days_of_week: list[str or ~azure.mgmt.costmanagement.models.DaysOfWeek] + :ivar weeks_of_month: Weeks in which cost analysis data will be emailed. This property is + applicable when frequency is Monthly and used in combination with daysOfWeek. + :vartype weeks_of_month: list[str or ~azure.mgmt.costmanagement.models.WeeksOfMonth] + :ivar day_of_month: UTC day on which cost analysis data will be emailed. Must be between 1 and + 31. This property is applicable when frequency is Monthly and overrides weeksOfMonth or + daysOfWeek. + :vartype day_of_month: int + :ivar start_date: The start date and time of the scheduled action (UTC). Required. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end date and time of the scheduled action (UTC). Required. + :vartype end_date: ~datetime.datetime + """ + + _validation = { + "frequency": {"required": True}, + "start_date": {"required": True}, + "end_date": {"required": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Setting]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "frequency": {"key": "frequency", "type": "str"}, + "hour_of_day": {"key": "hourOfDay", "type": "int"}, + "days_of_week": {"key": "daysOfWeek", "type": "[str]"}, + "weeks_of_month": {"key": "weeksOfMonth", "type": "[str]"}, + "day_of_month": {"key": "dayOfMonth", "type": "int"}, + "start_date": {"key": "startDate", "type": "iso-8601"}, + "end_date": {"key": "endDate", "type": "iso-8601"}, } def __init__( self, + *, + frequency: Union[str, "_models.ScheduleFrequency"], + start_date: datetime.datetime, + end_date: datetime.datetime, + hour_of_day: Optional[int] = None, + days_of_week: Optional[List[Union[str, "_models.DaysOfWeek"]]] = None, + weeks_of_month: Optional[List[Union[str, "_models.WeeksOfMonth"]]] = None, + day_of_month: Optional[int] = None, **kwargs ): - super(SettingsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None + """ + :keyword frequency: Frequency of the schedule. Required. Known values are: "Daily", "Weekly", + and "Monthly". + :paramtype frequency: str or ~azure.mgmt.costmanagement.models.ScheduleFrequency + :keyword hour_of_day: UTC time at which cost analysis data will be emailed. + :paramtype hour_of_day: int + :keyword days_of_week: Day names in english on which cost analysis data will be emailed. This + property is applicable when frequency is Weekly or Monthly. + :paramtype days_of_week: list[str or ~azure.mgmt.costmanagement.models.DaysOfWeek] + :keyword weeks_of_month: Weeks in which cost analysis data will be emailed. This property is + applicable when frequency is Monthly and used in combination with daysOfWeek. + :paramtype weeks_of_month: list[str or ~azure.mgmt.costmanagement.models.WeeksOfMonth] + :keyword day_of_month: UTC day on which cost analysis data will be emailed. Must be between 1 + and 31. This property is applicable when frequency is Monthly and overrides weeksOfMonth or + daysOfWeek. + :paramtype day_of_month: int + :keyword start_date: The start date and time of the scheduled action (UTC). Required. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end date and time of the scheduled action (UTC). Required. + :paramtype end_date: ~datetime.datetime + """ + super().__init__(**kwargs) + self.frequency = frequency + self.hour_of_day = hour_of_day + self.days_of_week = days_of_week + self.weeks_of_month = weeks_of_month + self.day_of_month = day_of_month + self.start_date = start_date + self.end_date = end_date + + +class SharedScopeBenefitRecommendationProperties( + BenefitRecommendationProperties +): # pylint: disable=too-many-instance-attributes + """The properties of the benefit recommendation when scope is 'Shared'. + Variables are only populated by the server, and will be ignored when sending a request. -class Status(msrest.serialization.Model): - """The status of the long running operation. + All required parameters must be populated in order to send to Azure. + + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendations. + :vartype first_consumption_date: ~datetime.datetime + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendations. + :vartype last_consumption_date: ~datetime.datetime + :ivar look_back_period: The number of days of usage evaluated for computing the + recommendations. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :vartype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :ivar total_hours: The total hours for which the cost is covered. Its equal to number of + records in a property 'properties/usage/charges'. + :vartype total_hours: int + :ivar usage: On-demand charges between firstConsumptionDate and lastConsumptionDate that were + used for computing benefit recommendations. + :vartype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :ivar arm_sku_name: ARM SKU name. 'Compute_Savings_Plan' for SavingsPlan. + :vartype arm_sku_name: str + :ivar term: Term period of the benefit. For example, P1Y or P3Y. Known values are: "P1Y" and + "P3Y". + :vartype term: str or ~azure.mgmt.costmanagement.models.Term + :ivar commitment_granularity: Grain of the proposed commitment amount. Supported values: + 'Hourly'. Known values are: "Hourly", "Daily", and "Monthly". + :vartype commitment_granularity: str or ~azure.mgmt.costmanagement.models.Grain + :ivar currency_code: An ISO 4217 currency code identifier for the costs and savings amounts. + :vartype currency_code: str + :ivar cost_without_benefit: The current cost without benefit, corresponds to 'totalHours' in + the look-back period. + :vartype cost_without_benefit: float + :ivar recommendation_details: The details of the proposed recommendation. + :vartype recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails + :ivar all_recommendation_details: The list of all benefit recommendations with the + recommendation details. + :vartype all_recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsList + :ivar scope: Benefit scope. For example, Single or Shared. Required. Known values are: "Single" + and "Shared". + :vartype scope: str or ~azure.mgmt.costmanagement.models.Scope + """ + + _validation = { + "first_consumption_date": {"readonly": True}, + "last_consumption_date": {"readonly": True}, + "total_hours": {"readonly": True}, + "arm_sku_name": {"readonly": True}, + "currency_code": {"readonly": True}, + "cost_without_benefit": {"readonly": True}, + "all_recommendation_details": {"readonly": True}, + "scope": {"required": True}, + } + + _attribute_map = { + "first_consumption_date": {"key": "firstConsumptionDate", "type": "iso-8601"}, + "last_consumption_date": {"key": "lastConsumptionDate", "type": "iso-8601"}, + "look_back_period": {"key": "lookBackPeriod", "type": "str"}, + "total_hours": {"key": "totalHours", "type": "int"}, + "usage": {"key": "usage", "type": "RecommendationUsageDetails"}, + "arm_sku_name": {"key": "armSkuName", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "commitment_granularity": {"key": "commitmentGranularity", "type": "str"}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "cost_without_benefit": {"key": "costWithoutBenefit", "type": "float"}, + "recommendation_details": {"key": "recommendationDetails", "type": "AllSavingsBenefitDetails"}, + "all_recommendation_details": {"key": "allRecommendationDetails", "type": "AllSavingsList"}, + "scope": {"key": "scope", "type": "str"}, + } + + def __init__( + self, + *, + look_back_period: Optional[Union[str, "_models.LookBackPeriod"]] = None, + usage: Optional["_models.RecommendationUsageDetails"] = None, + term: Optional[Union[str, "_models.Term"]] = None, + commitment_granularity: Optional[Union[str, "_models.Grain"]] = None, + recommendation_details: Optional["_models.AllSavingsBenefitDetails"] = None, + **kwargs + ): + """ + :keyword look_back_period: The number of days of usage evaluated for computing the + recommendations. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :paramtype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :keyword usage: On-demand charges between firstConsumptionDate and lastConsumptionDate that + were used for computing benefit recommendations. + :paramtype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :keyword term: Term period of the benefit. For example, P1Y or P3Y. Known values are: "P1Y" and + "P3Y". + :paramtype term: str or ~azure.mgmt.costmanagement.models.Term + :keyword commitment_granularity: Grain of the proposed commitment amount. Supported values: + 'Hourly'. Known values are: "Hourly", "Daily", and "Monthly". + :paramtype commitment_granularity: str or ~azure.mgmt.costmanagement.models.Grain + :keyword recommendation_details: The details of the proposed recommendation. + :paramtype recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails + """ + super().__init__( + look_back_period=look_back_period, + usage=usage, + term=term, + commitment_granularity=commitment_granularity, + recommendation_details=recommendation_details, + **kwargs + ) + self.scope = "Shared" # type: str + + +class SingleScopeBenefitRecommendationProperties( + BenefitRecommendationProperties +): # pylint: disable=too-many-instance-attributes + """The properties of the benefit recommendations when scope is 'Single'. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. - :param status: The status of the long running operation. Possible values include: "Running", - "Completed", "Failed". - :type status: str or ~azure.mgmt.costmanagement.models.OperationStatusType + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendations. + :vartype first_consumption_date: ~datetime.datetime + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendations. + :vartype last_consumption_date: ~datetime.datetime + :ivar look_back_period: The number of days of usage evaluated for computing the + recommendations. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :vartype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :ivar total_hours: The total hours for which the cost is covered. Its equal to number of + records in a property 'properties/usage/charges'. + :vartype total_hours: int + :ivar usage: On-demand charges between firstConsumptionDate and lastConsumptionDate that were + used for computing benefit recommendations. + :vartype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :ivar arm_sku_name: ARM SKU name. 'Compute_Savings_Plan' for SavingsPlan. + :vartype arm_sku_name: str + :ivar term: Term period of the benefit. For example, P1Y or P3Y. Known values are: "P1Y" and + "P3Y". + :vartype term: str or ~azure.mgmt.costmanagement.models.Term + :ivar commitment_granularity: Grain of the proposed commitment amount. Supported values: + 'Hourly'. Known values are: "Hourly", "Daily", and "Monthly". + :vartype commitment_granularity: str or ~azure.mgmt.costmanagement.models.Grain + :ivar currency_code: An ISO 4217 currency code identifier for the costs and savings amounts. + :vartype currency_code: str + :ivar cost_without_benefit: The current cost without benefit, corresponds to 'totalHours' in + the look-back period. + :vartype cost_without_benefit: float + :ivar recommendation_details: The details of the proposed recommendation. + :vartype recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails + :ivar all_recommendation_details: The list of all benefit recommendations with the + recommendation details. + :vartype all_recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsList + :ivar scope: Benefit scope. For example, Single or Shared. Required. Known values are: "Single" + and "Shared". + :vartype scope: str or ~azure.mgmt.costmanagement.models.Scope + :ivar subscription_id: The subscription ID that this single scope recommendation is for. + Applicable only if recommendation is for 'Single' scope. + :vartype subscription_id: str + :ivar resource_group: The resource group that this single scope recommendation is for. + Applicable only if recommendation is for 'Single' scope and 'ResourceGroup' request scope. + :vartype resource_group: str """ + _validation = { + "first_consumption_date": {"readonly": True}, + "last_consumption_date": {"readonly": True}, + "total_hours": {"readonly": True}, + "arm_sku_name": {"readonly": True}, + "currency_code": {"readonly": True}, + "cost_without_benefit": {"readonly": True}, + "all_recommendation_details": {"readonly": True}, + "scope": {"required": True}, + "subscription_id": {"readonly": True}, + "resource_group": {"readonly": True}, + } + _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, + "first_consumption_date": {"key": "firstConsumptionDate", "type": "iso-8601"}, + "last_consumption_date": {"key": "lastConsumptionDate", "type": "iso-8601"}, + "look_back_period": {"key": "lookBackPeriod", "type": "str"}, + "total_hours": {"key": "totalHours", "type": "int"}, + "usage": {"key": "usage", "type": "RecommendationUsageDetails"}, + "arm_sku_name": {"key": "armSkuName", "type": "str"}, + "term": {"key": "term", "type": "str"}, + "commitment_granularity": {"key": "commitmentGranularity", "type": "str"}, + "currency_code": {"key": "currencyCode", "type": "str"}, + "cost_without_benefit": {"key": "costWithoutBenefit", "type": "float"}, + "recommendation_details": {"key": "recommendationDetails", "type": "AllSavingsBenefitDetails"}, + "all_recommendation_details": {"key": "allRecommendationDetails", "type": "AllSavingsList"}, + "scope": {"key": "scope", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "resource_group": {"key": "resourceGroup", "type": "str"}, } def __init__( self, *, - status: Optional[Union[str, "OperationStatusType"]] = None, + look_back_period: Optional[Union[str, "_models.LookBackPeriod"]] = None, + usage: Optional["_models.RecommendationUsageDetails"] = None, + term: Optional[Union[str, "_models.Term"]] = None, + commitment_granularity: Optional[Union[str, "_models.Grain"]] = None, + recommendation_details: Optional["_models.AllSavingsBenefitDetails"] = None, **kwargs ): - super(Status, self).__init__(**kwargs) + """ + :keyword look_back_period: The number of days of usage evaluated for computing the + recommendations. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :paramtype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :keyword usage: On-demand charges between firstConsumptionDate and lastConsumptionDate that + were used for computing benefit recommendations. + :paramtype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :keyword term: Term period of the benefit. For example, P1Y or P3Y. Known values are: "P1Y" and + "P3Y". + :paramtype term: str or ~azure.mgmt.costmanagement.models.Term + :keyword commitment_granularity: Grain of the proposed commitment amount. Supported values: + 'Hourly'. Known values are: "Hourly", "Daily", and "Monthly". + :paramtype commitment_granularity: str or ~azure.mgmt.costmanagement.models.Grain + :keyword recommendation_details: The details of the proposed recommendation. + :paramtype recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsBenefitDetails + """ + super().__init__( + look_back_period=look_back_period, + usage=usage, + term=term, + commitment_granularity=commitment_granularity, + recommendation_details=recommendation_details, + **kwargs + ) + self.scope = "Single" # type: str + self.subscription_id = None + self.resource_group = None + + +class Status(_serialization.Model): + """The status of the long running operation. + + :ivar status: The status of the long running operation. Known values are: "InProgress", + "Completed", "Failed", "Queued", "NoDataFound", "ReadyToDownload", and "TimedOut". + :vartype status: str or ~azure.mgmt.costmanagement.models.ReportOperationStatusType + """ + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + } + + def __init__(self, *, status: Optional[Union[str, "_models.ReportOperationStatusType"]] = None, **kwargs): + """ + :keyword status: The status of the long running operation. Known values are: "InProgress", + "Completed", "Failed", "Queued", "NoDataFound", "ReadyToDownload", and "TimedOut". + :paramtype status: str or ~azure.mgmt.costmanagement.models.ReportOperationStatusType + """ + super().__init__(**kwargs) self.status = status -class View(ProxyResource): +class SystemData(_serialization.Model): + """Metadata pertaining to creation and last modification of the resource. + + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.costmanagement.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.costmanagement.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime + """ + + _attribute_map = { + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, + *, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + created_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + **kwargs + ): + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.costmanagement.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.costmanagement.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.created_by = created_by + self.created_by_type = created_by_type + self.created_at = created_at + self.last_modified_by = last_modified_by + self.last_modified_by_type = last_modified_by_type + self.last_modified_at = last_modified_at + + +class View(CostManagementProxyResource): # pylint: disable=too-many-instance-attributes """States and configurations of Cost Analysis. Variables are only populated by the server, and will be ignored when sending a request. @@ -2291,12 +5234,12 @@ class View(ProxyResource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + :ivar e_tag: eTag of the resource. To handle concurrent update scenario, this field will be used to determine whether the user is updating the latest version or not. - :type e_tag: str - :param display_name: User input name of the view. Required. - :type display_name: str - :param scope: Cost Management scope to save the view on. This includes + :vartype e_tag: str + :ivar display_name: User input name of the view. Required. + :vartype display_name: str + :ivar scope: Cost Management scope to save the view on. This includes 'subscriptions/{subscriptionId}' for subscription scope, 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, @@ -2313,76 +5256,74 @@ class View(ProxyResource): ExternalBillingAccount scope, and '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for ExternalSubscription scope. - :type scope: str + :vartype scope: str :ivar created_on: Date the user created this view. :vartype created_on: ~datetime.datetime :ivar modified_on: Date when the user last modified this view. :vartype modified_on: ~datetime.datetime - :ivar date_range: Selected date range for viewing cost in. + :ivar date_range: Date range of the current view. :vartype date_range: str - :ivar currency: Selected currency. + :ivar currency: Currency of the current view. :vartype currency: str - :param chart: Chart type of the main view in Cost Analysis. Required. Possible values include: - "Area", "Line", "StackedColumn", "GroupedColumn", "Table". - :type chart: str or ~azure.mgmt.costmanagement.models.ChartType - :param accumulated: Show costs accumulated over time. Possible values include: "true", "false". - :type accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType - :param metric: Metric to use when displaying costs. Possible values include: "ActualCost", - "AmortizedCost", "AHUB". - :type metric: str or ~azure.mgmt.costmanagement.models.MetricType - :param kpis: List of KPIs to show in Cost Analysis UI. - :type kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] - :param pivots: Configuration of 3 sub-views in the Cost Analysis UI. - :type pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] - :param type_properties_query_type: The type of the report. Usage represents actual usage, + :ivar chart: Chart type of the main view in Cost Analysis. Required. Known values are: "Area", + "Line", "StackedColumn", "GroupedColumn", and "Table". + :vartype chart: str or ~azure.mgmt.costmanagement.models.ChartType + :ivar accumulated: Show costs accumulated over time. Known values are: "true" and "false". + :vartype accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType + :ivar metric: Metric to use when displaying costs. Known values are: "ActualCost", + "AmortizedCost", and "AHUB". + :vartype metric: str or ~azure.mgmt.costmanagement.models.MetricType + :ivar kpis: List of KPIs to show in Cost Analysis UI. + :vartype kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] + :ivar pivots: Configuration of 3 sub-views in the Cost Analysis UI. + :vartype pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] + :ivar type_properties_query_type: The type of the report. Usage represents actual usage, forecast represents forecasted data and UsageAndForecast represents both usage and forecasted - data. Actual usage and forecasted data can be differentiated based on dates. Possible values - include: "Usage". - :type type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType - :param timeframe: The time frame for pulling data for the report. If custom, then a specific - time period must be provided. Possible values include: "WeekToDate", "MonthToDate", - "YearToDate", "Custom". - :type timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType - :param time_period: Has time period for pulling data for the report. - :type time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod - :param data_set: Has definition for data in this report config. - :type data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset - :ivar include_monetary_commitment: Include monetary commitment. + data. Actual usage and forecasted data can be differentiated based on dates. "Usage" + :vartype type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType + :ivar timeframe: The time frame for pulling data for the report. If custom, then a specific + time period must be provided. Known values are: "WeekToDate", "MonthToDate", "YearToDate", and + "Custom". + :vartype timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType + :ivar time_period: Has time period for pulling data for the report. + :vartype time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod + :ivar data_set: Has definition for data in this report config. + :vartype data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset + :ivar include_monetary_commitment: If true, report includes monetary commitment. :vartype include_monetary_commitment: bool """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_on': {'readonly': True}, - 'modified_on': {'readonly': True}, - 'date_range': {'readonly': True}, - 'currency': {'readonly': True}, - 'include_monetary_commitment': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'e_tag': {'key': 'eTag', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'modified_on': {'key': 'properties.modifiedOn', 'type': 'iso-8601'}, - 'date_range': {'key': 'properties.dateRange', 'type': 'str'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'chart': {'key': 'properties.chart', 'type': 'str'}, - 'accumulated': {'key': 'properties.accumulated', 'type': 'str'}, - 'metric': {'key': 'properties.metric', 'type': 'str'}, - 'kpis': {'key': 'properties.kpis', 'type': '[KpiProperties]'}, - 'pivots': {'key': 'properties.pivots', 'type': '[PivotProperties]'}, - 'type_properties_query_type': {'key': 'properties.query.type', 'type': 'str'}, - 'timeframe': {'key': 'properties.query.timeframe', 'type': 'str'}, - 'time_period': {'key': 'properties.query.timePeriod', 'type': 'ReportConfigTimePeriod'}, - 'data_set': {'key': 'properties.query.dataSet', 'type': 'ReportConfigDataset'}, - 'include_monetary_commitment': {'key': 'properties.query.includeMonetaryCommitment', 'type': 'bool'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "created_on": {"readonly": True}, + "modified_on": {"readonly": True}, + "date_range": {"readonly": True}, + "currency": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "e_tag": {"key": "eTag", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "modified_on": {"key": "properties.modifiedOn", "type": "iso-8601"}, + "date_range": {"key": "properties.dateRange", "type": "str"}, + "currency": {"key": "properties.currency", "type": "str"}, + "chart": {"key": "properties.chart", "type": "str"}, + "accumulated": {"key": "properties.accumulated", "type": "str"}, + "metric": {"key": "properties.metric", "type": "str"}, + "kpis": {"key": "properties.kpis", "type": "[KpiProperties]"}, + "pivots": {"key": "properties.pivots", "type": "[PivotProperties]"}, + "type_properties_query_type": {"key": "properties.query.type", "type": "str"}, + "timeframe": {"key": "properties.query.timeframe", "type": "str"}, + "time_period": {"key": "properties.query.timePeriod", "type": "ReportConfigTimePeriod"}, + "data_set": {"key": "properties.query.dataSet", "type": "ReportConfigDataset"}, + "include_monetary_commitment": {"key": "properties.query.includeMonetaryCommitment", "type": "bool"}, } def __init__( @@ -2391,18 +5332,70 @@ def __init__( e_tag: Optional[str] = None, display_name: Optional[str] = None, scope: Optional[str] = None, - chart: Optional[Union[str, "ChartType"]] = None, - accumulated: Optional[Union[str, "AccumulatedType"]] = None, - metric: Optional[Union[str, "MetricType"]] = None, - kpis: Optional[List["KpiProperties"]] = None, - pivots: Optional[List["PivotProperties"]] = None, - type_properties_query_type: Optional[Union[str, "ReportType"]] = None, - timeframe: Optional[Union[str, "ReportTimeframeType"]] = None, - time_period: Optional["ReportConfigTimePeriod"] = None, - data_set: Optional["ReportConfigDataset"] = None, + chart: Optional[Union[str, "_models.ChartType"]] = None, + accumulated: Optional[Union[str, "_models.AccumulatedType"]] = None, + metric: Optional[Union[str, "_models.MetricType"]] = None, + kpis: Optional[List["_models.KpiProperties"]] = None, + pivots: Optional[List["_models.PivotProperties"]] = None, + type_properties_query_type: Optional[Union[str, "_models.ReportType"]] = None, + timeframe: Optional[Union[str, "_models.ReportTimeframeType"]] = None, + time_period: Optional["_models.ReportConfigTimePeriod"] = None, + data_set: Optional["_models.ReportConfigDataset"] = None, + include_monetary_commitment: Optional[bool] = None, **kwargs ): - super(View, self).__init__(e_tag=e_tag, **kwargs) + """ + :keyword e_tag: eTag of the resource. To handle concurrent update scenario, this field will be + used to determine whether the user is updating the latest version or not. + :paramtype e_tag: str + :keyword display_name: User input name of the view. Required. + :paramtype display_name: str + :keyword scope: Cost Management scope to save the view on. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + '/providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + ExternalBillingAccount scope, and + '/providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + ExternalSubscription scope. + :paramtype scope: str + :keyword chart: Chart type of the main view in Cost Analysis. Required. Known values are: + "Area", "Line", "StackedColumn", "GroupedColumn", and "Table". + :paramtype chart: str or ~azure.mgmt.costmanagement.models.ChartType + :keyword accumulated: Show costs accumulated over time. Known values are: "true" and "false". + :paramtype accumulated: str or ~azure.mgmt.costmanagement.models.AccumulatedType + :keyword metric: Metric to use when displaying costs. Known values are: "ActualCost", + "AmortizedCost", and "AHUB". + :paramtype metric: str or ~azure.mgmt.costmanagement.models.MetricType + :keyword kpis: List of KPIs to show in Cost Analysis UI. + :paramtype kpis: list[~azure.mgmt.costmanagement.models.KpiProperties] + :keyword pivots: Configuration of 3 sub-views in the Cost Analysis UI. + :paramtype pivots: list[~azure.mgmt.costmanagement.models.PivotProperties] + :keyword type_properties_query_type: The type of the report. Usage represents actual usage, + forecast represents forecasted data and UsageAndForecast represents both usage and forecasted + data. Actual usage and forecasted data can be differentiated based on dates. "Usage" + :paramtype type_properties_query_type: str or ~azure.mgmt.costmanagement.models.ReportType + :keyword timeframe: The time frame for pulling data for the report. If custom, then a specific + time period must be provided. Known values are: "WeekToDate", "MonthToDate", "YearToDate", and + "Custom". + :paramtype timeframe: str or ~azure.mgmt.costmanagement.models.ReportTimeframeType + :keyword time_period: Has time period for pulling data for the report. + :paramtype time_period: ~azure.mgmt.costmanagement.models.ReportConfigTimePeriod + :keyword data_set: Has definition for data in this report config. + :paramtype data_set: ~azure.mgmt.costmanagement.models.ReportConfigDataset + :keyword include_monetary_commitment: If true, report includes monetary commitment. + :paramtype include_monetary_commitment: bool + """ + super().__init__(e_tag=e_tag, **kwargs) self.display_name = display_name self.scope = scope self.created_on = None @@ -2418,10 +5411,10 @@ def __init__( self.timeframe = timeframe self.time_period = time_period self.data_set = data_set - self.include_monetary_commitment = None + self.include_monetary_commitment = include_monetary_commitment -class ViewListResult(msrest.serialization.Model): +class ViewListResult(_serialization.Model): """Result of listing views. It contains a list of available views. Variables are only populated by the server, and will be ignored when sending a request. @@ -2433,19 +5426,17 @@ class ViewListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[View]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[View]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ViewListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py index c70a4cb564cb..2d305a7dc351 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/__init__.py @@ -6,24 +6,48 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._settings_operations import SettingsOperations +from ._operations import Operations from ._views_operations import ViewsOperations from ._alerts_operations import AlertsOperations from ._forecast_operations import ForecastOperations from ._dimensions_operations import DimensionsOperations from ._query_operations import QueryOperations from ._generate_reservation_details_report_operations import GenerateReservationDetailsReportOperations -from ._operations import Operations from ._exports_operations import ExportsOperations +from ._generate_cost_details_report_operations import GenerateCostDetailsReportOperations +from ._generate_detailed_cost_report_operations import GenerateDetailedCostReportOperations +from ._generate_detailed_cost_report_operation_results_operations import ( + GenerateDetailedCostReportOperationResultsOperations, +) +from ._generate_detailed_cost_report_operation_status_operations import ( + GenerateDetailedCostReportOperationStatusOperations, +) +from ._price_sheet_operations import PriceSheetOperations +from ._scheduled_actions_operations import ScheduledActionsOperations +from ._benefit_recommendations_operations import BenefitRecommendationsOperations +from ._benefit_utilization_summaries_operations import BenefitUtilizationSummariesOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'SettingsOperations', - 'ViewsOperations', - 'AlertsOperations', - 'ForecastOperations', - 'DimensionsOperations', - 'QueryOperations', - 'GenerateReservationDetailsReportOperations', - 'Operations', - 'ExportsOperations', + "Operations", + "ViewsOperations", + "AlertsOperations", + "ForecastOperations", + "DimensionsOperations", + "QueryOperations", + "GenerateReservationDetailsReportOperations", + "ExportsOperations", + "GenerateCostDetailsReportOperations", + "GenerateDetailedCostReportOperations", + "GenerateDetailedCostReportOperationResultsOperations", + "GenerateDetailedCostReportOperationStatusOperations", + "PriceSheetOperations", + "ScheduledActionsOperations", + "BenefitRecommendationsOperations", + "BenefitUtilizationSummariesOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py index 13969e75db88..39878262b5b6 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,51 +6,171 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/alerts") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_dismiss_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -class AlertsOperations(object): - """AlertsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_external_request( + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`alerts` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AlertsResult" + @distributed_trace + def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult: """Lists the alerts for scope defined. :param scope: The scope associated with alerts operations. This includes @@ -67,60 +188,61 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] + + request = build_list_request( + scope=scope, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts'} # type: ignore - def get( - self, - scope, # type: str - alert_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Alert" + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts"} # type: ignore + + @distributed_trace + def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: """Gets the alert for the scope by alert ID. :param scope: The scope associated with alerts operations. This includes @@ -138,64 +260,72 @@ def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + request = build_get_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @overload def dismiss( self, - scope, # type: str - alert_id, # type: str - parameters, # type: "_models.DismissAlertPayload" - **kwargs # type: Any - ): - # type: (...) -> "_models.Alert" + scope: str, + alert_id: str, + parameters: _models.DismissAlertPayload, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Alert: """Dismisses the specified alert. :param scope: The scope associated with alerts operations. This includes @@ -213,121 +343,219 @@ def dismiss( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param alert_id: Alert ID. + :param alert_id: Alert ID. Required. :type alert_id: str - :param parameters: Parameters supplied to the Dismiss Alert operation. + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Alert, or the result of cls(response) + :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Alert - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def dismiss( + self, scope: str, alert_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def dismiss( + self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, IO], **kwargs: Any + ) -> _models.Alert: + """Dismisses the specified alert. + + :param scope: The scope associated with alerts operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param alert_id: Alert ID. Required. + :type alert_id: str + :param parameters: Parameters supplied to the Dismiss Alert operation. Is either a model type + or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Alert or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Alert + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Alert"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.dismiss.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'alertId': self._serialize.url("alert_id", alert_id, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'DismissAlertPayload') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Alert] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "DismissAlertPayload") + + request = build_dismiss_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.dismiss.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Alert', pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - dismiss.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore + dismiss.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}"} # type: ignore + + @distributed_trace def list_external( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AlertsResult" + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + **kwargs: Any + ) -> _models.AlertsResult: """Lists the Alerts for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertsResult, or the result of cls(response) + :return: AlertsResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AlertsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list_external.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AlertsResult] + + request = build_list_external_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + template_url=self.list_external.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AlertsResult', pipeline_response) + deserialized = self._deserialize("AlertsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list_external.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts'} # type: ignore + + list_external.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/alerts"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py new file mode 100644 index 000000000000..62e7f41d301a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py @@ -0,0 +1,213 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + billing_scope: str, + *, + filter: Optional[str] = None, + orderby: Optional[str] = None, + expand: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations") + path_format_arguments = { + "billingScope": _SERIALIZER.url("billing_scope", billing_scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if orderby is not None: + _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class BenefitRecommendationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`benefit_recommendations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, + billing_scope: str, + filter: Optional[str] = None, + orderby: Optional[str] = None, + expand: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.BenefitRecommendationModel"]: + """List of recommendations for purchasing savings plan. + + :param billing_scope: The scope associated with benefit recommendation operations. This + includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, + /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for enterprise agreement + scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billing profile scope. Required. + :type billing_scope: str + :param filter: Can be used to filter benefitRecommendations by: properties/scope with allowed + values ['Single', 'Shared'] and default value 'Shared'; and properties/lookBackPeriod with + allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and default value 'Last60Days'; + properties/term with allowed values ['P1Y', 'P3Y'] and default value 'P3Y'; + properties/subscriptionId; properties/resourceGroup. Default value is None. + :type filter: str + :param orderby: May be used to order the recommendations by: properties/armSkuName. For the + savings plan, the results are in order by default. There is no need to use this clause. Default + value is None. + :type orderby: str + :param expand: May be used to expand the properties by: properties/usage, + properties/allRecommendationDetails. Default value is None. + :type expand: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitRecommendationModel or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.BenefitRecommendationModel] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitRecommendationsListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + billing_scope=billing_scope, + filter=filter, + orderby=orderby, + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitRecommendationsListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py new file mode 100644 index 000000000000..4045f0f98ee4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py @@ -0,0 +1,621 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_account_id_request( + billing_account_id: str, + *, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if grain_parameter is not None: + _params["grainParameter"] = _SERIALIZER.query("grain_parameter", grain_parameter, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_id_request( + billing_account_id: str, + billing_profile_id: str, + *, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if grain_parameter is not None: + _params["grainParameter"] = _SERIALIZER.query("grain_parameter", grain_parameter, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_savings_plan_order_request( + savings_plan_order_id: str, + *, + filter: Optional[str] = None, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries", + ) # pylint: disable=line-too-long + path_format_arguments = { + "savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if grain_parameter is not None: + _params["grainParameter"] = _SERIALIZER.query("grain_parameter", grain_parameter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_savings_plan_id_request( + savings_plan_order_id: str, + savings_plan_id: str, + *, + filter: Optional[str] = None, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries", + ) # pylint: disable=line-too-long + path_format_arguments = { + "savingsPlanOrderId": _SERIALIZER.url("savings_plan_order_id", savings_plan_order_id, "str"), + "savingsPlanId": _SERIALIZER.url("savings_plan_id", savings_plan_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if grain_parameter is not None: + _params["grainParameter"] = _SERIALIZER.query("grain_parameter", grain_parameter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class BenefitUtilizationSummariesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`benefit_utilization_summaries` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_billing_account_id( + self, + billing_account_id: str, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.BenefitUtilizationSummary"]: + """Lists savings plan utilization summaries for the enterprise agreement scope. Supported at grain + values: 'Daily' and 'Monthly'. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and + properties/usageDate. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_billing_account_id_request( + billing_account_id=billing_account_id, + grain_parameter=grain_parameter, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_account_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_billing_account_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore + + @distributed_trace + def list_by_billing_profile_id( + self, + billing_account_id: str, + billing_profile_id: str, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.BenefitUtilizationSummary"]: + """Lists savings plan utilization summaries for billing profile. Supported at grain values: + 'Daily' and 'Monthly'. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Billing profile ID. Required. + :type billing_profile_id: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :param filter: Supports filtering by properties/benefitId, properties/benefitOrderId and + properties/usageDate. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_billing_profile_id_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + grain_parameter=grain_parameter, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_profile_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_billing_profile_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore + + @distributed_trace + def list_by_savings_plan_order( + self, + savings_plan_order_id: str, + filter: Optional[str] = None, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + **kwargs: Any + ) -> Iterable["_models.BenefitUtilizationSummary"]: + """Lists the savings plan utilization summaries for daily or monthly grain. + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param filter: Supports filtering by properties/usageDate. Default value is None. + :type filter: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_savings_plan_order_request( + savings_plan_order_id=savings_plan_order_id, + filter=filter, + grain_parameter=grain_parameter, + api_version=api_version, + template_url=self.list_by_savings_plan_order.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_savings_plan_order.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore + + @distributed_trace + def list_by_savings_plan_id( + self, + savings_plan_order_id: str, + savings_plan_id: str, + filter: Optional[str] = None, + grain_parameter: Optional[Union[str, _models.GrainParameter]] = None, + **kwargs: Any + ) -> Iterable["_models.BenefitUtilizationSummary"]: + """Lists the savings plan utilization summaries for daily or monthly grain. + + :param savings_plan_order_id: Savings plan order ID. Required. + :type savings_plan_order_id: str + :param savings_plan_id: Savings plan ID. Required. + :type savings_plan_id: str + :param filter: Supports filtering by properties/usageDate. Default value is None. + :type filter: str + :param grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default + value is None. + :type grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either BenefitUtilizationSummary or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitUtilizationSummariesListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_savings_plan_id_request( + savings_plan_order_id=savings_plan_order_id, + savings_plan_id=savings_plan_id, + filter=filter, + grain_parameter=grain_parameter, + api_version=api_version, + template_url=self.list_by_savings_plan_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("BenefitUtilizationSummariesListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_savings_plan_id.metadata = {"url": "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/providers/Microsoft.CostManagement/benefitUtilizationSummaries"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py index ff843ebbf69e..9a94e4e524e3 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,56 +6,157 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +import urllib.parse -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class DimensionsOperations(object): - """DimensionsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_request( + scope: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/dimensions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_by_external_cloud_provider_type_request( + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + *, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=1000, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class DimensionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`dimensions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( self, - scope, # type: str - filter=None, # type: Optional[str] - expand=None, # type: Optional[str] - skiptoken=None, # type: Optional[str] - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DimensionsListResult"] + scope: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> Iterable["_models.Dimension"]: """Lists the dimensions by the defined scope. :param scope: The scope associated with dimension operations. This includes @@ -72,66 +174,81 @@ def list( 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + scope=scope, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -140,100 +257,119 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/dimensions'} # type: ignore + return ItemPaged(get_next, extract_data) + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/dimensions"} # type: ignore + + @distributed_trace def by_external_cloud_provider_type( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - filter=None, # type: Optional[str] - expand=None, # type: Optional[str] - skiptoken=None, # type: Optional[str] - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.DimensionsListResult"] + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + filter: Optional[str] = None, + expand: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any + ) -> Iterable["_models.Dimension"]: """Lists the dimensions by the external cloud provider type. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param filter: May be used to filter dimensions by properties/category, properties/usageStart, - properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. + properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. Default value is + None. :type filter: str :param expand: May be used to expand the properties/data within a dimension category. By - default, data is not included when listing dimensions. + default, data is not included when listing dimensions. Default value is None. :type expand: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N dimension data. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DimensionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.DimensionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Dimension or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.Dimension] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DimensionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + expand=expand, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('DimensionsListResult', pipeline_response) + deserialized = self._deserialize("DimensionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -242,17 +378,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions'} # type: ignore + return ItemPaged(get_next, extract_data) + + by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py index 89eefe5166d4..958ac4bdb38d 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,54 +6,219 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(scope: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(scope: str, export_name: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ExportsOperations(object): - """ExportsOperations operations. + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_execute_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_execution_history_request(scope: str, export_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "exportName": _SERIALIZER.url("export_name", export_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ExportsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`exports` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.ExportListResult" + @distributed_trace + def list(self, scope: str, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult: """The operation to list all exports at the given scope. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -67,63 +233,69 @@ def list( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last run of each export. Default + value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportListResult, or the result of cls(response) + :return: ExportListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportListResult] + + request = build_list_request( + scope=scope, + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportListResult', pipeline_response) + deserialized = self._deserialize("ExportListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports'} # type: ignore - def get( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Export" + list.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports"} # type: ignore + + @distributed_trace + def get(self, scope: str, export_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.Export: """The operation to get the export for the defined scope by export name. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -138,69 +310,82 @@ def get( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str + :param expand: May be used to expand the properties within an export. Currently only + 'runHistory' is supported and will return information for the last 10 runs of the export. + Default value is None. + :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Export] + + request = build_get_request( + scope=scope, + export_name=export_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @overload def create_or_update( self, - scope, # type: str - export_name, # type: str - parameters, # type: "_models.Export" - **kwargs # type: Any - ): - # type: (...) -> "_models.Export" + scope: str, + export_name: str, + parameters: _models.Export, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Export: """The operation to create or update a export. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -215,77 +400,167 @@ def create_or_update( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str - :param parameters: Parameters supplied to the CreateOrUpdate Export operation. + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.Export + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, scope: str, export_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Export or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.Export + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, scope: str, export_name: str, parameters: Union[_models.Export, IO], **kwargs: Any + ) -> _models.Export: + """The operation to create or update a export. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param export_name: Export Name. Required. + :type export_name: str + :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.Export or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Export, or the result of cls(response) + :return: Export or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.Export - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Export"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Export') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Export] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Export") + + request = build_create_or_update_request( + scope=scope, + export_name=export_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Export', pipeline_response) + deserialized = self._deserialize("Export", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore - def delete( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any + ) -> None: """The operation to delete a export. - :param scope: The scope associated with query and export operations. This includes + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -300,63 +575,65 @@ def delete( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore + delete.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}"} # type: ignore - def execute( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - """The operation to execute a export. - - :param scope: The scope associated with query and export operations. This includes + @distributed_trace + def execute( # pylint: disable=inconsistent-return-statements + self, scope: str, export_name: str, **kwargs: Any + ) -> None: + """The operation to run an export. + + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -371,63 +648,63 @@ def execute( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.execute.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.execute.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - execute.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run'} # type: ignore + execute.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/run"} # type: ignore - def get_execution_history( - self, - scope, # type: str - export_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.ExportExecutionListResult" - """The operation to get the execution history of an export for the defined scope by export name. - - :param scope: The scope associated with query and export operations. This includes + @distributed_trace + def get_execution_history(self, scope: str, export_name: str, **kwargs: Any) -> _models.ExportExecutionListResult: + """The operation to get the run history of an export for the defined scope and export name. + + :param scope: The scope associated with export operations. This includes '/subscriptions/{subscriptionId}/' for subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and @@ -442,52 +719,58 @@ def get_execution_history( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param export_name: Export Name. + :param export_name: Export Name. Required. :type export_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportExecutionListResult, or the result of cls(response) + :return: ExportExecutionListResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ExportExecutionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_execution_history.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - 'exportName': self._serialize.url("export_name", export_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ExportExecutionListResult] + + request = build_get_execution_history_request( + scope=scope, + export_name=export_name, + api_version=api_version, + template_url=self.get_execution_history.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ExportExecutionListResult', pipeline_response) + deserialized = self._deserialize("ExportExecutionListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_execution_history.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory'} # type: ignore + + get_execution_history.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/exports/{exportName}/runHistory"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py index 71c2e338e1e5..87053c2968cf 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,53 +6,138 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class ForecastOperations(object): - """ForecastOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_usage_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/forecast") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_external_cloud_provider_usage_request( + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ForecastOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`forecast` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload def usage( self, - scope, # type: str - parameters, # type: "_models.ForecastDefinition" - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.QueryResult"] + scope: str, + parameters: _models.ForecastDefinition, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.ForecastResult]: """Lists the forecast charges for scope defined. :param scope: The scope associated with forecast operations. This includes @@ -69,141 +155,338 @@ def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def usage( + self, + scope: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def usage( + self, scope: str, parameters: Union[_models.ForecastDefinition, IO], filter: Optional[str] = None, **kwargs: Any + ) -> Optional[_models.ForecastResult]: + """Lists the forecast charges for scope defined. + + :param scope: The scope associated with forecast operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ForecastResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_usage_request( + scope=scope, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/forecast'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/forecast"} # type: ignore + + @overload def external_cloud_provider_usage( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - parameters, # type: "_models.ForecastDefinition" - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.QueryResult" + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: _models.ForecastDefinition, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ForecastResult: """Lists the forecast charges for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition :param filter: May be used to filter forecasts by properties/usageDate (Utc time), properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', - and 'and'. It does not currently support 'ne', 'or', or 'not'. + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: IO, + filter: Optional[str] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. + Required. + :type parameters: IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. :type filter: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def external_cloud_provider_usage( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: Union[_models.ForecastDefinition, IO], + filter: Optional[str] = None, + **kwargs: Any + ) -> _models.ForecastResult: + """Lists the forecast charges for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or IO + :param filter: May be used to filter forecasts by properties/usageDate (Utc time), + properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', + and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None. + :type filter: str + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ForecastResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ForecastResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.external_cloud_provider_usage.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'ForecastDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ForecastResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ForecastDefinition") + + request = build_external_cloud_provider_usage_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + filter=filter, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.external_cloud_provider_usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("ForecastResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - external_cloud_provider_usage.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast'} # type: ignore + + external_cloud_provider_usage.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/forecast"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py new file mode 100644 index 000000000000..abb85608f83d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py @@ -0,0 +1,479 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_operation_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_operation_results_request(scope: str, operation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateCostDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_cost_details_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CostDetailsOperationResults]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateCostDetailsReportRequestDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateCostDetailsReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + @overload + def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateCostDetailsReportRequestDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, IO], **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """This API is the replacement for all previously release Usage Details APIs. Request to generate + a cost details report for the provided date range, billing period (Only enterprise customers) + or Invoice Id asynchronously at a certain scope. The initial call to request a report will + return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the + endpoint to poll to get the result of the report generation. The 'Retry-After' provides the + duration to wait before polling for the generated report. A call to poll the report operation + will provide a 202 response with a 'Location' header if the operation is still in progress. + Once the report generation operation completes, the polling endpoint will provide a 200 + response along with details on the report blob(s) that are available for download. The details + on the file(s) available for download will be available in the polling response body. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create cost details operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CostDetailsOperationResults] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateCostDetailsReport"} # type: ignore + + def _get_operation_results_initial( + self, scope: str, operation_id: str, **kwargs: Any + ) -> Optional[_models.CostDetailsOperationResults]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.CostDetailsOperationResults]] + + request = build_get_operation_results_request( + scope=scope, + operation_id=operation_id, + api_version=api_version, + template_url=self._get_operation_results_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _get_operation_results_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore + + @distributed_trace + def begin_get_operation_results( + self, scope: str, operation_id: str, **kwargs: Any + ) -> LROPoller[_models.CostDetailsOperationResults]: + """Get the result of the specified operation. This link is provided in the CostDetails creation + request response Location header. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param operation_id: The target operation Id. Required. + :type operation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either CostDetailsOperationResults or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CostDetailsOperationResults] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._get_operation_results_initial( # type: ignore + scope=scope, + operation_id=operation_id, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("CostDetailsOperationResults", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_get_operation_results.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/costDetailsOperationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py new file mode 100644 index 000000000000..0cc2d0a6b70c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_results_operations.py @@ -0,0 +1,209 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}") + path_format_arguments = { + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateDetailedCostReportOperationResultsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_results` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _get_initial( + self, operation_id: str, scope: str, **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self._get_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _get_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} # type: ignore + + @distributed_trace + def begin_get( + self, operation_id: str, scope: str, **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Gets the result of the specified operation. The link with this operationId is provided as a + response header of the initial request. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._get_initial( # type: ignore + operation_id=operation_id, + scope=scope, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationResults/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py new file mode 100644 index 000000000000..9e9300779dc7 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operation_status_operations.py @@ -0,0 +1,146 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(operation_id: str, scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}") + path_format_arguments = { + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateDetailedCostReportOperationStatusOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_detailed_cost_report_operation_status` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, operation_id: str, scope: str, **kwargs: Any) -> _models.GenerateDetailedCostReportOperationStatuses: + """Get the status of the specified operation. This link is provided in the + GenerateDetailedCostReport creation request response header. + + :param operation_id: The target operation Id. Required. + :type operation_id: str + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GenerateDetailedCostReportOperationStatuses or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationStatuses] + + request = build_get_request( + operation_id=operation_id, + scope=scope, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GenerateDetailedCostReportOperationStatuses", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/operationStatus/{operationId}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py new file mode 100644 index 000000000000..d1aa61e8aef0 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_detailed_cost_report_operations.py @@ -0,0 +1,317 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_create_operation_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateDetailedCostReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_detailed_cost_report` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _create_operation_initial( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> Optional[_models.GenerateDetailedCostReportOperationResult]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.GenerateDetailedCostReportOperationResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "GenerateDetailedCostReportDefinition") + + request = build_create_operation_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_operation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.GenerateDetailedCostReportErrorResponse, pipeline_response + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-Consumption-AsyncOperation") + ) + response_headers["Azure-AsyncOperation"] = self._deserialize( + "str", response.headers.get("Azure-AsyncOperation") + ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _create_operation_initial.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore + + @overload + def begin_create_operation( + self, + scope: str, + parameters: _models.GenerateDetailedCostReportDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(only enterprise + customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_operation( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(only enterprise + customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_operation( + self, scope: str, parameters: Union[_models.GenerateDetailedCostReportDefinition, IO], **kwargs: Any + ) -> LROPoller[_models.GenerateDetailedCostReportOperationResult]: + """Generates the detailed cost report for provided date range, billing period(only enterprise + customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header + Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the + operation will provide the status and if the operation is completed the blob file where + generated detailed cost report is being stored. + + :param scope: The ARM Resource ID for subscription, resource group, billing account, or other + billing scopes. For details, see https://aka.ms/costmgmt/scopes. Required. + :type scope: str + :param parameters: Parameters supplied to the Create detailed cost report operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either GenerateDetailedCostReportOperationResult + or the result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.GenerateDetailedCostReportOperationResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._create_operation_initial( # type: ignore + scope=scope, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("GenerateDetailedCostReportOperationResult", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_operation.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/generateDetailedCostReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py index 4c93c64e8755..fe00d3275649 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,306 +6,391 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_by_billing_account_id_request( + billing_account_id: str, *, start_date: str, end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +def build_by_billing_profile_id_request( + billing_account_id: str, billing_profile_id: str, *, start_date: str, end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") -class GenerateReservationDetailsReportOperations(object): - """GenerateReservationDetailsReportOperations operations. + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountId": _SERIALIZER.url("billing_account_id", billing_account_id, "str"), + "billingProfileId": _SERIALIZER.url("billing_profile_id", billing_profile_id, "str"), + } - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + _url = _format_url_section(_url, **path_format_arguments) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct parameters + _params["startDate"] = _SERIALIZER.query("start_date", start_date, "str") + _params["endDate"] = _SERIALIZER.query("end_date", end_date, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class GenerateReservationDetailsReportOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`generate_reservation_details_report` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") def _by_billing_account_id_initial( - self, - billing_account_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.OperationStatus"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_account_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_account_id_request( + billing_account_id=billing_account_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_account_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _by_billing_account_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_account_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace def begin_by_billing_account_id( - self, - billing_account_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.OperationStatus"] + self, billing_account_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously based on - enrollment id. + enrollment id. The Reservation usage details can be viewed only by certain enterprise roles. + For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role. - :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). + :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). Required. :type billing_account_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either OperationStatus or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._by_billing_account_id_initial( + raw_result = self._by_billing_account_id_initial( # type: ignore billing_account_id=billing_account_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_account_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_account_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore def _by_billing_profile_id_initial( - self, - billing_account_id, # type: str - billing_profile_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.OperationStatus"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.OperationStatus"]] + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> Optional[_models.OperationStatus]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self._by_billing_profile_id_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['startDate'] = self._serialize.query("start_date", start_date, 'str') - query_parameters['endDate'] = self._serialize.query("end_date", end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.OperationStatus]] + + request = build_by_billing_profile_id_request( + billing_account_id=billing_account_id, + billing_profile_id=billing_profile_id, + start_date=start_date, + end_date=end_date, + api_version=api_version, + template_url=self._by_billing_profile_id_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('OperationStatus', pipeline_response) + deserialized = self._deserialize("OperationStatus", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _by_billing_profile_id_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + _by_billing_profile_id_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore + + @distributed_trace def begin_by_billing_profile_id( - self, - billing_account_id, # type: str - billing_profile_id, # type: str - start_date, # type: str - end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.OperationStatus"] + self, billing_account_id: str, billing_profile_id: str, start_date: str, end_date: str, **kwargs: Any + ) -> LROPoller[_models.OperationStatus]: """Generates the reservations details report for provided date range asynchronously by billing - profile. + profile. The Reservation usage details can be viewed by only certain enterprise roles by + default. For more details on the roles see, + https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access. - :param billing_account_id: BillingAccount ID. + :param billing_account_id: Billing account ID. Required. :type billing_account_id: str - :param billing_profile_id: BillingProfile ID. + :param billing_profile_id: Billing profile ID. Required. :type billing_profile_id: str - :param start_date: Start Date. + :param start_date: Start Date. Required. :type start_date: str - :param end_date: End Date. + :param end_date: End Date. Required. :type end_date: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either OperationStatus or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either OperationStatus or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.OperationStatus] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationStatus"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationStatus] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._by_billing_profile_id_initial( + raw_result = self._by_billing_profile_id_initial( # type: ignore billing_account_id=billing_account_id, billing_profile_id=billing_profile_id, start_date=start_date, end_date=end_date, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('OperationStatus', pipeline_response) - + deserialized = self._deserialize("OperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountId': self._serialize.url("billing_account_id", billing_account_id, 'str'), - 'billingProfileId': self._serialize.url("billing_profile_id", billing_profile_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_by_billing_profile_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_by_billing_profile_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.CostManagement/generateReservationDetailsReport"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py index 4a538a66f2c5..35d797e55af8 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,137 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/operations") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.CostManagementOperation"]: """Lists all of the available cost management REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either CostManagementOperation or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.CostManagementOperation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +145,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.CostManagement/operations"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_patch.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_price_sheet_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_price_sheet_operations.py new file mode 100644 index 000000000000..e283527e8af8 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_price_sheet_operations.py @@ -0,0 +1,401 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_download_request( + billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url( + "billing_account_name", + billing_account_name, + "str", + pattern=r"([A-Za-z0-9]+(-[A-Za-z0-9]+)+):([A-Za-z0-9]+(-[A-Za-z0-9]+)+)_[0-9]{4}-[0-9]{2}-[0-9]{2}", + ), + "billingProfileName": _SERIALIZER.url( + "billing_profile_name", billing_profile_name, "str", pattern=r"([A-Za-z0-9]+(-[A-Za-z0-9]+)+)" + ), + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str", pattern=r"[A-Za-z0-9]+"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_download_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url( + "billing_account_name", + billing_account_name, + "str", + pattern=r"([A-Za-z0-9]+(-[A-Za-z0-9]+)+):([A-Za-z0-9]+(-[A-Za-z0-9]+)+)_[0-9]{4}-[0-9]{2}-[0-9]{2}", + ), + "billingProfileName": _SERIALIZER.url( + "billing_profile_name", billing_profile_name, "str", pattern=r"([A-Za-z0-9]+(-[A-Za-z0-9]+)+)" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PriceSheetOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`price_sheet` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def _download_initial( + self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any + ) -> Optional[_models.DownloadURL]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadURL]] + + request = build_download_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_name=invoice_name, + api_version=api_version, + template_url=self._download_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("DownloadURL", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) + response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _download_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore + + @distributed_trace + def begin_download( + self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any + ) -> LROPoller[_models.DownloadURL]: + """Gets a URL to download the pricesheet for an invoice. The operation is supported for billing + accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param invoice_name: The ID that uniquely identifies an invoice. Required. + :type invoice_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadURL or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.DownloadURL] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadURL] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._download_initial( # type: ignore + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_name=invoice_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DownloadURL", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices/{invoiceName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore + + def _download_by_billing_profile_initial( + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Optional[_models.DownloadURL]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadURL]] + + request = build_download_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self._download_by_billing_profile_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + response_headers = {} + if response.status_code == 200: + deserialized = self._deserialize("DownloadURL", pipeline_response) + + if response.status_code == 202: + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) + response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId")) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + + _download_by_billing_profile_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore + + @distributed_trace + def begin_download_by_billing_profile( + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> LROPoller[_models.DownloadURL]: + """Gets a URL to download the current month's pricesheet for a billing profile. The operation is + supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft + Customer Agreement.Due to Azure product growth, the Azure price sheet download experience in + this preview version will be updated from a single csv file to a Zip file containing multiple + csv files, each with max 200k records. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadURL or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.costmanagement.models.DownloadURL] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadURL] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] + if cont_token is None: + raw_result = self._download_by_billing_profile_initial( # type: ignore + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DownloadURL", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/providers/Microsoft.CostManagement/pricesheets/default/download"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py index b5dd2dc857ec..0941b5681a4a 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,52 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class QueryOperations(object): - """QueryOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_usage_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/query") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_usage_by_external_cloud_provider_type_request( + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query", + ) # pylint: disable=line-too-long + path_format_arguments = { + "externalCloudProviderType": _SERIALIZER.url( + "external_cloud_provider_type", external_cloud_provider_type, "str" + ), + "externalCloudProviderId": _SERIALIZER.url("external_cloud_provider_id", external_cloud_provider_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class QueryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`query` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload def usage( - self, - scope, # type: str - parameters, # type: "_models.QueryDefinition" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.QueryResult"] + self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: """Query the usage data for scope defined. :param scope: The scope associated with query and export operations. This includes @@ -68,128 +143,299 @@ def usage( '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' for invoiceSection scope, and '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' - specific for partners. + specific for partners. Required. :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def usage( + self, scope: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or None or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def usage( + self, scope: str, parameters: Union[_models.QueryDefinition, IO], **kwargs: Any + ) -> Optional[_models.QueryResult]: + """Query the usage data for scope defined. + + :param scope: The scope associated with query and export operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' + for Department scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group + scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' + for invoiceSection scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' + specific for partners. Required. + :type scope: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or None or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.QueryResult"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.QueryResult]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/query'} # type: ignore + usage.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/query"} # type: ignore + + @overload def usage_by_external_cloud_provider_type( self, - external_cloud_provider_type, # type: Union[str, "_models.ExternalCloudProviderType"] - external_cloud_provider_id, # type: str - parameters, # type: "_models.QueryDefinition" - **kwargs # type: Any - ): - # type: (...) -> "_models.QueryResult" + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: _models.QueryDefinition, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.QueryResult: """Query the usage data for external cloud provider type defined. :param external_cloud_provider_type: The external cloud provider type associated with dimension/query operations. This includes 'externalSubscriptions' for linked account and - 'externalBillingAccounts' for consolidated account. - :type external_cloud_provider_type: str or ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryResult, or the result of cls(response) + :return: QueryResult or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.QueryResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def usage_by_external_cloud_provider_type( + self, + external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType], + external_cloud_provider_id: str, + parameters: Union[_models.QueryDefinition, IO], + **kwargs: Any + ) -> _models.QueryResult: + """Query the usage data for external cloud provider type defined. + + :param external_cloud_provider_type: The external cloud provider type associated with + dimension/query operations. This includes 'externalSubscriptions' for linked account and + 'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions" + and "externalBillingAccounts". Required. + :type external_cloud_provider_type: str or + ~azure.mgmt.costmanagement.models.ExternalCloudProviderType + :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or + '{externalBillingAccountId}' for consolidated account used with dimension/query operations. + Required. + :type external_cloud_provider_id: str + :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: QueryResult or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.QueryResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.QueryResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.usage_by_external_cloud_provider_type.metadata['url'] # type: ignore - path_format_arguments = { - 'externalCloudProviderType': self._serialize.url("external_cloud_provider_type", external_cloud_provider_type, 'str'), - 'externalCloudProviderId': self._serialize.url("external_cloud_provider_id", external_cloud_provider_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'QueryDefinition') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "QueryDefinition") + + request = build_usage_by_external_cloud_provider_type_request( + external_cloud_provider_type=external_cloud_provider_type, + external_cloud_provider_id=external_cloud_provider_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.usage_by_external_cloud_provider_type.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryResult', pipeline_response) + deserialized = self._deserialize("QueryResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - usage_by_external_cloud_provider_type.metadata = {'url': '/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query'} # type: ignore + + usage_by_external_cloud_provider_type.metadata = {"url": "/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/query"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py new file mode 100644 index 000000000000..4287dbd5a343 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py @@ -0,0 +1,1528 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/scheduledActions") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_scope_request(scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/scheduledActions") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/scheduledActions/{name}") + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/scheduledActions/{name}") + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/scheduledActions/{name}") + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_run_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute") + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_run_by_scope_request(scope: str, name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}/execute") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/checkNameAvailability") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_by_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/checkNameAvailability") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ScheduledActionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`scheduled_actions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.ScheduledAction"]: + """List all private scheduled actions. + + :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator + is 'eq'. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ScheduledAction or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledActionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + filter=filter, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ScheduledActionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions"} # type: ignore + + @distributed_trace + def list_by_scope( + self, scope: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.ScheduledAction"]: + """List all shared scheduled actions within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param filter: May be used to filter scheduled actions by properties/viewId. Supported operator + is 'eq'. Default value is None. + :type filter: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ScheduledAction or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledActionListResult] + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_scope_request( + scope=scope, + filter=filter, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ScheduledActionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions"} # type: ignore + + @overload + def create_or_update( + self, + name: str, + scheduled_action: _models.ScheduledAction, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, name: str, scheduled_action: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, name: str, scheduled_action: Union[_models.ScheduledAction, IO], **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Is either a model type or a + IO type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(scheduled_action, (IO, bytes)): + _content = scheduled_action + else: + _json = self._serialize.body(scheduled_action, "ScheduledAction") + + request = build_create_or_update_request( + name=name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace + def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction: + """Get the private scheduled action by name. + + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + request = build_get_request( + name=name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace + def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + name=name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @overload + def create_or_update_by_scope( + self, + scope: str, + name: str, + scheduled_action: _models.ScheduledAction, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_scope( + self, scope: str, name: str, scheduled_action: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Required. + :type scheduled_action: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_scope( + self, scope: str, name: str, scheduled_action: Union[_models.ScheduledAction, IO], **kwargs: Any + ) -> _models.ScheduledAction: + """Create or update a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :param scheduled_action: Scheduled action to be created or updated. Is either a model type or a + IO type. Required. + :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(scheduled_action, (IO, bytes)): + _content = scheduled_action + else: + _json = self._serialize.body(scheduled_action, "ScheduledAction") + + request = build_create_or_update_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace + def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.ScheduledAction: + """Get the shared scheduled action from the given scope by name. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ScheduledAction or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ScheduledAction] + + request = build_get_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("ScheduledAction", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace + def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, name: str, **kwargs: Any + ) -> None: + """Delete a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.delete_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}"} # type: ignore + + @distributed_trace + def run(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Processes a private scheduled action. + + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_run_request( + name=name, + api_version=api_version, + template_url=self.run.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + run.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} # type: ignore + + @distributed_trace + def run_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, name: str, **kwargs: Any + ) -> None: + """Runs a shared scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param name: Scheduled action name. Required. + :type name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_run_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.run_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + run_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} # type: ignore + + @overload + def check_name_availability( + self, + check_name_availability_request: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action. + + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action. + + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action. + + :param check_name_availability_request: Scheduled action to be created or updated. Is either a + model type or a IO type. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(check_name_availability_request, (IO, bytes)): + _content = check_name_availability_request + else: + _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") + + request = build_check_name_availability_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_name_availability.metadata = {"url": "/providers/Microsoft.CostManagement/checkNameAvailability"} # type: ignore + + @overload + def check_name_availability_by_scope( + self, + scope: str, + check_name_availability_request: _models.CheckNameAvailabilityRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability_by_scope( + self, scope: str, check_name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param check_name_availability_request: Scheduled action to be created or updated. Required. + :type check_name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability_by_scope( + self, + scope: str, + check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, IO], + **kwargs: Any + ) -> _models.CheckNameAvailabilityResponse: + """Checks availability and correctness of the name for a scheduled action within the given scope. + + :param scope: The scope associated with scheduled action operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Note: Insight Alerts are only available on subscription scope. + Required. + :type scope: str + :param check_name_availability_request: Scheduled action to be created or updated. Is either a + model type or a IO type. Required. + :type check_name_availability_request: + ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckNameAvailabilityResponse or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(check_name_availability_request, (IO, bytes)): + _content = check_name_availability_request + else: + _json = self._serialize.body(check_name_availability_request, "CheckNameAvailabilityRequest") + + request = build_check_name_availability_by_scope_request( + scope=scope, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_name_availability_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_name_availability_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/checkNameAvailability"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py deleted file mode 100644 index 3140937a8c4c..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py +++ /dev/null @@ -1,281 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse -from azure.mgmt.core.exceptions import ARMErrorFormat - -from .. import models as _models - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class SettingsOperations(object): - """SettingsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. - """ - - models = _models - - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.SettingsListResult"] - """Lists all of the settings that have been customized. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SettingsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.SettingsListResult] - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SettingsListResult"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) - return request - - def extract_data(pipeline_response): - deserialized = self._deserialize('SettingsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/settings'} # type: ignore - - def get( - self, - setting_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Setting" - """Retrieves the current value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - def create_or_update( - self, - setting_name, # type: str - parameters, # type: "_models.Setting" - **kwargs # type: Any - ): - # type: (...) -> "_models.Setting" - """Sets a new value for a specific setting. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :param parameters: Body supplied to the CreateOrUpdate setting operation. - :type parameters: ~azure.mgmt.costmanagement.models.Setting - :keyword callable cls: A custom type or function that will be passed the direct response - :return: Setting, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.Setting - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Setting"] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Setting') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize('Setting', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore - - def delete( - self, - setting_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - """Remove the current value for a specific setting and reverts back to the default value, if - applicable. - - :param setting_name: Name of the setting. Allowed values: myscope. - :type setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'settingName': self._serialize.url("setting_name", setting_name, 'str', max_length=32, min_length=0), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200, 204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {'url': '/providers/Microsoft.CostManagement/settings/{settingName}'} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py index d7512a2a7003..598e85f13489 100644 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,313 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_scope_request(scope: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class ViewsOperations(object): - """ViewsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.costmanagement.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_create_or_update_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_scope_request(scope: str, view_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) # type: Literal["2022-10-01"] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.CostManagement/views/{viewName}") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str"), + "viewName": _SERIALIZER.url("view_name", view_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ViewsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`views` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ViewListResult"] + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.View"]: """Lists all views by tenant and object. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,27 +321,24 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.CostManagement/views'} # type: ignore + return ItemPaged(get_next, extract_data) - def list_by_scope( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ViewListResult"] + list.metadata = {"url": "/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace + def list_by_scope(self, scope: str, **kwargs: Any) -> Iterable["_models.View"]: """Lists all views at the given scope. :param scope: The scope associated with view operations. This includes @@ -133,46 +357,62 @@ def list_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ViewListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.ViewListResultor None] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either View or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.costmanagement.models.View] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ViewListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_scope_request( + scope=scope, + api_version=api_version, + template_url=self.list_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ViewListResult', pipeline_response) + deserialized = self._deserialize("ViewListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -181,204 +421,257 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + list_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views"} # type: ignore + + @distributed_trace + def get(self, view_name: str, **kwargs: Any) -> _models.View: """Gets the view by view name. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + request = build_get_request( + view_name=view_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload def create_or_update( - self, - view_name, # type: str - parameters, # type: "_models.View" - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + self, view_name: str, parameters: _models.View, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update(self, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_request( + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - def delete( - self, - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace + def delete(self, view_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements """The operation to delete a view. - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_request( + view_name=view_name, + api_version=api_version, + template_url=self.delete.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete.metadata = {"url": "/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore - def get_by_scope( - self, - scope, # type: str - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + @distributed_trace + def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View: """Gets the view for the defined scope by view name. :param scope: The scope associated with view operations. This includes @@ -397,64 +690,72 @@ def get_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.get_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + request = build_get_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.get_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + get_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @overload def create_or_update_by_scope( self, - scope, # type: str - view_name, # type: str - parameters, # type: "_models.View" - **kwargs # type: Any - ): - # type: (...) -> "_models.View" + scope: str, + view_name: str, + parameters: _models.View, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.View: """The operation to create or update a view. Update operation requires latest eTag to be set in the request. You may obtain the latest eTag by performing a get operation. Create operation does not require eTag. @@ -475,74 +776,166 @@ def create_or_update_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. :type parameters: ~azure.mgmt.costmanagement.models.View + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: View, or the result of cls(response) + :return: View or the result of cls(response) :rtype: ~azure.mgmt.costmanagement.models.View - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_by_scope( + self, scope: str, view_name: str, parameters: Union[_models.View, IO], **kwargs: Any + ) -> _models.View: + """The operation to create or update a view. Update operation requires latest eTag to be set in + the request. You may obtain the latest eTag by performing a get operation. Create operation + does not require eTag. + + :param scope: The scope associated with view operations. This includes + 'subscriptions/{subscriptionId}' for subscription scope, + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for + Department scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' + for EnrollmentAccount scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for BillingProfile scope, + 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}' + for InvoiceSection scope, 'providers/Microsoft.Management/managementGroups/{managementGroupId}' + for Management Group scope, + 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for + External Billing Account scope and + 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for + External Subscription scope. Required. + :type scope: str + :param view_name: View name. Required. + :type view_name: str + :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.costmanagement.models.View or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: View or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.View + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.View"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'View') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.View] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "View") + + request = build_create_or_update_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('View', pipeline_response) + deserialized = self._deserialize("View", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - def delete_by_scope( - self, - scope, # type: str - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + create_or_update_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore + + @distributed_trace + def delete_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, view_name: str, **kwargs: Any + ) -> None: """The operation to delete a view. :param scope: The scope associated with view operations. This includes @@ -561,49 +954,54 @@ def delete_by_scope( 'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for External Billing Account scope and 'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for - External Subscription scope. + External Subscription scope. Required. :type scope: str - :param view_name: View name. + :param view_name: View name. Required. :type view_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: None, or the result of cls(response) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-11-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'scope': self._serialize.url("scope", scope, 'str'), - 'viewName': self._serialize.url("view_name", view_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop( + "api_version", _params.pop("api-version", self._config.api_version) + ) # type: Literal["2022-10-01"] + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_by_scope_request( + scope=scope, + view_name=view_name, + api_version=api_version, + template_url=self.delete_by_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore + delete_by_scope.metadata = {"url": "/{scope}/providers/Microsoft.CostManagement/views/{viewName}"} # type: ignore diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_billing_account_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_billing_account_list.py new file mode 100644 index 000000000000..625abc9640d1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/benefit_recommendations_billing_account_list.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python benefit_recommendations_billing_account_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.benefit_recommendations.list( + billing_scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitRecommendationsByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py new file mode 100644 index 000000000000..b5bb07a53325 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top_legacy.py new file mode 100644 index 000000000000..f13c043cc3ab --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_dimensions_list_expand_and_top_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top_mca.py new file mode 100644 index 000000000000..b36c0023b616 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_expand_and_top_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_dimensions_list_expand_and_top_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_legacy.py new file mode 100644 index 000000000000..9b783373c3ff --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_dimensions_list_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_mca.py new file mode 100644 index 000000000000..4a909d49f2c4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_dimensions_list_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter_legacy.py new file mode 100644 index 000000000000..67b139a555d6 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_dimensions_list_with_filter_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter_mca.py new file mode 100644 index 000000000000..18aa8a51e66e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_dimensions_list_with_filter_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_dimensions_list_with_filter_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py new file mode 100644 index 000000000000..1b4628647f41 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping_legacy.py new file mode 100644 index 000000000000..fbc06c135d76 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping_legacy.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_query_grouping_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/70664866", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping_mca.py new file mode 100644 index 000000000000..bf0c9c6ebcdc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_grouping_mca.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_query_grouping_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_legacy.py new file mode 100644 index 000000000000..52ab82ffe603 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_legacy.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_query_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/70664866", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingAccountQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_mca.py new file mode 100644 index 000000000000..0906ec936fdf --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_account_query_mca.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_account_query_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingAccountQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py new file mode 100644 index 000000000000..e3d0e291e3a4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingProfileAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_expand_and_top_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_expand_and_top_mca.py new file mode 100644 index 000000000000..e28d1ab0f174 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_expand_and_top_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_dimensions_list_expand_and_top_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_mca.py new file mode 100644 index 000000000000..b4551d052232 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_dimensions_list_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_with_filter_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_with_filter_mca.py new file mode 100644 index 000000000000..26cf5ef67fa2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_dimensions_list_with_filter_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_dimensions_list_with_filter_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py new file mode 100644 index 000000000000..887aafbcf15e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BillingProfileForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_query_grouping_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_query_grouping_mca.py new file mode 100644 index 000000000000..82459da672fb --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_query_grouping_mca.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_query_grouping_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_query_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_query_mca.py new file mode 100644 index 000000000000..57d7ec2310fa --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/billing_profile_query_mca.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python billing_profile_query_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCABillingProfileQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_insight_alert_scheduled_action_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_insight_alert_scheduled_action_by_scope.py new file mode 100644 index 000000000000..b7ac0ac4ce37 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_insight_alert_scheduled_action_by_scope.py @@ -0,0 +1,57 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python create_or_update_insight_alert_scheduled_action_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.create_or_update_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + name="dailyAnomalyByResource", + scheduled_action={ + "kind": "InsightAlert", + "properties": { + "displayName": "Daily anomaly by resource", + "notification": { + "subject": "Cost anomaly detected in the resource", + "to": ["user@gmail.com", "team@gmail.com"], + }, + "schedule": { + "endDate": "2021-06-19T22:21:51.1287144Z", + "frequency": "Daily", + "startDate": "2020-06-19T22:21:51.1287144Z", + }, + "status": "Enabled", + "viewId": "/providers/Microsoft.CostManagement/views/swaggerExample", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-insightAlert-createOrUpdate-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_private_scheduled_action.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_private_scheduled_action.py new file mode 100644 index 000000000000..bcdc140924c3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_private_scheduled_action.py @@ -0,0 +1,56 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python create_or_update_private_scheduled_action.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.create_or_update( + name="monthlyCostByResource", + scheduled_action={ + "kind": "Email", + "properties": { + "displayName": "Monthly Cost By Resource", + "notification": {"subject": "Cost by resource this month", "to": ["user@gmail.com", "team@gmail.com"]}, + "schedule": { + "daysOfWeek": ["Monday"], + "endDate": "2021-06-19T22:21:51.1287144Z", + "frequency": "Monthly", + "hourOfDay": 10, + "startDate": "2020-06-19T22:21:51.1287144Z", + "weeksOfMonth": ["First", "Third"], + }, + "status": "Enabled", + "viewId": "/providers/Microsoft.CostManagement/views/swaggerExample", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-createOrUpdate-private.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_private_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_private_view.py new file mode 100644 index 000000000000..e09871ae27bc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_private_view.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python create_or_update_private_view.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.create_or_update( + view_name="swaggerExample", + parameters={ + "eTag": '"1d4ff9fe66f1d10"', + "properties": { + "accumulated": "true", + "chart": "Table", + "displayName": "swagger Example", + "kpis": [ + {"enabled": True, "id": None, "type": "Forecast"}, + { + "enabled": True, + "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Consumption/budgets/swaggerDemo", + "type": "Budget", + }, + ], + "metric": "ActualCost", + "pivots": [ + {"name": "ServiceName", "type": "Dimension"}, + {"name": "MeterCategory", "type": "Dimension"}, + {"name": "swaggerTagKey", "type": "TagKey"}, + ], + "query": { + "dataSet": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "Daily", + "grouping": [], + "sorting": [{"direction": "Ascending", "name": "UsageDate"}], + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateViewCreateOrUpdate.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_scheduled_action_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_scheduled_action_by_scope.py new file mode 100644 index 000000000000..695c27d7ee9e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/create_or_update_scheduled_action_by_scope.py @@ -0,0 +1,58 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python create_or_update_scheduled_action_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.create_or_update_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + name="monthlyCostByResource", + scheduled_action={ + "kind": "Email", + "properties": { + "displayName": "Monthly Cost By Resource", + "fileDestination": {"fileFormats": ["Csv"]}, + "notification": {"subject": "Cost by resource this month", "to": ["user@gmail.com", "team@gmail.com"]}, + "schedule": { + "daysOfWeek": ["Monday"], + "endDate": "2021-06-19T22:21:51.1287144Z", + "frequency": "Monthly", + "hourOfDay": 10, + "startDate": "2020-06-19T22:21:51.1287144Z", + "weeksOfMonth": ["First", "Third"], + }, + "status": "Enabled", + "viewId": "/providers/Microsoft.CostManagement/views/swaggerExample", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-createOrUpdate-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_expand_and_top_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_expand_and_top_mca.py new file mode 100644 index 000000000000..0b9df1f03006 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_expand_and_top_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_dimensions_list_expand_and_top_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_mca.py new file mode 100644 index 000000000000..473ceb5317fe --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_dimensions_list_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_with_filter_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_with_filter_mca.py new file mode 100644 index 000000000000..a3904170e9fa --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_dimensions_list_with_filter_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_dimensions_list_with_filter_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/5678", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_query_grouping_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_query_grouping_mca.py new file mode 100644 index 000000000000..370c57b3598f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_query_grouping_mca.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_query_grouping_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/5678", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_query_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_query_mca.py new file mode 100644 index 000000000000..d747fd1fd25b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/customer_query_mca.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python customer_query_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/5678", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCACustomerQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/delete_private_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/delete_private_view.py new file mode 100644 index 000000000000..e350deadd5e2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/delete_private_view.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python delete_private_view.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.delete( + view_name="TestView", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateViewDelete.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py new file mode 100644 index 000000000000..88c238b30566 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/departments/123", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top_legacy.py new file mode 100644 index 000000000000..5e642afe4c34 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_expand_and_top_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_dimensions_list_expand_and_top_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100/departments/123", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_legacy.py new file mode 100644 index 000000000000..8e4903cf4ade --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_dimensions_list_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100/departments/123", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter_legacy.py new file mode 100644 index 000000000000..006cc534aea9 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_dimensions_list_with_filter_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_dimensions_list_with_filter_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100/departments/123", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py new file mode 100644 index 000000000000..15b69c4b5200 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/departments/123", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping_legacy.py new file mode 100644 index 000000000000..749034add892 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_grouping_legacy.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_query_grouping_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/100/departments/123", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_legacy.py new file mode 100644 index 000000000000..90e9f5d78123 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/department_query_legacy.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python department_query_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/100/departments/123", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DepartmentQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py new file mode 100644 index 000000000000..1e246acd55bb --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/enrollmentAccounts/456", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top_legacy.py new file mode 100644 index 000000000000..9f185bbf54ea --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_expand_and_top_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_dimensions_list_expand_and_top_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_legacy.py new file mode 100644 index 000000000000..a1e0f832dd55 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_dimensions_list_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter_legacy.py new file mode 100644 index 000000000000..0f8601ded405 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_dimensions_list_with_filter_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_dimensions_list_with_filter_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py new file mode 100644 index 000000000000..a418aca1b8b4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/enrollmentAccounts/456", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping_legacy.py new file mode 100644 index 000000000000..1a9a0f056274 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_grouping_legacy.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_query_grouping_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "Daily", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_legacy.py new file mode 100644 index 000000000000..a050b8d77006 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/enrollment_account_query_legacy.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python enrollment_account_query_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/EnrollmentAccountQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py new file mode 100644 index 000000000000..24a9fdabca78 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_billing_account.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/123456", + export_name="TestExport", + parameters={ + "properties": { + "definition": { + "dataSet": { + "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "container": "exports", + "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", + "rootFolderPath": "ad-hoc", + } + }, + "format": "Csv", + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "status": "Active", + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py new file mode 100644 index 000000000000..ae5adf8565d1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_department.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/12/departments/1234", + export_name="TestExport", + parameters={ + "properties": { + "definition": { + "dataSet": { + "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "container": "exports", + "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", + "rootFolderPath": "ad-hoc", + } + }, + "format": "Csv", + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "status": "Active", + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py new file mode 100644 index 000000000000..259dd8f62917 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_enrollment_account.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + export_name="TestExport", + parameters={ + "properties": { + "definition": { + "dataSet": { + "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "container": "exports", + "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", + "rootFolderPath": "ad-hoc", + } + }, + "format": "Csv", + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "status": "Active", + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py new file mode 100644 index 000000000000..a69690f9e8c2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_management_group.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="providers/Microsoft.Management/managementGroups/TestMG", + export_name="TestExport", + parameters={ + "properties": { + "definition": { + "dataSet": { + "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "container": "exports", + "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", + "rootFolderPath": "ad-hoc", + } + }, + "format": "Csv", + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "status": "Active", + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py new file mode 100644 index 000000000000..c8fa59257795 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_resource_group.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + export_name="TestExport", + parameters={ + "properties": { + "definition": { + "dataSet": { + "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "container": "exports", + "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", + "rootFolderPath": "ad-hoc", + } + }, + "format": "Csv", + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "status": "Active", + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py new file mode 100644 index 000000000000..997f926419db --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_create_or_update_by_subscription.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_create_or_update_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.create_or_update( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + parameters={ + "properties": { + "definition": { + "dataSet": { + "configuration": {"columns": ["Date", "MeterId", "ResourceId", "ResourceLocation", "Quantity"]}, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "ActualCost", + }, + "deliveryInfo": { + "destination": { + "container": "exports", + "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Storage/storageAccounts/ccmeastusdiag182", + "rootFolderPath": "ad-hoc", + } + }, + "format": "Csv", + "schedule": { + "recurrence": "Weekly", + "recurrencePeriod": {"from": "2020-06-01T00:00:00Z", "to": "2020-10-31T00:00:00Z"}, + "status": "Active", + }, + } + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportCreateOrUpdateBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py new file mode 100644 index 000000000000..8b8ca4c5d943 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_delete_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.delete( + scope="providers/Microsoft.Billing/billingAccounts/123456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py new file mode 100644 index 000000000000..13999bc0febc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_department.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_delete_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.delete( + scope="providers/Microsoft.Billing/billingAccounts/12/departments/1234", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py new file mode 100644 index 000000000000..a98aa17281a1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_enrollment_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_delete_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.delete( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py new file mode 100644 index 000000000000..44aff58c1874 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_management_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_delete_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.delete( + scope="providers/Microsoft.Management/managementGroups/TestMG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py new file mode 100644 index 000000000000..def28d98d213 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_resource_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_delete_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.delete( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py new file mode 100644 index 000000000000..b10f8824b741 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_delete_by_subscription.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_delete_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.delete( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportDeleteBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py new file mode 100644 index 000000000000..8266b9a594d2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="providers/Microsoft.Billing/billingAccounts/123456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py new file mode 100644 index 000000000000..e6aa15d5361c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_department.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="providers/Microsoft.Billing/billingAccounts/12/departments/1234", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py new file mode 100644 index 000000000000..4960c604686d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_enrollment_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py new file mode 100644 index 000000000000..ac2e541426fc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_management_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="providers/Microsoft.Management/managementGroups/TestMG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py new file mode 100644 index 000000000000..307fb98bd806 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_resource_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py new file mode 100644 index 000000000000..efbd1e8048b7 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_get_by_subscription.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_get_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportGetBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py new file mode 100644 index 000000000000..a63c606016f2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.execute( + scope="providers/Microsoft.Billing/billingAccounts/123456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py new file mode 100644 index 000000000000..540d70bfb5b3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_department.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.execute( + scope="providers/Microsoft.Billing/billingAccounts/12/departments/1234", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py new file mode 100644 index 000000000000..77a3fccda67e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_enrollment_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.execute( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py new file mode 100644 index 000000000000..ab206641adf1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_management_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.execute( + scope="providers/Microsoft.Management/managementGroups/TestMG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py new file mode 100644 index 000000000000..27240ad02a34 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_resource_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.execute( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py new file mode 100644 index 000000000000..c73bc6d7f76c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_by_subscription.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.execute( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py new file mode 100644 index 000000000000..199740876c6b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="providers/Microsoft.Billing/billingAccounts/123456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py new file mode 100644 index 000000000000..380019a2e8e1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_department.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="providers/Microsoft.Billing/billingAccounts/12/departments/1234", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py new file mode 100644 index 000000000000..79922afbc76d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_enrollment_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py new file mode 100644 index 000000000000..37d279c1cd97 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_management_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="providers/Microsoft.Management/managementGroups/TestMG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py new file mode 100644 index 000000000000..494201812bf2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_resource_group.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py new file mode 100644 index 000000000000..4565b72e9911 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/export_run_history_get_by_subscription.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python export_run_history_get_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.get_execution_history( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + export_name="TestExport", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportRunHistoryGetBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py new file mode 100644 index 000000000000..6562d9dddf91 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_billing_account.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python exports_get_by_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.list( + scope="providers/Microsoft.Billing/billingAccounts/123456", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py new file mode 100644 index 000000000000..e5f7c4444277 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_department.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python exports_get_by_department.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.list( + scope="providers/Microsoft.Billing/billingAccounts/12/departments/123", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByDepartment.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py new file mode 100644 index 000000000000..de0b8d7490a8 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_enrollment_account.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python exports_get_by_enrollment_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.list( + scope="providers/Microsoft.Billing/billingAccounts/100/enrollmentAccounts/456", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByEnrollmentAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py new file mode 100644 index 000000000000..8b78725d765d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_management_group.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python exports_get_by_management_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.list( + scope="providers/Microsoft.Management/managementGroups/TestMG", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByManagementGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py new file mode 100644 index 000000000000..b9662dd0ff45 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_resource_group.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python exports_get_by_resource_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py new file mode 100644 index 000000000000..37fcdbd45b49 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/exports_get_by_subscription.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python exports_get_by_subscription.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.exports.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExportsGetBySubscription.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py new file mode 100644 index 000000000000..779eb2320f80 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_alerts.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_billing_account_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list_external( + external_cloud_provider_type="externalBillingAccounts", + external_cloud_provider_id="100", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_dimension_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_dimension_list.py new file mode 100644 index 000000000000..cfd8376e447b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_dimension_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_billing_account_dimension_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.by_external_cloud_provider_type( + external_cloud_provider_type="externalBillingAccounts", + external_cloud_provider_id="100", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountsDimensions.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py new file mode 100644 index 000000000000..dc1bb420b118 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_forecast.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_billing_account_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.external_cloud_provider_usage( + external_cloud_provider_type="externalBillingAccounts", + external_cloud_provider_id="100", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_query_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_query_list.py new file mode 100644 index 000000000000..dd9b1d56b757 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_billing_account_query_list.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_billing_account_query_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage_by_external_cloud_provider_type( + external_cloud_provider_type="externalBillingAccounts", + external_cloud_provider_id="100", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalBillingAccountsQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py new file mode 100644 index 000000000000..24103f6c6562 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_alerts.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_subscription_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list_external( + external_cloud_provider_type="externalSubscriptions", + external_cloud_provider_id="100", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_dimension_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_dimension_list.py new file mode 100644 index 000000000000..82f50d54bc88 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_dimension_list.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_subscription_dimension_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.by_external_cloud_provider_type( + external_cloud_provider_type="externalSubscriptions", + external_cloud_provider_id="100", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionsDimensions.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py new file mode 100644 index 000000000000..39a6ed464e0f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscription_forecast.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_subscription_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.external_cloud_provider_usage( + external_cloud_provider_type="externalSubscriptions", + external_cloud_provider_id="100", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py new file mode 100644 index 000000000000..5879a5230481 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/external_subscriptions_query.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python external_subscriptions_query.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage_by_external_cloud_provider_type( + external_cloud_provider_type="externalSubscriptions", + external_cloud_provider_id="100", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ExternalSubscriptionsQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py new file mode 100644 index 000000000000..8fc7ecb2911b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_billing_account_enterprise_agreement_customer_and_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345", + parameters={"billingPeriod": "202205", "metric": "ActualCost"}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByBillingAccountEnterpriseAgreementCustomerAndBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py new file mode 100644 index 000000000000..3cc8d1ae18e2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_billing_profile_and_invoice_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + parameters={"invoiceId": "M1234567", "metric": "ActualCost"}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByBillingProfileAndInvoiceId.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py new file mode 100644 index 000000000000..7e38e26e351f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_billing_profile_and_invoice_id_and_customer_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/13579", + parameters={"invoiceId": "M1234567", "metric": "ActualCost"}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByBillingProfileAndInvoiceIdAndCustomerId.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py new file mode 100644 index 000000000000..1d9fb4013da7 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_customer_and_time_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_customer_and_time_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/13579", + parameters={"metric": "ActualCost", "timePeriod": {"end": "2020-03-15", "start": "2020-03-01"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByCustomerAndTimePeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py new file mode 100644 index 000000000000..b7fd59c2d6f0 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_departments_and_time_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_departments_and_time_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="providers/Microsoft.Billing/departments/12345", + parameters={"metric": "ActualCost", "timePeriod": {"end": "2020-03-15", "start": "2020-03-01"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByDepartmentsAndTimePeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py new file mode 100644 index 000000000000..05857cda0b19 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_enrollment_accounts_and_time_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_enrollment_accounts_and_time_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="providers/Microsoft.Billing/enrollmentAccounts/1234", + parameters={"metric": "ActualCost", "timePeriod": {"end": "2020-03-15", "start": "2020-03-01"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportByEnrollmentAccountsAndTimePeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py new file mode 100644 index 000000000000..fa959fac4317 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_cost_details_report_by_subscription_and_time_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_cost_details_report_by_subscription_and_time_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_create_operation( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + parameters={"metric": "ActualCost", "timePeriod": {"end": "2020-03-15", "start": "2020-03-01"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateCostDetailsReportBySubscriptionAndTimePeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py new file mode 100644 index 000000000000..6c9aba183fb6 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_detailed_cost_report_by_billing_account_legacy_and_billing_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_detailed_cost_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345", + parameters={"billingPeriod": "202008", "metric": "ActualCost"}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByBillingAccountLegacyAndBillingPeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py new file mode 100644 index 000000000000..171adc5bea17 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_detailed_cost_report_by_billing_profile_and_invoice_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_detailed_cost_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + parameters={"invoiceId": "M1234567", "metric": "ActualCost"}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByBillingProfileAndInvoiceId.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py new file mode 100644 index 000000000000..66e8751344e3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_detailed_cost_report_by_billing_profile_and_invoice_id_and_customer_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_detailed_cost_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579", + parameters={"customerId": "456789", "invoiceId": "M1234567", "metric": "ActualCost"}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByBillingProfileAndInvoiceIdAndCustomerId.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py new file mode 100644 index 000000000000..6b4c1c570c67 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_customer_and_time_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_detailed_cost_report_by_customer_and_time_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_detailed_cost_report.begin_create_operation( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/customers/13579", + parameters={"metric": "ActualCost", "timePeriod": {"end": "2020-03-15", "start": "2020-03-01"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportByCustomerAndTimePeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py new file mode 100644 index 000000000000..002c901d4c44 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/generate_detailed_cost_report_by_subscription_and_time_period.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python generate_detailed_cost_report_by_subscription_and_time_period.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_detailed_cost_report.begin_create_operation( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + parameters={"metric": "ActualCost", "timePeriod": {"end": "2020-03-15", "start": "2020-03-01"}}, + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportBySubscriptionAndTimePeriod.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/get_details_of_the_operation_result.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/get_details_of_the_operation_result.py new file mode 100644 index 000000000000..ae8aff59026d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/get_details_of_the_operation_result.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python get_details_of_the_operation_result.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_cost_details_report.begin_get_operation_results( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + operation_id="00000000-0000-0000-0000-000000000000", + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/CostDetailsOperationResultsBySubscriptionScope.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/get_details_of_the_operation_status.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/get_details_of_the_operation_status.py new file mode 100644 index 000000000000..34a7e2786535 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/get_details_of_the_operation_status.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python get_details_of_the_operation_status.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_detailed_cost_report_operation_status.get( + operation_id="00000000-0000-0000-0000-000000000000", + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateDetailedCostReportOperationStatusBySubscriptionScope.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py new file mode 100644 index 000000000000..24be92520b5e --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/InvoiceSectionAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_expand_and_top_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_expand_and_top_mca.py new file mode 100644 index 000000000000..e05d46b14db1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_expand_and_top_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_dimensions_list_expand_and_top_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_mca.py new file mode 100644 index 000000000000..c4a07725f82c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_dimensions_list_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_with_filter_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_with_filter_mca.py new file mode 100644 index 000000000000..4b31258e0748 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_dimensions_list_with_filter_mca.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_dimensions_list_with_filter_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py new file mode 100644 index 000000000000..5ca0635445f2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/InvoiceSectionForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_query_grouping_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_query_grouping_mca.py new file mode 100644 index 000000000000..3a2c41c46e53 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_query_grouping_mca.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_query_grouping_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_query_mca.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_query_mca.py new file mode 100644 index 000000000000..2806276c3bc4 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/invoice_section_query_mca.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python invoice_section_query_mca.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Billing/billingAccounts/12345:6789/billingProfiles/13579/invoiceSections/9876", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/MCAInvoiceSectionQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top_legacy.py new file mode 100644 index 000000000000..63ffe448c71a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_expand_and_top_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python management_group_dimensions_list_expand_and_top_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Management/managementGroups/MyMgId", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupDimensionsListExpandAndTop.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_legacy.py new file mode 100644 index 000000000000..df07d8a00487 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python management_group_dimensions_list_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Management/managementGroups/MyMgId", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter_legacy.py new file mode 100644 index 000000000000..1ce215fa7568 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_dimensions_list_with_filter_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python management_group_dimensions_list_with_filter_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="providers/Microsoft.Management/managementGroups/MyMgId", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupDimensionsListWithFilter.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping_legacy.py new file mode 100644 index 000000000000..c2d9318c5f2a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_grouping_legacy.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python management_group_query_grouping_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Management/managementGroups/MyMgId", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_legacy.py new file mode 100644 index 000000000000..28fc66ee84cb --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/management_group_query_legacy.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python management_group_query_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="providers/Microsoft.Management/managementGroups/MyMgId", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ManagementGroupQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py new file mode 100644 index 000000000000..6c325487a5b9 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/operation_list.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python operation_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.operations.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/OperationList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/patch_resource_group_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/patch_resource_group_alerts.py new file mode 100644 index 000000000000..2ac6755fa379 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/patch_resource_group_alerts.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python patch_resource_group_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.dismiss( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer", + alert_id="22222222-2222-2222-2222-222222222222", + parameters={"properties": {"status": "Dismissed"}}, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DismissResourceGroupAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/patch_subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/patch_subscription_alerts.py new file mode 100644 index 000000000000..f9c4741ea35b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/patch_subscription_alerts.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python patch_subscription_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.dismiss( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + alert_id="22222222-2222-2222-2222-222222222222", + parameters={"properties": {"status": "Dismissed"}}, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/DismissSubscriptionAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py new file mode 100644 index 000000000000..2450cd629150 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python pricesheet_download.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.price_sheet.begin_download( + billing_account_name="7c05a543-80ff-571e-9f98-1063b3b53cf2:99ad03ad-2d1b-4889-a452-090ad407d25f_2019-05-31", + billing_profile_name="2USN-TPCD-BG7-TGB", + invoice_name="T000940677", + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PricesheetDownload.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py new file mode 100644 index 000000000000..e6a64be2fa83 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/pricesheet_download_by_billing_profile.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python pricesheet_download_by_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.price_sheet.begin_download_by_billing_profile( + billing_account_name="7c05a543-80ff-571e-9f98-1063b3b53cf2:99ad03ad-2d1b-4889-a452-090ad407d25f_2019-05-31", + billing_profile_name="2USN-TPCD-BG7-TGB", + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PricesheetDownloadByBillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_action.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_action.py new file mode 100644 index 000000000000..b8a398bb6e47 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_action.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python private_scheduled_action.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.get( + name="monthlyCostByResource", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-get-private.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_action_delete.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_action_delete.py new file mode 100644 index 000000000000..430d92a77b88 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_action_delete.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python private_scheduled_action_delete.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.delete( + name="monthlyCostByResource", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-delete-private.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_actions_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_actions_list.py new file mode 100644 index 000000000000..efd002ebf1b2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_actions_list.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python private_scheduled_actions_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-list-private.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_actions_list_filter_by_view_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_actions_list_filter_by_view_id.py new file mode 100644 index 000000000000..6814e9ba13ae --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_scheduled_actions_list_filter_by_view_id.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python private_scheduled_actions_list_filter_by_view_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-listWithFilter-private.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py new file mode 100644 index 000000000000..506133cc0ef2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python private_view.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.get( + view_name="swaggerExample", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateView.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py new file mode 100644 index 000000000000..ff5ce767ac30 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/private_view_list.py @@ -0,0 +1,38 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python private_view_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.list() + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/PrivateViewList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/reservation_details.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/reservation_details.py new file mode 100644 index 000000000000..8fe21d7aa2b8 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/reservation_details.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python reservation_details.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.generate_reservation_details_report.begin_by_billing_account_id( + billing_account_id="9845612", + start_date="2020-01-01", + end_date="2020-01-30", + ).result() + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/GenerateReservationDetailsReportByBillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py new file mode 100644 index 000000000000..4d2c8998f9a0 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_create_or_update_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_create_or_update_view.py new file mode 100644 index 000000000000..ddb41feb5c8f --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_create_or_update_view.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_create_or_update_view.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.create_or_update_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + view_name="swaggerExample", + parameters={ + "eTag": '"1d4ff9fe66f1d10"', + "properties": { + "accumulated": "true", + "chart": "Table", + "displayName": "swagger Example", + "kpis": [ + {"enabled": True, "id": None, "type": "Forecast"}, + { + "enabled": True, + "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG/providers/Microsoft.Consumption/budgets/swaggerDemo", + "type": "Budget", + }, + ], + "metric": "ActualCost", + "pivots": [ + {"name": "ServiceName", "type": "Dimension"}, + {"name": "MeterCategory", "type": "Dimension"}, + {"name": "swaggerTagKey", "type": "TagKey"}, + ], + "query": { + "dataSet": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "Daily", + "grouping": [], + "sorting": [{"direction": "Ascending", "name": "UsageDate"}], + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewCreateOrUpdateByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_delete_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_delete_view.py new file mode 100644 index 000000000000..3e11c6382498 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_delete_view.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_delete_view.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.delete_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + view_name="TestView", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewDeleteByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list_legacy.py new file mode 100644 index 000000000000..0751066e2ecd --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_dimensions_list_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_dimensions_list_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/system.orlando", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py new file mode 100644 index 000000000000..4c7ea0276418 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping_legacy.py new file mode 100644 index 000000000000..dccb30a3b80b --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_grouping_legacy.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_query_grouping_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "Daily", + "grouping": [{"name": "ResourceType", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_legacy.py new file mode 100644 index 000000000000..720819019ae1 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_query_legacy.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_query_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ResourceGroupQuery.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_view.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_view.py new file mode 100644 index 000000000000..e9fcfb3a18e2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_view.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_view.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.get_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + view_name="swaggerExample", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_view_list.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_view_list.py new file mode 100644 index 000000000000..369b82d349b3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/resource_group_view_list.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python resource_group_view_list.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.views.list_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MYDEVTESTRG", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/ViewListByResourceGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_billing_account.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_billing_account.py new file mode 100644 index 000000000000..7c1b071290df --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_billing_account.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python savings_plan_utilization_summaries_billing_account.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.benefit_utilization_summaries.list_by_billing_account_id( + billing_account_id="12345", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-BillingAccount.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_billing_profile.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_billing_profile.py new file mode 100644 index 000000000000..ec5ccd3453db --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_billing_profile.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python savings_plan_utilization_summaries_billing_profile.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.benefit_utilization_summaries.list_by_billing_profile_id( + billing_account_id="c0a00000-0e04-5ee3-000e-f0c6e00000ec:c0a00000-0e04-5ee3-000e-f0c6e00000ec", + billing_profile_id="200e5e90-000e-4960-8dcd-8d00a02db000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-BillingProfile.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_daily.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_daily.py new file mode 100644 index 000000000000..d925c8e02a7a --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_daily.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python savings_plan_utilization_summaries_daily.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.benefit_utilization_summaries.list_by_savings_plan_order( + savings_plan_order_id="66cccc66-6ccc-6c66-666c-66cc6c6c66c6", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-SavingsPlanOrderId-Daily.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_monthly_with_savings_plan_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_monthly_with_savings_plan_id.py new file mode 100644 index 000000000000..6b75daf0eb01 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/savings_plan_utilization_summaries_monthly_with_savings_plan_id.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python savings_plan_utilization_summaries_monthly_with_savings_plan_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.benefit_utilization_summaries.list_by_savings_plan_id( + savings_plan_order_id="66cccc66-6ccc-6c66-666c-66cc6c6c66c6", + savings_plan_id="222d22dd-d2d2-2dd2-222d-2dd2222ddddd", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/BenefitUtilizationSummaries/SavingsPlan-SavingsPlanId-Monthly.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_by_scope.py new file mode 100644 index 000000000000..66e919a9c25c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_by_scope.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_action_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.get_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + name="monthlyCostByResource", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-get-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_check_name_availability.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_check_name_availability.py new file mode 100644 index 000000000000..8b9234d05831 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_check_name_availability.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_action_check_name_availability.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.check_name_availability( + check_name_availability_request={"name": "testName", "type": "Microsoft.CostManagement/ScheduledActions"}, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/checkNameAvailability-private-scheduledAction.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_check_name_availability_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_check_name_availability_by_scope.py new file mode 100644 index 000000000000..b4143d3fec08 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_check_name_availability_by_scope.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_action_check_name_availability_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.check_name_availability_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + check_name_availability_request={"name": "testName", "type": "Microsoft.CostManagement/ScheduledActions"}, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/checkNameAvailability-shared-scheduledAction.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_delete_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_delete_by_scope.py new file mode 100644 index 000000000000..16475554ac21 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_delete_by_scope.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_action_delete_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.delete_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + name="monthlyCostByResource", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-delete-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_run_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_run_by_scope.py new file mode 100644 index 000000000000..d24de12f2a17 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_run_by_scope.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_action_run_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.run_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + name="monthlyCostByResource", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-sendNow-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_send_now.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_send_now.py new file mode 100644 index 000000000000..74503ffeab06 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_action_send_now.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_action_send_now.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.run( + name="monthlyCostByResource", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledAction-sendNow-private.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions_list_by_scope.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions_list_by_scope.py new file mode 100644 index 000000000000..64d591648bd6 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions_list_by_scope.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_actions_list_by_scope.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.list_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-list-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions_list_by_scope_filter_by_view_id.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions_list_by_scope_filter_by_view_id.py new file mode 100644 index 000000000000..1707a00ae03d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/scheduled_actions_list_by_scope_filter_by_view_id.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python scheduled_actions_list_by_scope_filter_by_view_id.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.scheduled_actions.list_by_scope( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/scheduledActions/scheduledActions-listWithFilter-shared.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alerts.py new file mode 100644 index 000000000000..c5e02e62edcc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_resource_group_alerts.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python single_resource_group_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer", + alert_id="22222222-2222-2222-2222-222222222222", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SingleResourceGroupAlert.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alerts.py new file mode 100644 index 000000000000..f3d53894a833 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/single_subscription_alerts.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python single_subscription_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.get( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + alert_id="22222222-2222-2222-2222-222222222222", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SingleSubscriptionAlert.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py new file mode 100644 index 000000000000..3402e29b0f72 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_alerts.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python subscription_alerts.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.alerts.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionAlerts.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list_legacy.py new file mode 100644 index 000000000000..33c508bb1abc --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_dimensions_list_legacy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python subscription_dimensions_list_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.dimensions.list( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionDimensionsList.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py new file mode 100644 index 000000000000..63c6ba54de7c --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_forecast.py @@ -0,0 +1,67 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python subscription_forecast.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.forecast.usage( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "Cost"}}, + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "includeActualCost": False, + "includeFreshPartialCost": False, + "timePeriod": {"from": "2022-08-01T00:00:00+00:00", "to": "2022-08-31T23:59:59+00:00"}, + "timeframe": "Custom", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionForecast.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping_legacy.py new file mode 100644 index 000000000000..eed3d3246164 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_grouping_legacy.py @@ -0,0 +1,48 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python subscription_query_grouping_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + parameters={ + "dataset": { + "aggregation": {"totalCost": {"function": "Sum", "name": "PreTaxCost"}}, + "granularity": "None", + "grouping": [{"name": "ResourceGroup", "type": "Dimension"}], + }, + "timeframe": "TheLastMonth", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionQueryGrouping.json +if __name__ == "__main__": + main() diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_legacy.py b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_legacy.py new file mode 100644 index 000000000000..e3a8e45fdcb5 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/generated_samples/subscription_query_legacy.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential +from azure.mgmt.costmanagement import CostManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-costmanagement +# USAGE + python subscription_query_legacy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = CostManagementClient( + credential=DefaultAzureCredential(), + ) + + response = client.query.usage( + scope="subscriptions/00000000-0000-0000-0000-000000000000", + parameters={ + "dataset": { + "filter": { + "and": [ + { + "or": [ + { + "dimensions": { + "name": "ResourceLocation", + "operator": "In", + "values": ["East US", "West Europe"], + } + }, + {"tags": {"name": "Environment", "operator": "In", "values": ["UAT", "Prod"]}}, + ] + }, + {"dimensions": {"name": "ResourceGroup", "operator": "In", "values": ["API"]}}, + ] + }, + "granularity": "Daily", + }, + "timeframe": "MonthToDate", + "type": "Usage", + }, + ) + print(response) + + +# x-ms-original-file: specification/cost-management/resource-manager/Microsoft.CostManagement/stable/2022-10-01/examples/SubscriptionQuery.json +if __name__ == "__main__": + main()