diff --git a/sdk/advisor/azure-mgmt-advisor/_meta.json b/sdk/advisor/azure-mgmt-advisor/_meta.json new file mode 100644 index 000000000000..75ead4edcbf7 --- /dev/null +++ b/sdk/advisor/azure-mgmt-advisor/_meta.json @@ -0,0 +1,11 @@ +{ + "autorest": "3.7.2", + "use": [ + "@autorest/python@5.12.0", + "@autorest/modelerfour@4.19.3" + ], + "commit": "9709080288d7005147ac5d41f31bf624d7818bea", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest_command": "autorest specification/advisor/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --python3-only --track2 --use=@autorest/python@5.12.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "readme": "specification/advisor/resource-manager/readme.md" +} \ No newline at end of file diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/__init__.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/__init__.py index ce9602fc0143..1d4e789c17a2 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/__init__.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/__init__.py @@ -12,8 +12,7 @@ __version__ = VERSION __all__ = ['AdvisorManagementClient'] -try: - from ._patch import patch_sdk # type: ignore - patch_sdk() -except ImportError: - pass +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_advisor_management_client.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_advisor_management_client.py index 3247b8cc1418..2f4f650bec53 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_advisor_management_client.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_advisor_management_client.py @@ -6,31 +6,27 @@ # 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, Optional, 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 AdvisorManagementClientConfiguration +from .operations import ConfigurationsOperations, Operations, RecommendationMetadataOperations, RecommendationsOperations, SuppressionsOperations + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential -from ._configuration import AdvisorManagementClientConfiguration -from .operations import RecommendationMetadataOperations -from .operations import ConfigurationsOperations -from .operations import RecommendationsOperations -from .operations import Operations -from .operations import SuppressionsOperations -from . import models - - -class AdvisorManagementClient(object): +class AdvisorManagementClient: """REST APIs for Azure Advisor. :ivar recommendation_metadata: RecommendationMetadataOperations operations - :vartype recommendation_metadata: azure.mgmt.advisor.operations.RecommendationMetadataOperations + :vartype recommendation_metadata: + azure.mgmt.advisor.operations.RecommendationMetadataOperations :ivar configurations: ConfigurationsOperations operations :vartype configurations: azure.mgmt.advisor.operations.ConfigurationsOperations :ivar recommendations: RecommendationsOperations operations @@ -43,37 +39,56 @@ class AdvisorManagementClient(object): :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is 'https://management.azure.com'. + :type base_url: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = AdvisorManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AdvisorManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **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._serialize.client_side_validation = False + self.recommendation_metadata = RecommendationMetadataOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.recommendations = RecommendationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.suppressions = SuppressionsOperations(self._client, self._config, self._serialize, self._deserialize) + + + def _send_request( + self, + request, # type: HttpRequest + **kwargs: Any + ) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> 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/python/protocol/quickstart + + :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.rest.HttpResponse + """ - self.recommendation_metadata = RecommendationMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) - self.configurations = ConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.recommendations = RecommendationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.suppressions = SuppressionsOperations( - self._client, self._config, self._serialize, self._deserialize) + 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/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_configuration.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_configuration.py index 702eb8c15285..ee1f717033f6 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_configuration.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_configuration.py @@ -6,18 +6,16 @@ # 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 @@ -35,16 +33,15 @@ class AdvisorManagementClientConfiguration(Configuration): def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + credential: "TokenCredential", + subscription_id: str, + **kwargs: Any + ) -> None: + super(AdvisorManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AdvisorManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id @@ -68,4 +65,4 @@ def _configure( 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/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_metadata.json b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_metadata.json new file mode 100644 index 000000000000..82ed605aa78a --- /dev/null +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_metadata.json @@ -0,0 +1,106 @@ +{ + "chosen_version": "2020-01-01", + "total_api_version_list": ["2020-01-01"], + "client": { + "name": "AdvisorManagementClient", + "filename": "_advisor_management_client", + "description": "REST APIs for Azure Advisor.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_lro_operations": false, + "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\": [\"AdvisorManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", + "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AdvisorManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" + }, + "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 + }, + "subscription_id": { + "signature": "subscription_id, # type: str", + "description": "The Azure subscription ID.", + "docstring_type": "str", + "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 + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The Azure subscription ID.", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, subscription_id", + "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=\"https://management.azure.com\", # type: 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: str = \"https://management.azure.com\",", + "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_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"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\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "operation_groups": { + "recommendation_metadata": "RecommendationMetadataOperations", + "configurations": "ConfigurationsOperations", + "recommendations": "RecommendationsOperations", + "operations": "Operations", + "suppressions": "SuppressionsOperations" + } +} \ No newline at end of file diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_patch.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_patch.py new file mode 100644 index 000000000000..74e48ecd07cf --- /dev/null +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# 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. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_vendor.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_vendor.py new file mode 100644 index 000000000000..138f663c53a4 --- /dev/null +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_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/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_version.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_version.py index b77ac9246082..6dddc002d43d 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_version.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "9.0.0" +VERSION = "9.0.0b1" diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/__init__.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/__init__.py index 7664234d2b8e..976e8350d6b9 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/__init__.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/__init__.py @@ -8,3 +8,8 @@ from ._advisor_management_client import AdvisorManagementClient __all__ = ['AdvisorManagementClient'] + +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_advisor_management_client.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_advisor_management_client.py index e3ec1109e996..c7b39a8e5008 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_advisor_management_client.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_advisor_management_client.py @@ -6,29 +6,27 @@ # 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, Optional, TYPE_CHECKING +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer +from .. import models +from ._configuration import AdvisorManagementClientConfiguration +from .operations import ConfigurationsOperations, Operations, RecommendationMetadataOperations, RecommendationsOperations, SuppressionsOperations + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import AdvisorManagementClientConfiguration -from .operations import RecommendationMetadataOperations -from .operations import ConfigurationsOperations -from .operations import RecommendationsOperations -from .operations import Operations -from .operations import SuppressionsOperations -from .. import models - - -class AdvisorManagementClient(object): +class AdvisorManagementClient: """REST APIs for Azure Advisor. :ivar recommendation_metadata: RecommendationMetadataOperations operations - :vartype recommendation_metadata: azure.mgmt.advisor.aio.operations.RecommendationMetadataOperations + :vartype recommendation_metadata: + azure.mgmt.advisor.aio.operations.RecommendationMetadataOperations :ivar configurations: ConfigurationsOperations operations :vartype configurations: azure.mgmt.advisor.aio.operations.ConfigurationsOperations :ivar recommendations: RecommendationsOperations operations @@ -41,36 +39,56 @@ class AdvisorManagementClient(object): :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Azure subscription ID. :type subscription_id: str - :param str base_url: Service URL + :param base_url: Service URL. Default value is 'https://management.azure.com'. + :type base_url: str """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = AdvisorManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = AdvisorManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **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.recommendation_metadata = RecommendationMetadataOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.recommendations = RecommendationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.suppressions = SuppressionsOperations(self._client, self._config, self._serialize, self._deserialize) + + + def _send_request( + self, + request: HttpRequest, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> 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/python/protocol/quickstart + + :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.rest.AsyncHttpResponse + """ - self.recommendation_metadata = RecommendationMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) - self.configurations = ConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.recommendations = RecommendationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.suppressions = SuppressionsOperations( - self._client, self._config, self._serialize, self._deserialize) + 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/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_configuration.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_configuration.py index 435bf128a735..851ae30737b7 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_configuration.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/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 @@ -37,11 +37,11 @@ def __init__( subscription_id: str, **kwargs: Any ) -> None: + super(AdvisorManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(AdvisorManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id @@ -64,4 +64,4 @@ def _configure( 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/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_patch.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_patch.py new file mode 100644 index 000000000000..74e48ecd07cf --- /dev/null +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# 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. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_configurations_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_configurations_operations.py index 67e44455c615..5ddab1e7ce43 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_configurations_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_configurations_operations.py @@ -5,17 +5,22 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import functools 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.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.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - +from ..._vendor import _convert_request +from ...operations._configurations_operations import build_create_in_resource_group_request, build_create_in_subscription_request, build_list_by_resource_group_request, build_list_by_subscription_request T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -41,9 +46,10 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._deserialize = deserializer self._config = config + @distributed_trace def list_by_subscription( self, - **kwargs + **kwargs: Any ) -> AsyncIterable["_models.ConfigurationListResult"]: """Retrieve Azure Advisor configurations. @@ -51,8 +57,10 @@ def list_by_subscription( groups. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.ConfigurationListResult] + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.ConfigurationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] @@ -60,34 +68,29 @@ def list_by_subscription( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + template_url=self.list_by_subscription.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -100,22 +103,24 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize(_models.ArmErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged( get_next, extract_data ) list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations'} # type: ignore + @distributed_trace_async async def create_in_subscription( self, configuration_name: Union[str, "_models.ConfigurationName"], config_contract: "_models.ConfigData", - **kwargs + **kwargs: Any ) -> "_models.ConfigData": """Create/Overwrite Azure Advisor configuration. @@ -136,37 +141,27 @@ async def create_in_subscription( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_in_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'configurationName': self._serialize.url("configuration_name", configuration_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') + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(config_contract, 'ConfigData') - # 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') + request = build_create_in_subscription_request( + subscription_id=self._config.subscription_id, + configuration_name=configuration_name, + content_type=content_type, + json=_json, + template_url=self.create_in_subscription.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(config_contract, 'ConfigData') - 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(_models.ArmErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('ConfigData', pipeline_response) @@ -175,12 +170,15 @@ async def create_in_subscription( return cls(pipeline_response, deserialized, {}) return deserialized + create_in_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations/{configurationName}'} # type: ignore + + @distributed_trace def list_by_resource_group( self, resource_group: str, - **kwargs + **kwargs: Any ) -> AsyncIterable["_models.ConfigurationListResult"]: """Retrieve Azure Advisor configurations. @@ -189,8 +187,10 @@ def list_by_resource_group( :param resource_group: The name of the Azure resource group. :type resource_group: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.ConfigurationListResult] + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.ConfigurationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ConfigurationListResult"] @@ -198,35 +198,31 @@ def list_by_resource_group( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroup': self._serialize.url("resource_group", resource_group, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group=resource_group, + template_url=self.list_by_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group=resource_group, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -239,23 +235,25 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize(_models.ArmErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations'} # type: ignore + @distributed_trace_async async def create_in_resource_group( self, configuration_name: Union[str, "_models.ConfigurationName"], resource_group: str, config_contract: "_models.ConfigData", - **kwargs + **kwargs: Any ) -> "_models.ConfigData": """Create/Overwrite Azure Advisor configuration. @@ -277,38 +275,28 @@ async def create_in_resource_group( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_in_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), - 'resourceGroup': self._serialize.url("resource_group", resource_group, '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') + content_type = kwargs.pop('content_type', "application/json") # type: Optional[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') + _json = self._serialize.body(config_contract, 'ConfigData') + + request = build_create_in_resource_group_request( + subscription_id=self._config.subscription_id, + configuration_name=configuration_name, + resource_group=resource_group, + content_type=content_type, + json=_json, + template_url=self.create_in_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(config_contract, 'ConfigData') - 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(_models.ArmErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('ConfigData', pipeline_response) @@ -317,4 +305,6 @@ async def create_in_resource_group( return cls(pipeline_response, deserialized, {}) return deserialized + create_in_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations/{configurationName}'} # type: ignore + diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_operations.py index 3fe50c593ca2..14a9cd9a4e4a 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_operations.py @@ -5,17 +5,22 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import functools 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.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.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') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -41,15 +46,18 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._deserialize = deserializer self._config = config + @distributed_trace def list( self, - **kwargs + **kwargs: Any ) -> AsyncIterable["_models.OperationEntityListResult"]: """Lists all the available Advisor 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 OperationEntityListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.OperationEntityListResult] + :return: An iterator like instance of either OperationEntityListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.OperationEntityListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationEntityListResult"] @@ -57,30 +65,27 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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) + + request = build_list_request( + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationEntityListResult', pipeline_response) + deserialized = self._deserialize("OperationEntityListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,10 +99,12 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged( get_next, extract_data ) diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendation_metadata_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendation_metadata_operations.py index d27f76a07f7c..6761994373a7 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendation_metadata_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendation_metadata_operations.py @@ -5,17 +5,22 @@ # 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 functools +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.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.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - +from ..._vendor import _convert_request +from ...operations._recommendation_metadata_operations import build_get_request, build_list_request T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -41,11 +46,12 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._deserialize = deserializer self._config = config + @distributed_trace_async async def get( self, name: str, - **kwargs - ) -> Union["_models.MetadataEntity", "_models.ARMErrorResponseBody"]: + **kwargs: Any + ) -> "_models.MetadataEntity": """Gets the metadata entity. Gets the metadata entity. @@ -53,64 +59,58 @@ async def get( :param name: Name of metadata entity. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: MetadataEntity or ARMErrorResponseBody, or the result of cls(response) - :rtype: ~azure.mgmt.advisor.models.MetadataEntity or ~azure.mgmt.advisor.models.ARMErrorResponseBody + :return: MetadataEntity, or the result of cls(response) + :rtype: ~azure.mgmt.advisor.models.MetadataEntity :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.MetadataEntity", "_models.ARMErrorResponseBody"]] + cls = kwargs.pop('cls', None) # type: ClsType["_models.MetadataEntity"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 409: ResourceExistsError, + 404: lambda response: ResourceNotFoundError(response=response, model=self._deserialize(_models.ARMErrorResponseBody, response), error_format=ARMErrorFormat), } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'name': self._serialize.url("name", 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 = build_get_request( + name=name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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, 404]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize('MetadataEntity', pipeline_response) - - if response.status_code == 404: - deserialized = self._deserialize('ARMErrorResponseBody', pipeline_response) + deserialized = self._deserialize('MetadataEntity', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized + get.metadata = {'url': '/providers/Microsoft.Advisor/metadata/{name}'} # type: ignore + + @distributed_trace def list( self, - **kwargs + **kwargs: Any ) -> AsyncIterable["_models.MetadataEntityListResult"]: """Gets the list of metadata entities. Gets the list of metadata entities. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either MetadataEntityListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.MetadataEntityListResult] + :return: An iterator like instance of either MetadataEntityListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.MetadataEntityListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MetadataEntityListResult"] @@ -118,30 +118,27 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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) + + request = build_list_request( + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('MetadataEntityListResult', pipeline_response) + deserialized = self._deserialize("MetadataEntityListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -155,10 +152,12 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged( get_next, extract_data ) diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendations_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendations_operations.py index 2f99233dc3f7..882d255666db 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendations_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_recommendations_operations.py @@ -5,17 +5,22 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import functools 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.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.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - +from ..._vendor import _convert_request +from ...operations._recommendations_operations import build_generate_request, build_get_generate_status_request, build_get_request, build_list_request T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -41,9 +46,10 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._deserialize = deserializer self._config = config + @distributed_trace_async async def generate( self, - **kwargs + **kwargs: Any ) -> None: """Initiates the recommendation generation or computation process for a subscription. This operation is asynchronous. The generated recommendations are stored in a cache in the Advisor @@ -59,43 +65,39 @@ async def generate( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - - # Construct URL - url = self.generate.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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] + + request = build_generate_request( + subscription_id=self._config.subscription_id, + template_url=self.generate.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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 [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} response_headers['Location']=self._deserialize('str', response.headers.get('Location')) response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + if cls: return cls(pipeline_response, None, response_headers) generate.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations'} # type: ignore + + @distributed_trace_async async def get_generate_status( self, operation_id: str, - **kwargs + **kwargs: Any ) -> None: """Retrieves the status of the recommendation computation or generation process. Invoke this API after calling the generation recommendation. The URI of this API is returned in the Location @@ -114,42 +116,37 @@ async def get_generate_status( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - - # Construct URL - url = self.get_generate_status.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'operationId': self._serialize.url("operation_id", operation_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] + + request = build_get_generate_status_request( + subscription_id=self._config.subscription_id, + operation_id=operation_id, + template_url=self.get_generate_status.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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 [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) get_generate_status.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations/{operationId}'} # type: ignore + + @distributed_trace def list( self, filter: Optional[str] = None, top: Optional[int] = None, skip_token: Optional[str] = None, - **kwargs + **kwargs: Any ) -> AsyncIterable["_models.ResourceRecommendationBaseListResult"]: """Obtains cached recommendations for a subscription. The recommendations are generated or computed by invoking generateRecommendations. @@ -165,8 +162,10 @@ def list( :param skip_token: The page-continuation token to use with a paged version of this API. :type skip_token: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ResourceRecommendationBaseListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.ResourceRecommendationBaseListResult] + :return: An iterator like instance of either ResourceRecommendationBaseListResult or the result + of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.ResourceRecommendationBaseListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceRecommendationBaseListResult"] @@ -174,40 +173,35 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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 top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if skip_token is not None: - query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + skip_token=skip_token, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + skip_token=skip_token, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ResourceRecommendationBaseListResult', pipeline_response) + deserialized = self._deserialize("ResourceRecommendationBaseListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -221,20 +215,23 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/recommendations'} # type: ignore + @distributed_trace_async async def get( self, resource_uri: str, recommendation_id: str, - **kwargs + **kwargs: Any ) -> "_models.ResourceRecommendationBase": """Obtains details of a cached recommendation. @@ -253,32 +250,23 @@ async def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_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 = build_get_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('ResourceRecommendationBase', pipeline_response) @@ -286,4 +274,6 @@ async def get( return cls(pipeline_response, deserialized, {}) return deserialized + get.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}'} # type: ignore + diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_suppressions_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_suppressions_operations.py index 99073a34d763..34feb424f4a0 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_suppressions_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/aio/operations/_suppressions_operations.py @@ -5,17 +5,22 @@ # 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 functools +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.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.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - +from ..._vendor import _convert_request +from ...operations._suppressions_operations import build_create_request, build_delete_request, build_get_request, build_list_request T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -41,13 +46,14 @@ def __init__(self, client, config, serializer, deserializer) -> None: self._deserialize = deserializer self._config = config + @distributed_trace_async async def get( self, resource_uri: str, recommendation_id: str, name: str, - **kwargs - ) -> Union["_models.SuppressionContract", "_models.ArmErrorResponse"]: + **kwargs: Any + ) -> "_models.SuppressionContract": """Obtains the details of a suppression. :param resource_uri: The fully qualified Azure Resource Manager identifier of the resource to @@ -58,63 +64,55 @@ async def get( :param name: The name of the suppression. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SuppressionContract or ArmErrorResponse, or the result of cls(response) - :rtype: ~azure.mgmt.advisor.models.SuppressionContract or ~azure.mgmt.advisor.models.ArmErrorResponse + :return: SuppressionContract, or the result of cls(response) + :rtype: ~azure.mgmt.advisor.models.SuppressionContract :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.SuppressionContract", "_models.ArmErrorResponse"]] + cls = kwargs.pop('cls', None) # type: ClsType["_models.SuppressionContract"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 409: ResourceExistsError, + 404: lambda response: ResourceNotFoundError(response=response, model=self._deserialize(_models.ArmErrorResponse, response), error_format=ARMErrorFormat), } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_id, 'str'), - 'name': self._serialize.url("name", 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 = build_get_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + name=name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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, 404]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('SuppressionContract', pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 404: - deserialized = self._deserialize('ArmErrorResponse', pipeline_response) + deserialized = self._deserialize('SuppressionContract', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized + get.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}'} # type: ignore + + @distributed_trace_async async def create( self, resource_uri: str, recommendation_id: str, name: str, suppression_contract: "_models.SuppressionContract", - **kwargs - ) -> Union["_models.SuppressionContract", "_models.ArmErrorResponse"]: + **kwargs: Any + ) -> "_models.SuppressionContract": """Enables the snoozed or dismissed attribute of a recommendation. The snoozed or dismissed attribute is referred to as a suppression. Use this API to create or update the snoozed or dismissed status of a recommendation. @@ -130,66 +128,58 @@ async def create( duration. :type suppression_contract: ~azure.mgmt.advisor.models.SuppressionContract :keyword callable cls: A custom type or function that will be passed the direct response - :return: SuppressionContract or ArmErrorResponse, or the result of cls(response) - :rtype: ~azure.mgmt.advisor.models.SuppressionContract or ~azure.mgmt.advisor.models.ArmErrorResponse + :return: SuppressionContract, or the result of cls(response) + :rtype: ~azure.mgmt.advisor.models.SuppressionContract :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.SuppressionContract", "_models.ArmErrorResponse"]] + cls = kwargs.pop('cls', None) # type: ClsType["_models.SuppressionContract"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 409: ResourceExistsError, + 404: lambda response: ResourceNotFoundError(response=response, model=self._deserialize(_models.ArmErrorResponse, response), error_format=ARMErrorFormat), } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_id, 'str'), - 'name': self._serialize.url("name", 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') + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(suppression_contract, 'SuppressionContract') - # 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') + request = build_create_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + name=name, + content_type=content_type, + json=_json, + template_url=self.create.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(suppression_contract, 'SuppressionContract') - 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, 404]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize('SuppressionContract', pipeline_response) - - if response.status_code == 404: - deserialized = self._deserialize('ArmErrorResponse', pipeline_response) + deserialized = self._deserialize('SuppressionContract', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized + create.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}'} # type: ignore + + @distributed_trace_async async def delete( self, resource_uri: str, recommendation_id: str, name: str, - **kwargs + **kwargs: Any ) -> None: """Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. @@ -211,42 +201,37 @@ async def delete( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_id, 'str'), - 'name': self._serialize.url("name", 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] + + request = build_delete_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + name=name, + template_url=self.delete.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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 [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}'} # type: ignore + + @distributed_trace def list( self, top: Optional[int] = None, skip_token: Optional[str] = None, - **kwargs + **kwargs: Any ) -> AsyncIterable["_models.SuppressionContractListResult"]: """Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. @@ -256,8 +241,10 @@ def list( :param skip_token: The page-continuation token to use with a paged version of this API. :type skip_token: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SuppressionContractListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.SuppressionContractListResult] + :return: An iterator like instance of either SuppressionContractListResult or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.advisor.models.SuppressionContractListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SuppressionContractListResult"] @@ -265,38 +252,33 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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 top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if skip_token is not None: - query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('SuppressionContractListResult', pipeline_response) + deserialized = self._deserialize("SuppressionContractListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -310,10 +292,12 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return AsyncItemPaged( get_next, extract_data ) diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/__init__.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/__init__.py index b5a374bf6f81..d09b766d3bcc 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/__init__.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/__init__.py @@ -6,44 +6,25 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import ARMErrorResponseBody - from ._models_py3 import ArmErrorResponse - from ._models_py3 import ConfigData - from ._models_py3 import ConfigurationListResult - from ._models_py3 import DigestConfig - from ._models_py3 import MetadataEntity - from ._models_py3 import MetadataEntityListResult - from ._models_py3 import MetadataSupportedValueDetail - from ._models_py3 import OperationDisplayInfo - from ._models_py3 import OperationEntity - from ._models_py3 import OperationEntityListResult - from ._models_py3 import Resource - from ._models_py3 import ResourceMetadata - from ._models_py3 import ResourceRecommendationBase - from ._models_py3 import ResourceRecommendationBaseListResult - from ._models_py3 import ShortDescription - from ._models_py3 import SuppressionContract - from ._models_py3 import SuppressionContractListResult -except (SyntaxError, ImportError): - from ._models import ARMErrorResponseBody # type: ignore - from ._models import ArmErrorResponse # type: ignore - from ._models import ConfigData # type: ignore - from ._models import ConfigurationListResult # type: ignore - from ._models import DigestConfig # type: ignore - from ._models import MetadataEntity # type: ignore - from ._models import MetadataEntityListResult # type: ignore - from ._models import MetadataSupportedValueDetail # type: ignore - from ._models import OperationDisplayInfo # type: ignore - from ._models import OperationEntity # type: ignore - from ._models import OperationEntityListResult # type: ignore - from ._models import Resource # type: ignore - from ._models import ResourceMetadata # type: ignore - from ._models import ResourceRecommendationBase # type: ignore - from ._models import ResourceRecommendationBaseListResult # type: ignore - from ._models import ShortDescription # type: ignore - from ._models import SuppressionContract # type: ignore - from ._models import SuppressionContractListResult # type: ignore +from ._models_py3 import ARMErrorResponseBody +from ._models_py3 import ArmErrorResponse +from ._models_py3 import ConfigData +from ._models_py3 import ConfigurationListResult +from ._models_py3 import DigestConfig +from ._models_py3 import MetadataEntity +from ._models_py3 import MetadataEntityListResult +from ._models_py3 import MetadataSupportedValueDetail +from ._models_py3 import OperationDisplayInfo +from ._models_py3 import OperationEntity +from ._models_py3 import OperationEntityListResult +from ._models_py3 import Resource +from ._models_py3 import ResourceMetadata +from ._models_py3 import ResourceRecommendationBase +from ._models_py3 import ResourceRecommendationBaseListResult +from ._models_py3 import ShortDescription +from ._models_py3 import SuppressionContract +from ._models_py3 import SuppressionContractListResult + from ._advisor_management_client_enums import ( Category, diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_advisor_management_client_enums.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_advisor_management_client_enums.py index e4d1caa3eae3..82bf341da18a 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_advisor_management_client_enums.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_advisor_management_client_enums.py @@ -6,27 +6,12 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta +from enum import Enum from six import with_metaclass +from azure.core import CaseInsensitiveEnumMeta -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 Category(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class Category(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): HIGH_AVAILABILITY = "HighAvailability" SECURITY = "Security" @@ -34,11 +19,11 @@ class Category(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): COST = "Cost" OPERATIONAL_EXCELLENCE = "OperationalExcellence" -class ConfigurationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class ConfigurationName(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): DEFAULT = "default" -class CpuThreshold(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class CpuThreshold(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """Minimum percentage threshold for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid values: 5 (default), 10, 15 or 20. """ @@ -48,14 +33,14 @@ class CpuThreshold(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): FIFTEEN = "15" TWENTY = "20" -class DigestConfigState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class DigestConfigState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """State of digest configuration. """ ACTIVE = "Active" DISABLED = "Disabled" -class Impact(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class Impact(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """The business impact of the recommendation. """ @@ -63,7 +48,7 @@ class Impact(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): MEDIUM = "Medium" LOW = "Low" -class Risk(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class Risk(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """The potential risk of not implementing the recommendation. """ @@ -71,6 +56,6 @@ class Risk(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): WARNING = "Warning" NONE = "None" -class Scenario(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class Scenario(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): ALERTS = "Alerts" diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models.py deleted file mode 100644 index c61d143176dd..000000000000 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models.py +++ /dev/null @@ -1,589 +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 ArmErrorResponse(msrest.serialization.Model): - """ArmErrorResponse. - - :param error: ARM error response body. - :type error: ~azure.mgmt.advisor.models.ARMErrorResponseBody - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ARMErrorResponseBody'}, - } - - def __init__( - self, - **kwargs - ): - super(ArmErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ARMErrorResponseBody(msrest.serialization.Model): - """ARM error response body. - - :param message: Gets or sets the string that describes the error in detail and provides - debugging information. - :type message: str - :param code: Gets or sets the string that can be used to programmatically identify the error. - :type code: str - """ - - _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'code': {'key': 'code', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ARMErrorResponseBody, self).__init__(**kwargs) - self.message = kwargs.get('message', None) - self.code = kwargs.get('code', None) - - -class Resource(msrest.serialization.Model): - """An Azure resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The resource ID. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class ConfigData(Resource): - """The Advisor configuration data structure. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The resource ID. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. - :vartype type: str - :param exclude: Exclude the resource from Advisor evaluations. Valid values: False (default) or - True. - :type exclude: bool - :param low_cpu_threshold: Minimum percentage threshold for Advisor low CPU utilization - evaluation. Valid only for subscriptions. Valid values: 5 (default), 10, 15 or 20. Possible - values include: "5", "10", "15", "20". - :type low_cpu_threshold: str or ~azure.mgmt.advisor.models.CpuThreshold - :param digests: Advisor digest configuration. Valid only for subscriptions. - :type digests: list[~azure.mgmt.advisor.models.DigestConfig] - """ - - _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'}, - 'exclude': {'key': 'properties.exclude', 'type': 'bool'}, - 'low_cpu_threshold': {'key': 'properties.lowCpuThreshold', 'type': 'str'}, - 'digests': {'key': 'properties.digests', 'type': '[DigestConfig]'}, - } - - def __init__( - self, - **kwargs - ): - super(ConfigData, self).__init__(**kwargs) - self.exclude = kwargs.get('exclude', None) - self.low_cpu_threshold = kwargs.get('low_cpu_threshold', None) - self.digests = kwargs.get('digests', None) - - -class ConfigurationListResult(msrest.serialization.Model): - """The list of Advisor configurations. - - :param value: The list of configurations. - :type value: list[~azure.mgmt.advisor.models.ConfigData] - :param next_link: The link used to get the next page of configurations. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[ConfigData]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ConfigurationListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class DigestConfig(msrest.serialization.Model): - """Advisor Digest configuration entity. - - :param name: Name of digest configuration. Value is case-insensitive and must be unique within - a subscription. - :type name: str - :param action_group_resource_id: Action group resource id used by digest. - :type action_group_resource_id: str - :param frequency: Frequency that digest will be triggered, in days. Value must be between 7 and - 30 days inclusive. - :type frequency: int - :param categories: Categories to send digest for. If categories are not provided, then digest - will be sent for all categories. - :type categories: list[str or ~azure.mgmt.advisor.models.Category] - :param language: Language for digest content body. Value must be ISO 639-1 code for one of - Azure portal supported languages. Otherwise, it will be converted into one. Default value is - English (en). - :type language: str - :param state: State of digest configuration. Possible values include: "Active", "Disabled". - :type state: str or ~azure.mgmt.advisor.models.DigestConfigState - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'action_group_resource_id': {'key': 'actionGroupResourceId', 'type': 'str'}, - 'frequency': {'key': 'frequency', 'type': 'int'}, - 'categories': {'key': 'categories', 'type': '[str]'}, - 'language': {'key': 'language', 'type': 'str'}, - 'state': {'key': 'state', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DigestConfig, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.action_group_resource_id = kwargs.get('action_group_resource_id', None) - self.frequency = kwargs.get('frequency', None) - self.categories = kwargs.get('categories', None) - self.language = kwargs.get('language', None) - self.state = kwargs.get('state', None) - - -class MetadataEntity(msrest.serialization.Model): - """The metadata entity contract. - - :param id: The resource Id of the metadata entity. - :type id: str - :param type: The type of the metadata entity. - :type type: str - :param name: The name of the metadata entity. - :type name: str - :param display_name: The display name. - :type display_name: str - :param depends_on: The list of keys on which this entity depends on. - :type depends_on: list[str] - :param applicable_scenarios: The list of scenarios applicable to this metadata entity. - :type applicable_scenarios: list[str or ~azure.mgmt.advisor.models.Scenario] - :param supported_values: The list of supported values. - :type supported_values: list[~azure.mgmt.advisor.models.MetadataSupportedValueDetail] - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'depends_on': {'key': 'properties.dependsOn', 'type': '[str]'}, - 'applicable_scenarios': {'key': 'properties.applicableScenarios', 'type': '[str]'}, - 'supported_values': {'key': 'properties.supportedValues', 'type': '[MetadataSupportedValueDetail]'}, - } - - def __init__( - self, - **kwargs - ): - super(MetadataEntity, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.type = kwargs.get('type', None) - self.name = kwargs.get('name', None) - self.display_name = kwargs.get('display_name', None) - self.depends_on = kwargs.get('depends_on', None) - self.applicable_scenarios = kwargs.get('applicable_scenarios', None) - self.supported_values = kwargs.get('supported_values', None) - - -class MetadataEntityListResult(msrest.serialization.Model): - """The list of metadata entities. - - :param value: The list of metadata entities. - :type value: list[~azure.mgmt.advisor.models.MetadataEntity] - :param next_link: The link used to get the next page of metadata. - :type next_link: str - """ - - _attribute_map = { - 'value': {'key': 'value', 'type': '[MetadataEntity]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(MetadataEntityListResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = kwargs.get('next_link', None) - - -class MetadataSupportedValueDetail(msrest.serialization.Model): - """The metadata supported value detail. - - :param id: The id. - :type id: str - :param display_name: The display name. - :type display_name: str - """ - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(MetadataSupportedValueDetail, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.display_name = kwargs.get('display_name', None) - - -class OperationDisplayInfo(msrest.serialization.Model): - """The operation supported by Advisor. - - :param description: The description of the operation. - :type description: str - :param operation: The action that users can perform, based on their permission level. - :type operation: str - :param provider: Service provider: Microsoft Advisor. - :type provider: str - :param resource: Resource on which the operation is performed. - :type resource: str - """ - - _attribute_map = { - 'description': {'key': 'description', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplayInfo, self).__init__(**kwargs) - self.description = kwargs.get('description', None) - self.operation = kwargs.get('operation', None) - self.provider = kwargs.get('provider', None) - self.resource = kwargs.get('resource', None) - - -class OperationEntity(msrest.serialization.Model): - """The operation supported by Advisor. - - :param name: Operation name: {provider}/{resource}/{operation}. - :type name: str - :param display: The operation supported by Advisor. - :type display: ~azure.mgmt.advisor.models.OperationDisplayInfo - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplayInfo'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationEntity, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display = kwargs.get('display', None) - - -class OperationEntityListResult(msrest.serialization.Model): - """The list of Advisor operations. - - :param next_link: The link used to get the next page of operations. - :type next_link: str - :param value: The list of operations. - :type value: list[~azure.mgmt.advisor.models.OperationEntity] - """ - - _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[OperationEntity]'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationEntityListResult, self).__init__(**kwargs) - self.next_link = kwargs.get('next_link', None) - self.value = kwargs.get('value', None) - - -class ResourceMetadata(msrest.serialization.Model): - """Recommendation resource metadata. - - :param resource_id: Azure resource Id of the assessed resource. - :type resource_id: str - :param source: Source from which recommendation is generated. - :type source: str - """ - - _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'source': {'key': 'source', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ResourceMetadata, self).__init__(**kwargs) - self.resource_id = kwargs.get('resource_id', None) - self.source = kwargs.get('source', None) - - -class ResourceRecommendationBase(Resource): - """Advisor Recommendation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The resource ID. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. - :vartype type: str - :param category: The category of the recommendation. Possible values include: - "HighAvailability", "Security", "Performance", "Cost", "OperationalExcellence". - :type category: str or ~azure.mgmt.advisor.models.Category - :param impact: The business impact of the recommendation. Possible values include: "High", - "Medium", "Low". - :type impact: str or ~azure.mgmt.advisor.models.Impact - :param impacted_field: The resource type identified by Advisor. - :type impacted_field: str - :param impacted_value: The resource identified by Advisor. - :type impacted_value: str - :param last_updated: The most recent time that Advisor checked the validity of the - recommendation. - :type last_updated: ~datetime.datetime - :param metadata: The recommendation metadata. - :type metadata: dict[str, object] - :param recommendation_type_id: The recommendation-type GUID. - :type recommendation_type_id: str - :param risk: The potential risk of not implementing the recommendation. Possible values - include: "Error", "Warning", "None". - :type risk: str or ~azure.mgmt.advisor.models.Risk - :param short_description: A summary of the recommendation. - :type short_description: ~azure.mgmt.advisor.models.ShortDescription - :param suppression_ids: The list of snoozed and dismissed rules for the recommendation. - :type suppression_ids: list[str] - :param extended_properties: Extended properties. - :type extended_properties: dict[str, str] - :param resource_metadata: Metadata of resource that was assessed. - :type resource_metadata: ~azure.mgmt.advisor.models.ResourceMetadata - """ - - _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'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'impact': {'key': 'properties.impact', 'type': 'str'}, - 'impacted_field': {'key': 'properties.impactedField', 'type': 'str'}, - 'impacted_value': {'key': 'properties.impactedValue', 'type': 'str'}, - 'last_updated': {'key': 'properties.lastUpdated', 'type': 'iso-8601'}, - 'metadata': {'key': 'properties.metadata', 'type': '{object}'}, - 'recommendation_type_id': {'key': 'properties.recommendationTypeId', 'type': 'str'}, - 'risk': {'key': 'properties.risk', 'type': 'str'}, - 'short_description': {'key': 'properties.shortDescription', 'type': 'ShortDescription'}, - 'suppression_ids': {'key': 'properties.suppressionIds', 'type': '[str]'}, - 'extended_properties': {'key': 'properties.extendedProperties', 'type': '{str}'}, - 'resource_metadata': {'key': 'properties.resourceMetadata', 'type': 'ResourceMetadata'}, - } - - def __init__( - self, - **kwargs - ): - super(ResourceRecommendationBase, self).__init__(**kwargs) - self.category = kwargs.get('category', None) - self.impact = kwargs.get('impact', None) - self.impacted_field = kwargs.get('impacted_field', None) - self.impacted_value = kwargs.get('impacted_value', None) - self.last_updated = kwargs.get('last_updated', None) - self.metadata = kwargs.get('metadata', None) - self.recommendation_type_id = kwargs.get('recommendation_type_id', None) - self.risk = kwargs.get('risk', None) - self.short_description = kwargs.get('short_description', None) - self.suppression_ids = kwargs.get('suppression_ids', None) - self.extended_properties = kwargs.get('extended_properties', None) - self.resource_metadata = kwargs.get('resource_metadata', None) - - -class ResourceRecommendationBaseListResult(msrest.serialization.Model): - """The list of Advisor recommendations. - - :param next_link: The link used to get the next page of recommendations. - :type next_link: str - :param value: The list of recommendations. - :type value: list[~azure.mgmt.advisor.models.ResourceRecommendationBase] - """ - - _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[ResourceRecommendationBase]'}, - } - - def __init__( - self, - **kwargs - ): - super(ResourceRecommendationBaseListResult, self).__init__(**kwargs) - self.next_link = kwargs.get('next_link', None) - self.value = kwargs.get('value', None) - - -class ShortDescription(msrest.serialization.Model): - """A summary of the recommendation. - - :param problem: The issue or opportunity identified by the recommendation. - :type problem: str - :param solution: The remediation action suggested by the recommendation. - :type solution: str - """ - - _attribute_map = { - 'problem': {'key': 'problem', 'type': 'str'}, - 'solution': {'key': 'solution', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ShortDescription, self).__init__(**kwargs) - self.problem = kwargs.get('problem', None) - self.solution = kwargs.get('solution', None) - - -class SuppressionContract(Resource): - """The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The resource ID. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. - :vartype type: str - :param suppression_id: The GUID of the suppression. - :type suppression_id: str - :param ttl: The duration for which the suppression is valid. - :type ttl: str - :ivar expiration_time_stamp: Gets or sets the expiration time stamp. - :vartype expiration_time_stamp: ~datetime.datetime - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'expiration_time_stamp': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'suppression_id': {'key': 'properties.suppressionId', 'type': 'str'}, - 'ttl': {'key': 'properties.ttl', 'type': 'str'}, - 'expiration_time_stamp': {'key': 'properties.expirationTimeStamp', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(SuppressionContract, self).__init__(**kwargs) - self.suppression_id = kwargs.get('suppression_id', None) - self.ttl = kwargs.get('ttl', None) - self.expiration_time_stamp = None - - -class SuppressionContractListResult(msrest.serialization.Model): - """The list of Advisor suppressions. - - :param next_link: The link used to get the next page of suppressions. - :type next_link: str - :param value: The list of suppressions. - :type value: list[~azure.mgmt.advisor.models.SuppressionContract] - """ - - _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[SuppressionContract]'}, - } - - def __init__( - self, - **kwargs - ): - super(SuppressionContractListResult, self).__init__(**kwargs) - self.next_link = kwargs.get('next_link', None) - self.value = kwargs.get('value', None) diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models_py3.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models_py3.py index 476150e82f26..55f2f4277203 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models_py3.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/models/_models_py3.py @@ -7,7 +7,7 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization @@ -18,8 +18,8 @@ class ArmErrorResponse(msrest.serialization.Model): """ArmErrorResponse. - :param error: ARM error response body. - :type error: ~azure.mgmt.advisor.models.ARMErrorResponseBody + :ivar error: ARM error response body. + :vartype error: ~azure.mgmt.advisor.models.ARMErrorResponseBody """ _attribute_map = { @@ -32,6 +32,10 @@ def __init__( error: Optional["ARMErrorResponseBody"] = None, **kwargs ): + """ + :keyword error: ARM error response body. + :paramtype error: ~azure.mgmt.advisor.models.ARMErrorResponseBody + """ super(ArmErrorResponse, self).__init__(**kwargs) self.error = error @@ -39,11 +43,11 @@ def __init__( class ARMErrorResponseBody(msrest.serialization.Model): """ARM error response body. - :param message: Gets or sets the string that describes the error in detail and provides + :ivar message: Gets or sets the string that describes the error in detail and provides debugging information. - :type message: str - :param code: Gets or sets the string that can be used to programmatically identify the error. - :type code: str + :vartype message: str + :ivar code: Gets or sets the string that can be used to programmatically identify the error. + :vartype code: str """ _attribute_map = { @@ -58,6 +62,13 @@ def __init__( code: Optional[str] = None, **kwargs ): + """ + :keyword message: Gets or sets the string that describes the error in detail and provides + debugging information. + :paramtype message: str + :keyword code: Gets or sets the string that can be used to programmatically identify the error. + :paramtype code: str + """ super(ARMErrorResponseBody, self).__init__(**kwargs) self.message = message self.code = code @@ -92,6 +103,8 @@ def __init__( self, **kwargs ): + """ + """ super(Resource, self).__init__(**kwargs) self.id = None self.name = None @@ -109,15 +122,15 @@ class ConfigData(Resource): :vartype name: str :ivar type: The type of the resource. :vartype type: str - :param exclude: Exclude the resource from Advisor evaluations. Valid values: False (default) or + :ivar exclude: Exclude the resource from Advisor evaluations. Valid values: False (default) or True. - :type exclude: bool - :param low_cpu_threshold: Minimum percentage threshold for Advisor low CPU utilization + :vartype exclude: bool + :ivar low_cpu_threshold: Minimum percentage threshold for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid values: 5 (default), 10, 15 or 20. Possible values include: "5", "10", "15", "20". - :type low_cpu_threshold: str or ~azure.mgmt.advisor.models.CpuThreshold - :param digests: Advisor digest configuration. Valid only for subscriptions. - :type digests: list[~azure.mgmt.advisor.models.DigestConfig] + :vartype low_cpu_threshold: str or ~azure.mgmt.advisor.models.CpuThreshold + :ivar digests: Advisor digest configuration. Valid only for subscriptions. + :vartype digests: list[~azure.mgmt.advisor.models.DigestConfig] """ _validation = { @@ -143,6 +156,17 @@ def __init__( digests: Optional[List["DigestConfig"]] = None, **kwargs ): + """ + :keyword exclude: Exclude the resource from Advisor evaluations. Valid values: False (default) + or True. + :paramtype exclude: bool + :keyword low_cpu_threshold: Minimum percentage threshold for Advisor low CPU utilization + evaluation. Valid only for subscriptions. Valid values: 5 (default), 10, 15 or 20. Possible + values include: "5", "10", "15", "20". + :paramtype low_cpu_threshold: str or ~azure.mgmt.advisor.models.CpuThreshold + :keyword digests: Advisor digest configuration. Valid only for subscriptions. + :paramtype digests: list[~azure.mgmt.advisor.models.DigestConfig] + """ super(ConfigData, self).__init__(**kwargs) self.exclude = exclude self.low_cpu_threshold = low_cpu_threshold @@ -152,10 +176,10 @@ def __init__( class ConfigurationListResult(msrest.serialization.Model): """The list of Advisor configurations. - :param value: The list of configurations. - :type value: list[~azure.mgmt.advisor.models.ConfigData] - :param next_link: The link used to get the next page of configurations. - :type next_link: str + :ivar value: The list of configurations. + :vartype value: list[~azure.mgmt.advisor.models.ConfigData] + :ivar next_link: The link used to get the next page of configurations. + :vartype next_link: str """ _attribute_map = { @@ -170,6 +194,12 @@ def __init__( next_link: Optional[str] = None, **kwargs ): + """ + :keyword value: The list of configurations. + :paramtype value: list[~azure.mgmt.advisor.models.ConfigData] + :keyword next_link: The link used to get the next page of configurations. + :paramtype next_link: str + """ super(ConfigurationListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link @@ -178,23 +208,23 @@ def __init__( class DigestConfig(msrest.serialization.Model): """Advisor Digest configuration entity. - :param name: Name of digest configuration. Value is case-insensitive and must be unique within - a subscription. - :type name: str - :param action_group_resource_id: Action group resource id used by digest. - :type action_group_resource_id: str - :param frequency: Frequency that digest will be triggered, in days. Value must be between 7 and + :ivar name: Name of digest configuration. Value is case-insensitive and must be unique within a + subscription. + :vartype name: str + :ivar action_group_resource_id: Action group resource id used by digest. + :vartype action_group_resource_id: str + :ivar frequency: Frequency that digest will be triggered, in days. Value must be between 7 and 30 days inclusive. - :type frequency: int - :param categories: Categories to send digest for. If categories are not provided, then digest + :vartype frequency: int + :ivar categories: Categories to send digest for. If categories are not provided, then digest will be sent for all categories. - :type categories: list[str or ~azure.mgmt.advisor.models.Category] - :param language: Language for digest content body. Value must be ISO 639-1 code for one of - Azure portal supported languages. Otherwise, it will be converted into one. Default value is - English (en). - :type language: str - :param state: State of digest configuration. Possible values include: "Active", "Disabled". - :type state: str or ~azure.mgmt.advisor.models.DigestConfigState + :vartype categories: list[str or ~azure.mgmt.advisor.models.Category] + :ivar language: Language for digest content body. Value must be ISO 639-1 code for one of Azure + portal supported languages. Otherwise, it will be converted into one. Default value is English + (en). + :vartype language: str + :ivar state: State of digest configuration. Possible values include: "Active", "Disabled". + :vartype state: str or ~azure.mgmt.advisor.models.DigestConfigState """ _attribute_map = { @@ -217,6 +247,25 @@ def __init__( state: Optional[Union[str, "DigestConfigState"]] = None, **kwargs ): + """ + :keyword name: Name of digest configuration. Value is case-insensitive and must be unique + within a subscription. + :paramtype name: str + :keyword action_group_resource_id: Action group resource id used by digest. + :paramtype action_group_resource_id: str + :keyword frequency: Frequency that digest will be triggered, in days. Value must be between 7 + and 30 days inclusive. + :paramtype frequency: int + :keyword categories: Categories to send digest for. If categories are not provided, then digest + will be sent for all categories. + :paramtype categories: list[str or ~azure.mgmt.advisor.models.Category] + :keyword language: Language for digest content body. Value must be ISO 639-1 code for one of + Azure portal supported languages. Otherwise, it will be converted into one. Default value is + English (en). + :paramtype language: str + :keyword state: State of digest configuration. Possible values include: "Active", "Disabled". + :paramtype state: str or ~azure.mgmt.advisor.models.DigestConfigState + """ super(DigestConfig, self).__init__(**kwargs) self.name = name self.action_group_resource_id = action_group_resource_id @@ -229,20 +278,20 @@ def __init__( class MetadataEntity(msrest.serialization.Model): """The metadata entity contract. - :param id: The resource Id of the metadata entity. - :type id: str - :param type: The type of the metadata entity. - :type type: str - :param name: The name of the metadata entity. - :type name: str - :param display_name: The display name. - :type display_name: str - :param depends_on: The list of keys on which this entity depends on. - :type depends_on: list[str] - :param applicable_scenarios: The list of scenarios applicable to this metadata entity. - :type applicable_scenarios: list[str or ~azure.mgmt.advisor.models.Scenario] - :param supported_values: The list of supported values. - :type supported_values: list[~azure.mgmt.advisor.models.MetadataSupportedValueDetail] + :ivar id: The resource Id of the metadata entity. + :vartype id: str + :ivar type: The type of the metadata entity. + :vartype type: str + :ivar name: The name of the metadata entity. + :vartype name: str + :ivar display_name: The display name. + :vartype display_name: str + :ivar depends_on: The list of keys on which this entity depends on. + :vartype depends_on: list[str] + :ivar applicable_scenarios: The list of scenarios applicable to this metadata entity. + :vartype applicable_scenarios: list[str or ~azure.mgmt.advisor.models.Scenario] + :ivar supported_values: The list of supported values. + :vartype supported_values: list[~azure.mgmt.advisor.models.MetadataSupportedValueDetail] """ _attribute_map = { @@ -267,6 +316,22 @@ def __init__( supported_values: Optional[List["MetadataSupportedValueDetail"]] = None, **kwargs ): + """ + :keyword id: The resource Id of the metadata entity. + :paramtype id: str + :keyword type: The type of the metadata entity. + :paramtype type: str + :keyword name: The name of the metadata entity. + :paramtype name: str + :keyword display_name: The display name. + :paramtype display_name: str + :keyword depends_on: The list of keys on which this entity depends on. + :paramtype depends_on: list[str] + :keyword applicable_scenarios: The list of scenarios applicable to this metadata entity. + :paramtype applicable_scenarios: list[str or ~azure.mgmt.advisor.models.Scenario] + :keyword supported_values: The list of supported values. + :paramtype supported_values: list[~azure.mgmt.advisor.models.MetadataSupportedValueDetail] + """ super(MetadataEntity, self).__init__(**kwargs) self.id = id self.type = type @@ -280,10 +345,10 @@ def __init__( class MetadataEntityListResult(msrest.serialization.Model): """The list of metadata entities. - :param value: The list of metadata entities. - :type value: list[~azure.mgmt.advisor.models.MetadataEntity] - :param next_link: The link used to get the next page of metadata. - :type next_link: str + :ivar value: The list of metadata entities. + :vartype value: list[~azure.mgmt.advisor.models.MetadataEntity] + :ivar next_link: The link used to get the next page of metadata. + :vartype next_link: str """ _attribute_map = { @@ -298,6 +363,12 @@ def __init__( next_link: Optional[str] = None, **kwargs ): + """ + :keyword value: The list of metadata entities. + :paramtype value: list[~azure.mgmt.advisor.models.MetadataEntity] + :keyword next_link: The link used to get the next page of metadata. + :paramtype next_link: str + """ super(MetadataEntityListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link @@ -306,10 +377,10 @@ def __init__( class MetadataSupportedValueDetail(msrest.serialization.Model): """The metadata supported value detail. - :param id: The id. - :type id: str - :param display_name: The display name. - :type display_name: str + :ivar id: The id. + :vartype id: str + :ivar display_name: The display name. + :vartype display_name: str """ _attribute_map = { @@ -324,6 +395,12 @@ def __init__( display_name: Optional[str] = None, **kwargs ): + """ + :keyword id: The id. + :paramtype id: str + :keyword display_name: The display name. + :paramtype display_name: str + """ super(MetadataSupportedValueDetail, self).__init__(**kwargs) self.id = id self.display_name = display_name @@ -332,14 +409,14 @@ def __init__( class OperationDisplayInfo(msrest.serialization.Model): """The operation supported by Advisor. - :param description: The description of the operation. - :type description: str - :param operation: The action that users can perform, based on their permission level. - :type operation: str - :param provider: Service provider: Microsoft Advisor. - :type provider: str - :param resource: Resource on which the operation is performed. - :type resource: str + :ivar description: The description of the operation. + :vartype description: str + :ivar operation: The action that users can perform, based on their permission level. + :vartype operation: str + :ivar provider: Service provider: Microsoft Advisor. + :vartype provider: str + :ivar resource: Resource on which the operation is performed. + :vartype resource: str """ _attribute_map = { @@ -358,6 +435,16 @@ def __init__( resource: Optional[str] = None, **kwargs ): + """ + :keyword description: The description of the operation. + :paramtype description: str + :keyword operation: The action that users can perform, based on their permission level. + :paramtype operation: str + :keyword provider: Service provider: Microsoft Advisor. + :paramtype provider: str + :keyword resource: Resource on which the operation is performed. + :paramtype resource: str + """ super(OperationDisplayInfo, self).__init__(**kwargs) self.description = description self.operation = operation @@ -368,10 +455,10 @@ def __init__( class OperationEntity(msrest.serialization.Model): """The operation supported by Advisor. - :param name: Operation name: {provider}/{resource}/{operation}. - :type name: str - :param display: The operation supported by Advisor. - :type display: ~azure.mgmt.advisor.models.OperationDisplayInfo + :ivar name: Operation name: {provider}/{resource}/{operation}. + :vartype name: str + :ivar display: The operation supported by Advisor. + :vartype display: ~azure.mgmt.advisor.models.OperationDisplayInfo """ _attribute_map = { @@ -386,6 +473,12 @@ def __init__( display: Optional["OperationDisplayInfo"] = None, **kwargs ): + """ + :keyword name: Operation name: {provider}/{resource}/{operation}. + :paramtype name: str + :keyword display: The operation supported by Advisor. + :paramtype display: ~azure.mgmt.advisor.models.OperationDisplayInfo + """ super(OperationEntity, self).__init__(**kwargs) self.name = name self.display = display @@ -394,10 +487,10 @@ def __init__( class OperationEntityListResult(msrest.serialization.Model): """The list of Advisor operations. - :param next_link: The link used to get the next page of operations. - :type next_link: str - :param value: The list of operations. - :type value: list[~azure.mgmt.advisor.models.OperationEntity] + :ivar next_link: The link used to get the next page of operations. + :vartype next_link: str + :ivar value: The list of operations. + :vartype value: list[~azure.mgmt.advisor.models.OperationEntity] """ _attribute_map = { @@ -412,6 +505,12 @@ def __init__( value: Optional[List["OperationEntity"]] = None, **kwargs ): + """ + :keyword next_link: The link used to get the next page of operations. + :paramtype next_link: str + :keyword value: The list of operations. + :paramtype value: list[~azure.mgmt.advisor.models.OperationEntity] + """ super(OperationEntityListResult, self).__init__(**kwargs) self.next_link = next_link self.value = value @@ -420,15 +519,24 @@ def __init__( class ResourceMetadata(msrest.serialization.Model): """Recommendation resource metadata. - :param resource_id: Azure resource Id of the assessed resource. - :type resource_id: str - :param source: Source from which recommendation is generated. - :type source: str + :ivar resource_id: Azure resource Id of the assessed resource. + :vartype resource_id: str + :ivar source: Source from which recommendation is generated. + :vartype source: str + :ivar action: The action to view resource. + :vartype action: dict[str, any] + :ivar singular: The singular user friendly name of resource type. eg: virtual machine. + :vartype singular: str + :ivar plural: The plural user friendly name of resource type. eg: virtual machines. + :vartype plural: str """ _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'source': {'key': 'source', 'type': 'str'}, + 'action': {'key': 'action', 'type': '{object}'}, + 'singular': {'key': 'singular', 'type': 'str'}, + 'plural': {'key': 'plural', 'type': 'str'}, } def __init__( @@ -436,11 +544,29 @@ def __init__( *, resource_id: Optional[str] = None, source: Optional[str] = None, + action: Optional[Dict[str, Any]] = None, + singular: Optional[str] = None, + plural: Optional[str] = None, **kwargs ): + """ + :keyword resource_id: Azure resource Id of the assessed resource. + :paramtype resource_id: str + :keyword source: Source from which recommendation is generated. + :paramtype source: str + :keyword action: The action to view resource. + :paramtype action: dict[str, any] + :keyword singular: The singular user friendly name of resource type. eg: virtual machine. + :paramtype singular: str + :keyword plural: The plural user friendly name of resource type. eg: virtual machines. + :paramtype plural: str + """ super(ResourceMetadata, self).__init__(**kwargs) self.resource_id = resource_id self.source = source + self.action = action + self.singular = singular + self.plural = plural class ResourceRecommendationBase(Resource): @@ -454,34 +580,49 @@ class ResourceRecommendationBase(Resource): :vartype name: str :ivar type: The type of the resource. :vartype type: str - :param category: The category of the recommendation. Possible values include: + :ivar category: The category of the recommendation. Possible values include: "HighAvailability", "Security", "Performance", "Cost", "OperationalExcellence". - :type category: str or ~azure.mgmt.advisor.models.Category - :param impact: The business impact of the recommendation. Possible values include: "High", + :vartype category: str or ~azure.mgmt.advisor.models.Category + :ivar impact: The business impact of the recommendation. Possible values include: "High", "Medium", "Low". - :type impact: str or ~azure.mgmt.advisor.models.Impact - :param impacted_field: The resource type identified by Advisor. - :type impacted_field: str - :param impacted_value: The resource identified by Advisor. - :type impacted_value: str - :param last_updated: The most recent time that Advisor checked the validity of the + :vartype impact: str or ~azure.mgmt.advisor.models.Impact + :ivar impacted_field: The resource type identified by Advisor. + :vartype impacted_field: str + :ivar impacted_value: The resource identified by Advisor. + :vartype impacted_value: str + :ivar last_updated: The most recent time that Advisor checked the validity of the recommendation. - :type last_updated: ~datetime.datetime - :param metadata: The recommendation metadata. - :type metadata: dict[str, object] - :param recommendation_type_id: The recommendation-type GUID. - :type recommendation_type_id: str - :param risk: The potential risk of not implementing the recommendation. Possible values - include: "Error", "Warning", "None". - :type risk: str or ~azure.mgmt.advisor.models.Risk - :param short_description: A summary of the recommendation. - :type short_description: ~azure.mgmt.advisor.models.ShortDescription - :param suppression_ids: The list of snoozed and dismissed rules for the recommendation. - :type suppression_ids: list[str] - :param extended_properties: Extended properties. - :type extended_properties: dict[str, str] - :param resource_metadata: Metadata of resource that was assessed. - :type resource_metadata: ~azure.mgmt.advisor.models.ResourceMetadata + :vartype last_updated: ~datetime.datetime + :ivar metadata: The recommendation metadata. + :vartype metadata: dict[str, any] + :ivar recommendation_type_id: The recommendation-type GUID. + :vartype recommendation_type_id: str + :ivar risk: The potential risk of not implementing the recommendation. Possible values include: + "Error", "Warning", "None". + :vartype risk: str or ~azure.mgmt.advisor.models.Risk + :ivar short_description: A summary of the recommendation. + :vartype short_description: ~azure.mgmt.advisor.models.ShortDescription + :ivar suppression_ids: The list of snoozed and dismissed rules for the recommendation. + :vartype suppression_ids: list[str] + :ivar extended_properties: Extended properties. + :vartype extended_properties: dict[str, str] + :ivar resource_metadata: Metadata of resource that was assessed. + :vartype resource_metadata: ~azure.mgmt.advisor.models.ResourceMetadata + :ivar description: The detailed description of recommendation. + :vartype description: str + :ivar label: The label of recommendation. + :vartype label: str + :ivar learn_more_link: The link to learn more about recommendation and generation logic. + :vartype learn_more_link: str + :ivar potential_benefits: The potential benefit of implementing recommendation. + :vartype potential_benefits: str + :ivar actions: The list of recommended actions to implement recommendation. + :vartype actions: list[dict[str, any]] + :ivar remediation: The automated way to apply recommendation. + :vartype remediation: dict[str, any] + :ivar exposed_metadata_properties: The recommendation metadata properties exposed to customer + to provide additional information. + :vartype exposed_metadata_properties: dict[str, any] """ _validation = { @@ -506,6 +647,13 @@ class ResourceRecommendationBase(Resource): 'suppression_ids': {'key': 'properties.suppressionIds', 'type': '[str]'}, 'extended_properties': {'key': 'properties.extendedProperties', 'type': '{str}'}, 'resource_metadata': {'key': 'properties.resourceMetadata', 'type': 'ResourceMetadata'}, + 'description': {'key': 'properties.description', 'type': 'str'}, + 'label': {'key': 'properties.label', 'type': 'str'}, + 'learn_more_link': {'key': 'properties.learnMoreLink', 'type': 'str'}, + 'potential_benefits': {'key': 'properties.potentialBenefits', 'type': 'str'}, + 'actions': {'key': 'properties.actions', 'type': '[{object}]'}, + 'remediation': {'key': 'properties.remediation', 'type': '{object}'}, + 'exposed_metadata_properties': {'key': 'properties.exposedMetadataProperties', 'type': '{object}'}, } def __init__( @@ -516,15 +664,67 @@ def __init__( impacted_field: Optional[str] = None, impacted_value: Optional[str] = None, last_updated: Optional[datetime.datetime] = None, - metadata: Optional[Dict[str, object]] = None, + metadata: Optional[Dict[str, Any]] = None, recommendation_type_id: Optional[str] = None, risk: Optional[Union[str, "Risk"]] = None, short_description: Optional["ShortDescription"] = None, suppression_ids: Optional[List[str]] = None, extended_properties: Optional[Dict[str, str]] = None, resource_metadata: Optional["ResourceMetadata"] = None, + description: Optional[str] = None, + label: Optional[str] = None, + learn_more_link: Optional[str] = None, + potential_benefits: Optional[str] = None, + actions: Optional[List[Dict[str, Any]]] = None, + remediation: Optional[Dict[str, Any]] = None, + exposed_metadata_properties: Optional[Dict[str, Any]] = None, **kwargs ): + """ + :keyword category: The category of the recommendation. Possible values include: + "HighAvailability", "Security", "Performance", "Cost", "OperationalExcellence". + :paramtype category: str or ~azure.mgmt.advisor.models.Category + :keyword impact: The business impact of the recommendation. Possible values include: "High", + "Medium", "Low". + :paramtype impact: str or ~azure.mgmt.advisor.models.Impact + :keyword impacted_field: The resource type identified by Advisor. + :paramtype impacted_field: str + :keyword impacted_value: The resource identified by Advisor. + :paramtype impacted_value: str + :keyword last_updated: The most recent time that Advisor checked the validity of the + recommendation. + :paramtype last_updated: ~datetime.datetime + :keyword metadata: The recommendation metadata. + :paramtype metadata: dict[str, any] + :keyword recommendation_type_id: The recommendation-type GUID. + :paramtype recommendation_type_id: str + :keyword risk: The potential risk of not implementing the recommendation. Possible values + include: "Error", "Warning", "None". + :paramtype risk: str or ~azure.mgmt.advisor.models.Risk + :keyword short_description: A summary of the recommendation. + :paramtype short_description: ~azure.mgmt.advisor.models.ShortDescription + :keyword suppression_ids: The list of snoozed and dismissed rules for the recommendation. + :paramtype suppression_ids: list[str] + :keyword extended_properties: Extended properties. + :paramtype extended_properties: dict[str, str] + :keyword resource_metadata: Metadata of resource that was assessed. + :paramtype resource_metadata: ~azure.mgmt.advisor.models.ResourceMetadata + :keyword description: The detailed description of recommendation. + :paramtype description: str + :keyword label: The label of recommendation. + :paramtype label: str + :keyword learn_more_link: The link to learn more about recommendation and generation logic. + :paramtype learn_more_link: str + :keyword potential_benefits: The potential benefit of implementing recommendation. + :paramtype potential_benefits: str + :keyword actions: The list of recommended actions to implement recommendation. + :paramtype actions: list[dict[str, any]] + :keyword remediation: The automated way to apply recommendation. + :paramtype remediation: dict[str, any] + :keyword exposed_metadata_properties: The recommendation metadata properties exposed to + customer to provide additional information. + :paramtype exposed_metadata_properties: dict[str, any] + """ super(ResourceRecommendationBase, self).__init__(**kwargs) self.category = category self.impact = impact @@ -538,15 +738,22 @@ def __init__( self.suppression_ids = suppression_ids self.extended_properties = extended_properties self.resource_metadata = resource_metadata + self.description = description + self.label = label + self.learn_more_link = learn_more_link + self.potential_benefits = potential_benefits + self.actions = actions + self.remediation = remediation + self.exposed_metadata_properties = exposed_metadata_properties class ResourceRecommendationBaseListResult(msrest.serialization.Model): """The list of Advisor recommendations. - :param next_link: The link used to get the next page of recommendations. - :type next_link: str - :param value: The list of recommendations. - :type value: list[~azure.mgmt.advisor.models.ResourceRecommendationBase] + :ivar next_link: The link used to get the next page of recommendations. + :vartype next_link: str + :ivar value: The list of recommendations. + :vartype value: list[~azure.mgmt.advisor.models.ResourceRecommendationBase] """ _attribute_map = { @@ -561,6 +768,12 @@ def __init__( value: Optional[List["ResourceRecommendationBase"]] = None, **kwargs ): + """ + :keyword next_link: The link used to get the next page of recommendations. + :paramtype next_link: str + :keyword value: The list of recommendations. + :paramtype value: list[~azure.mgmt.advisor.models.ResourceRecommendationBase] + """ super(ResourceRecommendationBaseListResult, self).__init__(**kwargs) self.next_link = next_link self.value = value @@ -569,10 +782,10 @@ def __init__( class ShortDescription(msrest.serialization.Model): """A summary of the recommendation. - :param problem: The issue or opportunity identified by the recommendation. - :type problem: str - :param solution: The remediation action suggested by the recommendation. - :type solution: str + :ivar problem: The issue or opportunity identified by the recommendation. + :vartype problem: str + :ivar solution: The remediation action suggested by the recommendation. + :vartype solution: str """ _attribute_map = { @@ -587,6 +800,12 @@ def __init__( solution: Optional[str] = None, **kwargs ): + """ + :keyword problem: The issue or opportunity identified by the recommendation. + :paramtype problem: str + :keyword solution: The remediation action suggested by the recommendation. + :paramtype solution: str + """ super(ShortDescription, self).__init__(**kwargs) self.problem = problem self.solution = solution @@ -603,10 +822,10 @@ class SuppressionContract(Resource): :vartype name: str :ivar type: The type of the resource. :vartype type: str - :param suppression_id: The GUID of the suppression. - :type suppression_id: str - :param ttl: The duration for which the suppression is valid. - :type ttl: str + :ivar suppression_id: The GUID of the suppression. + :vartype suppression_id: str + :ivar ttl: The duration for which the suppression is valid. + :vartype ttl: str :ivar expiration_time_stamp: Gets or sets the expiration time stamp. :vartype expiration_time_stamp: ~datetime.datetime """ @@ -634,6 +853,12 @@ def __init__( ttl: Optional[str] = None, **kwargs ): + """ + :keyword suppression_id: The GUID of the suppression. + :paramtype suppression_id: str + :keyword ttl: The duration for which the suppression is valid. + :paramtype ttl: str + """ super(SuppressionContract, self).__init__(**kwargs) self.suppression_id = suppression_id self.ttl = ttl @@ -643,10 +868,10 @@ def __init__( class SuppressionContractListResult(msrest.serialization.Model): """The list of Advisor suppressions. - :param next_link: The link used to get the next page of suppressions. - :type next_link: str - :param value: The list of suppressions. - :type value: list[~azure.mgmt.advisor.models.SuppressionContract] + :ivar next_link: The link used to get the next page of suppressions. + :vartype next_link: str + :ivar value: The list of suppressions. + :vartype value: list[~azure.mgmt.advisor.models.SuppressionContract] """ _attribute_map = { @@ -661,6 +886,12 @@ def __init__( value: Optional[List["SuppressionContract"]] = None, **kwargs ): + """ + :keyword next_link: The link used to get the next page of suppressions. + :paramtype next_link: str + :keyword value: The list of suppressions. + :paramtype value: list[~azure.mgmt.advisor.models.SuppressionContract] + """ super(SuppressionContractListResult, self).__init__(**kwargs) self.next_link = next_link self.value = value diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_configurations_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_configurations_operations.py index 12a83d42a93b..89f867fe2f87 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_configurations_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_configurations_operations.py @@ -5,23 +5,176 @@ # 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 functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union 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.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer 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]] +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_list_by_subscription_request( + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_in_subscription_request( + subscription_id: str, + configuration_name: Union[str, "_models.ConfigurationName"], + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations/{configurationName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_list_by_resource_group_request( + subscription_id: str, + resource_group: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "resourceGroup": _SERIALIZER.url("resource_group", resource_group, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_in_resource_group_request( + subscription_id: str, + configuration_name: Union[str, "_models.ConfigurationName"], + resource_group: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations/{configurationName}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + "resourceGroup": _SERIALIZER.url("resource_group", resource_group, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) class ConfigurationsOperations(object): """ConfigurationsOperations operations. @@ -45,18 +198,19 @@ def __init__(self, client, config, serializer, deserializer): self._deserialize = deserializer self._config = config + @distributed_trace def list_by_subscription( self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ConfigurationListResult"] + **kwargs: Any + ) -> Iterable["_models.ConfigurationListResult"]: """Retrieve Azure Advisor configurations. Retrieve Azure Advisor configurations and also retrieve configurations of contained resource groups. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.ConfigurationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ @@ -65,34 +219,29 @@ def list_by_subscription( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + template_url=self.list_by_subscription.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_subscription_request( + subscription_id=self._config.subscription_id, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,24 +254,25 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize(_models.ArmErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged( get_next, extract_data ) list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations'} # type: ignore + @distributed_trace def create_in_subscription( self, - configuration_name, # type: Union[str, "_models.ConfigurationName"] - config_contract, # type: "_models.ConfigData" - **kwargs # type: Any - ): - # type: (...) -> "_models.ConfigData" + configuration_name: Union[str, "_models.ConfigurationName"], + config_contract: "_models.ConfigData", + **kwargs: Any + ) -> "_models.ConfigData": """Create/Overwrite Azure Advisor configuration. Create/Overwrite Azure Advisor configuration and also delete all configurations of contained @@ -142,37 +292,27 @@ def create_in_subscription( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_in_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'configurationName': self._serialize.url("configuration_name", configuration_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') + content_type = kwargs.pop('content_type', "application/json") # type: Optional[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') + _json = self._serialize.body(config_contract, 'ConfigData') + + request = build_create_in_subscription_request( + subscription_id=self._config.subscription_id, + configuration_name=configuration_name, + content_type=content_type, + json=_json, + template_url=self.create_in_subscription.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(config_contract, 'ConfigData') - 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(_models.ArmErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('ConfigData', pipeline_response) @@ -181,14 +321,16 @@ def create_in_subscription( return cls(pipeline_response, deserialized, {}) return deserialized + create_in_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/configurations/{configurationName}'} # type: ignore + + @distributed_trace def list_by_resource_group( self, - resource_group, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ConfigurationListResult"] + resource_group: str, + **kwargs: Any + ) -> Iterable["_models.ConfigurationListResult"]: """Retrieve Azure Advisor configurations. Retrieve Azure Advisor configurations. @@ -196,7 +338,8 @@ def list_by_resource_group( :param resource_group: The name of the Azure resource group. :type resource_group: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of cls(response) + :return: An iterator like instance of either ConfigurationListResult or the result of + cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.ConfigurationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ @@ -205,35 +348,31 @@ def list_by_resource_group( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroup': self._serialize.url("resource_group", resource_group, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group=resource_group, + template_url=self.list_by_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_resource_group_request( + subscription_id=self._config.subscription_id, + resource_group=resource_group, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -246,25 +385,26 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize(_models.ArmErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations'} # type: ignore + @distributed_trace def create_in_resource_group( self, - configuration_name, # type: Union[str, "_models.ConfigurationName"] - resource_group, # type: str - config_contract, # type: "_models.ConfigData" - **kwargs # type: Any - ): - # type: (...) -> "_models.ConfigData" + configuration_name: Union[str, "_models.ConfigurationName"], + resource_group: str, + config_contract: "_models.ConfigData", + **kwargs: Any + ) -> "_models.ConfigData": """Create/Overwrite Azure Advisor configuration. Create/Overwrite Azure Advisor configuration. @@ -285,38 +425,28 @@ def create_in_resource_group( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_in_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'configurationName': self._serialize.url("configuration_name", configuration_name, 'str'), - 'resourceGroup': self._serialize.url("resource_group", resource_group, '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') + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(config_contract, 'ConfigData') - # 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') + request = build_create_in_resource_group_request( + subscription_id=self._config.subscription_id, + configuration_name=configuration_name, + resource_group=resource_group, + content_type=content_type, + json=_json, + template_url=self.create_in_resource_group.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(config_contract, 'ConfigData') - 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(_models.ArmErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('ConfigData', pipeline_response) @@ -325,4 +455,6 @@ def create_in_resource_group( return cls(pipeline_response, deserialized, {}) return deserialized + create_in_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Advisor/configurations/{configurationName}'} # type: ignore + diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_operations.py index f2745798f193..09eb33a0ebf5 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_operations.py @@ -5,23 +5,50 @@ # 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 functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar 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.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer 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]] +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 + +def build_list_request( + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/providers/Microsoft.Advisor/operations') + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) class Operations(object): """Operations operations. @@ -45,15 +72,16 @@ def __init__(self, client, config, serializer, deserializer): self._deserialize = deserializer self._config = config + @distributed_trace def list( self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationEntityListResult"] + **kwargs: Any + ) -> Iterable["_models.OperationEntityListResult"]: """Lists all the available Advisor 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 OperationEntityListResult or the result of cls(response) + :return: An iterator like instance of either OperationEntityListResult or the result of + cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.OperationEntityListResult] :raises: ~azure.core.exceptions.HttpResponseError """ @@ -62,30 +90,27 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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) + + request = build_list_request( + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationEntityListResult', pipeline_response) + deserialized = self._deserialize("OperationEntityListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -99,10 +124,12 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged( get_next, extract_data ) diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendation_metadata_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendation_metadata_operations.py index aa850acf7984..fcdabd84552a 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendation_metadata_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendation_metadata_operations.py @@ -5,23 +5,81 @@ # 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 functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar 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.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer 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]] +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( + name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/providers/Microsoft.Advisor/metadata/{name}') + path_format_arguments = { + "name": _SERIALIZER.url("name", name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_request( + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/providers/Microsoft.Advisor/metadata') + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) class RecommendationMetadataOperations(object): """RecommendationMetadataOperations operations. @@ -45,12 +103,12 @@ def __init__(self, client, config, serializer, deserializer): self._deserialize = deserializer self._config = config + @distributed_trace def get( self, - name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Union["_models.MetadataEntity", "_models.ARMErrorResponseBody"] + name: str, + **kwargs: Any + ) -> "_models.MetadataEntity": """Gets the metadata entity. Gets the metadata entity. @@ -58,64 +116,56 @@ def get( :param name: Name of metadata entity. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: MetadataEntity or ARMErrorResponseBody, or the result of cls(response) - :rtype: ~azure.mgmt.advisor.models.MetadataEntity or ~azure.mgmt.advisor.models.ARMErrorResponseBody + :return: MetadataEntity, or the result of cls(response) + :rtype: ~azure.mgmt.advisor.models.MetadataEntity :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.MetadataEntity", "_models.ARMErrorResponseBody"]] + cls = kwargs.pop('cls', None) # type: ClsType["_models.MetadataEntity"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 409: ResourceExistsError, + 404: lambda response: ResourceNotFoundError(response=response, model=self._deserialize(_models.ARMErrorResponseBody, response), error_format=ARMErrorFormat), } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - accept = "application/json" - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'name': self._serialize.url("name", 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 = build_get_request( + name=name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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, 404]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize('MetadataEntity', pipeline_response) - - if response.status_code == 404: - deserialized = self._deserialize('ARMErrorResponseBody', pipeline_response) + deserialized = self._deserialize('MetadataEntity', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized + get.metadata = {'url': '/providers/Microsoft.Advisor/metadata/{name}'} # type: ignore + + @distributed_trace def list( self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.MetadataEntityListResult"] + **kwargs: Any + ) -> Iterable["_models.MetadataEntityListResult"]: """Gets the list of metadata entities. Gets the list of metadata entities. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either MetadataEntityListResult or the result of cls(response) + :return: An iterator like instance of either MetadataEntityListResult or the result of + cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.MetadataEntityListResult] :raises: ~azure.core.exceptions.HttpResponseError """ @@ -124,30 +174,27 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = build_list_request( + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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) + + request = build_list_request( + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('MetadataEntityListResult', pipeline_response) + deserialized = self._deserialize("MetadataEntityListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -161,10 +208,12 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged( get_next, extract_data ) diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendations_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendations_operations.py index 13b4cf0fba58..88fed9814050 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendations_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_recommendations_operations.py @@ -5,23 +5,163 @@ # 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 functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar 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.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer 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]] +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_generate_request( + subscription_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_generate_status_request( + subscription_id: str, + operation_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations/{operationId}') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "operationId": _SERIALIZER.url("operation_id", operation_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_request( + subscription_id: str, + *, + filter: Optional[str] = None, + top: Optional[int] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/recommendations') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + if filter is not None: + query_parameters['$filter'] = _SERIALIZER.query("filter", filter, 'str') + if top is not None: + query_parameters['$top'] = _SERIALIZER.query("top", top, 'int') + if skip_token is not None: + query_parameters['$skipToken'] = _SERIALIZER.query("skip_token", skip_token, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_request( + resource_uri: str, + recommendation_id: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}') + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, 'str'), + "recommendationId": _SERIALIZER.url("recommendation_id", recommendation_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) class RecommendationsOperations(object): """RecommendationsOperations operations. @@ -45,11 +185,11 @@ def __init__(self, client, config, serializer, deserializer): self._deserialize = deserializer self._config = config + @distributed_trace def generate( self, - **kwargs # type: Any - ): - # type: (...) -> None + **kwargs: Any + ) -> None: """Initiates the recommendation generation or computation process for a subscription. This operation is asynchronous. The generated recommendations are stored in a cache in the Advisor service. @@ -64,45 +204,40 @@ def generate( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - - # Construct URL - url = self.generate.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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] + + request = build_generate_request( + subscription_id=self._config.subscription_id, + template_url=self.generate.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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 [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} response_headers['Location']=self._deserialize('str', response.headers.get('Location')) response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + if cls: return cls(pipeline_response, None, response_headers) generate.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations'} # type: ignore + + @distributed_trace def get_generate_status( self, - operation_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + operation_id: str, + **kwargs: Any + ) -> None: """Retrieves the status of the recommendation computation or generation process. Invoke this API after calling the generation recommendation. The URI of this API is returned in the Location field of the response header. @@ -120,44 +255,38 @@ def get_generate_status( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - - # Construct URL - url = self.get_generate_status.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'operationId': self._serialize.url("operation_id", operation_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] + + request = build_get_generate_status_request( + subscription_id=self._config.subscription_id, + operation_id=operation_id, + template_url=self.get_generate_status.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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 [202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) get_generate_status.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/generateRecommendations/{operationId}'} # type: ignore + + @distributed_trace def list( self, - filter=None, # type: Optional[str] - top=None, # type: Optional[int] - skip_token=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ResourceRecommendationBaseListResult"] + filter: Optional[str] = None, + top: Optional[int] = None, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.ResourceRecommendationBaseListResult"]: """Obtains cached recommendations for a subscription. The recommendations are generated or computed by invoking generateRecommendations. @@ -172,8 +301,10 @@ def list( :param skip_token: The page-continuation token to use with a paged version of this API. :type skip_token: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ResourceRecommendationBaseListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.ResourceRecommendationBaseListResult] + :return: An iterator like instance of either ResourceRecommendationBaseListResult or the result + of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.ResourceRecommendationBaseListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceRecommendationBaseListResult"] @@ -181,40 +312,35 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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 top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if skip_token is not None: - query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + skip_token=skip_token, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + top=top, + skip_token=skip_token, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ResourceRecommendationBaseListResult', pipeline_response) + deserialized = self._deserialize("ResourceRecommendationBaseListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -228,22 +354,24 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/recommendations'} # type: ignore + @distributed_trace def get( self, - resource_uri, # type: str - recommendation_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.ResourceRecommendationBase" + resource_uri: str, + recommendation_id: str, + **kwargs: Any + ) -> "_models.ResourceRecommendationBase": """Obtains details of a cached recommendation. :param resource_uri: The fully qualified Azure Resource Manager identifier of the resource to @@ -261,32 +389,23 @@ def get( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_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 = build_get_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('ResourceRecommendationBase', pipeline_response) @@ -294,4 +413,6 @@ def get( return cls(pipeline_response, deserialized, {}) return deserialized + get.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}'} # type: ignore + diff --git a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_suppressions_operations.py b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_suppressions_operations.py index e6264f43763b..5b7aad7b310d 100644 --- a/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_suppressions_operations.py +++ b/sdk/advisor/azure-mgmt-advisor/azure/mgmt/advisor/operations/_suppressions_operations.py @@ -5,23 +5,178 @@ # 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 functools +from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar 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.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat +from msrest import Serializer 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]] +from .._vendor import _convert_request, _format_url_section +T = TypeVar('T') +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + +def build_get_request( + resource_uri: str, + recommendation_id: str, + name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}') + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, 'str'), + "recommendationId": _SERIALIZER.url("recommendation_id", recommendation_id, 'str'), + "name": _SERIALIZER.url("name", name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_create_request( + resource_uri: str, + recommendation_id: str, + name: str, + *, + json: JSONType = None, + content: Any = None, + **kwargs: Any +) -> HttpRequest: + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}') + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, 'str'), + "recommendationId": _SERIALIZER.url("recommendation_id", recommendation_id, 'str'), + "name": _SERIALIZER.url("name", name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="PUT", + url=url, + params=query_parameters, + headers=header_parameters, + json=json, + content=content, + **kwargs + ) + + +def build_delete_request( + resource_uri: str, + recommendation_id: str, + name: str, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}') + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, 'str'), + "recommendationId": _SERIALIZER.url("recommendation_id", recommendation_id, 'str'), + "name": _SERIALIZER.url("name", name, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_list_request( + subscription_id: str, + *, + top: Optional[int] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + api_version = "2020-01-01" + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.Advisor/suppressions') + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + if top is not None: + query_parameters['$top'] = _SERIALIZER.query("top", top, 'int') + if skip_token is not None: + query_parameters['$skipToken'] = _SERIALIZER.query("skip_token", skip_token, 'str') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) class SuppressionsOperations(object): """SuppressionsOperations operations. @@ -45,14 +200,14 @@ def __init__(self, client, config, serializer, deserializer): self._deserialize = deserializer self._config = config + @distributed_trace def get( self, - resource_uri, # type: str - recommendation_id, # type: str - name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Union["_models.SuppressionContract", "_models.ArmErrorResponse"] + resource_uri: str, + recommendation_id: str, + name: str, + **kwargs: Any + ) -> "_models.SuppressionContract": """Obtains the details of a suppression. :param resource_uri: The fully qualified Azure Resource Manager identifier of the resource to @@ -63,64 +218,55 @@ def get( :param name: The name of the suppression. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SuppressionContract or ArmErrorResponse, or the result of cls(response) - :rtype: ~azure.mgmt.advisor.models.SuppressionContract or ~azure.mgmt.advisor.models.ArmErrorResponse + :return: SuppressionContract, or the result of cls(response) + :rtype: ~azure.mgmt.advisor.models.SuppressionContract :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.SuppressionContract", "_models.ArmErrorResponse"]] + cls = kwargs.pop('cls', None) # type: ClsType["_models.SuppressionContract"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 409: ResourceExistsError, + 404: lambda response: ResourceNotFoundError(response=response, model=self._deserialize(_models.ArmErrorResponse, response), error_format=ARMErrorFormat), } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_id, 'str'), - 'name': self._serialize.url("name", 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 = build_get_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + name=name, + template_url=self.get.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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, 404]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize('SuppressionContract', pipeline_response) - - if response.status_code == 404: - deserialized = self._deserialize('ArmErrorResponse', pipeline_response) + deserialized = self._deserialize('SuppressionContract', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized + get.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}'} # type: ignore + + @distributed_trace def create( self, - resource_uri, # type: str - recommendation_id, # type: str - name, # type: str - suppression_contract, # type: "_models.SuppressionContract" - **kwargs # type: Any - ): - # type: (...) -> Union["_models.SuppressionContract", "_models.ArmErrorResponse"] + resource_uri: str, + recommendation_id: str, + name: str, + suppression_contract: "_models.SuppressionContract", + **kwargs: Any + ) -> "_models.SuppressionContract": """Enables the snoozed or dismissed attribute of a recommendation. The snoozed or dismissed attribute is referred to as a suppression. Use this API to create or update the snoozed or dismissed status of a recommendation. @@ -136,68 +282,59 @@ def create( duration. :type suppression_contract: ~azure.mgmt.advisor.models.SuppressionContract :keyword callable cls: A custom type or function that will be passed the direct response - :return: SuppressionContract or ArmErrorResponse, or the result of cls(response) - :rtype: ~azure.mgmt.advisor.models.SuppressionContract or ~azure.mgmt.advisor.models.ArmErrorResponse + :return: SuppressionContract, or the result of cls(response) + :rtype: ~azure.mgmt.advisor.models.SuppressionContract :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[Union["_models.SuppressionContract", "_models.ArmErrorResponse"]] + cls = kwargs.pop('cls', None) # type: ClsType["_models.SuppressionContract"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 409: ResourceExistsError, + 404: lambda response: ResourceNotFoundError(response=response, model=self._deserialize(_models.ArmErrorResponse, response), error_format=ARMErrorFormat), } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_id, 'str'), - 'name': self._serialize.url("name", 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') + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + + _json = self._serialize.body(suppression_contract, 'SuppressionContract') - # 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') + request = build_create_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + name=name, + content_type=content_type, + json=_json, + template_url=self.create.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(suppression_contract, 'SuppressionContract') - 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, 404]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) - - if response.status_code == 200: - deserialized = self._deserialize('SuppressionContract', pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 404: - deserialized = self._deserialize('ArmErrorResponse', pipeline_response) + deserialized = self._deserialize('SuppressionContract', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized + create.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}'} # type: ignore + + @distributed_trace def delete( self, - resource_uri, # type: str - recommendation_id, # type: str - name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + resource_uri: str, + recommendation_id: str, + name: str, + **kwargs: Any + ) -> None: """Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. @@ -218,44 +355,38 @@ def delete( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-01" - - # Construct URL - url = self.delete.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceUri': self._serialize.url("resource_uri", resource_uri, 'str'), - 'recommendationId': self._serialize.url("recommendation_id", recommendation_id, 'str'), - 'name': self._serialize.url("name", 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] + + request = build_delete_request( + resource_uri=resource_uri, + recommendation_id=recommendation_id, + name=name, + template_url=self.delete.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) - 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 [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = {'url': '/{resourceUri}/providers/Microsoft.Advisor/recommendations/{recommendationId}/suppressions/{name}'} # type: ignore + + @distributed_trace def list( self, - top=None, # type: Optional[int] - skip_token=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.SuppressionContractListResult"] + top: Optional[int] = None, + skip_token: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.SuppressionContractListResult"]: """Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. @@ -264,7 +395,8 @@ def list( :param skip_token: The page-continuation token to use with a paged version of this API. :type skip_token: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either SuppressionContractListResult or the result of cls(response) + :return: An iterator like instance of either SuppressionContractListResult or the result of + cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.advisor.models.SuppressionContractListResult] :raises: ~azure.core.exceptions.HttpResponseError """ @@ -273,38 +405,33 @@ def list( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-01-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 = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_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 top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - if skip_token is not None: - query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + template_url=self.list.metadata['url'], + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + top=top, + skip_token=skip_token, + template_url=next_link, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('SuppressionContractListResult', pipeline_response) + deserialized = self._deserialize("SuppressionContractListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -318,10 +445,12 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ArmErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response + return ItemPaged( get_next, extract_data )