From 6c4c1dc9e411303176d2d3ddb66d4a9a920088a0 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Wed, 19 Oct 2022 22:07:48 +0000 Subject: [PATCH] CodeGen from PR 20776 in Azure/azure-rest-api-specs Merge 967ad16569ec18bcd2546a4691e5f063e8dacd9a into b25c293b86861309fb7806985f1fcfce24060f84 --- .../azure-mgmt-costmanagement/_meta.json | 12 +- .../azure/mgmt/costmanagement/__init__.py | 13 +- .../mgmt/costmanagement/_configuration.py | 55 +- .../costmanagement/_cost_management_client.py | 156 +- .../azure/mgmt/costmanagement/_metadata.json | 99 - .../azure/mgmt/costmanagement/_patch.py | 20 + .../mgmt/costmanagement/_serialization.py | 1970 +++++++++ .../azure/mgmt/costmanagement/_vendor.py | 27 + .../azure/mgmt/costmanagement/_version.py | 2 +- .../azure/mgmt/costmanagement/aio/__init__.py | 13 +- .../mgmt/costmanagement/aio/_configuration.py | 52 +- .../aio/_cost_management_client.py | 148 +- .../azure/mgmt/costmanagement/aio/_patch.py | 20 + .../costmanagement/aio/operations/__init__.py | 34 +- .../aio/operations/_alerts_operations.py | 325 -- .../_benefit_recommendation_operations.py | 116 + .../_benefit_recommendations_operations.py | 166 + ...enefit_utilization_summaries_operations.py | 459 ++ .../aio/operations/_dimensions_operations.py | 252 -- .../aio/operations/_exports_operations.py | 483 --- .../aio/operations/_forecast_operations.py | 203 - ...generate_cost_details_report_operations.py | 456 ++ ...e_reservation_details_report_operations.py | 302 -- .../aio/operations/_operations.py | 133 +- .../costmanagement/aio/operations/_patch.py | 20 + .../aio/operations/_query_operations.py | 189 - .../_scheduled_actions_operations.py | 1214 ++++++ .../aio/operations/_settings_operations.py | 273 -- .../aio/operations/_views_operations.py | 597 --- .../mgmt/costmanagement/models/__init__.py | 357 +- .../models/_cost_management_client_enums.py | 369 +- .../mgmt/costmanagement/models/_models.py | 2225 ---------- .../mgmt/costmanagement/models/_models_py3.py | 3734 ++++++++--------- .../mgmt/costmanagement/models/_patch.py | 20 + .../costmanagement/operations/__init__.py | 34 +- .../operations/_alerts_operations.py | 333 -- .../_benefit_recommendation_operations.py | 144 + .../_benefit_recommendations_operations.py | 206 + ...enefit_utilization_summaries_operations.py | 609 +++ .../operations/_dimensions_operations.py | 258 -- .../operations/_exports_operations.py | 493 --- .../operations/_forecast_operations.py | 209 - ...generate_cost_details_report_operations.py | 510 +++ ...e_reservation_details_report_operations.py | 310 -- .../costmanagement/operations/_operations.py | 163 +- .../mgmt/costmanagement/operations/_patch.py | 20 + .../operations/_query_operations.py | 195 - .../_scheduled_actions_operations.py | 1499 +++++++ .../operations/_settings_operations.py | 281 -- .../operations/_views_operations.py | 609 --- 50 files changed, 9889 insertions(+), 10498 deletions(-) delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_metadata.json create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_patch.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_serialization.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/_vendor.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/_patch.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendation_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_patch.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_settings_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_models.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/models/_patch.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendation_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_patch.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py create mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_settings_operations.py delete mode 100644 sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py diff --git a/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json b/sdk/costmanagement/azure-mgmt-costmanagement/_meta.json index 8041e01d515b..5d38e999db48 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": "99260846f25919e315f65815efdced0cb0ceb597", + "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.1.11", + "@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 --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.11 --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..04ace69e34c8 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,15 @@ 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..8c4a6d917567 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,59 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +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 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: str + 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..dc9ed0d8c3b6 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,108 +6,108 @@ # 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 ( + BenefitRecommendationOperations, + BenefitRecommendationsOperations, + BenefitUtilizationSummariesOperations, + GenerateCostDetailsReportOperations, + Operations, + ScheduledActionsOperations, +) 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: # pylint: disable=client-accepts-api-version-keyword + """CostManagement management client provides access to CostManagement resources for Azure + Enterprise Subscriptions. -class CostManagementClient(object): - """CostManagementClient. - - :ivar settings: SettingsOperations operations - :vartype settings: azure.mgmt.costmanagement.operations.SettingsOperations - :ivar views: ViewsOperations operations - :vartype views: azure.mgmt.costmanagement.operations.ViewsOperations - :ivar alerts: AlertsOperations operations - :vartype alerts: azure.mgmt.costmanagement.operations.AlertsOperations - :ivar forecast: ForecastOperations operations - :vartype forecast: azure.mgmt.costmanagement.operations.ForecastOperations - :ivar dimensions: DimensionsOperations operations - :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 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 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_recommendation: BenefitRecommendationOperations operations + :vartype benefit_recommendation: + azure.mgmt.costmanagement.operations.BenefitRecommendationOperations + :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.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._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.generate_cost_details_report = GenerateCostDetailsReportOperations( + 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_recommendation = BenefitRecommendationOperations( + 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..05984fcaff95 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,15 @@ # -------------------------------------------------------------------------- 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..6d873e46cf85 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 @@ -10,7 +10,7 @@ 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 @@ -19,43 +19,43 @@ 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: str + 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..162636614d26 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,104 +6,108 @@ # 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 ( + BenefitRecommendationOperations, + BenefitRecommendationsOperations, + BenefitUtilizationSummariesOperations, + GenerateCostDetailsReportOperations, + Operations, + ScheduledActionsOperations, +) 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: # pylint: disable=client-accepts-api-version-keyword + """CostManagement management client provides access to CostManagement resources for Azure + Enterprise Subscriptions. -class CostManagementClient(object): - """CostManagementClient. - - :ivar settings: SettingsOperations operations - :vartype settings: azure.mgmt.costmanagement.aio.operations.SettingsOperations - :ivar views: ViewsOperations operations - :vartype views: azure.mgmt.costmanagement.aio.operations.ViewsOperations - :ivar alerts: AlertsOperations operations - :vartype alerts: azure.mgmt.costmanagement.aio.operations.AlertsOperations - :ivar forecast: ForecastOperations operations - :vartype forecast: azure.mgmt.costmanagement.aio.operations.ForecastOperations - :ivar dimensions: DimensionsOperations operations - :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 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 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_recommendation: BenefitRecommendationOperations operations + :vartype benefit_recommendation: + azure.mgmt.costmanagement.aio.operations.BenefitRecommendationOperations + :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._serialize.client_side_validation = False + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.generate_cost_details_report = GenerateCostDetailsReportOperations( + 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_recommendation = BenefitRecommendationOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.benefit_utilization_summaries = BenefitUtilizationSummariesOperations( + self._client, self._config, self._serialize, self._deserialize + ) - 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.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) - - 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..0ee2bdde1f67 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,24 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._settings_operations import SettingsOperations -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 ._scheduled_actions_operations import ScheduledActionsOperations +from ._benefit_recommendations_operations import BenefitRecommendationsOperations +from ._benefit_recommendation_operations import BenefitRecommendationOperations +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", + "GenerateCostDetailsReportOperations", + "ScheduledActionsOperations", + "BenefitRecommendationsOperations", + "BenefitRecommendationOperations", + "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 deleted file mode 100644 index 216d5ebc7b21..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_alerts_operations.py +++ /dev/null @@ -1,325 +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, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -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 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. - - :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 - - 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 - '/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. - :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) - :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :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.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') - - 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('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": - """Gets the alert for the scope by alert ID. - - :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. - :type scope: str - :param alert_id: Alert ID. - :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) - :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" - 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), - } - 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('Alert', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore - - async def dismiss( - self, - scope: str, - alert_id: str, - parameters: "_models.DismissAlertPayload", - **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. - :type scope: str - :param alert_id: Alert ID. - :type alert_id: str - :param parameters: Parameters supplied to the Dismiss Alert operation. - :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload - :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), - } - 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) - 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('Alert', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - dismiss.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore - - async def list_external( - self, - 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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :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) - :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :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'), - } - 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('AlertsResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - 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_recommendation_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendation_operations.py new file mode 100644 index 000000000000..845c6e78a64d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendation_operations.py @@ -0,0 +1,116 @@ +# 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. +# -------------------------------------------------------------------------- +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._benefit_recommendation_operations import build_get_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class BenefitRecommendationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s + :attr:`benefit_recommendation` 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, billing_scope: str, recommendation_id: str, **kwargs: Any + ) -> _models.BenefitRecommendationModel: + """Details of a benefit plan recommendation for what-if analysis. + + :param billing_scope: The scope associated with benefit recommendation details operations. This + includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, + /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope. Required. + :type billing_scope: str + :param recommendation_id: The ID of the recommendation. Required. + :type recommendation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BenefitRecommendationModel or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.BenefitRecommendationModel + :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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitRecommendationModel] + + request = build_get_request( + billing_scope=billing_scope, + recommendation_id=recommendation_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 + ) + + 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("BenefitRecommendationModel", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations/{recommendationId}"} # 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..e8f2a2835877 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_recommendations_operations.py @@ -0,0 +1,166 @@ +# 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. +# -------------------------------------------------------------------------- +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 + +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 benefit (reservation or savings plan). + + :param billing_scope: The scope associated with benefit recommendation details operations. This + includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, + /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile 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'; kind with default + value 'SavingsPlan'; properties/armSkuName with allowed values ['Compute', 'SQL'] - if + mentioned kind SavingsPlan is applied implicitly; properties/subscriptionId; + properties/resourceGroup. Default value is None. + :type filter: str + :param orderby: May be used to order the recommendations by: properties/armSkuName. This + implicitly filters the results by the corresponding benefit type. 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: str + 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..09c6a28485d3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_benefit_utilization_summaries_operations.py @@ -0,0 +1,459 @@ +# 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. +# -------------------------------------------------------------------------- +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, +) + +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 benefit utilization summaries for the provided billingAccount. This API provides benefit + utilization summaries only for enrollment accounts. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param grain_parameter: Daily or monthly 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/benefitType, properties/benefitId, + properties/benefitOrderId and properties/usageDate. properties/benefitType is defaulted to + savingsPlan. 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: str + 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 benefit utilization summaries for billingProfile. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure billing profile ID. Required. + :type billing_profile_id: str + :param grain_parameter: Daily or monthly 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/benefitType, properties/benefitId, + properties/benefitOrderId and properties/usageDate. properties/benefitType is defaulted to + savingsPlan. 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: str + 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: Daily or monthly 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: str + 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: Daily or monthly 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: str + 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 deleted file mode 100644 index 090f2e992e2d..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_dimensions_operations.py +++ /dev/null @@ -1,252 +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, Union -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 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. - - :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, - scope: str, - filter: Optional[str] = None, - expand: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs: Any - ) -> AsyncIterable["_models.DimensionsListResult"]: - """Lists the dimensions by the defined scope. - - :param scope: The scope associated with dimension 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.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. - :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'. - :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. - :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. - :type skiptoken: str - :param top: May be used to limit the number of results to the most recent N dimension data. - :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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] - 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 - 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) - 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('DimensionsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return 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, 204]: - 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': '/{scope}/providers/Microsoft.CostManagement/dimensions'} # type: ignore - - def by_external_cloud_provider_type( - self, - 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"]: - """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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :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'. - :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. - :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. - :type skiptoken: str - :param top: May be used to limit the number of results to the most recent N dimension data. - :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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] - 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.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) - 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('DimensionsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return 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 - ) - 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 deleted file mode 100644 index 2f3497eee08b..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_exports_operations.py +++ /dev/null @@ -1,483 +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, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -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 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. - - :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 - - async def list( - self, - scope: str, - **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 - '/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. - :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportListResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.ExportListResult - :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), - } - 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('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": - """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 - '/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. - :type scope: str - :param export_name: Export Name. - :type export_name: 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" - 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') - - # 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('Export', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore - - async def create_or_update( - self, - scope: str, - export_name: str, - parameters: "_models.Export", - **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 - '/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. - :type scope: str - :param export_name: Export Name. - :type export_name: str - :param parameters: Parameters supplied to the CreateOrUpdate Export operation. - :type parameters: ~azure.mgmt.costmanagement.models.Export - :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'), - } - 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) - 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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('Export', pipeline_response) - - if response.status_code == 201: - 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 - ) -> None: - """The operation to delete a export. - - :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. - :type scope: str - :param export_name: Export Name. - :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) - :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 = { - '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') - - 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) - 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 - - async def execute( - self, - scope: str, - export_name: str, - **kwargs: Any - ) -> None: - """The operation to execute a export. - - :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. - :type scope: str - :param export_name: Export Name. - :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) - :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.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') - - 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) - 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 - - 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. - - :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. - :type scope: str - :param export_name: Export Name. - :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) - :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :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'), - } - 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('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 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 deleted file mode 100644 index 8524f06621a5..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_forecast_operations.py +++ /dev/null @@ -1,203 +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, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -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 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. - - :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 - - async def usage( - self, - scope: str, - parameters: "_models.ForecastDefinition", - filter: Optional[str] = None, - **kwargs: Any - ) -> Optional["_models.QueryResult"]: - """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. - :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. - :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'. - :type filter: 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 - """ - 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), - } - 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) - 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) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/forecast'} # type: ignore - - async def external_cloud_provider_usage( - self, - external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], - external_cloud_provider_id: str, - parameters: "_models.ForecastDefinition", - filter: Optional[str] = None, - **kwargs: Any - ) -> "_models.QueryResult": - """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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. - :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'. - :type filter: 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.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'), - } - 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) - 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('QueryResult', 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 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..6423f07d78c2 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_cost_details_report_operations.py @@ -0,0 +1,456 @@ +# 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. +# -------------------------------------------------------------------------- +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, +) + +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: str + 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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: str + 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: str + 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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: 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._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_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py deleted file mode 100644 index 04654269eb88..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_generate_reservation_details_report_operations.py +++ /dev/null @@ -1,302 +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, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -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.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -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') -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. - - :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 - - 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"]] - 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_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') - - # 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 = 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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - deserialized = None - if response.status_code == 200: - 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')) - - 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 - - async def begin_by_billing_account_id( - 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. - - :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). - :type billing_account_id: str - :param start_date: Start Date. - :type start_date: str - :param end_date: End Date. - :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. - :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) - :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] - if cont_token is None: - raw_result = await self._by_billing_account_id_initial( - billing_account_id=billing_account_id, - start_date=start_date, - end_date=end_date, - cls=lambda x,y,z: x, - **kwargs - ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(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 cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - 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 - - 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"]] - 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'), - } - 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') - - # 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 = 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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - response_headers = {} - deserialized = None - if response.status_code == 200: - 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')) - - 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 - - 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"]: - """Generates the reservations details report for provided date range asynchronously by billing - profile. - - :param billing_account_id: BillingAccount ID. - :type billing_account_id: str - :param billing_profile_id: BillingProfile ID. - :type billing_profile_id: str - :param start_date: Start Date. - :type start_date: str - :param end_date: End Date. - :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. - :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) - :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] - if cont_token is None: - raw_result = await self._by_billing_profile_id_initial( - 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, - **kwargs - ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(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 cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - 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 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..a11a63f3b4c0 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,109 @@ # 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 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 +from ..._vendor import _convert_request +from ...operations._operations import build_list_request -T = TypeVar('T') +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: str + 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 +117,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/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py deleted file mode 100644 index 7a973c90e3c8..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_query_operations.py +++ /dev/null @@ -1,189 +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, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings - -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 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. - - :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 - - async def usage( - self, - scope: str, - parameters: "_models.QueryDefinition", - **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. - :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition - :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 - """ - 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), - } - 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) - 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) - - deserialized = None - if response.status_code == 200: - 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 - - async def usage_by_external_cloud_provider_type( - self, - external_cloud_provider_type: Union[str, "_models.ExternalCloudProviderType"], - external_cloud_provider_id: str, - parameters: "_models.QueryDefinition", - **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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition - :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'), - } - 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) - 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('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 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..7c470925bbac --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_scheduled_actions_operations.py @@ -0,0 +1,1214 @@ +# 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. +# -------------------------------------------------------------------------- +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_execute_by_scope_request, + build_execute_request, + build_get_by_scope_request, + build_get_request, + build_list_by_scope_request, + build_list_request, +) + +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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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 execute(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Execute 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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_request( + name=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 + ) + + 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, {}) + + execute.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} # type: ignore + + @distributed_trace_async + async def execute_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, name: str, **kwargs: Any + ) -> None: + """Execute 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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.execute_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, {}) + + execute_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: str + 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: str + 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 deleted file mode 100644 index a82f547d6103..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/aio/operations/_views_operations.py +++ /dev/null @@ -1,597 +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, Union -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 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. - - :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.ViewListResult"]: - """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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] - 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('ViewListResult', 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, 204]: - 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/views'} # type: ignore - - def list_by_scope( - self, - scope: str, - **kwargs: Any - ) -> AsyncIterable["_models.ViewListResult"]: - """Lists all views at the given scope. - - :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. - :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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] - 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_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) - 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('ViewListResult', 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, 204]: - 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_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views'} # type: ignore - - async def get( - self, - view_name: str, - **kwargs: Any - ) -> "_models.View": - """Gets the view by view name. - - :param view_name: View name. - :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) - :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 - } - 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') - - # 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('View', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - - async def create_or_update( - self, - view_name: str, - parameters: "_models.View", - **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. - :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. - :type parameters: ~azure.mgmt.costmanagement.models.View - :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 - } - 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 = await self._client._pipeline.run(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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) - - if response.status_code == 201: - 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: - """The operation to delete a view. - - :param view_name: View name. - :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) - :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 = { - '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['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/views/{viewName}'} # type: ignore - - 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 - '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. - :type scope: str - :param view_name: View name. - :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) - :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 - } - 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') - - # 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('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 - - async def create_or_update_by_scope( - self, - scope: str, - view_name: str, - parameters: "_models.View", - **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. - :type scope: str - :param view_name: View name. - :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. - :type parameters: ~azure.mgmt.costmanagement.models.View - :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 - } - 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 = await self._client._pipeline.run(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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) - - if response.status_code == 201: - 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 - ) -> None: - """The operation to delete a view. - - :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. - :type scope: str - :param view_name: View name. - :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) - :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_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['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_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..d6e6cd2d6f34 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,126 @@ # 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 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 CostDetailsOperationResults +from ._models_py3 import CostDetailsTimePeriod +from ._models_py3 import CostManagementOperation +from ._models_py3 import ErrorDetails +from ._models_py3 import ErrorResponse +from ._models_py3 import FileDestination +from ._models_py3 import GenerateCostDetailsReportErrorResponse +from ._models_py3 import GenerateCostDetailsReportRequestDefinition +from ._models_py3 import IncludedQuantityUtilizationSummary +from ._models_py3 import IncludedQuantityUtilizationSummaryProperties +from ._models_py3 import NotificationProperties +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import ProxyResource +from ._models_py3 import RecommendationUsageDetails +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 SystemData -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 ActionType +from ._cost_management_client_enums import BenefitKind +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 FileFormat +from ._cost_management_client_enums import Grain +from ._cost_management_client_enums import GrainParameter +from ._cost_management_client_enums import LookBackPeriod +from ._cost_management_client_enums import Origin +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 Term +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', + "AllSavingsBenefitDetails", + "AllSavingsList", + "BenefitRecommendationModel", + "BenefitRecommendationProperties", + "BenefitRecommendationsListResult", + "BenefitResource", + "BenefitUtilizationSummariesListResult", + "BenefitUtilizationSummary", + "BenefitUtilizationSummaryProperties", + "BlobInfo", + "CheckNameAvailabilityRequest", + "CheckNameAvailabilityResponse", + "CostDetailsOperationResults", + "CostDetailsTimePeriod", + "CostManagementOperation", + "ErrorDetails", + "ErrorResponse", + "FileDestination", + "GenerateCostDetailsReportErrorResponse", + "GenerateCostDetailsReportRequestDefinition", + "IncludedQuantityUtilizationSummary", + "IncludedQuantityUtilizationSummaryProperties", + "NotificationProperties", + "Operation", + "OperationDisplay", + "OperationListResult", + "ProxyResource", + "RecommendationUsageDetails", + "Resource", + "SavingsPlanUtilizationSummary", + "SavingsPlanUtilizationSummaryProperties", + "ScheduleProperties", + "ScheduledAction", + "ScheduledActionListResult", + "ScheduledActionProxyResource", + "SharedScopeBenefitRecommendationProperties", + "SingleScopeBenefitRecommendationProperties", + "SystemData", + "ActionType", + "BenefitKind", + "CheckNameAvailabilityReason", + "CostDetailsDataFormat", + "CostDetailsMetricType", + "CostDetailsStatusType", + "CreatedByType", + "DaysOfWeek", + "FileFormat", + "Grain", + "GrainParameter", + "LookBackPeriod", + "Origin", + "ScheduleFrequency", + "ScheduledActionKind", + "ScheduledActionStatus", + "Scope", + "Term", + "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..3fef5bd90ea0 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,313 +6,186 @@ # 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. - """ - - TRUE = "true" - FALSE = "false" - -class AlertCategory(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Alert category - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta - COST = "Cost" - USAGE = "Usage" - BILLING = "Billing" - SYSTEM = "System" -class AlertCriteria(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Criteria that triggered alert - """ +class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.""" - COST_THRESHOLD_EXCEEDED = "CostThresholdExceeded" - USAGE_THRESHOLD_EXCEEDED = "UsageThresholdExceeded" - CREDIT_THRESHOLD_APPROACHING = "CreditThresholdApproaching" - CREDIT_THRESHOLD_REACHED = "CreditThresholdReached" - QUOTA_THRESHOLD_APPROACHING = "QuotaThresholdApproaching" - QUOTA_THRESHOLD_REACHED = "QuotaThresholdReached" - MULTI_CURRENCY = "MultiCurrency" - FORECAST_COST_THRESHOLD_EXCEEDED = "ForecastCostThresholdExceeded" - FORECAST_USAGE_THRESHOLD_EXCEEDED = "ForecastUsageThresholdExceeded" - INVOICE_DUE_DATE_APPROACHING = "InvoiceDueDateApproaching" - INVOICE_DUE_DATE_REACHED = "InvoiceDueDateReached" - CROSS_CLOUD_NEW_DATA_AVAILABLE = "CrossCloudNewDataAvailable" - CROSS_CLOUD_COLLECTION_ERROR = "CrossCloudCollectionError" - GENERAL_THRESHOLD_ERROR = "GeneralThresholdError" - -class AlertOperator(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """operator used to compare currentSpend with amount - """ + INTERNAL = "Internal" - NONE = "None" - EQUAL_TO = "EqualTo" - GREATER_THAN = "GreaterThan" - GREATER_THAN_OR_EQUAL_TO = "GreaterThanOrEqualTo" - LESS_THAN = "LessThan" - LESS_THAN_OR_EQUAL_TO = "LessThanOrEqualTo" -class AlertSource(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Source of alert - """ +class BenefitKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind/type of the benefit.""" - PRESET = "Preset" - USER = "User" + #: Benefit is IncludedQuantity. + INCLUDED_QUANTITY = "IncludedQuantity" + #: Benefit is Reservation. + RESERVATION = "Reservation" + #: Benefit is SavingsPlan. + SAVINGS_PLAN = "SavingsPlan" -class AlertStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """alert status - """ - NONE = "None" - ACTIVE = "Active" - OVERRIDDEN = "Overridden" - RESOLVED = "Resolved" - DISMISSED = "Dismissed" +class CheckNameAvailabilityReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The reason why the given name is not available.""" -class AlertTimeGrainType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Type of timegrain cadence - """ + INVALID = "Invalid" + ALREADY_EXISTS = "AlreadyExists" - NONE = "None" - MONTHLY = "Monthly" - QUARTERLY = "Quarterly" - ANNUALLY = "Annually" - BILLING_MONTH = "BillingMonth" - BILLING_QUARTER = "BillingQuarter" - BILLING_ANNUAL = "BillingAnnual" - -class AlertType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """type of alert - """ - BUDGET = "Budget" - INVOICE = "Invoice" - CREDIT = "Credit" - QUOTA = "Quota" - GENERAL = "General" - X_CLOUD = "xCloud" - BUDGET_FORECAST = "BudgetForecast" +class CostDetailsDataFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The data format of the report.""" -class ChartType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Chart type of the main view in Cost Analysis. Required. - """ + #: Csv data format. + CSV_COST_DETAILS_DATA_FORMAT = "Csv" - AREA = "Area" - LINE = "Line" - STACKED_COLUMN = "StackedColumn" - GROUPED_COLUMN = "GroupedColumn" - TABLE = "Table" -class ExecutionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the export execution. - """ +class CostDetailsMetricType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the detailed report. By default ActualCost is provided.""" - QUEUED = "Queued" - IN_PROGRESS = "InProgress" - COMPLETED = "Completed" - FAILED = "Failed" - TIMEOUT = "Timeout" - NEW_DATA_NOT_AVAILABLE = "NewDataNotAvailable" - DATA_NOT_AVAILABLE = "DataNotAvailable" + #: Actual cost data. + ACTUAL_COST_COST_DETAILS_METRIC_TYPE = "ActualCost" + #: Amortized cost data. + AMORTIZED_COST_COST_DETAILS_METRIC_TYPE = "AmortizedCost" -class ExecutionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the export execution. - """ - ON_DEMAND = "OnDemand" - SCHEDULED = "Scheduled" +class CostDetailsStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the cost details operation.""" -class ExportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the query. - """ + #: 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" - USAGE = "Usage" - ACTUAL_COST = "ActualCost" - AMORTIZED_COST = "AmortizedCost" -class ExternalCloudProviderType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" - EXTERNAL_SUBSCRIPTIONS = "externalSubscriptions" - EXTERNAL_BILLING_ACCOUNTS = "externalBillingAccounts" + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" -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" - CUSTOM = "Custom" +class DaysOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Days of Week.""" -class ForecastType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the forecast. - """ + MONDAY = "Monday" + TUESDAY = "Tuesday" + WEDNESDAY = "Wednesday" + THURSDAY = "Thursday" + FRIDAY = "Friday" + SATURDAY = "Saturday" + SUNDAY = "Sunday" - USAGE = "Usage" - ACTUAL_COST = "ActualCost" - AMORTIZED_COST = "AmortizedCost" -class FormatType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The format of the export being delivered. - """ +class FileFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Destination of the view data. Currently only CSV format 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" - SUM = "Sum" -class GranularityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The granularity of rows in the query. - """ +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). - """ - - FORECAST = "Forecast" - BUDGET = "Budget" -class MetricType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Metric to use when displaying costs. - """ +class GrainParameter(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """GrainParameter.""" - ACTUAL_COST = "ActualCost" - AMORTIZED_COST = "AmortizedCost" - AHUB = "AHUB" + #: 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 OperationStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the long running operation. - """ - RUNNING = "Running" - COMPLETED = "Completed" - FAILED = "Failed" +class LookBackPeriod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The number of days used to look back.""" -class OperatorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The operator to use for comparison. - """ + #: 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" - IN_ENUM = "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". """ - DIMENSION = "Dimension" - TAG_KEY = "TagKey" + USER = "user" + SYSTEM = "system" + USER_SYSTEM = "user,system" -class QueryColumnType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the column in the export. - """ - TAG = "Tag" - DIMENSION = "Dimension" +class ScheduledActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind of the scheduled action.""" -class RecurrenceType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The schedule recurrence. - """ + #: 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" - DAILY = "Daily" - WEEKLY = "Weekly" - MONTHLY = "Monthly" - ANNUALLY = "Annually" -class ReportConfigColumnType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the column in the report. - """ - - TAG = "Tag" - DIMENSION = "Dimension" +class ScheduledActionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the scheduled action.""" -class ReportConfigSortingDirection(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Direction of sort. - """ + #: Scheduled action is saved but will not be executed. + DISABLED = "Disabled" + #: Scheduled action is saved and will be executed. + ENABLED = "Enabled" + #: Scheduled action is expired. + EXPIRED = "Expired" - ASCENDING = "Ascending" - DESCENDING = "Descending" -class ReportGranularityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The granularity of rows in the report. - """ +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 ReportTimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The time frame for pulling data for the report. If custom, then a specific time period must be - provided. - """ - WEEK_TO_DATE = "WeekToDate" - MONTH_TO_DATE = "MonthToDate" - YEAR_TO_DATE = "YearToDate" - CUSTOM = "Custom" +class Scope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Kind of the recommendation scope.""" -class ReportType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """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. - """ + #: Single scope recommendation. + SINGLE = "Single" + #: Shared scope recommendation. + SHARED = "Shared" - 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 Term(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Grain which corresponds to value.""" - LAST_USED = "LastUsed" - SCOPE_PICKER = "ScopePicker" - SPECIFIC_SCOPE = "SpecificScope" + #: Benefit term is 1 year. + P1_Y = "P1Y" + #: Benefit term is 3 years. + P3_Y = "P3Y" -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. - """ - ACTIVE = "Active" - INACTIVE = "Inactive" - -class TimeframeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The time frame for pulling data for the query. If custom, then a specific time period must be - provided. - """ +class WeeksOfMonth(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Weeks of month.""" - MONTH_TO_DATE = "MonthToDate" - BILLING_MONTH_TO_DATE = "BillingMonthToDate" - THE_LAST_MONTH = "TheLastMonth" - THE_LAST_BILLING_MONTH = "TheLastBillingMonth" - WEEK_TO_DATE = "WeekToDate" - CUSTOM = "Custom" + 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..670750b59828 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,2445 +8,2148 @@ # -------------------------------------------------------------------------- import datetime -from typing import Any, Dict, List, Optional, Union +from typing import List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._cost_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class Resource(msrest.serialization.Model): - """The Resource model definition. +class AllSavingsBenefitDetails(_serialization.Model): + """The properties of the benefit plan recommendation details for a saving. + + 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. + :vartype overage_cost: float + :ivar benefit_cost: The exact cost of the estimated usage using plan. It's equal to + (commitmentAmount * totalHours). + :vartype benefit_cost: float + :ivar total_cost: The cost of the suggested commitment. + :vartype total_cost: float + :ivar savings_amount: The amount saved by purchasing the recommended quantity of benefit. + :vartype savings_amount: float + :ivar savings_percentage: The savings in percentage by purchasing the recommended quantity of + benefit. + :vartype savings_percentage: float + :ivar coverage_percentage: Expected coverage at this commitment. + :vartype coverage_percentage: float + :ivar commitment_amount: The commitment amount for the benefit. + :vartype commitment_amount: float + :ivar average_utilization_percentage: Estimated average utilization percentage at this + commitment. + :vartype average_utilization_percentage: float + :ivar wastage_cost: Wastage cost at this commitment. + :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): + """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.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: 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 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] """ _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"}, } - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None - self.tags = None -class Alert(Resource): - """An individual alert. +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: 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 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] - :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 + :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}, - '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}'}, - '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'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "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, - **kwargs - ): - super(Alert, 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 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 + 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 + + +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 plan recommendation. + :vartype properties: ~azure.mgmt.costmanagement.models.BenefitRecommendationProperties """ + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + } + _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'criteria': {'key': 'criteria', '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, *, - type: Optional[Union[str, "AlertType"]] = None, - category: Optional[Union[str, "AlertCategory"]] = None, - criteria: Optional[Union[str, "AlertCriteria"]] = None, + kind: Optional[Union[str, "_models.BenefitKind"]] = None, + properties: Optional["_models.BenefitRecommendationProperties"] = None, **kwargs ): - super(AlertPropertiesDefinition, self).__init__(**kwargs) - self.type = type - self.category = category - self.criteria = criteria - - -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 + """ + :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 plan recommendation. + :paramtype properties: ~azure.mgmt.costmanagement.models.BenefitRecommendationProperties + """ + super().__init__(kind=kind, **kwargs) + self.properties = properties + + +class BenefitRecommendationProperties(_serialization.Model): # pylint: disable=too-many-instance-attributes + """The properties of the benefit plan recommendation. + + 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. + + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendation. + :vartype first_consumption_date: ~datetime.datetime + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_consumption_date: ~datetime.datetime + :ivar look_back_period: The number of days of usage used to look back for computing the + recommendation. 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: The additional details about the usage which are considered while computing + benefit recommendations. + :vartype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :ivar arm_sku_name: ARM SKU name. For example, Standard_D1_V2 for Reservations and + 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. For example, hourly, + monthly etc. 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' + property in a given 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. + :vartype all_recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsList + :ivar scope: Scope of the benefit. 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 = { - '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'}, + "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, *, - time_grain_type: Optional[Union[str, "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, - threshold: Optional[float] = None, - operator: Optional[Union[str, "AlertOperator"]] = None, - amount: Optional[float] = None, - unit: Optional[str] = None, - current_spend: Optional[float] = None, - contact_emails: Optional[List[str]] = None, - contact_groups: Optional[List[str]] = None, - contact_roles: Optional[List[str]] = None, - overriding_alert: Optional[str] = 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(AlertPropertiesDetails, self).__init__(**kwargs) - self.time_grain_type = time_grain_type - self.period_start_date = period_start_date - self.triggered_by = triggered_by - self.resource_group_filter = resource_group_filter - self.resource_filter = resource_filter - self.meter_filter = meter_filter - self.tag_filter = tag_filter - self.threshold = threshold - self.operator = operator - self.amount = amount - self.unit = unit - self.current_spend = current_spend - self.contact_emails = contact_emails - self.contact_groups = contact_groups - self.contact_roles = contact_roles - self.overriding_alert = overriding_alert - - -class AlertsResult(msrest.serialization.Model): - """Result of alerts. + """ + :keyword look_back_period: The number of days of usage used to look back for computing the + recommendation. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :paramtype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :keyword usage: The additional details about the usage which are considered while 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. For example, hourly, + monthly etc. 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: 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. + :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}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Alert]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BenefitRecommendationModel]"}, + "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 BenefitUtilizationSummariesListResult(_serialization.Model): + """Result of listing benefit utilization summaries. - 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 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 + :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 = { - 'id': {'required': True}, - 'name': {'required': True}, - 'channel': {'required': True}, - 'subchannel': {'required': True}, + "value": {"readonly": True}, + "next_link": {"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'}, + "value": {"key": "value", "type": "[BenefitUtilizationSummary]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - id: str, - name: str, - channel: str, - subchannel: str, - parent: Optional[str] = None, - status: Optional[str] = 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 + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None -class CommonExportProperties(msrest.serialization.Model): - """The common properties of the export. +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. - :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 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, SavingsPlan or IncludedQuantity. Required. Known values are: + "IncludedQuantity", "Reservation", and "SavingsPlan". + :vartype kind: str or ~azure.mgmt.costmanagement.models.BenefitKind """ _validation = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"required": True}, } _attribute_map = { - 'format': {'key': 'format', 'type': 'str'}, - 'delivery_info': {'key': 'deliveryInfo', 'type': 'ExportDeliveryInfo'}, - 'definition': {'key': 'definition', 'type': 'ExportDefinition'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, } - def __init__( - self, - *, - delivery_info: "ExportDeliveryInfo", - definition: "ExportDefinition", - format: Optional[Union[str, "FormatType"]] = None, - **kwargs - ): - super(CommonExportProperties, self).__init__(**kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition + _subtype_map = { + "kind": { + "IncludedQuantity": "IncludedQuantityUtilizationSummary", + "SavingsPlan": "SavingsPlanUtilizationSummary", + } + } + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.kind = None # type: Optional[str] -class Dimension(Resource): - """Dimension. + +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 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 + :ivar arm_sku_name: ARM SKU name. For example, Standard_D1_V2 for reservations and + ComputeSavingsPlan for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of a benefit within a benefit order. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. Each + benefit order ID represents a single purchase transaction. For example: A reservation order + contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. For example, reservation or savings plan. 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 record. If the grain of data is + monthly, it will be first day of month. + :vartype usage_date: ~datetime.datetime """ _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}, + "arm_sku_name": {"readonly": True}, + "benefit_id": {"readonly": True}, + "benefit_order_id": {"readonly": True}, + "usage_date": {"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'}, - } + "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, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. For example, reservation or savings plan. 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 + """ - 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 + _attribute_map = { + "blob_link": {"key": "blobLink", "type": "str"}, + "byte_count": {"key": "byteCount", "type": "int"}, + } + 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 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. +class CheckNameAvailabilityRequest(_serialization.Model): + """The check availability request body. - :ivar value: The list of dimensions. - :vartype value: list[~azure.mgmt.costmanagement.models.Dimension] + :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 """ - _validation = { - 'value': {'readonly': True}, - } + _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 + + +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 = { - 'value': {'key': 'value', 'type': '[Dimension]'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( self, + *, + name_available: Optional[bool] = None, + reason: Optional[Union[str, "_models.CheckNameAvailabilityReason"]] = None, + message: Optional[str] = None, **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 + """ + :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 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 = { - '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'}, + "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, *, - 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, + 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 ): - super(DismissAlertPayload, self).__init__(**kwargs) - self.definition = definition - self.description = description - self.source = source - self.details = details - self.cost_entity_id = cost_entity_id + """ + :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.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 + 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 ErrorDetails(msrest.serialization.Model): - """The details of the error. +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. - 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 code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str + :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 = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, + "start": {"required": True}, + "end": {"required": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "start": {"key": "start", "type": "str"}, + "end": {"key": "end", "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: + 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 -* - 429 TooManyRequests - Request is throttled. Retry after waiting for the time specified in the "x-ms-ratelimit-microsoft.consumption-retry-after" header. +class Operation(_serialization.Model): + """Details of a REST API operation, returned from the Resource Provider Operations API. -* - 503 ServiceUnavailable - Service is temporarily unavailable. Retry after waiting for the time specified in the "Retry-After" header. + Variables are only populated by the server, and will be ignored when sending a request. - :param error: The details of the error. - :type error: ~azure.mgmt.costmanagement.models.ErrorDetails + :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 """ - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, + _validation = { + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, } - def __init__( - self, - *, - error: Optional["ErrorDetails"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = error + _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 ProxyResource(msrest.serialization.Model): - """The Resource model definition. +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 id: Resource Id. - :vartype id: str - :ivar name: Resource name. + :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 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 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 = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, + "origin": {"readonly": True}, + "action_type": {"readonly": True}, + "id": {"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, - *, - e_tag: Optional[str] = None, - **kwargs - ): - super(ProxyResource, self).__init__(**kwargs) + "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 - self.name = None - self.type = None - self.e_tag = e_tag -class Export(ProxyResource): - """A export resource. +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 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 + :ivar code: Error code. + :vartype code: str + :ivar message: Error message indicating why the operation failed. + :vartype message: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "code": {"readonly": True}, + "message": {"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'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - 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, - **kwargs - ): - super(Export, self).__init__(e_tag=e_tag, **kwargs) - self.format = format - self.delivery_info = delivery_info - self.definition = definition - self.schedule = schedule + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None -class ExportDefinition(msrest.serialization.Model): - """The definition of a query. +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. - All required parameters must be populated in order to send to Azure. + Some Error responses: - :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 + + * + 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 """ - _validation = { - 'type': {'required': True}, - 'timeframe': {'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 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 = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'data_set': {'key': 'dataSet', 'type': 'QueryDatasetAutoGenerated'}, + "file_formats": {"key": "fileFormats", "type": "[str]"}, } - 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, *, 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 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 + """ + :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 ExportExecution(Resource): - """A export execution. +class IncludedQuantityUtilizationSummary(BenefitUtilizationSummary): + """Included Quantity 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 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] - :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 + :ivar kind: Reservation, SavingsPlan or IncludedQuantity. 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, Standard_D1_V2 for reservations and + ComputeSavingsPlan for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of a benefit within a benefit order. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. Each + benefit order ID represents a single purchase transaction. For example: A reservation order + contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. For example, reservation or savings plan. 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 record. If the grain of data is + monthly, it will be first day of month. + :vartype usage_date: ~datetime.datetime + :ivar utilization_percentage: This is the utilized percentage for the benefit ID. + :vartype utilization_percentage: float """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'tags': {'readonly': 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 = { - '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, - *, - 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, - **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 - - -class ExportExecutionListResult(msrest.serialization.Model): - """Result of listing exports execution history of a export by name. + "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, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. For example, reservation or savings plan. 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. 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] + :ivar arm_sku_name: ARM SKU name. For example, Standard_D1_V2 for reservations and + ComputeSavingsPlan for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of a benefit within a benefit order. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. Each + benefit order ID represents a single purchase transaction. For example: A reservation order + contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. For example, reservation or savings plan. 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 record. If the grain of data is + monthly, it will be first day of month. + :vartype usage_date: ~datetime.datetime + :ivar utilization_percentage: This is the utilized percentage for the benefit ID. + :vartype utilization_percentage: float """ _validation = { - 'value': {'readonly': 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 = { - 'value': {'key': 'value', 'type': '[ExportExecution]'}, + "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, - **kwargs - ): - super(ExportExecutionListResult, self).__init__(**kwargs) - self.value = None + def __init__(self, *, benefit_type: Optional[Union[str, "_models.BenefitKind"]] = None, **kwargs): + """ + :keyword benefit_type: The benefit type. For example, reservation or savings plan. 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 ExportListResult(msrest.serialization.Model): - """Result of listing exports. It contains a list of available exports in the scope provided. +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 value: The list of exports. - :vartype value: list[~azure.mgmt.costmanagement.models.Export] + :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 = { - 'value': {'readonly': True}, + "to": {"required": True, "max_items": 20, "min_items": 1}, + "subject": {"required": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Export]'}, + "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, + *, + to: List[str], + subject: str, + language: Optional[str] = None, + message: Optional[str] = None, + regional_format: Optional[str] = None, **kwargs ): - super(ExportListResult, self).__init__(**kwargs) - self.value = None + """ + :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 ExportProperties(CommonExportProperties): - """The properties of the export. +class OperationDisplay(_serialization.Model): + """Localized display information for this particular operation. - 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 provider: The localized friendly form of the resource provider name, e.g. "Microsoft + Monitoring Insights" or "Microsoft Compute". + :vartype provider: str + :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: 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 = { - 'delivery_info': {'required': True}, - 'definition': {'required': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"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'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - *, - delivery_info: "ExportDeliveryInfo", - definition: "ExportDefinition", - format: Optional[Union[str, "FormatType"]] = None, - schedule: Optional["ExportSchedule"] = None, - **kwargs - ): - super(ExportProperties, self).__init__(format=format, delivery_info=delivery_info, definition=definition, **kwargs) - self.schedule = schedule + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.provider = None + self.resource = None + self.operation = None + self.description = None -class ExportRecurrencePeriod(msrest.serialization.Model): - """The start and end date for recurrence schedule. +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. - 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 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 value: List of cost management operations supported by the Microsoft.CostManagement + resource provider. + :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 = { - 'from_property': {'required': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'from_property': {'key': 'from', 'type': 'iso-8601'}, - 'to': {'key': 'to', 'type': 'iso-8601'}, + "value": {"key": "value", "type": "[CostManagementOperation]"}, + "next_link": {"key": "nextLink", "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, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None -class ExportSchedule(msrest.serialization.Model): - """The schedule associated with a export. +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location. - 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 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 """ _validation = { - 'recurrence': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"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"}, } - 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 + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) -class ForecastDefinition(msrest.serialization.Model): - """The definition of a forecast. +class RecommendationUsageDetails(_serialization.Model): + """The additional details about the usage which are considered while computing benefit recommendations. - 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 usage_grain: The grain of the usage. For example, hourly or monthly etc. Known values + are: "Hourly", "Daily", and "Monthly". + :vartype usage_grain: str or ~azure.mgmt.costmanagement.models.Grain + :ivar charges: current cost without benefit i.e. charges at the specified grain. + :vartype charges: list[float] """ _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'}, + "charges": {"readonly": True}, } - 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 - - -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'}, + "usage_grain": {"key": "usageGrain", "type": "str"}, + "charges": {"key": "charges", "type": "[float]"}, } - def __init__( - self, - *, - type: Optional[Union[str, "KpiType"]] = None, - id: Optional[str] = None, - enabled: Optional[bool] = None, - **kwargs - ): - super(KpiProperties, self).__init__(**kwargs) - self.type = type - self.id = id - self.enabled = enabled + def __init__(self, *, usage_grain: Optional[Union[str, "_models.Grain"]] = None, **kwargs): + """ + :keyword usage_grain: The grain of the usage. For example, hourly or monthly etc. 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 Operation(msrest.serialization.Model): - """A Cost management REST API operation. +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 name: Operation name: {provider}/{resource}/{operation}. + 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: The name of the resource. :vartype name: str - :param display: The object that represents the operation. - :type display: ~azure.mgmt.costmanagement.models.OperationDisplay + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar kind: Reservation, SavingsPlan or IncludedQuantity. 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, Standard_D1_V2 for reservations and + ComputeSavingsPlan for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of a benefit within a benefit order. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. Each + benefit order ID represents a single purchase transaction. For example: A reservation order + contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. For example, reservation or savings plan. 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 record. If the grain of data is + monthly, it will be first day of month. + :vartype usage_date: ~datetime.datetime + :ivar avg_utilization_percentage: This is the average utilization percentage for the benefit + ID. + :vartype avg_utilization_percentage: float + :ivar min_utilization_percentage: This is the minimum hourly utilization in the usage time (day + or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4, utilization + was 10%, this field will return 10% for that day. + :vartype min_utilization_percentage: float + :ivar max_utilization_percentage: This is the maximum hourly utilization in the usage time (day + or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4, utilization + was 100%, this field will return 100% for that day. + :vartype max_utilization_percentage: float """ _validation = { - 'name': {'readonly': 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}, + "avg_utilization_percentage": {"readonly": True}, + "min_utilization_percentage": {"readonly": True}, + "max_utilization_percentage": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - *, - display: Optional["OperationDisplay"] = None, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.display = display - - -class OperationDisplay(msrest.serialization.Model): - """The object that represents the operation. + "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. For example, reservation or savings plan. 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 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 + :ivar arm_sku_name: ARM SKU name. For example, Standard_D1_V2 for reservations and + ComputeSavingsPlan for savings plan. + :vartype arm_sku_name: str + :ivar benefit_id: The benefit ID is the identifier of a benefit within a benefit order. + :vartype benefit_id: str + :ivar benefit_order_id: The benefit order ID is the identifier for a benefit purchase. Each + benefit order ID represents a single purchase transaction. For example: A reservation order + contains reservations. The reservation order specifies the VM size and region for the + reservations. + :vartype benefit_order_id: str + :ivar benefit_type: The benefit type. For example, reservation or savings plan. 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 record. If the grain of data is + monthly, it will be first day of month. + :vartype usage_date: ~datetime.datetime + :ivar avg_utilization_percentage: This is the average utilization percentage for the benefit + ID. + :vartype avg_utilization_percentage: float + :ivar min_utilization_percentage: This is the minimum hourly utilization in the usage time (day + or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4, utilization + was 10%, this field will return 10% for that day. + :vartype min_utilization_percentage: float + :ivar max_utilization_percentage: This is the maximum hourly utilization in the usage time (day + or month). E.g. if usage record corresponds to 12/10/2017 and on that for hour 4, utilization + was 100%, this field will return 100% for that day. + :vartype max_utilization_percentage: float """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': 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 = { - '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. + "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. For example, reservation or savings plan. 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 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 + :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 = { - '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'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "e_tag": {"readonly": True}, + "system_data": {"readonly": True}, } - def __init__( - self, - *, - status: Optional["Status"] = None, - report_url: Optional[str] = None, - valid_until: Optional[datetime.datetime] = None, - **kwargs - ): - super(OperationStatus, self).__init__(**kwargs) - self.status = status - self.report_url = report_url - self.valid_until = valid_until - - -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'}, + "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, - *, - type: Optional[Union[str, "PivotType"]] = None, - name: Optional[str] = None, - **kwargs - ): - super(PivotProperties, self).__init__(**kwargs) - self.type = type - self.name = name + 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 ProxySettingResource(msrest.serialization.Model): - """The Resource model definition. +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: 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 + :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'}, + "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, + status: Optional[Union[str, "_models.ScheduledActionStatus"]] = None, + view_id: Optional[str] = None, **kwargs ): - super(ProxySettingResource, self).__init__(**kwargs) - self.id = None - self.name = None - self.kind = None - self.type = None + """ + :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.status = status + self.view_id = view_id -class QueryAggregation(msrest.serialization.Model): - """The aggregation expression to be used in the query. +class ScheduledActionListResult(_serialization.Model): + """Scheduled actions list result. It contains a list of scheduled actions. - 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 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 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 = { - 'name': {'required': True}, - 'function': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'function': {'key': 'function', 'type': 'str'}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } - def __init__( - self, - *, - name: str, - function: Union[str, "FunctionType"], - **kwargs - ): - super(QueryAggregation, self).__init__(**kwargs) - self.name = name - self.function = 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'}, + "value": {"key": "value", "type": "[ScheduledAction]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - name: Optional[str] = None, - type: Optional[str] = None, - **kwargs - ): - super(QueryColumn, self).__init__(**kwargs) - self.name = name - self.type = type + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None -class QueryComparisonExpression(msrest.serialization.Model): - """The comparison expression to be used in the query. +class ScheduleProperties(_serialization.Model): + """The properties of the schedule. 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, - *, - name: str, - operator: Union[str, "OperatorType"], - values: List[str], - **kwargs - ): - super(QueryComparisonExpression, self).__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): - """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 + :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 = { - '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'}, + "frequency": {"required": True}, + "start_date": {"required": True}, + "end_date": {"required": True}, } - 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, - **kwargs - ): - super(QueryDatasetAutoGenerated, self).__init__(**kwargs) - self.granularity = granularity - self.configuration = configuration - self.aggregation = aggregation - self.grouping = grouping - self.filter = filter - - -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]'}, + "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, *, - columns: Optional[List[str]] = None, + 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(QueryDatasetConfiguration, self).__init__(**kwargs) - self.columns = columns - + """ + :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 plan recommendation when scope is 'Shared'. -class QueryDefinition(msrest.serialization.Model): - """The definition of a query. + 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 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 + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendation. + :vartype first_consumption_date: ~datetime.datetime + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_consumption_date: ~datetime.datetime + :ivar look_back_period: The number of days of usage used to look back for computing the + recommendation. 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: The additional details about the usage which are considered while computing + benefit recommendations. + :vartype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :ivar arm_sku_name: ARM SKU name. For example, Standard_D1_V2 for Reservations and + 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. For example, hourly, + monthly etc. 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' + property in a given 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. + :vartype all_recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsList + :ivar scope: Scope of the benefit. For example, Single or Shared. Required. Known values are: + "Single" and "Shared". + :vartype scope: str or ~azure.mgmt.costmanagement.models.Scope """ _validation = { - 'type': {'required': True}, - 'timeframe': {'required': True}, - 'dataset': {'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 = { - 'type': {'key': 'type', 'type': 'str'}, - 'timeframe': {'key': 'timeframe', 'type': 'str'}, - 'time_period': {'key': 'timePeriod', 'type': 'QueryTimePeriod'}, - 'dataset': {'key': 'dataset', 'type': 'QueryDataset'}, + "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, *, - type: Union[str, "ExportType"], - timeframe: Union[str, "TimeframeType"], - dataset: "QueryDataset", - time_period: Optional["QueryTimePeriod"] = 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(QueryDefinition, self).__init__(**kwargs) - self.type = type - self.timeframe = timeframe - self.time_period = time_period - self.dataset = dataset + """ + :keyword look_back_period: The number of days of usage used to look back for computing the + recommendation. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :paramtype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :keyword usage: The additional details about the usage which are considered while 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. For example, hourly, + monthly etc. 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 plan recommendation when scope is 'Single'. + Variables are only populated by the server, and will be ignored when sending a request. -class QueryFilter(msrest.serialization.Model): - """The filter expression to be used in the export. + All required parameters must be populated in order to send to Azure. - :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 + :ivar first_consumption_date: The first usage date used for looking back for computing the + recommendation. + :vartype first_consumption_date: ~datetime.datetime + :ivar last_consumption_date: The last usage date used for looking back for computing the + recommendation. + :vartype last_consumption_date: ~datetime.datetime + :ivar look_back_period: The number of days of usage used to look back for computing the + recommendation. 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: The additional details about the usage which are considered while computing + benefit recommendations. + :vartype usage: ~azure.mgmt.costmanagement.models.RecommendationUsageDetails + :ivar arm_sku_name: ARM SKU name. For example, Standard_D1_V2 for Reservations and + 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. For example, hourly, + monthly etc. 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' + property in a given 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. + :vartype all_recommendation_details: ~azure.mgmt.costmanagement.models.AllSavingsList + :ivar scope: Scope of the benefit. 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 = { - 'and_property': {'min_items': 2}, - 'or_property': {'min_items': 2}, + "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 = { - 'and_property': {'key': 'and', 'type': '[QueryFilter]'}, - 'or_property': {'key': 'or', 'type': '[QueryFilter]'}, - 'dimensions': {'key': 'dimensions', 'type': 'QueryComparisonExpression'}, - 'tags': {'key': 'tags', 'type': 'QueryComparisonExpression'}, + "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, *, - and_property: Optional[List["QueryFilter"]] = None, - or_property: Optional[List["QueryFilter"]] = None, - dimensions: Optional["QueryComparisonExpression"] = None, - tags: Optional["QueryComparisonExpression"] = 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(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): - """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 + """ + :keyword look_back_period: The number of days of usage used to look back for computing the + recommendation. Known values are: "Last7Days", "Last30Days", and "Last60Days". + :paramtype look_back_period: str or ~azure.mgmt.costmanagement.models.LookBackPeriod + :keyword usage: The additional details about the usage which are considered while 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. For example, hourly, + monthly etc. 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 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 """ - _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'}, + "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, *, - and_property: Optional[List["QueryFilterAutoGenerated"]] = None, - or_property: Optional[List["QueryFilterAutoGenerated"]] = None, - dimensions: Optional["QueryComparisonExpression"] = None, - tags: Optional["QueryComparisonExpression"] = None, + 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 ): - super(QueryFilterAutoGenerated, self).__init__(**kwargs) - self.and_property = and_property - self.or_property = or_property - self.dimensions = dimensions - self.tags = tags - - -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, - *, - type: Union[str, "QueryColumnType"], - name: str, - **kwargs - ): - super(QueryGrouping, self).__init__(**kwargs) - self.type = type - self.name = 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, - *, - e_tag: Optional[str] = None, - next_link: Optional[str] = None, - columns: Optional[List["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 - self.next_link = next_link - self.columns = columns - self.rows = rows - - -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, - *, - from_property: datetime.datetime, - to: datetime.datetime, - **kwargs - ): - super(QueryTimePeriod, self).__init__(**kwargs) - self.from_property = from_property - self.to = 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, - *, - name: str, - function: Union[str, "FunctionType"], - **kwargs - ): - super(ReportConfigAggregation, self).__init__(**kwargs) - self.name = name - self.function = 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, - *, - name: str, - operator: Union[str, "OperatorType"], - values: List[str], - **kwargs - ): - super(ReportConfigComparisonExpression, self).__init__(**kwargs) - self.name = name - self.operator = operator - self.values = 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, - *, - 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, - **kwargs - ): - super(ReportConfigDataset, self).__init__(**kwargs) - self.granularity = granularity - self.configuration = configuration - self.aggregation = aggregation - self.grouping = grouping - self.sorting = sorting - self.filter = filter - - -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, - *, - columns: Optional[List[str]] = None, - **kwargs - ): - super(ReportConfigDatasetConfiguration, self).__init__(**kwargs) - self.columns = columns - - -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, - *, - 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, - **kwargs - ): - super(ReportConfigFilter, self).__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): - """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, - *, - type: Union[str, "ReportConfigColumnType"], - name: str, - **kwargs - ): - super(ReportConfigGrouping, self).__init__(**kwargs) - self.type = type - self.name = 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, - *, - name: str, - direction: Optional[Union[str, "ReportConfigSortingDirection"]] = None, - **kwargs - ): - super(ReportConfigSorting, self).__init__(**kwargs) - self.direction = direction - self.name = 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, - *, - from_property: datetime.datetime, - to: datetime.datetime, - **kwargs - ): - super(ReportConfigTimePeriod, self).__init__(**kwargs) - self.from_property = from_property - self.to = 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, - *, - scope: Optional[str] = None, - start_on: Optional[Union[str, "SettingsPropertiesStartOn"]] = None, - cache: Optional[List["CacheItem"]] = None, - **kwargs - ): - super(Setting, self).__init__(**kwargs) - self.scope = scope - self.start_on = start_on - self.cache = cache - - -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, - *, - status: Optional[Union[str, "OperationStatusType"]] = None, - **kwargs - ): - super(Status, self).__init__(**kwargs) - self.status = status - - -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, - *, - 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, - **kwargs - ): - super(View, self).__init__(e_tag=e_tag, **kwargs) - self.display_name = display_name - self.scope = scope - self.created_on = None - self.modified_on = None - self.date_range = None - self.currency = None - self.chart = chart - self.accumulated = accumulated - self.metric = metric - self.kpis = kpis - self.pivots = pivots - self.type_properties_query_type = type_properties_query_type - self.timeframe = timeframe - self.time_period = time_period - self.data_set = data_set - 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 + """ + :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 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..0ee2bdde1f67 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,24 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._settings_operations import SettingsOperations -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 ._scheduled_actions_operations import ScheduledActionsOperations +from ._benefit_recommendations_operations import BenefitRecommendationsOperations +from ._benefit_recommendation_operations import BenefitRecommendationOperations +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", + "GenerateCostDetailsReportOperations", + "ScheduledActionsOperations", + "BenefitRecommendationsOperations", + "BenefitRecommendationOperations", + "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 deleted file mode 100644 index 13969e75db88..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_alerts_operations.py +++ /dev/null @@ -1,333 +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.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, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -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. - - :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, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AlertsResult" - """Lists the alerts for scope defined. - - :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. - :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) - :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :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.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') - - 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('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" - """Gets the alert for the scope by alert ID. - - :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. - :type scope: str - :param alert_id: Alert ID. - :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) - :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" - 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), - } - 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('Alert', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore - - def dismiss( - self, - scope, # type: str - alert_id, # type: str - parameters, # type: "_models.DismissAlertPayload" - **kwargs # type: Any - ): - # type: (...) -> "_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. - :type scope: str - :param alert_id: Alert ID. - :type alert_id: str - :param parameters: Parameters supplied to the Dismiss Alert operation. - :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload - :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), - } - 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) - 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('Alert', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - dismiss.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}'} # type: ignore - - 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" - """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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :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) - :rtype: ~azure.mgmt.costmanagement.models.AlertsResult - :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'), - } - 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('AlertsResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - 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_recommendation_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendation_operations.py new file mode 100644 index 000000000000..cb2aa9d31545 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendation_operations.py @@ -0,0 +1,144 @@ +# 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. +# -------------------------------------------------------------------------- +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 + +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(billing_scope: str, recommendation_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: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations/{recommendationId}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingScope": _SERIALIZER.url("billing_scope", billing_scope, "str", skip_quote=True), + "recommendationId": _SERIALIZER.url("recommendation_id", recommendation_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) + + +class BenefitRecommendationOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.costmanagement.CostManagementClient`'s + :attr:`benefit_recommendation` 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, billing_scope: str, recommendation_id: str, **kwargs: Any) -> _models.BenefitRecommendationModel: + """Details of a benefit plan recommendation for what-if analysis. + + :param billing_scope: The scope associated with benefit recommendation details operations. This + includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, + /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile scope. Required. + :type billing_scope: str + :param recommendation_id: The ID of the recommendation. Required. + :type recommendation_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BenefitRecommendationModel or the result of cls(response) + :rtype: ~azure.mgmt.costmanagement.models.BenefitRecommendationModel + :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: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BenefitRecommendationModel] + + request = build_get_request( + billing_scope=billing_scope, + recommendation_id=recommendation_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 + ) + + 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("BenefitRecommendationModel", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = {"url": "/{billingScope}/providers/Microsoft.CostManagement/benefitRecommendations/{recommendationId}"} # 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..4a37e720a841 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_recommendations_operations.py @@ -0,0 +1,206 @@ +# 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. +# -------------------------------------------------------------------------- +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 + +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: str + 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 benefit (reservation or savings plan). + + :param billing_scope: The scope associated with benefit recommendation details operations. This + includes '/subscriptions/{subscriptionId}/' for subscription scope, + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope, + /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for BillingAccount scope, and + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' + for billingProfile 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'; kind with default + value 'SavingsPlan'; properties/armSkuName with allowed values ['Compute', 'SQL'] - if + mentioned kind SavingsPlan is applied implicitly; properties/subscriptionId; + properties/resourceGroup. Default value is None. + :type filter: str + :param orderby: May be used to order the recommendations by: properties/armSkuName. This + implicitly filters the results by the corresponding benefit type. 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: str + 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..26c6331d4246 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_benefit_utilization_summaries_operations.py @@ -0,0 +1,609 @@ +# 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. +# -------------------------------------------------------------------------- +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 + +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: str + 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: str + 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: str + 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: str + 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 benefit utilization summaries for the provided billingAccount. This API provides benefit + utilization summaries only for enrollment accounts. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param grain_parameter: Daily or monthly 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/benefitType, properties/benefitId, + properties/benefitOrderId and properties/usageDate. properties/benefitType is defaulted to + savingsPlan. 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: str + 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 benefit utilization summaries for billingProfile. + + :param billing_account_id: Billing account ID. Required. + :type billing_account_id: str + :param billing_profile_id: Azure billing profile ID. Required. + :type billing_profile_id: str + :param grain_parameter: Daily or monthly 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/benefitType, properties/benefitId, + properties/benefitOrderId and properties/usageDate. properties/benefitType is defaulted to + savingsPlan. 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: str + 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: Daily or monthly 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: str + 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: Daily or monthly 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: str + 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 deleted file mode 100644 index ff843ebbf69e..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_dimensions_operations.py +++ /dev/null @@ -1,258 +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, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -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. - - :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, - 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"] - """Lists the dimensions by the defined scope. - - :param scope: The scope associated with dimension 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.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. - :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'. - :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. - :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. - :type skiptoken: str - :param top: May be used to limit the number of results to the most recent N dimension data. - :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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] - 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 - 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) - 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('DimensionsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return 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, 204]: - 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': '/{scope}/providers/Microsoft.CostManagement/dimensions'} # type: ignore - - 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"] - """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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :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'. - :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. - :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. - :type skiptoken: str - :param top: May be used to limit the number of results to the most recent N dimension data. - :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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DimensionsListResult"] - 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.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) - 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('DimensionsListResult', pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return 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 - ) - 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 deleted file mode 100644 index 89eefe5166d4..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_exports_operations.py +++ /dev/null @@ -1,493 +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.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, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class ExportsOperations(object): - """ExportsOperations 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, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.ExportListResult" - """The operation to list all exports at the given scope. - - :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. - :type scope: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: ExportListResult, or the result of cls(response) - :rtype: ~azure.mgmt.costmanagement.models.ExportListResult - :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), - } - 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('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" - """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 - '/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. - :type scope: str - :param export_name: Export Name. - :type export_name: 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" - 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') - - # 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('Export', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/exports/{exportName}'} # type: ignore - - def create_or_update( - self, - scope, # type: str - export_name, # type: str - parameters, # type: "_models.Export" - **kwargs # type: Any - ): - # type: (...) -> "_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 - '/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. - :type scope: str - :param export_name: Export Name. - :type export_name: str - :param parameters: Parameters supplied to the CreateOrUpdate Export operation. - :type parameters: ~azure.mgmt.costmanagement.models.Export - :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'), - } - 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) - 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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('Export', pipeline_response) - - if response.status_code == 201: - 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 - """The operation to delete a export. - - :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. - :type scope: str - :param export_name: Export Name. - :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) - :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 = { - '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') - - 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) - 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 - - 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 - '/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. - :type scope: str - :param export_name: Export Name. - :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) - :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.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') - - 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) - 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 - - 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 - '/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. - :type scope: str - :param export_name: Export Name. - :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) - :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult - :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'), - } - 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('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 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 deleted file mode 100644 index 71c2e338e1e5..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_forecast_operations.py +++ /dev/null @@ -1,209 +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.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, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -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. - - :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 usage( - self, - scope, # type: str - parameters, # type: "_models.ForecastDefinition" - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.QueryResult"] - """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. - :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. - :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'. - :type filter: 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 - """ - 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), - } - 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) - 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) - - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize('QueryResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - usage.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/forecast'} # type: ignore - - 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" - """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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. - :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'. - :type filter: 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.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'), - } - 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) - 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('QueryResult', 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 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..0a5dd77bfbc3 --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_cost_details_report_operations.py @@ -0,0 +1,510 @@ +# 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. +# -------------------------------------------------------------------------- +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 + +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: str + 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: str + 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: str + 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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: str + 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: str + 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 scope associated with usage details operations. This includes + '/subscriptions/{subscriptionId}/' for subscription scope, + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, + '/providers/Microsoft.Billing/departments/{departmentId}' for Department scope, + '/providers/Microsoft.Billing/enrollmentAccounts/{enrollmentAccountId}' for EnrollmentAccount + scope. Also, Modern Commerce Account scopes are + '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for billingAccount 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 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: 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._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_reservation_details_report_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py deleted file mode 100644 index 4c93c64e8755..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py +++ /dev/null @@ -1,310 +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.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.mgmt.core.exceptions import ARMErrorFormat -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from .. import models as _models - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class GenerateReservationDetailsReportOperations(object): - """GenerateReservationDetailsReportOperations 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 _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"]] - 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_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') - - # 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, 202]: - 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) - - response_headers = {} - deserialized = None - if response.status_code == 200: - 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')) - - 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 - - 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"] - """Generates the reservations details report for provided date range asynchronously based on - enrollment id. - - :param billing_account_id: Enrollment ID (Legacy BillingAccount ID). - :type billing_account_id: str - :param start_date: Start Date. - :type start_date: str - :param end_date: End Date. - :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. - :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) - :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] - if cont_token is None: - raw_result = self._by_billing_account_id_initial( - billing_account_id=billing_account_id, - start_date=start_date, - end_date=end_date, - cls=lambda x,y,z: x, - **kwargs - ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(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 cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - 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 - - 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"]] - 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'), - } - 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') - - # 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, 202]: - 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) - - response_headers = {} - deserialized = None - if response.status_code == 200: - 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')) - - 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 - - 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"] - """Generates the reservations details report for provided date range asynchronously by billing - profile. - - :param billing_account_id: BillingAccount ID. - :type billing_account_id: str - :param billing_profile_id: BillingProfile ID. - :type billing_profile_id: str - :param start_date: Start Date. - :type start_date: str - :param end_date: End Date. - :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. - :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) - :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] - if cont_token is None: - raw_result = self._by_billing_profile_id_initial( - 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, - **kwargs - ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(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 cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - 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 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..6b5458cfb7f4 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,130 @@ # 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 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 + +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: str + 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: str + 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 +138,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/_query_operations.py b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py deleted file mode 100644 index b5dd2dc857ec..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_query_operations.py +++ /dev/null @@ -1,195 +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.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, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -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. - - :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 usage( - self, - scope, # type: str - parameters, # type: "_models.QueryDefinition" - **kwargs # type: Any - ): - # type: (...) -> 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. - :type scope: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition - :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 - """ - 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), - } - 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) - 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) - - deserialized = None - if response.status_code == 200: - 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 - - 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" - """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 - :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or - '{externalBillingAccountId}' for consolidated account used with dimension/query operations. - :type external_cloud_provider_id: str - :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. - :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition - :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'), - } - 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) - 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('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 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..6209ff0dba7d --- /dev/null +++ b/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_scheduled_actions_operations.py @@ -0,0 +1,1499 @@ +# 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. +# -------------------------------------------------------------------------- +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 + +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: str + 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: str + 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: str + 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: 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 + _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: 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 + _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: str + 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: 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 + _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: 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 + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_execute_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: str + 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_execute_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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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: str + 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 execute(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Execute 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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_request( + name=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 + ) + + 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, {}) + + execute.metadata = {"url": "/providers/Microsoft.CostManagement/scheduledActions/{name}/execute"} # type: ignore + + @distributed_trace + def execute_by_scope( # pylint: disable=inconsistent-return-statements + self, scope: str, name: str, **kwargs: Any + ) -> None: + """Execute 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: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_execute_by_scope_request( + scope=scope, + name=name, + api_version=api_version, + template_url=self.execute_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, {}) + + execute_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: str + 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: str + 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 deleted file mode 100644 index d7512a2a7003..000000000000 --- a/sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_views_operations.py +++ /dev/null @@ -1,609 +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, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class ViewsOperations(object): - """ViewsOperations 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.ViewListResult"] - """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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] - 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('ViewListResult', 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, 204]: - 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/views'} # type: ignore - - def list_by_scope( - self, - scope, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ViewListResult"] - """Lists all views at the given scope. - - :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. - :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 - """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ViewListResult"] - 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_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) - 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('ViewListResult', 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, 204]: - 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_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views'} # type: ignore - - def get( - self, - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.View" - """Gets the view by view name. - - :param view_name: View name. - :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) - :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 - } - 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') - - # 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('View', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - get.metadata = {'url': '/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore - - def create_or_update( - self, - view_name, # type: str - parameters, # type: "_models.View" - **kwargs # type: Any - ): - # type: (...) -> "_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. - :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. - :type parameters: ~azure.mgmt.costmanagement.models.View - :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 - } - 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) - 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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) - - if response.status_code == 201: - 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 - """The operation to delete a view. - - :param view_name: View name. - :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) - :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 = { - '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['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/views/{viewName}'} # type: ignore - - def get_by_scope( - self, - scope, # type: str - view_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.View" - """Gets the view for the defined scope by view name. - - :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. - :type scope: str - :param view_name: View name. - :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) - :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 - } - 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') - - # 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('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 - - def create_or_update_by_scope( - self, - scope, # type: str - view_name, # type: str - parameters, # type: "_models.View" - **kwargs # type: Any - ): - # type: (...) -> "_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. - :type scope: str - :param view_name: View name. - :type view_name: str - :param parameters: Parameters supplied to the CreateOrUpdate View operation. - :type parameters: ~azure.mgmt.costmanagement.models.View - :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 - } - 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) - 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) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('View', pipeline_response) - - if response.status_code == 201: - 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 - """The operation to delete a view. - - :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. - :type scope: str - :param view_name: View name. - :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) - :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_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['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_by_scope.metadata = {'url': '/{scope}/providers/Microsoft.CostManagement/views/{viewName}'} # type: ignore